xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp (revision 700637cbb5e582861067a11aaca4d053546871d2)
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/ASTMutationListener.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/ComparisonCategories.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DynamicRecursiveASTVisitor.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/AttributeCommonInfo.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/EnterExpressionEvaluationContext.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Ownership.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaCUDA.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/SemaObjC.h"
47 #include "clang/Sema/SemaOpenMP.h"
48 #include "clang/Sema/Template.h"
49 #include "clang/Sema/TemplateDeduction.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/Support/ConvertUTF.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include <map>
56 #include <optional>
57 #include <set>
58 
59 using namespace clang;
60 
61 //===----------------------------------------------------------------------===//
62 // CheckDefaultArgumentVisitor
63 //===----------------------------------------------------------------------===//
64 
65 namespace {
66 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
67 /// the default argument of a parameter to determine whether it
68 /// contains any ill-formed subexpressions. For example, this will
69 /// diagnose the use of local variables or parameters within the
70 /// default argument expression.
71 class CheckDefaultArgumentVisitor
72     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
73   Sema &S;
74   const Expr *DefaultArg;
75 
76 public:
CheckDefaultArgumentVisitor(Sema & S,const Expr * DefaultArg)77   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
78       : S(S), DefaultArg(DefaultArg) {}
79 
80   bool VisitExpr(const Expr *Node);
81   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
82   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
83   bool VisitLambdaExpr(const LambdaExpr *Lambda);
84   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
85 };
86 
87 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(const Expr * Node)88 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
89   bool IsInvalid = false;
90   for (const Stmt *SubStmt : Node->children())
91     if (SubStmt)
92       IsInvalid |= Visit(SubStmt);
93   return IsInvalid;
94 }
95 
96 /// VisitDeclRefExpr - Visit a reference to a declaration, to
97 /// determine whether this declaration can be used in the default
98 /// argument expression.
VisitDeclRefExpr(const DeclRefExpr * DRE)99 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
100   const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
101 
102   if (!isa<VarDecl, BindingDecl>(Decl))
103     return false;
104 
105   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
106     // C++ [dcl.fct.default]p9:
107     //   [...] parameters of a function shall not be used in default
108     //   argument expressions, even if they are not evaluated. [...]
109     //
110     // C++17 [dcl.fct.default]p9 (by CWG 2082):
111     //   [...] A parameter shall not appear as a potentially-evaluated
112     //   expression in a default argument. [...]
113     //
114     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_param)
117              << Param->getDeclName() << DefaultArg->getSourceRange();
118   } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
119     // C++ [dcl.fct.default]p7:
120     //   Local variables shall not be used in default argument
121     //   expressions.
122     //
123     // C++17 [dcl.fct.default]p7 (by CWG 2082):
124     //   A local variable shall not appear as a potentially-evaluated
125     //   expression in a default argument.
126     //
127     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
128     //   Note: A local variable cannot be odr-used (6.3) in a default
129     //   argument.
130     //
131     if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
132       return S.Diag(DRE->getBeginLoc(),
133                     diag::err_param_default_argument_references_local)
134              << Decl << DefaultArg->getSourceRange();
135   }
136   return false;
137 }
138 
139 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(const CXXThisExpr * ThisE)140 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
141   // C++ [dcl.fct.default]p8:
142   //   The keyword this shall not be used in a default argument of a
143   //   member function.
144   return S.Diag(ThisE->getBeginLoc(),
145                 diag::err_param_default_argument_references_this)
146          << ThisE->getSourceRange();
147 }
148 
VisitPseudoObjectExpr(const PseudoObjectExpr * POE)149 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
150     const PseudoObjectExpr *POE) {
151   bool Invalid = false;
152   for (const Expr *E : POE->semantics()) {
153     // Look through bindings.
154     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
155       E = OVE->getSourceExpr();
156       assert(E && "pseudo-object binding without source expression?");
157     }
158 
159     Invalid |= Visit(E);
160   }
161   return Invalid;
162 }
163 
VisitLambdaExpr(const LambdaExpr * Lambda)164 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
165   // [expr.prim.lambda.capture]p9
166   // a lambda-expression appearing in a default argument cannot implicitly or
167   // explicitly capture any local entity. Such a lambda-expression can still
168   // have an init-capture if any full-expression in its initializer satisfies
169   // the constraints of an expression appearing in a default argument.
170   bool Invalid = false;
171   for (const LambdaCapture &LC : Lambda->captures()) {
172     if (!Lambda->isInitCapture(&LC))
173       return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
174     // Init captures are always VarDecl.
175     auto *D = cast<VarDecl>(LC.getCapturedVar());
176     Invalid |= Visit(D->getInit());
177   }
178   return Invalid;
179 }
180 } // namespace
181 
182 void
CalledDecl(SourceLocation CallLoc,const CXXMethodDecl * Method)183 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
184                                                  const CXXMethodDecl *Method) {
185   // If we have an MSAny spec already, don't bother.
186   if (!Method || ComputedEST == EST_MSAny)
187     return;
188 
189   const FunctionProtoType *Proto
190     = Method->getType()->getAs<FunctionProtoType>();
191   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
192   if (!Proto)
193     return;
194 
195   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
196 
197   // If we have a throw-all spec at this point, ignore the function.
198   if (ComputedEST == EST_None)
199     return;
200 
201   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
202     EST = EST_BasicNoexcept;
203 
204   switch (EST) {
205   case EST_Unparsed:
206   case EST_Uninstantiated:
207   case EST_Unevaluated:
208     llvm_unreachable("should not see unresolved exception specs here");
209 
210   // If this function can throw any exceptions, make a note of that.
211   case EST_MSAny:
212   case EST_None:
213     // FIXME: Whichever we see last of MSAny and None determines our result.
214     // We should make a consistent, order-independent choice here.
215     ClearExceptions();
216     ComputedEST = EST;
217     return;
218   case EST_NoexceptFalse:
219     ClearExceptions();
220     ComputedEST = EST_None;
221     return;
222   // FIXME: If the call to this decl is using any of its default arguments, we
223   // need to search them for potentially-throwing calls.
224   // If this function has a basic noexcept, it doesn't affect the outcome.
225   case EST_BasicNoexcept:
226   case EST_NoexceptTrue:
227   case EST_NoThrow:
228     return;
229   // If we're still at noexcept(true) and there's a throw() callee,
230   // change to that specification.
231   case EST_DynamicNone:
232     if (ComputedEST == EST_BasicNoexcept)
233       ComputedEST = EST_DynamicNone;
234     return;
235   case EST_DependentNoexcept:
236     llvm_unreachable(
237         "should not generate implicit declarations for dependent cases");
238   case EST_Dynamic:
239     break;
240   }
241   assert(EST == EST_Dynamic && "EST case not considered earlier.");
242   assert(ComputedEST != EST_None &&
243          "Shouldn't collect exceptions when throw-all is guaranteed.");
244   ComputedEST = EST_Dynamic;
245   // Record the exceptions in this function's exception specification.
246   for (const auto &E : Proto->exceptions())
247     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
248       Exceptions.push_back(E);
249 }
250 
CalledStmt(Stmt * S)251 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
252   if (!S || ComputedEST == EST_MSAny)
253     return;
254 
255   // FIXME:
256   //
257   // C++0x [except.spec]p14:
258   //   [An] implicit exception-specification specifies the type-id T if and
259   // only if T is allowed by the exception-specification of a function directly
260   // invoked by f's implicit definition; f shall allow all exceptions if any
261   // function it directly invokes allows all exceptions, and f shall allow no
262   // exceptions if every function it directly invokes allows no exceptions.
263   //
264   // Note in particular that if an implicit exception-specification is generated
265   // for a function containing a throw-expression, that specification can still
266   // be noexcept(true).
267   //
268   // Note also that 'directly invoked' is not defined in the standard, and there
269   // is no indication that we should only consider potentially-evaluated calls.
270   //
271   // Ultimately we should implement the intent of the standard: the exception
272   // specification should be the set of exceptions which can be thrown by the
273   // implicit definition. For now, we assume that any non-nothrow expression can
274   // throw any exception.
275 
276   if (Self->canThrow(S))
277     ComputedEST = EST_None;
278 }
279 
ConvertParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)280 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
281                                              SourceLocation EqualLoc) {
282   if (RequireCompleteType(Param->getLocation(), Param->getType(),
283                           diag::err_typecheck_decl_incomplete_type))
284     return true;
285 
286   // C++ [dcl.fct.default]p5
287   //   A default argument expression is implicitly converted (clause
288   //   4) to the parameter type. The default argument expression has
289   //   the same semantic constraints as the initializer expression in
290   //   a declaration of a variable of the parameter type, using the
291   //   copy-initialization semantics (8.5).
292   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
293                                                                     Param);
294   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
295                                                            EqualLoc);
296   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
297   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
298   if (Result.isInvalid())
299     return true;
300   Arg = Result.getAs<Expr>();
301 
302   CheckCompletedExpr(Arg, EqualLoc);
303   Arg = MaybeCreateExprWithCleanups(Arg);
304 
305   return Arg;
306 }
307 
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)308 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
309                                    SourceLocation EqualLoc) {
310   // Add the default argument to the parameter
311   Param->setDefaultArg(Arg);
312 
313   // We have already instantiated this parameter; provide each of the
314   // instantiations with the uninstantiated default argument.
315   UnparsedDefaultArgInstantiationsMap::iterator InstPos
316     = UnparsedDefaultArgInstantiations.find(Param);
317   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
318     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
319       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
320 
321     // We're done tracking this parameter's instantiations.
322     UnparsedDefaultArgInstantiations.erase(InstPos);
323   }
324 }
325 
326 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)327 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
328                                 Expr *DefaultArg) {
329   if (!param || !DefaultArg)
330     return;
331 
332   ParmVarDecl *Param = cast<ParmVarDecl>(param);
333   UnparsedDefaultArgLocs.erase(Param);
334 
335   // Default arguments are only permitted in C++
336   if (!getLangOpts().CPlusPlus) {
337     Diag(EqualLoc, diag::err_param_default_argument)
338       << DefaultArg->getSourceRange();
339     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
340   }
341 
342   // Check for unexpanded parameter packs.
343   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))
344     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
345 
346   // C++11 [dcl.fct.default]p3
347   //   A default argument expression [...] shall not be specified for a
348   //   parameter pack.
349   if (Param->isParameterPack()) {
350     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
351         << DefaultArg->getSourceRange();
352     // Recover by discarding the default argument.
353     Param->setDefaultArg(nullptr);
354     return;
355   }
356 
357   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
358   if (Result.isInvalid())
359     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 
361   DefaultArg = Result.getAs<Expr>();
362 
363   // Check that the default argument is well-formed
364   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
365   if (DefaultArgChecker.Visit(DefaultArg))
366     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
367 
368   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
369 }
370 
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)371 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
372                                              SourceLocation EqualLoc,
373                                              SourceLocation ArgLoc) {
374   if (!param)
375     return;
376 
377   ParmVarDecl *Param = cast<ParmVarDecl>(param);
378   Param->setUnparsedDefaultArg();
379   UnparsedDefaultArgLocs[Param] = ArgLoc;
380 }
381 
ActOnParamDefaultArgumentError(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)382 void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
383                                           Expr *DefaultArg) {
384   if (!param)
385     return;
386 
387   ParmVarDecl *Param = cast<ParmVarDecl>(param);
388   Param->setInvalidDecl();
389   UnparsedDefaultArgLocs.erase(Param);
390   ExprResult RE;
391   if (DefaultArg) {
392     RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
393                             Param->getType().getNonReferenceType());
394   } else {
395     RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
396                             Param->getType().getNonReferenceType());
397   }
398   Param->setDefaultArg(RE.get());
399 }
400 
CheckExtraCXXDefaultArguments(Declarator & D)401 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
402   // C++ [dcl.fct.default]p3
403   //   A default argument expression shall be specified only in the
404   //   parameter-declaration-clause of a function declaration or in a
405   //   template-parameter (14.1). It shall not be specified for a
406   //   parameter pack. If it is specified in a
407   //   parameter-declaration-clause, it shall not occur within a
408   //   declarator or abstract-declarator of a parameter-declaration.
409   bool MightBeFunction = D.isFunctionDeclarationContext();
410   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
411     DeclaratorChunk &chunk = D.getTypeObject(i);
412     if (chunk.Kind == DeclaratorChunk::Function) {
413       if (MightBeFunction) {
414         // This is a function declaration. It can have default arguments, but
415         // keep looking in case its return type is a function type with default
416         // arguments.
417         MightBeFunction = false;
418         continue;
419       }
420       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
421            ++argIdx) {
422         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
423         if (Param->hasUnparsedDefaultArg()) {
424           std::unique_ptr<CachedTokens> Toks =
425               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
426           SourceRange SR;
427           if (Toks->size() > 1)
428             SR = SourceRange((*Toks)[1].getLocation(),
429                              Toks->back().getLocation());
430           else
431             SR = UnparsedDefaultArgLocs[Param];
432           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
433             << SR;
434         } else if (Param->getDefaultArg()) {
435           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436             << Param->getDefaultArg()->getSourceRange();
437           Param->setDefaultArg(nullptr);
438         }
439       }
440     } else if (chunk.Kind != DeclaratorChunk::Paren) {
441       MightBeFunction = false;
442     }
443   }
444 }
445 
functionDeclHasDefaultArgument(const FunctionDecl * FD)446 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
447   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
448     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
449   });
450 }
451 
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)452 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
453                                 Scope *S) {
454   bool Invalid = false;
455 
456   // The declaration context corresponding to the scope is the semantic
457   // parent, unless this is a local function declaration, in which case
458   // it is that surrounding function.
459   DeclContext *ScopeDC = New->isLocalExternDecl()
460                              ? New->getLexicalDeclContext()
461                              : New->getDeclContext();
462 
463   // Find the previous declaration for the purpose of default arguments.
464   FunctionDecl *PrevForDefaultArgs = Old;
465   for (/**/; PrevForDefaultArgs;
466        // Don't bother looking back past the latest decl if this is a local
467        // extern declaration; nothing else could work.
468        PrevForDefaultArgs = New->isLocalExternDecl()
469                                 ? nullptr
470                                 : PrevForDefaultArgs->getPreviousDecl()) {
471     // Ignore hidden declarations.
472     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
473       continue;
474 
475     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
476         !New->isCXXClassMember()) {
477       // Ignore default arguments of old decl if they are not in
478       // the same scope and this is not an out-of-line definition of
479       // a member function.
480       continue;
481     }
482 
483     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
484       // If only one of these is a local function declaration, then they are
485       // declared in different scopes, even though isDeclInScope may think
486       // they're in the same scope. (If both are local, the scope check is
487       // sufficient, and if neither is local, then they are in the same scope.)
488       continue;
489     }
490 
491     // We found the right previous declaration.
492     break;
493   }
494 
495   // C++ [dcl.fct.default]p4:
496   //   For non-template functions, default arguments can be added in
497   //   later declarations of a function in the same
498   //   scope. Declarations in different scopes have completely
499   //   distinct sets of default arguments. That is, declarations in
500   //   inner scopes do not acquire default arguments from
501   //   declarations in outer scopes, and vice versa. In a given
502   //   function declaration, all parameters subsequent to a
503   //   parameter with a default argument shall have default
504   //   arguments supplied in this or previous declarations. A
505   //   default argument shall not be redefined by a later
506   //   declaration (not even to the same value).
507   //
508   // C++ [dcl.fct.default]p6:
509   //   Except for member functions of class templates, the default arguments
510   //   in a member function definition that appears outside of the class
511   //   definition are added to the set of default arguments provided by the
512   //   member function declaration in the class definition.
513   for (unsigned p = 0, NumParams = PrevForDefaultArgs
514                                        ? PrevForDefaultArgs->getNumParams()
515                                        : 0;
516        p < NumParams; ++p) {
517     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
518     ParmVarDecl *NewParam = New->getParamDecl(p);
519 
520     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
521     bool NewParamHasDfl = NewParam->hasDefaultArg();
522 
523     if (OldParamHasDfl && NewParamHasDfl) {
524       unsigned DiagDefaultParamID =
525         diag::err_param_default_argument_redefinition;
526 
527       // MSVC accepts that default parameters be redefined for member functions
528       // of template class. The new default parameter's value is ignored.
529       Invalid = true;
530       if (getLangOpts().MicrosoftExt) {
531         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
532         if (MD && MD->getParent()->getDescribedClassTemplate()) {
533           // Merge the old default argument into the new parameter.
534           NewParam->setHasInheritedDefaultArg();
535           if (OldParam->hasUninstantiatedDefaultArg())
536             NewParam->setUninstantiatedDefaultArg(
537                                       OldParam->getUninstantiatedDefaultArg());
538           else
539             NewParam->setDefaultArg(OldParam->getInit());
540           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
541           Invalid = false;
542         }
543       }
544 
545       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
546       // hint here. Alternatively, we could walk the type-source information
547       // for NewParam to find the last source location in the type... but it
548       // isn't worth the effort right now. This is the kind of test case that
549       // is hard to get right:
550       //   int f(int);
551       //   void g(int (*fp)(int) = f);
552       //   void g(int (*fp)(int) = &f);
553       Diag(NewParam->getLocation(), DiagDefaultParamID)
554         << NewParam->getDefaultArgRange();
555 
556       // Look for the function declaration where the default argument was
557       // actually written, which may be a declaration prior to Old.
558       for (auto Older = PrevForDefaultArgs;
559            OldParam->hasInheritedDefaultArg(); /**/) {
560         Older = Older->getPreviousDecl();
561         OldParam = Older->getParamDecl(p);
562       }
563 
564       Diag(OldParam->getLocation(), diag::note_previous_definition)
565         << OldParam->getDefaultArgRange();
566     } else if (OldParamHasDfl) {
567       // Merge the old default argument into the new parameter unless the new
568       // function is a friend declaration in a template class. In the latter
569       // case the default arguments will be inherited when the friend
570       // declaration will be instantiated.
571       if (New->getFriendObjectKind() == Decl::FOK_None ||
572           !New->getLexicalDeclContext()->isDependentContext()) {
573         // It's important to use getInit() here;  getDefaultArg()
574         // strips off any top-level ExprWithCleanups.
575         NewParam->setHasInheritedDefaultArg();
576         if (OldParam->hasUnparsedDefaultArg())
577           NewParam->setUnparsedDefaultArg();
578         else if (OldParam->hasUninstantiatedDefaultArg())
579           NewParam->setUninstantiatedDefaultArg(
580                                        OldParam->getUninstantiatedDefaultArg());
581         else
582           NewParam->setDefaultArg(OldParam->getInit());
583       }
584     } else if (NewParamHasDfl) {
585       if (New->getDescribedFunctionTemplate()) {
586         // Paragraph 4, quoted above, only applies to non-template functions.
587         Diag(NewParam->getLocation(),
588              diag::err_param_default_argument_template_redecl)
589           << NewParam->getDefaultArgRange();
590         Diag(PrevForDefaultArgs->getLocation(),
591              diag::note_template_prev_declaration)
592             << false;
593       } else if (New->getTemplateSpecializationKind()
594                    != TSK_ImplicitInstantiation &&
595                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
596         // C++ [temp.expr.spec]p21:
597         //   Default function arguments shall not be specified in a declaration
598         //   or a definition for one of the following explicit specializations:
599         //     - the explicit specialization of a function template;
600         //     - the explicit specialization of a member function template;
601         //     - the explicit specialization of a member function of a class
602         //       template where the class template specialization to which the
603         //       member function specialization belongs is implicitly
604         //       instantiated.
605         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
606           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
607           << New->getDeclName()
608           << NewParam->getDefaultArgRange();
609       } else if (New->getDeclContext()->isDependentContext()) {
610         // C++ [dcl.fct.default]p6 (DR217):
611         //   Default arguments for a member function of a class template shall
612         //   be specified on the initial declaration of the member function
613         //   within the class template.
614         //
615         // Reading the tea leaves a bit in DR217 and its reference to DR205
616         // leads me to the conclusion that one cannot add default function
617         // arguments for an out-of-line definition of a member function of a
618         // dependent type.
619         int WhichKind = 2;
620         if (CXXRecordDecl *Record
621               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
622           if (Record->getDescribedClassTemplate())
623             WhichKind = 0;
624           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
625             WhichKind = 1;
626           else
627             WhichKind = 2;
628         }
629 
630         Diag(NewParam->getLocation(),
631              diag::err_param_default_argument_member_template_redecl)
632           << WhichKind
633           << NewParam->getDefaultArgRange();
634       }
635     }
636   }
637 
638   // DR1344: If a default argument is added outside a class definition and that
639   // default argument makes the function a special member function, the program
640   // is ill-formed. This can only happen for constructors.
641   if (isa<CXXConstructorDecl>(New) &&
642       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
643     CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
644                          OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
645     if (NewSM != OldSM) {
646       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
647       assert(NewParam->hasDefaultArg());
648       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
649           << NewParam->getDefaultArgRange() << NewSM;
650       Diag(Old->getLocation(), diag::note_previous_declaration);
651     }
652   }
653 
654   const FunctionDecl *Def;
655   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
656   // template has a constexpr specifier then all its declarations shall
657   // contain the constexpr specifier.
658   if (New->getConstexprKind() != Old->getConstexprKind()) {
659     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
660         << New << static_cast<int>(New->getConstexprKind())
661         << static_cast<int>(Old->getConstexprKind());
662     Diag(Old->getLocation(), diag::note_previous_declaration);
663     Invalid = true;
664   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
665              Old->isDefined(Def) &&
666              // If a friend function is inlined but does not have 'inline'
667              // specifier, it is a definition. Do not report attribute conflict
668              // in this case, redefinition will be diagnosed later.
669              (New->isInlineSpecified() ||
670               New->getFriendObjectKind() == Decl::FOK_None)) {
671     // C++11 [dcl.fcn.spec]p4:
672     //   If the definition of a function appears in a translation unit before its
673     //   first declaration as inline, the program is ill-formed.
674     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
675     Diag(Def->getLocation(), diag::note_previous_definition);
676     Invalid = true;
677   }
678 
679   // C++17 [temp.deduct.guide]p3:
680   //   Two deduction guide declarations in the same translation unit
681   //   for the same class template shall not have equivalent
682   //   parameter-declaration-clauses.
683   if (isa<CXXDeductionGuideDecl>(New) &&
684       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
685     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
686     Diag(Old->getLocation(), diag::note_previous_declaration);
687   }
688 
689   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
690   // argument expression, that declaration shall be a definition and shall be
691   // the only declaration of the function or function template in the
692   // translation unit.
693   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
694       functionDeclHasDefaultArgument(Old)) {
695     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
696     Diag(Old->getLocation(), diag::note_previous_declaration);
697     Invalid = true;
698   }
699 
700   // C++11 [temp.friend]p4 (DR329):
701   //   When a function is defined in a friend function declaration in a class
702   //   template, the function is instantiated when the function is odr-used.
703   //   The same restrictions on multiple declarations and definitions that
704   //   apply to non-template function declarations and definitions also apply
705   //   to these implicit definitions.
706   const FunctionDecl *OldDefinition = nullptr;
707   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
708       Old->isDefined(OldDefinition, true))
709     CheckForFunctionRedefinition(New, OldDefinition);
710 
711   return Invalid;
712 }
713 
DiagPlaceholderVariableDefinition(SourceLocation Loc)714 void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
715   Diag(Loc, getLangOpts().CPlusPlus26
716                 ? diag::warn_cxx23_placeholder_var_definition
717                 : diag::ext_placeholder_var_definition);
718 }
719 
720 NamedDecl *
ActOnDecompositionDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)721 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
722                                    MultiTemplateParamsArg TemplateParamLists) {
723   assert(D.isDecompositionDeclarator());
724   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
725 
726   // The syntax only allows a decomposition declarator as a simple-declaration,
727   // a for-range-declaration, or a condition in Clang, but we parse it in more
728   // cases than that.
729   if (!D.mayHaveDecompositionDeclarator()) {
730     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
731       << Decomp.getSourceRange();
732     return nullptr;
733   }
734 
735   if (!TemplateParamLists.empty()) {
736     // C++17 [temp]/1:
737     //   A template defines a family of class, functions, or variables, or an
738     //   alias for a family of types.
739     //
740     // Structured bindings are not included.
741     Diag(TemplateParamLists.front()->getTemplateLoc(),
742          diag::err_decomp_decl_template);
743     return nullptr;
744   }
745 
746   unsigned DiagID;
747   if (!getLangOpts().CPlusPlus17)
748     DiagID = diag::compat_pre_cxx17_decomp_decl;
749   else if (D.getContext() == DeclaratorContext::Condition)
750     DiagID = getLangOpts().CPlusPlus26
751                  ? diag::compat_cxx26_decomp_decl_cond
752                  : diag::compat_pre_cxx26_decomp_decl_cond;
753   else
754     DiagID = diag::compat_cxx17_decomp_decl;
755 
756   Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
757 
758   // The semantic context is always just the current context.
759   DeclContext *const DC = CurContext;
760 
761   // C++17 [dcl.dcl]/8:
762   //   The decl-specifier-seq shall contain only the type-specifier auto
763   //   and cv-qualifiers.
764   // C++20 [dcl.dcl]/8:
765   //   If decl-specifier-seq contains any decl-specifier other than static,
766   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
767   // C++23 [dcl.pre]/6:
768   //   Each decl-specifier in the decl-specifier-seq shall be static,
769   //   thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
770   auto &DS = D.getDeclSpec();
771   {
772     // Note: While constrained-auto needs to be checked, we do so separately so
773     // we can emit a better diagnostic.
774     SmallVector<StringRef, 8> BadSpecifiers;
775     SmallVector<SourceLocation, 8> BadSpecifierLocs;
776     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
777     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
778     if (auto SCS = DS.getStorageClassSpec()) {
779       if (SCS == DeclSpec::SCS_static) {
780         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
781         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
782       } else {
783         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
784         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
785       }
786     }
787     if (auto TSCS = DS.getThreadStorageClassSpec()) {
788       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
789       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
790     }
791     if (DS.hasConstexprSpecifier()) {
792       BadSpecifiers.push_back(
793           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
794       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
795     }
796     if (DS.isInlineSpecified()) {
797       BadSpecifiers.push_back("inline");
798       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
799     }
800 
801     if (!BadSpecifiers.empty()) {
802       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
803       Err << (int)BadSpecifiers.size()
804           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
805       // Don't add FixItHints to remove the specifiers; we do still respect
806       // them when building the underlying variable.
807       for (auto Loc : BadSpecifierLocs)
808         Err << SourceRange(Loc, Loc);
809     } else if (!CPlusPlus20Specifiers.empty()) {
810       auto &&Warn = DiagCompat(CPlusPlus20SpecifierLocs.front(),
811                                diag_compat::decomp_decl_spec);
812       Warn << (int)CPlusPlus20Specifiers.size()
813            << llvm::join(CPlusPlus20Specifiers.begin(),
814                          CPlusPlus20Specifiers.end(), " ");
815       for (auto Loc : CPlusPlus20SpecifierLocs)
816         Warn << SourceRange(Loc, Loc);
817     }
818     // We can't recover from it being declared as a typedef.
819     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
820       return nullptr;
821   }
822 
823   // C++2a [dcl.struct.bind]p1:
824   //   A cv that includes volatile is deprecated
825   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
826       getLangOpts().CPlusPlus20)
827     Diag(DS.getVolatileSpecLoc(),
828          diag::warn_deprecated_volatile_structured_binding);
829 
830   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
831   QualType R = TInfo->getType();
832 
833   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
834                                       UPPC_DeclarationType))
835     D.setInvalidType();
836 
837   // The syntax only allows a single ref-qualifier prior to the decomposition
838   // declarator. No other declarator chunks are permitted. Also check the type
839   // specifier here.
840   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
841       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
842       (D.getNumTypeObjects() == 1 &&
843        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
844     Diag(Decomp.getLSquareLoc(),
845          (D.hasGroupingParens() ||
846           (D.getNumTypeObjects() &&
847            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
848              ? diag::err_decomp_decl_parens
849              : diag::err_decomp_decl_type)
850         << R;
851 
852     // In most cases, there's no actual problem with an explicitly-specified
853     // type, but a function type won't work here, and ActOnVariableDeclarator
854     // shouldn't be called for such a type.
855     if (R->isFunctionType())
856       D.setInvalidType();
857   }
858 
859   // Constrained auto is prohibited by [decl.pre]p6, so check that here.
860   if (DS.isConstrainedAuto()) {
861     TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
862     assert(TemplRep->Kind == TNK_Concept_template &&
863            "No other template kind should be possible for a constrained auto");
864 
865     SourceRange TemplRange{TemplRep->TemplateNameLoc,
866                            TemplRep->RAngleLoc.isValid()
867                                ? TemplRep->RAngleLoc
868                                : TemplRep->TemplateNameLoc};
869     Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
870         << TemplRange << FixItHint::CreateRemoval(TemplRange);
871   }
872 
873   // Build the BindingDecls.
874   SmallVector<BindingDecl*, 8> Bindings;
875 
876   // Build the BindingDecls.
877   for (auto &B : D.getDecompositionDeclarator().bindings()) {
878     // Check for name conflicts.
879     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
880     IdentifierInfo *VarName = B.Name;
881     assert(VarName && "Cannot have an unnamed binding declaration");
882 
883     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
884                           RedeclarationKind::ForVisibleRedeclaration);
885     LookupName(Previous, S,
886                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
887 
888     // It's not permitted to shadow a template parameter name.
889     if (Previous.isSingleResult() &&
890         Previous.getFoundDecl()->isTemplateParameter()) {
891       DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
892       Previous.clear();
893     }
894 
895     QualType QT;
896     if (B.EllipsisLoc.isValid()) {
897       if (!cast<Decl>(DC)->isTemplated())
898         Diag(B.EllipsisLoc, diag::err_pack_outside_template);
899       QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
900                                         /*ExpectsPackInType=*/false);
901     }
902 
903     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
904 
905     ProcessDeclAttributeList(S, BD, *B.Attrs);
906 
907     // Find the shadowed declaration before filtering for scope.
908     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
909                                   ? getShadowedDeclaration(BD, Previous)
910                                   : nullptr;
911 
912     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
913                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
914     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
915                          /*AllowInlineNamespace*/false);
916 
917     bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
918                          DC->isFunctionOrMethod() && VarName->isPlaceholder();
919     if (!Previous.empty()) {
920       if (IsPlaceholder) {
921         bool sameDC = (Previous.end() - 1)
922                           ->getDeclContext()
923                           ->getRedeclContext()
924                           ->Equals(DC->getRedeclContext());
925         if (sameDC &&
926             isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
927           Previous.clear();
928           DiagPlaceholderVariableDefinition(B.NameLoc);
929         }
930       } else {
931         auto *Old = Previous.getRepresentativeDecl();
932         Diag(B.NameLoc, diag::err_redefinition) << B.Name;
933         Diag(Old->getLocation(), diag::note_previous_definition);
934       }
935     } else if (ShadowedDecl && !D.isRedeclaration()) {
936       CheckShadow(BD, ShadowedDecl, Previous);
937     }
938     PushOnScopeChains(BD, S, true);
939     Bindings.push_back(BD);
940     ParsingInitForAutoVars.insert(BD);
941   }
942 
943   // There are no prior lookup results for the variable itself, because it
944   // is unnamed.
945   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
946                                Decomp.getLSquareLoc());
947   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
948                         RedeclarationKind::ForVisibleRedeclaration);
949 
950   // Build the variable that holds the non-decomposed object.
951   bool AddToScope = true;
952   NamedDecl *New =
953       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
954                               MultiTemplateParamsArg(), AddToScope, Bindings);
955   if (AddToScope) {
956     S->AddDecl(New);
957     CurContext->addHiddenDecl(New);
958   }
959 
960   if (OpenMP().isInOpenMPDeclareTargetContext())
961     OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
962 
963   return New;
964 }
965 
966 // Check the arity of the structured bindings.
967 // Create the resolved pack expr if needed.
CheckBindingsCount(Sema & S,DecompositionDecl * DD,QualType DecompType,ArrayRef<BindingDecl * > Bindings,unsigned MemberCount)968 static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
969                                QualType DecompType,
970                                ArrayRef<BindingDecl *> Bindings,
971                                unsigned MemberCount) {
972   auto BindingWithPackItr = llvm::find_if(
973       Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
974   bool HasPack = BindingWithPackItr != Bindings.end();
975   bool IsValid;
976   if (!HasPack) {
977     IsValid = Bindings.size() == MemberCount;
978   } else {
979     // There may not be more members than non-pack bindings.
980     IsValid = MemberCount >= Bindings.size() - 1;
981   }
982 
983   if (IsValid && HasPack) {
984     // Create the pack expr and assign it to the binding.
985     unsigned PackSize = MemberCount - Bindings.size() + 1;
986 
987     BindingDecl *BPack = *BindingWithPackItr;
988     BPack->setDecomposedDecl(DD);
989     SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
990     // Create the nested BindingDecls.
991     for (unsigned I = 0; I < PackSize; ++I) {
992       BindingDecl *NestedBD = BindingDecl::Create(
993           S.Context, BPack->getDeclContext(), BPack->getLocation(),
994           BPack->getIdentifier(), QualType());
995       NestedBD->setDecomposedDecl(DD);
996       NestedBDs[I] = NestedBD;
997     }
998 
999     QualType PackType = S.Context.getPackExpansionType(
1000         S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1001     auto *PackExpr = FunctionParmPackExpr::Create(
1002         S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1003     BPack->setBinding(PackType, PackExpr);
1004   }
1005 
1006   if (IsValid)
1007     return false;
1008 
1009   S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1010       << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1011       << (MemberCount < Bindings.size());
1012   return true;
1013 }
1014 
checkSimpleDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const llvm::APSInt & NumElemsAPS,QualType ElemType,llvm::function_ref<ExprResult (SourceLocation,Expr *,unsigned)> GetInit)1015 static bool checkSimpleDecomposition(
1016     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1017     QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1018     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1019   unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1020   auto *DD = cast<DecompositionDecl>(Src);
1021 
1022   if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1023     return true;
1024 
1025   unsigned I = 0;
1026   for (auto *B : DD->flat_bindings()) {
1027     SourceLocation Loc = B->getLocation();
1028     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1029     if (E.isInvalid())
1030       return true;
1031     E = GetInit(Loc, E.get(), I++);
1032     if (E.isInvalid())
1033       return true;
1034     B->setBinding(ElemType, E.get());
1035   }
1036 
1037   return false;
1038 }
1039 
checkArrayLikeDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const llvm::APSInt & NumElems,QualType ElemType)1040 static bool checkArrayLikeDecomposition(Sema &S,
1041                                         ArrayRef<BindingDecl *> Bindings,
1042                                         ValueDecl *Src, QualType DecompType,
1043                                         const llvm::APSInt &NumElems,
1044                                         QualType ElemType) {
1045   return checkSimpleDecomposition(
1046       S, Bindings, Src, DecompType, NumElems, ElemType,
1047       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1048         ExprResult E = S.ActOnIntegerConstant(Loc, I);
1049         if (E.isInvalid())
1050           return ExprError();
1051         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1052       });
1053 }
1054 
checkArrayDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const ConstantArrayType * CAT)1055 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1056                                     ValueDecl *Src, QualType DecompType,
1057                                     const ConstantArrayType *CAT) {
1058   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1059                                      llvm::APSInt(CAT->getSize()),
1060                                      CAT->getElementType());
1061 }
1062 
checkVectorDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const VectorType * VT)1063 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1064                                      ValueDecl *Src, QualType DecompType,
1065                                      const VectorType *VT) {
1066   return checkArrayLikeDecomposition(
1067       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1068       S.Context.getQualifiedType(VT->getElementType(),
1069                                  DecompType.getQualifiers()));
1070 }
1071 
checkComplexDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const ComplexType * CT)1072 static bool checkComplexDecomposition(Sema &S,
1073                                       ArrayRef<BindingDecl *> Bindings,
1074                                       ValueDecl *Src, QualType DecompType,
1075                                       const ComplexType *CT) {
1076   return checkSimpleDecomposition(
1077       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1078       S.Context.getQualifiedType(CT->getElementType(),
1079                                  DecompType.getQualifiers()),
1080       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1081         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1082       });
1083 }
1084 
printTemplateArgs(const PrintingPolicy & PrintingPolicy,TemplateArgumentListInfo & Args,const TemplateParameterList * Params)1085 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1086                                      TemplateArgumentListInfo &Args,
1087                                      const TemplateParameterList *Params) {
1088   SmallString<128> SS;
1089   llvm::raw_svector_ostream OS(SS);
1090   bool First = true;
1091   unsigned I = 0;
1092   for (auto &Arg : Args.arguments()) {
1093     if (!First)
1094       OS << ", ";
1095     Arg.getArgument().print(PrintingPolicy, OS,
1096                             TemplateParameterList::shouldIncludeTypeForArgument(
1097                                 PrintingPolicy, Params, I));
1098     First = false;
1099     I++;
1100   }
1101   return std::string(OS.str());
1102 }
1103 
lookupStdTypeTraitMember(Sema & S,LookupResult & TraitMemberLookup,SourceLocation Loc,StringRef Trait,TemplateArgumentListInfo & Args,unsigned DiagID)1104 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1105                                      SourceLocation Loc, StringRef Trait,
1106                                      TemplateArgumentListInfo &Args,
1107                                      unsigned DiagID) {
1108   auto DiagnoseMissing = [&] {
1109     if (DiagID)
1110       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1111                                                Args, /*Params*/ nullptr);
1112     return true;
1113   };
1114 
1115   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1116   NamespaceDecl *Std = S.getStdNamespace();
1117   if (!Std)
1118     return DiagnoseMissing();
1119 
1120   // Look up the trait itself, within namespace std. We can diagnose various
1121   // problems with this lookup even if we've been asked to not diagnose a
1122   // missing specialization, because this can only fail if the user has been
1123   // declaring their own names in namespace std or we don't support the
1124   // standard library implementation in use.
1125   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1126                       Loc, Sema::LookupOrdinaryName);
1127   if (!S.LookupQualifiedName(Result, Std))
1128     return DiagnoseMissing();
1129   if (Result.isAmbiguous())
1130     return true;
1131 
1132   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1133   if (!TraitTD) {
1134     Result.suppressDiagnostics();
1135     NamedDecl *Found = *Result.begin();
1136     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1137     S.Diag(Found->getLocation(), diag::note_declared_at);
1138     return true;
1139   }
1140 
1141   // Build the template-id.
1142   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1143   if (TraitTy.isNull())
1144     return true;
1145   if (!S.isCompleteType(Loc, TraitTy)) {
1146     if (DiagID)
1147       S.RequireCompleteType(
1148           Loc, TraitTy, DiagID,
1149           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1150                             TraitTD->getTemplateParameters()));
1151     return true;
1152   }
1153 
1154   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1155   assert(RD && "specialization of class template is not a class?");
1156 
1157   // Look up the member of the trait type.
1158   S.LookupQualifiedName(TraitMemberLookup, RD);
1159   return TraitMemberLookup.isAmbiguous();
1160 }
1161 
1162 static TemplateArgumentLoc
getTrivialIntegralTemplateArgument(Sema & S,SourceLocation Loc,QualType T,uint64_t I)1163 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1164                                    uint64_t I) {
1165   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1166   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1167 }
1168 
1169 static TemplateArgumentLoc
getTrivialTypeTemplateArgument(Sema & S,SourceLocation Loc,QualType T)1170 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1171   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1172 }
1173 
1174 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1175 
isTupleLike(Sema & S,SourceLocation Loc,QualType T,llvm::APSInt & Size)1176 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1177                                llvm::APSInt &Size) {
1178   EnterExpressionEvaluationContext ContextRAII(
1179       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1180 
1181   DeclarationName Value = S.PP.getIdentifierInfo("value");
1182   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1183 
1184   // Form template argument list for tuple_size<T>.
1185   TemplateArgumentListInfo Args(Loc, Loc);
1186   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1187 
1188   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1189   // it's not tuple-like.
1190   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1191       R.empty())
1192     return IsTupleLike::NotTupleLike;
1193 
1194   // If we get this far, we've committed to the tuple interpretation, but
1195   // we can still fail if there actually isn't a usable ::value.
1196 
1197   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1198     LookupResult &R;
1199     TemplateArgumentListInfo &Args;
1200     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1201         : R(R), Args(Args) {}
1202     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1203                                                SourceLocation Loc) override {
1204       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1205              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1206                                   /*Params*/ nullptr);
1207     }
1208   } Diagnoser(R, Args);
1209 
1210   ExprResult E =
1211       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1212   if (E.isInvalid())
1213     return IsTupleLike::Error;
1214 
1215   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1216   if (E.isInvalid())
1217     return IsTupleLike::Error;
1218 
1219   return IsTupleLike::TupleLike;
1220 }
1221 
1222 /// \return std::tuple_element<I, T>::type.
getTupleLikeElementType(Sema & S,SourceLocation Loc,unsigned I,QualType T)1223 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1224                                         unsigned I, QualType T) {
1225   // Form template argument list for tuple_element<I, T>.
1226   TemplateArgumentListInfo Args(Loc, Loc);
1227   Args.addArgument(
1228       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1229   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1230 
1231   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1232   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1233   if (lookupStdTypeTraitMember(
1234           S, R, Loc, "tuple_element", Args,
1235           diag::err_decomp_decl_std_tuple_element_not_specialized))
1236     return QualType();
1237 
1238   auto *TD = R.getAsSingle<TypeDecl>();
1239   if (!TD) {
1240     R.suppressDiagnostics();
1241     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1242         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1243                              /*Params*/ nullptr);
1244     if (!R.empty())
1245       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1246     return QualType();
1247   }
1248 
1249   return S.Context.getTypeDeclType(TD);
1250 }
1251 
1252 namespace {
1253 struct InitializingBinding {
1254   Sema &S;
InitializingBinding__anon42c808800811::InitializingBinding1255   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1256     Sema::CodeSynthesisContext Ctx;
1257     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1258     Ctx.PointOfInstantiation = BD->getLocation();
1259     Ctx.Entity = BD;
1260     S.pushCodeSynthesisContext(Ctx);
1261   }
~InitializingBinding__anon42c808800811::InitializingBinding1262   ~InitializingBinding() {
1263     S.popCodeSynthesisContext();
1264   }
1265 };
1266 }
1267 
checkTupleLikeDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,VarDecl * Src,QualType DecompType,const llvm::APSInt & TupleSize)1268 static bool checkTupleLikeDecomposition(Sema &S,
1269                                         ArrayRef<BindingDecl *> Bindings,
1270                                         VarDecl *Src, QualType DecompType,
1271                                         const llvm::APSInt &TupleSize) {
1272   auto *DD = cast<DecompositionDecl>(Src);
1273   unsigned NumElems = (unsigned)TupleSize.getLimitedValue(UINT_MAX);
1274   if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1275     return true;
1276 
1277   if (Bindings.empty())
1278     return false;
1279 
1280   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1281 
1282   // [dcl.decomp]p3:
1283   //   The unqualified-id get is looked up in the scope of E by class member
1284   //   access lookup ...
1285   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1286   bool UseMemberGet = false;
1287   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1288     if (auto *RD = DecompType->getAsCXXRecordDecl())
1289       S.LookupQualifiedName(MemberGet, RD);
1290     if (MemberGet.isAmbiguous())
1291       return true;
1292     //   ... and if that finds at least one declaration that is a function
1293     //   template whose first template parameter is a non-type parameter ...
1294     for (NamedDecl *D : MemberGet) {
1295       if (FunctionTemplateDecl *FTD =
1296               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1297         TemplateParameterList *TPL = FTD->getTemplateParameters();
1298         if (TPL->size() != 0 &&
1299             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1300           //   ... the initializer is e.get<i>().
1301           UseMemberGet = true;
1302           break;
1303         }
1304       }
1305     }
1306   }
1307 
1308   unsigned I = 0;
1309   for (auto *B : DD->flat_bindings()) {
1310     InitializingBinding InitContext(S, B);
1311     SourceLocation Loc = B->getLocation();
1312 
1313     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1314     if (E.isInvalid())
1315       return true;
1316 
1317     //   e is an lvalue if the type of the entity is an lvalue reference and
1318     //   an xvalue otherwise
1319     if (!Src->getType()->isLValueReferenceType())
1320       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1321                                    E.get(), nullptr, VK_XValue,
1322                                    FPOptionsOverride());
1323 
1324     TemplateArgumentListInfo Args(Loc, Loc);
1325     Args.addArgument(
1326         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1327 
1328     if (UseMemberGet) {
1329       //   if [lookup of member get] finds at least one declaration, the
1330       //   initializer is e.get<i-1>().
1331       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1332                                      CXXScopeSpec(), SourceLocation(), nullptr,
1333                                      MemberGet, &Args, nullptr);
1334       if (E.isInvalid())
1335         return true;
1336 
1337       E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1338     } else {
1339       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1340       //   in the associated namespaces.
1341       Expr *Get = UnresolvedLookupExpr::Create(
1342           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1343           DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1344           UnresolvedSetIterator(), UnresolvedSetIterator(),
1345           /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1346 
1347       Expr *Arg = E.get();
1348       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1349     }
1350     if (E.isInvalid())
1351       return true;
1352     Expr *Init = E.get();
1353 
1354     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1355     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1356     if (T.isNull())
1357       return true;
1358 
1359     //   each vi is a variable of type "reference to T" initialized with the
1360     //   initializer, where the reference is an lvalue reference if the
1361     //   initializer is an lvalue and an rvalue reference otherwise
1362     QualType RefType =
1363         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1364     if (RefType.isNull())
1365       return true;
1366     auto *RefVD = VarDecl::Create(
1367         S.Context, Src->getDeclContext(), Loc, Loc,
1368         B->getDeclName().getAsIdentifierInfo(), RefType,
1369         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1370     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1371     RefVD->setTSCSpec(Src->getTSCSpec());
1372     RefVD->setImplicit();
1373     if (Src->isInlineSpecified())
1374       RefVD->setInlineSpecified();
1375     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1376 
1377     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1378     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1379     InitializationSequence Seq(S, Entity, Kind, Init);
1380     E = Seq.Perform(S, Entity, Kind, Init);
1381     if (E.isInvalid())
1382       return true;
1383     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1384     if (E.isInvalid())
1385       return true;
1386     RefVD->setInit(E.get());
1387     S.CheckCompleteVariableDeclaration(RefVD);
1388 
1389     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1390                                    DeclarationNameInfo(B->getDeclName(), Loc),
1391                                    RefVD);
1392     if (E.isInvalid())
1393       return true;
1394 
1395     B->setBinding(T, E.get());
1396     I++;
1397   }
1398 
1399   return false;
1400 }
1401 
1402 /// Find the base class to decompose in a built-in decomposition of a class type.
1403 /// This base class search is, unfortunately, not quite like any other that we
1404 /// perform anywhere else in C++.
findDecomposableBaseClass(Sema & S,SourceLocation Loc,const CXXRecordDecl * RD,CXXCastPath & BasePath)1405 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1406                                                 const CXXRecordDecl *RD,
1407                                                 CXXCastPath &BasePath) {
1408   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1409                           CXXBasePath &Path) {
1410     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1411   };
1412 
1413   const CXXRecordDecl *ClassWithFields = nullptr;
1414   AccessSpecifier AS = AS_public;
1415   if (RD->hasDirectFields())
1416     // [dcl.decomp]p4:
1417     //   Otherwise, all of E's non-static data members shall be public direct
1418     //   members of E ...
1419     ClassWithFields = RD;
1420   else {
1421     //   ... or of ...
1422     CXXBasePaths Paths;
1423     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1424     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1425       // If no classes have fields, just decompose RD itself. (This will work
1426       // if and only if zero bindings were provided.)
1427       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1428     }
1429 
1430     CXXBasePath *BestPath = nullptr;
1431     for (auto &P : Paths) {
1432       if (!BestPath)
1433         BestPath = &P;
1434       else if (!S.Context.hasSameType(P.back().Base->getType(),
1435                                       BestPath->back().Base->getType())) {
1436         //   ... the same ...
1437         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1438           << false << RD << BestPath->back().Base->getType()
1439           << P.back().Base->getType();
1440         return DeclAccessPair();
1441       } else if (P.Access < BestPath->Access) {
1442         BestPath = &P;
1443       }
1444     }
1445 
1446     //   ... unambiguous ...
1447     QualType BaseType = BestPath->back().Base->getType();
1448     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1449       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1450         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1451       return DeclAccessPair();
1452     }
1453 
1454     //   ... [accessible, implied by other rules] base class of E.
1455     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1456                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1457     AS = BestPath->Access;
1458 
1459     ClassWithFields = BaseType->getAsCXXRecordDecl();
1460     S.BuildBasePathArray(Paths, BasePath);
1461   }
1462 
1463   // The above search did not check whether the selected class itself has base
1464   // classes with fields, so check that now.
1465   CXXBasePaths Paths;
1466   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1467     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1468       << (ClassWithFields == RD) << RD << ClassWithFields
1469       << Paths.front().back().Base->getType();
1470     return DeclAccessPair();
1471   }
1472 
1473   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1474 }
1475 
CheckMemberDecompositionFields(Sema & S,SourceLocation Loc,const CXXRecordDecl * OrigRD,QualType DecompType,DeclAccessPair BasePair)1476 static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1477                                            const CXXRecordDecl *OrigRD,
1478                                            QualType DecompType,
1479                                            DeclAccessPair BasePair) {
1480   const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1481   if (!RD)
1482     return true;
1483 
1484   for (auto *FD : RD->fields()) {
1485     if (FD->isUnnamedBitField())
1486       continue;
1487 
1488     // All the non-static data members are required to be nameable, so they
1489     // must all have names.
1490     if (!FD->getDeclName()) {
1491       if (RD->isLambda()) {
1492         S.Diag(Loc, diag::err_decomp_decl_lambda);
1493         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1494         return true;
1495       }
1496 
1497       if (FD->isAnonymousStructOrUnion()) {
1498         S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1499             << DecompType << FD->getType()->isUnionType();
1500         S.Diag(FD->getLocation(), diag::note_declared_at);
1501         return true;
1502       }
1503 
1504       // FIXME: Are there any other ways we could have an anonymous member?
1505     }
1506     // The field must be accessible in the context of the structured binding.
1507     // We already checked that the base class is accessible.
1508     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1509     // const_cast here.
1510     S.CheckStructuredBindingMemberAccess(
1511         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1512         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1513                                      BasePair.getAccess(), FD->getAccess())));
1514   }
1515   return false;
1516 }
1517 
checkMemberDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const CXXRecordDecl * OrigRD)1518 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1519                                      ValueDecl *Src, QualType DecompType,
1520                                      const CXXRecordDecl *OrigRD) {
1521   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1522                             diag::err_incomplete_type))
1523     return true;
1524 
1525   CXXCastPath BasePath;
1526   DeclAccessPair BasePair =
1527       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1528   const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1529   if (!RD)
1530     return true;
1531   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1532                                                  DecompType.getQualifiers());
1533 
1534   auto *DD = cast<DecompositionDecl>(Src);
1535   unsigned NumFields = llvm::count_if(
1536       RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1537   if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1538     return true;
1539 
1540   //   all of E's non-static data members shall be [...] well-formed
1541   //   when named as e.name in the context of the structured binding,
1542   //   E shall not have an anonymous union member, ...
1543   auto FlatBindings = DD->flat_bindings();
1544   assert(llvm::range_size(FlatBindings) == NumFields);
1545   auto FlatBindingsItr = FlatBindings.begin();
1546 
1547   if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1548                                      BasePair))
1549     return true;
1550 
1551   for (auto *FD : RD->fields()) {
1552     if (FD->isUnnamedBitField())
1553       continue;
1554 
1555     // We have a real field to bind.
1556     assert(FlatBindingsItr != FlatBindings.end());
1557     BindingDecl *B = *(FlatBindingsItr++);
1558     SourceLocation Loc = B->getLocation();
1559 
1560     // Initialize the binding to Src.FD.
1561     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1562     if (E.isInvalid())
1563       return true;
1564     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1565                             VK_LValue, &BasePath);
1566     if (E.isInvalid())
1567       return true;
1568     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1569                                   CXXScopeSpec(), FD,
1570                                   DeclAccessPair::make(FD, FD->getAccess()),
1571                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1572     if (E.isInvalid())
1573       return true;
1574 
1575     // If the type of the member is T, the referenced type is cv T, where cv is
1576     // the cv-qualification of the decomposition expression.
1577     //
1578     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1579     // 'const' to the type of the field.
1580     Qualifiers Q = DecompType.getQualifiers();
1581     if (FD->isMutable())
1582       Q.removeConst();
1583     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1584   }
1585 
1586   return false;
1587 }
1588 
CheckCompleteDecompositionDeclaration(DecompositionDecl * DD)1589 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1590   QualType DecompType = DD->getType();
1591 
1592   // If the type of the decomposition is dependent, then so is the type of
1593   // each binding.
1594   if (DecompType->isDependentType()) {
1595     // Note that all of the types are still Null or PackExpansionType.
1596     for (auto *B : DD->bindings()) {
1597       // Do not overwrite any pack type.
1598       if (B->getType().isNull())
1599         B->setType(Context.DependentTy);
1600     }
1601     return;
1602   }
1603 
1604   DecompType = DecompType.getNonReferenceType();
1605   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1606 
1607   // C++1z [dcl.decomp]/2:
1608   //   If E is an array type [...]
1609   // As an extension, we also support decomposition of built-in complex and
1610   // vector types.
1611   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1612     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1613       DD->setInvalidDecl();
1614     return;
1615   }
1616   if (auto *VT = DecompType->getAs<VectorType>()) {
1617     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1618       DD->setInvalidDecl();
1619     return;
1620   }
1621   if (auto *CT = DecompType->getAs<ComplexType>()) {
1622     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1623       DD->setInvalidDecl();
1624     return;
1625   }
1626 
1627   // C++1z [dcl.decomp]/3:
1628   //   if the expression std::tuple_size<E>::value is a well-formed integral
1629   //   constant expression, [...]
1630   llvm::APSInt TupleSize(32);
1631   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1632   case IsTupleLike::Error:
1633     DD->setInvalidDecl();
1634     return;
1635 
1636   case IsTupleLike::TupleLike:
1637     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1638       DD->setInvalidDecl();
1639     return;
1640 
1641   case IsTupleLike::NotTupleLike:
1642     break;
1643   }
1644 
1645   // C++1z [dcl.dcl]/8:
1646   //   [E shall be of array or non-union class type]
1647   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1648   if (!RD || RD->isUnion()) {
1649     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1650         << DD << !RD << DecompType;
1651     DD->setInvalidDecl();
1652     return;
1653   }
1654 
1655   // C++1z [dcl.decomp]/4:
1656   //   all of E's non-static data members shall be [...] direct members of
1657   //   E or of the same unambiguous public base class of E, ...
1658   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1659     DD->setInvalidDecl();
1660 }
1661 
GetDecompositionElementCount(QualType T,SourceLocation Loc)1662 UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1663                                                   SourceLocation Loc) {
1664   const ASTContext &Ctx = getASTContext();
1665   assert(!T->isDependentType());
1666 
1667   Qualifiers Quals;
1668   QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1669   Quals.removeCVRQualifiers();
1670   T = Context.getQualifiedType(Unqual, Quals);
1671 
1672   if (auto *CAT = Ctx.getAsConstantArrayType(T))
1673     return static_cast<unsigned>(CAT->getSize().getZExtValue());
1674   if (auto *VT = T->getAs<VectorType>())
1675     return VT->getNumElements();
1676   if (T->getAs<ComplexType>())
1677     return 2u;
1678 
1679   llvm::APSInt TupleSize(Ctx.getTypeSize(Ctx.getSizeType()));
1680   switch (isTupleLike(*this, Loc, T, TupleSize)) {
1681   case IsTupleLike::Error:
1682     return std::nullopt;
1683   case IsTupleLike::TupleLike:
1684     return static_cast<unsigned>(TupleSize.getExtValue());
1685   case IsTupleLike::NotTupleLike:
1686     break;
1687   }
1688 
1689   const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1690   if (!OrigRD || OrigRD->isUnion())
1691     return std::nullopt;
1692 
1693   if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1694     return std::nullopt;
1695 
1696   CXXCastPath BasePath;
1697   DeclAccessPair BasePair =
1698       findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1699   const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1700   if (!RD)
1701     return std::nullopt;
1702 
1703   unsigned NumFields = llvm::count_if(
1704       RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1705 
1706   if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1707     return std::nullopt;
1708 
1709   return NumFields;
1710 }
1711 
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)1712 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1713   // Shortcut if exceptions are disabled.
1714   if (!getLangOpts().CXXExceptions)
1715     return;
1716 
1717   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1718          "Should only be called if types are otherwise the same.");
1719 
1720   QualType NewType = New->getType();
1721   QualType OldType = Old->getType();
1722 
1723   // We're only interested in pointers and references to functions, as well
1724   // as pointers to member functions.
1725   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1726     NewType = R->getPointeeType();
1727     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1728   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1729     NewType = P->getPointeeType();
1730     OldType = OldType->castAs<PointerType>()->getPointeeType();
1731   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1732     NewType = M->getPointeeType();
1733     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1734   }
1735 
1736   if (!NewType->isFunctionProtoType())
1737     return;
1738 
1739   // There's lots of special cases for functions. For function pointers, system
1740   // libraries are hopefully not as broken so that we don't need these
1741   // workarounds.
1742   if (CheckEquivalentExceptionSpec(
1743         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1744         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1745     New->setInvalidDecl();
1746   }
1747 }
1748 
1749 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1750 /// function declaration are well-formed according to C++
1751 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)1752 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1753   // This checking doesn't make sense for explicit specializations; their
1754   // default arguments are determined by the declaration we're specializing,
1755   // not by FD.
1756   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1757     return;
1758   if (auto *FTD = FD->getDescribedFunctionTemplate())
1759     if (FTD->isMemberSpecialization())
1760       return;
1761 
1762   unsigned NumParams = FD->getNumParams();
1763   unsigned ParamIdx = 0;
1764 
1765   // Find first parameter with a default argument
1766   for (; ParamIdx < NumParams; ++ParamIdx) {
1767     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1768     if (Param->hasDefaultArg())
1769       break;
1770   }
1771 
1772   // C++20 [dcl.fct.default]p4:
1773   //   In a given function declaration, each parameter subsequent to a parameter
1774   //   with a default argument shall have a default argument supplied in this or
1775   //   a previous declaration, unless the parameter was expanded from a
1776   //   parameter pack, or shall be a function parameter pack.
1777   for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1778     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1779     if (Param->hasDefaultArg() || Param->isParameterPack() ||
1780         (CurrentInstantiationScope &&
1781          CurrentInstantiationScope->isLocalPackExpansion(Param)))
1782       continue;
1783     if (Param->isInvalidDecl())
1784       /* We already complained about this parameter. */;
1785     else if (Param->getIdentifier())
1786       Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1787           << Param->getIdentifier();
1788     else
1789       Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1790   }
1791 }
1792 
1793 /// Check that the given type is a literal type. Issue a diagnostic if not,
1794 /// if Kind is Diagnose.
1795 /// \return \c true if a problem has been found (and optionally diagnosed).
1796 template <typename... Ts>
CheckLiteralType(Sema & SemaRef,Sema::CheckConstexprKind Kind,SourceLocation Loc,QualType T,unsigned DiagID,Ts &&...DiagArgs)1797 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1798                              SourceLocation Loc, QualType T, unsigned DiagID,
1799                              Ts &&...DiagArgs) {
1800   if (T->isDependentType())
1801     return false;
1802 
1803   switch (Kind) {
1804   case Sema::CheckConstexprKind::Diagnose:
1805     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1806                                       std::forward<Ts>(DiagArgs)...);
1807 
1808   case Sema::CheckConstexprKind::CheckValid:
1809     return !T->isLiteralType(SemaRef.Context);
1810   }
1811 
1812   llvm_unreachable("unknown CheckConstexprKind");
1813 }
1814 
1815 /// Determine whether a destructor cannot be constexpr due to
CheckConstexprDestructorSubobjects(Sema & SemaRef,const CXXDestructorDecl * DD,Sema::CheckConstexprKind Kind)1816 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1817                                                const CXXDestructorDecl *DD,
1818                                                Sema::CheckConstexprKind Kind) {
1819   assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1820          "this check is obsolete for C++23");
1821   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1822     const CXXRecordDecl *RD =
1823         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1824     if (!RD || RD->hasConstexprDestructor())
1825       return true;
1826 
1827     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1828       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1829           << static_cast<int>(DD->getConstexprKind()) << !FD
1830           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1831       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1832           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1833     }
1834     return false;
1835   };
1836 
1837   const CXXRecordDecl *RD = DD->getParent();
1838   for (const CXXBaseSpecifier &B : RD->bases())
1839     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1840       return false;
1841   for (const FieldDecl *FD : RD->fields())
1842     if (!Check(FD->getLocation(), FD->getType(), FD))
1843       return false;
1844   return true;
1845 }
1846 
1847 /// Check whether a function's parameter types are all literal types. If so,
1848 /// return true. If not, produce a suitable diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD,Sema::CheckConstexprKind Kind)1849 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1850                                          const FunctionDecl *FD,
1851                                          Sema::CheckConstexprKind Kind) {
1852   assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1853          "this check is obsolete for C++23");
1854   unsigned ArgIndex = 0;
1855   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1856   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1857                                               e = FT->param_type_end();
1858        i != e; ++i, ++ArgIndex) {
1859     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1860     assert(PD && "null in a parameter list");
1861     SourceLocation ParamLoc = PD->getLocation();
1862     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1863                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1864                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1865                          FD->isConsteval()))
1866       return false;
1867   }
1868   return true;
1869 }
1870 
1871 /// Check whether a function's return type is a literal type. If so, return
1872 /// true. If not, produce a suitable diagnostic and return false.
CheckConstexprReturnType(Sema & SemaRef,const FunctionDecl * FD,Sema::CheckConstexprKind Kind)1873 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1874                                      Sema::CheckConstexprKind Kind) {
1875   assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1876          "this check is obsolete for C++23");
1877   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1878                        diag::err_constexpr_non_literal_return,
1879                        FD->isConsteval()))
1880     return false;
1881   return true;
1882 }
1883 
1884 /// Get diagnostic %select index for tag kind for
1885 /// record diagnostic message.
1886 /// WARNING: Indexes apply to particular diagnostics only!
1887 ///
1888 /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)1889 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1890   switch (Tag) {
1891   case TagTypeKind::Struct:
1892     return 0;
1893   case TagTypeKind::Interface:
1894     return 1;
1895   case TagTypeKind::Class:
1896     return 2;
1897   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1898   }
1899 }
1900 
1901 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1902                                        Stmt *Body,
1903                                        Sema::CheckConstexprKind Kind);
1904 static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1905 
CheckConstexprFunctionDefinition(const FunctionDecl * NewFD,CheckConstexprKind Kind)1906 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1907                                             CheckConstexprKind Kind) {
1908   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1909   if (MD && MD->isInstance()) {
1910     // C++11 [dcl.constexpr]p4:
1911     //  The definition of a constexpr constructor shall satisfy the following
1912     //  constraints:
1913     //  - the class shall not have any virtual base classes;
1914     //
1915     // FIXME: This only applies to constructors and destructors, not arbitrary
1916     // member functions.
1917     const CXXRecordDecl *RD = MD->getParent();
1918     if (RD->getNumVBases()) {
1919       if (Kind == CheckConstexprKind::CheckValid)
1920         return false;
1921 
1922       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1923         << isa<CXXConstructorDecl>(NewFD)
1924         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1925       for (const auto &I : RD->vbases())
1926         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1927             << I.getSourceRange();
1928       return false;
1929     }
1930   }
1931 
1932   if (!isa<CXXConstructorDecl>(NewFD)) {
1933     // C++11 [dcl.constexpr]p3:
1934     //  The definition of a constexpr function shall satisfy the following
1935     //  constraints:
1936     // - it shall not be virtual; (removed in C++20)
1937     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1938     if (Method && Method->isVirtual()) {
1939       if (getLangOpts().CPlusPlus20) {
1940         if (Kind == CheckConstexprKind::Diagnose)
1941           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1942       } else {
1943         if (Kind == CheckConstexprKind::CheckValid)
1944           return false;
1945 
1946         Method = Method->getCanonicalDecl();
1947         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1948 
1949         // If it's not obvious why this function is virtual, find an overridden
1950         // function which uses the 'virtual' keyword.
1951         const CXXMethodDecl *WrittenVirtual = Method;
1952         while (!WrittenVirtual->isVirtualAsWritten())
1953           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1954         if (WrittenVirtual != Method)
1955           Diag(WrittenVirtual->getLocation(),
1956                diag::note_overridden_virtual_function);
1957         return false;
1958       }
1959     }
1960 
1961     // - its return type shall be a literal type; (removed in C++23)
1962     if (!getLangOpts().CPlusPlus23 &&
1963         !CheckConstexprReturnType(*this, NewFD, Kind))
1964       return false;
1965   }
1966 
1967   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1968     // A destructor can be constexpr only if the defaulted destructor could be;
1969     // we don't need to check the members and bases if we already know they all
1970     // have constexpr destructors. (removed in C++23)
1971     if (!getLangOpts().CPlusPlus23 &&
1972         !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1973       if (Kind == CheckConstexprKind::CheckValid)
1974         return false;
1975       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1976         return false;
1977     }
1978   }
1979 
1980   // - each of its parameter types shall be a literal type; (removed in C++23)
1981   if (!getLangOpts().CPlusPlus23 &&
1982       !CheckConstexprParameterTypes(*this, NewFD, Kind))
1983     return false;
1984 
1985   Stmt *Body = NewFD->getBody();
1986   assert(Body &&
1987          "CheckConstexprFunctionDefinition called on function with no body");
1988   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1989 }
1990 
1991 /// Check the given declaration statement is legal within a constexpr function
1992 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1993 ///
1994 /// \return true if the body is OK (maybe only as an extension), false if we
1995 ///         have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS,SourceLocation & Cxx1yLoc,Sema::CheckConstexprKind Kind)1996 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1997                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1998                                    Sema::CheckConstexprKind Kind) {
1999   // C++11 [dcl.constexpr]p3 and p4:
2000   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
2001   //  contain only
2002   for (const auto *DclIt : DS->decls()) {
2003     switch (DclIt->getKind()) {
2004     case Decl::StaticAssert:
2005     case Decl::Using:
2006     case Decl::UsingShadow:
2007     case Decl::UsingDirective:
2008     case Decl::UnresolvedUsingTypename:
2009     case Decl::UnresolvedUsingValue:
2010     case Decl::UsingEnum:
2011       //   - static_assert-declarations
2012       //   - using-declarations,
2013       //   - using-directives,
2014       //   - using-enum-declaration
2015       continue;
2016 
2017     case Decl::Typedef:
2018     case Decl::TypeAlias: {
2019       //   - typedef declarations and alias-declarations that do not define
2020       //     classes or enumerations,
2021       const auto *TN = cast<TypedefNameDecl>(DclIt);
2022       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2023         // Don't allow variably-modified types in constexpr functions.
2024         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2025           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2026           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2027             << TL.getSourceRange() << TL.getType()
2028             << isa<CXXConstructorDecl>(Dcl);
2029         }
2030         return false;
2031       }
2032       continue;
2033     }
2034 
2035     case Decl::Enum:
2036     case Decl::CXXRecord:
2037       // C++1y allows types to be defined, not just declared.
2038       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2039         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2040           SemaRef.DiagCompat(DS->getBeginLoc(),
2041                              diag_compat::constexpr_type_definition)
2042               << isa<CXXConstructorDecl>(Dcl);
2043         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2044           return false;
2045         }
2046       }
2047       continue;
2048 
2049     case Decl::EnumConstant:
2050     case Decl::IndirectField:
2051     case Decl::ParmVar:
2052       // These can only appear with other declarations which are banned in
2053       // C++11 and permitted in C++1y, so ignore them.
2054       continue;
2055 
2056     case Decl::Var:
2057     case Decl::Decomposition: {
2058       // C++1y [dcl.constexpr]p3 allows anything except:
2059       //   a definition of a variable of non-literal type or of static or
2060       //   thread storage duration or [before C++2a] for which no
2061       //   initialization is performed.
2062       const auto *VD = cast<VarDecl>(DclIt);
2063       if (VD->isThisDeclarationADefinition()) {
2064         if (VD->isStaticLocal()) {
2065           if (Kind == Sema::CheckConstexprKind::Diagnose) {
2066             SemaRef.DiagCompat(VD->getLocation(),
2067                                diag_compat::constexpr_static_var)
2068                 << isa<CXXConstructorDecl>(Dcl)
2069                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2070           } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2071             return false;
2072           }
2073         }
2074         if (SemaRef.LangOpts.CPlusPlus23) {
2075           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2076                            diag::warn_cxx20_compat_constexpr_var,
2077                            isa<CXXConstructorDecl>(Dcl));
2078         } else if (CheckLiteralType(
2079                        SemaRef, Kind, VD->getLocation(), VD->getType(),
2080                        diag::err_constexpr_local_var_non_literal_type,
2081                        isa<CXXConstructorDecl>(Dcl))) {
2082           return false;
2083         }
2084         if (!VD->getType()->isDependentType() &&
2085             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2086           if (Kind == Sema::CheckConstexprKind::Diagnose) {
2087             SemaRef.DiagCompat(VD->getLocation(),
2088                                diag_compat::constexpr_local_var_no_init)
2089                 << isa<CXXConstructorDecl>(Dcl);
2090           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2091             return false;
2092           }
2093           continue;
2094         }
2095       }
2096       if (Kind == Sema::CheckConstexprKind::Diagnose) {
2097         SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2098             << isa<CXXConstructorDecl>(Dcl);
2099       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2100         return false;
2101       }
2102       continue;
2103     }
2104 
2105     case Decl::NamespaceAlias:
2106     case Decl::Function:
2107       // These are disallowed in C++11 and permitted in C++1y. Allow them
2108       // everywhere as an extension.
2109       if (!Cxx1yLoc.isValid())
2110         Cxx1yLoc = DS->getBeginLoc();
2111       continue;
2112 
2113     default:
2114       if (Kind == Sema::CheckConstexprKind::Diagnose) {
2115         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2116             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2117       }
2118       return false;
2119     }
2120   }
2121 
2122   return true;
2123 }
2124 
2125 /// Check that the given field is initialized within a constexpr constructor.
2126 ///
2127 /// \param Dcl The constexpr constructor being checked.
2128 /// \param Field The field being checked. This may be a member of an anonymous
2129 ///        struct or union nested within the class being checked.
2130 /// \param Inits All declarations, including anonymous struct/union members and
2131 ///        indirect members, for which any initialization was provided.
2132 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2133 ///        multiple notes for different members to the same error.
2134 /// \param Kind Whether we're diagnosing a constructor as written or determining
2135 ///        whether the formal requirements are satisfied.
2136 /// \return \c false if we're checking for validity and the constructor does
2137 ///         not satisfy the requirements on a constexpr constructor.
CheckConstexprCtorInitializer(Sema & SemaRef,const FunctionDecl * Dcl,FieldDecl * Field,llvm::SmallSet<Decl *,16> & Inits,bool & Diagnosed,Sema::CheckConstexprKind Kind)2138 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2139                                           const FunctionDecl *Dcl,
2140                                           FieldDecl *Field,
2141                                           llvm::SmallSet<Decl*, 16> &Inits,
2142                                           bool &Diagnosed,
2143                                           Sema::CheckConstexprKind Kind) {
2144   // In C++20 onwards, there's nothing to check for validity.
2145   if (Kind == Sema::CheckConstexprKind::CheckValid &&
2146       SemaRef.getLangOpts().CPlusPlus20)
2147     return true;
2148 
2149   if (Field->isInvalidDecl())
2150     return true;
2151 
2152   if (Field->isUnnamedBitField())
2153     return true;
2154 
2155   // Anonymous unions with no variant members and empty anonymous structs do not
2156   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2157   // indirect fields don't need initializing.
2158   if (Field->isAnonymousStructOrUnion() &&
2159       (Field->getType()->isUnionType()
2160            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2161            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2162     return true;
2163 
2164   if (!Inits.count(Field)) {
2165     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2166       if (!Diagnosed) {
2167         SemaRef.DiagCompat(Dcl->getLocation(),
2168                            diag_compat::constexpr_ctor_missing_init);
2169         Diagnosed = true;
2170       }
2171       SemaRef.Diag(Field->getLocation(),
2172                    diag::note_constexpr_ctor_missing_init);
2173     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2174       return false;
2175     }
2176   } else if (Field->isAnonymousStructOrUnion()) {
2177     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2178     for (auto *I : RD->fields())
2179       // If an anonymous union contains an anonymous struct of which any member
2180       // is initialized, all members must be initialized.
2181       if (!RD->isUnion() || Inits.count(I))
2182         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2183                                            Kind))
2184           return false;
2185   }
2186   return true;
2187 }
2188 
2189 /// Check the provided statement is allowed in a constexpr function
2190 /// definition.
2191 static bool
CheckConstexprFunctionStmt(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * S,SmallVectorImpl<SourceLocation> & ReturnStmts,SourceLocation & Cxx1yLoc,SourceLocation & Cxx2aLoc,SourceLocation & Cxx2bLoc,Sema::CheckConstexprKind Kind)2192 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2193                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2194                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2195                            SourceLocation &Cxx2bLoc,
2196                            Sema::CheckConstexprKind Kind) {
2197   // - its function-body shall be [...] a compound-statement that contains only
2198   switch (S->getStmtClass()) {
2199   case Stmt::NullStmtClass:
2200     //   - null statements,
2201     return true;
2202 
2203   case Stmt::DeclStmtClass:
2204     //   - static_assert-declarations
2205     //   - using-declarations,
2206     //   - using-directives,
2207     //   - typedef declarations and alias-declarations that do not define
2208     //     classes or enumerations,
2209     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2210       return false;
2211     return true;
2212 
2213   case Stmt::ReturnStmtClass:
2214     //   - and exactly one return statement;
2215     if (isa<CXXConstructorDecl>(Dcl)) {
2216       // C++1y allows return statements in constexpr constructors.
2217       if (!Cxx1yLoc.isValid())
2218         Cxx1yLoc = S->getBeginLoc();
2219       return true;
2220     }
2221 
2222     ReturnStmts.push_back(S->getBeginLoc());
2223     return true;
2224 
2225   case Stmt::AttributedStmtClass:
2226     // Attributes on a statement don't affect its formal kind and hence don't
2227     // affect its validity in a constexpr function.
2228     return CheckConstexprFunctionStmt(
2229         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2230         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2231 
2232   case Stmt::CompoundStmtClass: {
2233     // C++1y allows compound-statements.
2234     if (!Cxx1yLoc.isValid())
2235       Cxx1yLoc = S->getBeginLoc();
2236 
2237     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2238     for (auto *BodyIt : CompStmt->body()) {
2239       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2240                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2241         return false;
2242     }
2243     return true;
2244   }
2245 
2246   case Stmt::IfStmtClass: {
2247     // C++1y allows if-statements.
2248     if (!Cxx1yLoc.isValid())
2249       Cxx1yLoc = S->getBeginLoc();
2250 
2251     IfStmt *If = cast<IfStmt>(S);
2252     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2253                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2254       return false;
2255     if (If->getElse() &&
2256         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2257                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2258       return false;
2259     return true;
2260   }
2261 
2262   case Stmt::WhileStmtClass:
2263   case Stmt::DoStmtClass:
2264   case Stmt::ForStmtClass:
2265   case Stmt::CXXForRangeStmtClass:
2266   case Stmt::ContinueStmtClass:
2267     // C++1y allows all of these. We don't allow them as extensions in C++11,
2268     // because they don't make sense without variable mutation.
2269     if (!SemaRef.getLangOpts().CPlusPlus14)
2270       break;
2271     if (!Cxx1yLoc.isValid())
2272       Cxx1yLoc = S->getBeginLoc();
2273     for (Stmt *SubStmt : S->children()) {
2274       if (SubStmt &&
2275           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2276                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2277         return false;
2278     }
2279     return true;
2280 
2281   case Stmt::SwitchStmtClass:
2282   case Stmt::CaseStmtClass:
2283   case Stmt::DefaultStmtClass:
2284   case Stmt::BreakStmtClass:
2285     // C++1y allows switch-statements, and since they don't need variable
2286     // mutation, we can reasonably allow them in C++11 as an extension.
2287     if (!Cxx1yLoc.isValid())
2288       Cxx1yLoc = S->getBeginLoc();
2289     for (Stmt *SubStmt : S->children()) {
2290       if (SubStmt &&
2291           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2292                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2293         return false;
2294     }
2295     return true;
2296 
2297   case Stmt::LabelStmtClass:
2298   case Stmt::GotoStmtClass:
2299     if (Cxx2bLoc.isInvalid())
2300       Cxx2bLoc = S->getBeginLoc();
2301     for (Stmt *SubStmt : S->children()) {
2302       if (SubStmt &&
2303           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2304                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2305         return false;
2306     }
2307     return true;
2308 
2309   case Stmt::GCCAsmStmtClass:
2310   case Stmt::MSAsmStmtClass:
2311     // C++2a allows inline assembly statements.
2312   case Stmt::CXXTryStmtClass:
2313     if (Cxx2aLoc.isInvalid())
2314       Cxx2aLoc = S->getBeginLoc();
2315     for (Stmt *SubStmt : S->children()) {
2316       if (SubStmt &&
2317           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2318                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2319         return false;
2320     }
2321     return true;
2322 
2323   case Stmt::CXXCatchStmtClass:
2324     // Do not bother checking the language mode (already covered by the
2325     // try block check).
2326     if (!CheckConstexprFunctionStmt(
2327             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2328             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2329       return false;
2330     return true;
2331 
2332   default:
2333     if (!isa<Expr>(S))
2334       break;
2335 
2336     // C++1y allows expression-statements.
2337     if (!Cxx1yLoc.isValid())
2338       Cxx1yLoc = S->getBeginLoc();
2339     return true;
2340   }
2341 
2342   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2343     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2344         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2345   }
2346   return false;
2347 }
2348 
2349 /// Check the body for the given constexpr function declaration only contains
2350 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2351 ///
2352 /// \return true if the body is OK, false if we have found or diagnosed a
2353 /// problem.
CheckConstexprFunctionBody(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * Body,Sema::CheckConstexprKind Kind)2354 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2355                                        Stmt *Body,
2356                                        Sema::CheckConstexprKind Kind) {
2357   SmallVector<SourceLocation, 4> ReturnStmts;
2358 
2359   if (isa<CXXTryStmt>(Body)) {
2360     // C++11 [dcl.constexpr]p3:
2361     //  The definition of a constexpr function shall satisfy the following
2362     //  constraints: [...]
2363     // - its function-body shall be = delete, = default, or a
2364     //   compound-statement
2365     //
2366     // C++11 [dcl.constexpr]p4:
2367     //  In the definition of a constexpr constructor, [...]
2368     // - its function-body shall not be a function-try-block;
2369     //
2370     // This restriction is lifted in C++2a, as long as inner statements also
2371     // apply the general constexpr rules.
2372     switch (Kind) {
2373     case Sema::CheckConstexprKind::CheckValid:
2374       if (!SemaRef.getLangOpts().CPlusPlus20)
2375         return false;
2376       break;
2377 
2378     case Sema::CheckConstexprKind::Diagnose:
2379       SemaRef.DiagCompat(Body->getBeginLoc(),
2380                          diag_compat::constexpr_function_try_block)
2381           << isa<CXXConstructorDecl>(Dcl);
2382       break;
2383     }
2384   }
2385 
2386   // - its function-body shall be [...] a compound-statement that contains only
2387   //   [... list of cases ...]
2388   //
2389   // Note that walking the children here is enough to properly check for
2390   // CompoundStmt and CXXTryStmt body.
2391   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2392   for (Stmt *SubStmt : Body->children()) {
2393     if (SubStmt &&
2394         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2395                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2396       return false;
2397   }
2398 
2399   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2400     // If this is only valid as an extension, report that we don't satisfy the
2401     // constraints of the current language.
2402     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2403         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2404         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2405       return false;
2406   } else if (Cxx2bLoc.isValid()) {
2407     SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2408         << isa<CXXConstructorDecl>(Dcl);
2409   } else if (Cxx2aLoc.isValid()) {
2410     SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2411         << isa<CXXConstructorDecl>(Dcl);
2412   } else if (Cxx1yLoc.isValid()) {
2413     SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2414         << isa<CXXConstructorDecl>(Dcl);
2415   }
2416 
2417   if (const CXXConstructorDecl *Constructor
2418         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2419     const CXXRecordDecl *RD = Constructor->getParent();
2420     // DR1359:
2421     // - every non-variant non-static data member and base class sub-object
2422     //   shall be initialized;
2423     // DR1460:
2424     // - if the class is a union having variant members, exactly one of them
2425     //   shall be initialized;
2426     if (RD->isUnion()) {
2427       if (Constructor->getNumCtorInitializers() == 0 &&
2428           RD->hasVariantMembers()) {
2429         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2430           SemaRef.DiagCompat(Dcl->getLocation(),
2431                              diag_compat::constexpr_union_ctor_no_init);
2432         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2433           return false;
2434         }
2435       }
2436     } else if (!Constructor->isDependentContext() &&
2437                !Constructor->isDelegatingConstructor()) {
2438       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2439 
2440       // Skip detailed checking if we have enough initializers, and we would
2441       // allow at most one initializer per member.
2442       bool AnyAnonStructUnionMembers = false;
2443       unsigned Fields = 0;
2444       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2445            E = RD->field_end(); I != E; ++I, ++Fields) {
2446         if (I->isAnonymousStructOrUnion()) {
2447           AnyAnonStructUnionMembers = true;
2448           break;
2449         }
2450       }
2451       // DR1460:
2452       // - if the class is a union-like class, but is not a union, for each of
2453       //   its anonymous union members having variant members, exactly one of
2454       //   them shall be initialized;
2455       if (AnyAnonStructUnionMembers ||
2456           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2457         // Check initialization of non-static data members. Base classes are
2458         // always initialized so do not need to be checked. Dependent bases
2459         // might not have initializers in the member initializer list.
2460         llvm::SmallSet<Decl*, 16> Inits;
2461         for (const auto *I: Constructor->inits()) {
2462           if (FieldDecl *FD = I->getMember())
2463             Inits.insert(FD);
2464           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2465             Inits.insert(ID->chain_begin(), ID->chain_end());
2466         }
2467 
2468         bool Diagnosed = false;
2469         for (auto *I : RD->fields())
2470           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2471                                              Kind))
2472             return false;
2473       }
2474     }
2475   } else {
2476     if (ReturnStmts.empty()) {
2477       switch (Kind) {
2478       case Sema::CheckConstexprKind::Diagnose:
2479         if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2480           return false;
2481         break;
2482 
2483       case Sema::CheckConstexprKind::CheckValid:
2484         // The formal requirements don't include this rule in C++14, even
2485         // though the "must be able to produce a constant expression" rules
2486         // still imply it in some cases.
2487         if (!SemaRef.getLangOpts().CPlusPlus14)
2488           return false;
2489         break;
2490       }
2491     } else if (ReturnStmts.size() > 1) {
2492       switch (Kind) {
2493       case Sema::CheckConstexprKind::Diagnose:
2494         SemaRef.DiagCompat(ReturnStmts.back(),
2495                            diag_compat::constexpr_body_multiple_return);
2496         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2497           SemaRef.Diag(ReturnStmts[I],
2498                        diag::note_constexpr_body_previous_return);
2499         break;
2500 
2501       case Sema::CheckConstexprKind::CheckValid:
2502         if (!SemaRef.getLangOpts().CPlusPlus14)
2503           return false;
2504         break;
2505       }
2506     }
2507   }
2508 
2509   // C++11 [dcl.constexpr]p5:
2510   //   if no function argument values exist such that the function invocation
2511   //   substitution would produce a constant expression, the program is
2512   //   ill-formed; no diagnostic required.
2513   // C++11 [dcl.constexpr]p3:
2514   //   - every constructor call and implicit conversion used in initializing the
2515   //     return value shall be one of those allowed in a constant expression.
2516   // C++11 [dcl.constexpr]p4:
2517   //   - every constructor involved in initializing non-static data members and
2518   //     base class sub-objects shall be a constexpr constructor.
2519   //
2520   // Note that this rule is distinct from the "requirements for a constexpr
2521   // function", so is not checked in CheckValid mode. Because the check for
2522   // constexpr potential is expensive, skip the check if the diagnostic is
2523   // disabled, the function is declared in a system header, or we're in C++23
2524   // or later mode (see https://wg21.link/P2448).
2525   bool SkipCheck =
2526       !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2527       SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2528       SemaRef.getDiagnostics().isIgnored(
2529           diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2530   SmallVector<PartialDiagnosticAt, 8> Diags;
2531   if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2532       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2533     SemaRef.Diag(Dcl->getLocation(),
2534                  diag::ext_constexpr_function_never_constant_expr)
2535         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2536         << Dcl->getNameInfo().getSourceRange();
2537     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2538       SemaRef.Diag(Diags[I].first, Diags[I].second);
2539     // Don't return false here: we allow this for compatibility in
2540     // system headers.
2541   }
2542 
2543   return true;
2544 }
2545 
CheckConstexprMissingReturn(Sema & SemaRef,const FunctionDecl * Dcl)2546 static bool CheckConstexprMissingReturn(Sema &SemaRef,
2547                                         const FunctionDecl *Dcl) {
2548   bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2549                                Dcl->getReturnType()->isDependentType();
2550   // Skip emitting a missing return error diagnostic for non-void functions
2551   // since C++23 no longer mandates constexpr functions to yield constant
2552   // expressions.
2553   if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2554     return true;
2555 
2556   // C++14 doesn't require constexpr functions to contain a 'return'
2557   // statement. We still do, unless the return type might be void, because
2558   // otherwise if there's no return statement, the function cannot
2559   // be used in a core constant expression.
2560   bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2561   SemaRef.Diag(Dcl->getLocation(),
2562                OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2563                   : diag::err_constexpr_body_no_return)
2564       << Dcl->isConsteval();
2565   return OK;
2566 }
2567 
CheckImmediateEscalatingFunctionDefinition(FunctionDecl * FD,const sema::FunctionScopeInfo * FSI)2568 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2569     FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2570   if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2571     return true;
2572   FD->setBodyContainsImmediateEscalatingExpressions(
2573       FSI->FoundImmediateEscalatingExpression);
2574   if (FSI->FoundImmediateEscalatingExpression) {
2575     auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2576     if (it != UndefinedButUsed.end()) {
2577       Diag(it->second, diag::err_immediate_function_used_before_definition)
2578           << it->first;
2579       Diag(FD->getLocation(), diag::note_defined_here) << FD;
2580       if (FD->isImmediateFunction() && !FD->isConsteval())
2581         DiagnoseImmediateEscalatingReason(FD);
2582       return false;
2583     }
2584   }
2585   return true;
2586 }
2587 
DiagnoseImmediateEscalatingReason(FunctionDecl * FD)2588 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2589   assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2590          "expected an immediate function");
2591   assert(FD->hasBody() && "expected the function to have a body");
2592   struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2593     Sema &SemaRef;
2594 
2595     const FunctionDecl *ImmediateFn;
2596     bool ImmediateFnIsConstructor;
2597     CXXConstructorDecl *CurrentConstructor = nullptr;
2598     CXXCtorInitializer *CurrentInit = nullptr;
2599 
2600     ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2601         : SemaRef(SemaRef), ImmediateFn(FD),
2602           ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2603       ShouldVisitImplicitCode = true;
2604       ShouldVisitLambdaBody = false;
2605     }
2606 
2607     void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2608       SourceLocation Loc = E->getBeginLoc();
2609       SourceRange Range = E->getSourceRange();
2610       if (CurrentConstructor && CurrentInit) {
2611         Loc = CurrentConstructor->getLocation();
2612         Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2613                                          : SourceRange();
2614       }
2615 
2616       FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2617 
2618       SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2619           << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2620           << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2621           << (InitializedField != nullptr)
2622           << (CurrentInit && !CurrentInit->isWritten())
2623           << InitializedField << Range;
2624     }
2625     bool TraverseCallExpr(CallExpr *E) override {
2626       if (const auto *DR =
2627               dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2628           DR && DR->isImmediateEscalating()) {
2629         Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2630         return false;
2631       }
2632 
2633       for (Expr *A : E->arguments())
2634         if (!TraverseStmt(A))
2635           return false;
2636 
2637       return true;
2638     }
2639 
2640     bool VisitDeclRefExpr(DeclRefExpr *E) override {
2641       if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2642           ReferencedFn && E->isImmediateEscalating()) {
2643         Diag(E, ReferencedFn, /*IsCall=*/false);
2644         return false;
2645       }
2646 
2647       return true;
2648     }
2649 
2650     bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2651       CXXConstructorDecl *D = E->getConstructor();
2652       if (E->isImmediateEscalating()) {
2653         Diag(E, D, /*IsCall=*/true);
2654         return false;
2655       }
2656       return true;
2657     }
2658 
2659     bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2660       llvm::SaveAndRestore RAII(CurrentInit, Init);
2661       return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2662     }
2663 
2664     bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2665       llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2666       return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2667     }
2668 
2669     bool TraverseType(QualType T) override { return true; }
2670     bool VisitBlockExpr(BlockExpr *T) override { return true; }
2671 
2672   } Visitor(*this, FD);
2673   Visitor.TraverseDecl(FD);
2674 }
2675 
getCurrentClass(Scope *,const CXXScopeSpec * SS)2676 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2677   assert(getLangOpts().CPlusPlus && "No class names in C!");
2678 
2679   if (SS && SS->isInvalid())
2680     return nullptr;
2681 
2682   if (SS && SS->isNotEmpty()) {
2683     DeclContext *DC = computeDeclContext(*SS, true);
2684     return dyn_cast_or_null<CXXRecordDecl>(DC);
2685   }
2686 
2687   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2688 }
2689 
isCurrentClassName(const IdentifierInfo & II,Scope * S,const CXXScopeSpec * SS)2690 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2691                               const CXXScopeSpec *SS) {
2692   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2693   return CurDecl && &II == CurDecl->getIdentifier();
2694 }
2695 
isCurrentClassNameTypo(IdentifierInfo * & II,const CXXScopeSpec * SS)2696 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2697   assert(getLangOpts().CPlusPlus && "No class names in C!");
2698 
2699   if (!getLangOpts().SpellChecking)
2700     return false;
2701 
2702   CXXRecordDecl *CurDecl;
2703   if (SS && SS->isSet() && !SS->isInvalid()) {
2704     DeclContext *DC = computeDeclContext(*SS, true);
2705     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2706   } else
2707     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2708 
2709   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2710       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2711           < II->getLength()) {
2712     II = CurDecl->getIdentifier();
2713     return true;
2714   }
2715 
2716   return false;
2717 }
2718 
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)2719 CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2720                                            SourceRange SpecifierRange,
2721                                            bool Virtual, AccessSpecifier Access,
2722                                            TypeSourceInfo *TInfo,
2723                                            SourceLocation EllipsisLoc) {
2724   QualType BaseType = TInfo->getType();
2725   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2726   if (BaseType->containsErrors()) {
2727     // Already emitted a diagnostic when parsing the error type.
2728     return nullptr;
2729   }
2730 
2731   if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2732     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2733       << TInfo->getTypeLoc().getSourceRange();
2734     EllipsisLoc = SourceLocation();
2735   }
2736 
2737   auto *BaseDecl =
2738       dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2739   // C++ [class.derived.general]p2:
2740   //   A class-or-decltype shall denote a (possibly cv-qualified) class type
2741   //   that is not an incompletely defined class; any cv-qualifiers are
2742   //   ignored.
2743   if (BaseDecl) {
2744     // C++ [class.union.general]p4:
2745     // [...]  A union shall not be used as a base class.
2746     if (BaseDecl->isUnion()) {
2747       Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2748       return nullptr;
2749     }
2750 
2751     if (BaseType.hasQualifiers()) {
2752       std::string Quals =
2753           BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2754       Diag(BaseLoc, diag::warn_qual_base_type)
2755           << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2756       Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2757     }
2758 
2759     // For the MS ABI, propagate DLL attributes to base class templates.
2760     if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2761         Context.getTargetInfo().getTriple().isPS()) {
2762       if (Attr *ClassAttr = getDLLAttr(Class)) {
2763         if (auto *BaseSpec =
2764                 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2765           propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2766                                               BaseLoc);
2767         }
2768       }
2769     }
2770 
2771     if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2772                             SpecifierRange)) {
2773       Class->setInvalidDecl();
2774       return nullptr;
2775     }
2776 
2777     BaseDecl = BaseDecl->getDefinition();
2778     assert(BaseDecl && "Base type is not incomplete, but has no definition");
2779 
2780     // Microsoft docs say:
2781     // "If a base-class has a code_seg attribute, derived classes must have the
2782     // same attribute."
2783     const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2784     const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2785     if ((DerivedCSA || BaseCSA) &&
2786         (!BaseCSA || !DerivedCSA ||
2787          BaseCSA->getName() != DerivedCSA->getName())) {
2788       Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2789       Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2790           << BaseDecl;
2791       return nullptr;
2792     }
2793 
2794     // A class which contains a flexible array member is not suitable for use as
2795     // a base class:
2796     //   - If the layout determines that a base comes before another base,
2797     //     the flexible array member would index into the subsequent base.
2798     //   - If the layout determines that base comes before the derived class,
2799     //     the flexible array member would index into the derived class.
2800     if (BaseDecl->hasFlexibleArrayMember()) {
2801       Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2802           << BaseDecl->getDeclName();
2803       return nullptr;
2804     }
2805 
2806     // C++ [class]p3:
2807     //   If a class is marked final and it appears as a base-type-specifier in
2808     //   base-clause, the program is ill-formed.
2809     if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2810       Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2811           << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2812       Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2813           << BaseDecl->getDeclName() << FA->getRange();
2814       return nullptr;
2815     }
2816 
2817     // If the base class is invalid the derived class is as well.
2818     if (BaseDecl->isInvalidDecl())
2819       Class->setInvalidDecl();
2820   } else if (BaseType->isDependentType()) {
2821     // Make sure that we don't make an ill-formed AST where the type of the
2822     // Class is non-dependent and its attached base class specifier is an
2823     // dependent type, which violates invariants in many clang code paths (e.g.
2824     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2825     // explicitly mark the Class decl invalid. The diagnostic was already
2826     // emitted.
2827     if (!Class->isDependentContext())
2828       Class->setInvalidDecl();
2829   } else {
2830     // The base class is some non-dependent non-class type.
2831     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2832     return nullptr;
2833   }
2834 
2835   // In HLSL, unspecified class access is public rather than private.
2836   if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2837       Access == AS_none)
2838     Access = AS_public;
2839 
2840   // Create the base specifier.
2841   return new (Context) CXXBaseSpecifier(
2842       SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2843       Access, TInfo, EllipsisLoc);
2844 }
2845 
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,const ParsedAttributesView & Attributes,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)2846 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2847                                     const ParsedAttributesView &Attributes,
2848                                     bool Virtual, AccessSpecifier Access,
2849                                     ParsedType basetype, SourceLocation BaseLoc,
2850                                     SourceLocation EllipsisLoc) {
2851   if (!classdecl)
2852     return true;
2853 
2854   AdjustDeclIfTemplate(classdecl);
2855   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2856   if (!Class)
2857     return true;
2858 
2859   // We haven't yet attached the base specifiers.
2860   Class->setIsParsingBaseSpecifiers();
2861 
2862   // We do not support any C++11 attributes on base-specifiers yet.
2863   // Diagnose any attributes we see.
2864   for (const ParsedAttr &AL : Attributes) {
2865     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2866       continue;
2867     if (AL.getKind() == ParsedAttr::UnknownAttribute)
2868       DiagnoseUnknownAttribute(AL);
2869     else
2870       Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2871           << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2872   }
2873 
2874   TypeSourceInfo *TInfo = nullptr;
2875   GetTypeFromParser(basetype, &TInfo);
2876 
2877   if (EllipsisLoc.isInvalid() &&
2878       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2879                                       UPPC_BaseType))
2880     return true;
2881 
2882   // C++ [class.union.general]p4:
2883   //   [...] A union shall not have base classes.
2884   if (Class->isUnion()) {
2885     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2886         << SpecifierRange;
2887     return true;
2888   }
2889 
2890   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2891                                                       Virtual, Access, TInfo,
2892                                                       EllipsisLoc))
2893     return BaseSpec;
2894 
2895   Class->setInvalidDecl();
2896   return true;
2897 }
2898 
2899 /// Use small set to collect indirect bases.  As this is only used
2900 /// locally, there's no need to abstract the small size parameter.
2901 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2902 
2903 /// Recursively add the bases of Type.  Don't add Type itself.
2904 static void
NoteIndirectBases(ASTContext & Context,IndirectBaseSet & Set,const QualType & Type)2905 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2906                   const QualType &Type)
2907 {
2908   // Even though the incoming type is a base, it might not be
2909   // a class -- it could be a template parm, for instance.
2910   if (auto Rec = Type->getAs<RecordType>()) {
2911     auto Decl = Rec->getAsCXXRecordDecl();
2912 
2913     // Iterate over its bases.
2914     for (const auto &BaseSpec : Decl->bases()) {
2915       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2916         .getUnqualifiedType();
2917       if (Set.insert(Base).second)
2918         // If we've not already seen it, recurse.
2919         NoteIndirectBases(Context, Set, Base);
2920     }
2921   }
2922 }
2923 
AttachBaseSpecifiers(CXXRecordDecl * Class,MutableArrayRef<CXXBaseSpecifier * > Bases)2924 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2925                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2926  if (Bases.empty())
2927     return false;
2928 
2929   // Used to keep track of which base types we have already seen, so
2930   // that we can properly diagnose redundant direct base types. Note
2931   // that the key is always the unqualified canonical type of the base
2932   // class.
2933   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2934 
2935   // Used to track indirect bases so we can see if a direct base is
2936   // ambiguous.
2937   IndirectBaseSet IndirectBaseTypes;
2938 
2939   // Copy non-redundant base specifiers into permanent storage.
2940   unsigned NumGoodBases = 0;
2941   bool Invalid = false;
2942   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2943     QualType NewBaseType
2944       = Context.getCanonicalType(Bases[idx]->getType());
2945     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2946 
2947     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2948     if (KnownBase) {
2949       // C++ [class.mi]p3:
2950       //   A class shall not be specified as a direct base class of a
2951       //   derived class more than once.
2952       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2953           << KnownBase->getType() << Bases[idx]->getSourceRange();
2954 
2955       // Delete the duplicate base class specifier; we're going to
2956       // overwrite its pointer later.
2957       Context.Deallocate(Bases[idx]);
2958 
2959       Invalid = true;
2960     } else {
2961       // Okay, add this new base class.
2962       KnownBase = Bases[idx];
2963       Bases[NumGoodBases++] = Bases[idx];
2964 
2965       if (NewBaseType->isDependentType())
2966         continue;
2967       // Note this base's direct & indirect bases, if there could be ambiguity.
2968       if (Bases.size() > 1)
2969         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2970 
2971       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2972         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2973         if (Class->isInterface() &&
2974               (!RD->isInterfaceLike() ||
2975                KnownBase->getAccessSpecifier() != AS_public)) {
2976           // The Microsoft extension __interface does not permit bases that
2977           // are not themselves public interfaces.
2978           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2979               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2980               << RD->getSourceRange();
2981           Invalid = true;
2982         }
2983         if (RD->hasAttr<WeakAttr>())
2984           Class->addAttr(WeakAttr::CreateImplicit(Context));
2985       }
2986     }
2987   }
2988 
2989   // Attach the remaining base class specifiers to the derived class.
2990   Class->setBases(Bases.data(), NumGoodBases);
2991 
2992   // Check that the only base classes that are duplicate are virtual.
2993   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2994     // Check whether this direct base is inaccessible due to ambiguity.
2995     QualType BaseType = Bases[idx]->getType();
2996 
2997     // Skip all dependent types in templates being used as base specifiers.
2998     // Checks below assume that the base specifier is a CXXRecord.
2999     if (BaseType->isDependentType())
3000       continue;
3001 
3002     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3003       .getUnqualifiedType();
3004 
3005     if (IndirectBaseTypes.count(CanonicalBase)) {
3006       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3007                          /*DetectVirtual=*/true);
3008       bool found
3009         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3010       assert(found);
3011       (void)found;
3012 
3013       if (Paths.isAmbiguous(CanonicalBase))
3014         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3015             << BaseType << getAmbiguousPathsDisplayString(Paths)
3016             << Bases[idx]->getSourceRange();
3017       else
3018         assert(Bases[idx]->isVirtual());
3019     }
3020 
3021     // Delete the base class specifier, since its data has been copied
3022     // into the CXXRecordDecl.
3023     Context.Deallocate(Bases[idx]);
3024   }
3025 
3026   return Invalid;
3027 }
3028 
ActOnBaseSpecifiers(Decl * ClassDecl,MutableArrayRef<CXXBaseSpecifier * > Bases)3029 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3030                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
3031   if (!ClassDecl || Bases.empty())
3032     return;
3033 
3034   AdjustDeclIfTemplate(ClassDecl);
3035   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3036 }
3037 
IsDerivedFrom(SourceLocation Loc,CXXRecordDecl * Derived,CXXRecordDecl * Base,CXXBasePaths & Paths)3038 bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3039                          CXXRecordDecl *Base, CXXBasePaths &Paths) {
3040   if (!getLangOpts().CPlusPlus)
3041     return false;
3042 
3043   if (!Base || !Derived)
3044     return false;
3045 
3046   // If either the base or the derived type is invalid, don't try to
3047   // check whether one is derived from the other.
3048   if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3049     return false;
3050 
3051   // FIXME: In a modules build, do we need the entire path to be visible for us
3052   // to be able to use the inheritance relationship?
3053   if (!isCompleteType(Loc, Context.getTypeDeclType(Derived)) &&
3054       !Derived->isBeingDefined())
3055     return false;
3056 
3057   return Derived->isDerivedFrom(Base, Paths);
3058 }
3059 
IsDerivedFrom(SourceLocation Loc,CXXRecordDecl * Derived,CXXRecordDecl * Base)3060 bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3061                          CXXRecordDecl *Base) {
3062   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3063                      /*DetectVirtual=*/false);
3064   return IsDerivedFrom(Loc, Derived, Base, Paths);
3065 }
3066 
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base)3067 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3068   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3069                      /*DetectVirtual=*/false);
3070   return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3071                        Base->getAsCXXRecordDecl(), Paths);
3072 }
3073 
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base,CXXBasePaths & Paths)3074 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3075                          CXXBasePaths &Paths) {
3076   return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3077                        Base->getAsCXXRecordDecl(), Paths);
3078 }
3079 
BuildBasePathArray(const CXXBasePath & Path,CXXCastPath & BasePathArray)3080 static void BuildBasePathArray(const CXXBasePath &Path,
3081                                CXXCastPath &BasePathArray) {
3082   // We first go backward and check if we have a virtual base.
3083   // FIXME: It would be better if CXXBasePath had the base specifier for
3084   // the nearest virtual base.
3085   unsigned Start = 0;
3086   for (unsigned I = Path.size(); I != 0; --I) {
3087     if (Path[I - 1].Base->isVirtual()) {
3088       Start = I - 1;
3089       break;
3090     }
3091   }
3092 
3093   // Now add all bases.
3094   for (unsigned I = Start, E = Path.size(); I != E; ++I)
3095     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3096 }
3097 
3098 
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)3099 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3100                               CXXCastPath &BasePathArray) {
3101   assert(BasePathArray.empty() && "Base path array must be empty!");
3102   assert(Paths.isRecordingPaths() && "Must record paths!");
3103   return ::BuildBasePathArray(Paths.front(), BasePathArray);
3104 }
3105 
3106 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbiguousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath,bool IgnoreAccess)3107 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3108                                    unsigned InaccessibleBaseID,
3109                                    unsigned AmbiguousBaseConvID,
3110                                    SourceLocation Loc, SourceRange Range,
3111                                    DeclarationName Name,
3112                                    CXXCastPath *BasePath,
3113                                    bool IgnoreAccess) {
3114   // First, determine whether the path from Derived to Base is
3115   // ambiguous. This is slightly more expensive than checking whether
3116   // the Derived to Base conversion exists, because here we need to
3117   // explore multiple paths to determine if there is an ambiguity.
3118   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3119                      /*DetectVirtual=*/false);
3120   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3121   if (!DerivationOkay)
3122     return true;
3123 
3124   const CXXBasePath *Path = nullptr;
3125   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3126     Path = &Paths.front();
3127 
3128   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3129   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3130   // user to access such bases.
3131   if (!Path && getLangOpts().MSVCCompat) {
3132     for (const CXXBasePath &PossiblePath : Paths) {
3133       if (PossiblePath.size() == 1) {
3134         Path = &PossiblePath;
3135         if (AmbiguousBaseConvID)
3136           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3137               << Base << Derived << Range;
3138         break;
3139       }
3140     }
3141   }
3142 
3143   if (Path) {
3144     if (!IgnoreAccess) {
3145       // Check that the base class can be accessed.
3146       switch (
3147           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3148       case AR_inaccessible:
3149         return true;
3150       case AR_accessible:
3151       case AR_dependent:
3152       case AR_delayed:
3153         break;
3154       }
3155     }
3156 
3157     // Build a base path if necessary.
3158     if (BasePath)
3159       ::BuildBasePathArray(*Path, *BasePath);
3160     return false;
3161   }
3162 
3163   if (AmbiguousBaseConvID) {
3164     // We know that the derived-to-base conversion is ambiguous, and
3165     // we're going to produce a diagnostic. Perform the derived-to-base
3166     // search just one more time to compute all of the possible paths so
3167     // that we can print them out. This is more expensive than any of
3168     // the previous derived-to-base checks we've done, but at this point
3169     // performance isn't as much of an issue.
3170     Paths.clear();
3171     Paths.setRecordingPaths(true);
3172     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3173     assert(StillOkay && "Can only be used with a derived-to-base conversion");
3174     (void)StillOkay;
3175 
3176     // Build up a textual representation of the ambiguous paths, e.g.,
3177     // D -> B -> A, that will be used to illustrate the ambiguous
3178     // conversions in the diagnostic. We only print one of the paths
3179     // to each base class subobject.
3180     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3181 
3182     Diag(Loc, AmbiguousBaseConvID)
3183     << Derived << Base << PathDisplayStr << Range << Name;
3184   }
3185   return true;
3186 }
3187 
3188 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)3189 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3190                                    SourceLocation Loc, SourceRange Range,
3191                                    CXXCastPath *BasePath,
3192                                    bool IgnoreAccess) {
3193   return CheckDerivedToBaseConversion(
3194       Derived, Base, diag::err_upcast_to_inaccessible_base,
3195       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3196       BasePath, IgnoreAccess);
3197 }
3198 
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)3199 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3200   std::string PathDisplayStr;
3201   std::set<unsigned> DisplayedPaths;
3202   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3203        Path != Paths.end(); ++Path) {
3204     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3205       // We haven't displayed a path to this particular base
3206       // class subobject yet.
3207       PathDisplayStr += "\n    ";
3208       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3209       for (CXXBasePath::const_iterator Element = Path->begin();
3210            Element != Path->end(); ++Element)
3211         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3212     }
3213   }
3214 
3215   return PathDisplayStr;
3216 }
3217 
3218 //===----------------------------------------------------------------------===//
3219 // C++ class member Handling
3220 //===----------------------------------------------------------------------===//
3221 
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,const ParsedAttributesView & Attrs)3222 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3223                                 SourceLocation ColonLoc,
3224                                 const ParsedAttributesView &Attrs) {
3225   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3226   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3227                                                   ASLoc, ColonLoc);
3228   CurContext->addHiddenDecl(ASDecl);
3229   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3230 }
3231 
CheckOverrideControl(NamedDecl * D)3232 void Sema::CheckOverrideControl(NamedDecl *D) {
3233   if (D->isInvalidDecl())
3234     return;
3235 
3236   // We only care about "override" and "final" declarations.
3237   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3238     return;
3239 
3240   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3241 
3242   // We can't check dependent instance methods.
3243   if (MD && MD->isInstance() &&
3244       (MD->getParent()->hasAnyDependentBases() ||
3245        MD->getType()->isDependentType()))
3246     return;
3247 
3248   if (MD && !MD->isVirtual()) {
3249     // If we have a non-virtual method, check if it hides a virtual method.
3250     // (In that case, it's most likely the method has the wrong type.)
3251     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3252     FindHiddenVirtualMethods(MD, OverloadedMethods);
3253 
3254     if (!OverloadedMethods.empty()) {
3255       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3256         Diag(OA->getLocation(),
3257              diag::override_keyword_hides_virtual_member_function)
3258           << "override" << (OverloadedMethods.size() > 1);
3259       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3260         Diag(FA->getLocation(),
3261              diag::override_keyword_hides_virtual_member_function)
3262           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3263           << (OverloadedMethods.size() > 1);
3264       }
3265       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3266       MD->setInvalidDecl();
3267       return;
3268     }
3269     // Fall through into the general case diagnostic.
3270     // FIXME: We might want to attempt typo correction here.
3271   }
3272 
3273   if (!MD || !MD->isVirtual()) {
3274     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3275       Diag(OA->getLocation(),
3276            diag::override_keyword_only_allowed_on_virtual_member_functions)
3277         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3278       D->dropAttr<OverrideAttr>();
3279     }
3280     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3281       Diag(FA->getLocation(),
3282            diag::override_keyword_only_allowed_on_virtual_member_functions)
3283         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3284         << FixItHint::CreateRemoval(FA->getLocation());
3285       D->dropAttr<FinalAttr>();
3286     }
3287     return;
3288   }
3289 
3290   // C++11 [class.virtual]p5:
3291   //   If a function is marked with the virt-specifier override and
3292   //   does not override a member function of a base class, the program is
3293   //   ill-formed.
3294   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3295   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3296     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3297       << MD->getDeclName();
3298 }
3299 
DiagnoseAbsenceOfOverrideControl(NamedDecl * D,bool Inconsistent)3300 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3301   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3302     return;
3303   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3304   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3305     return;
3306 
3307   SourceLocation Loc = MD->getLocation();
3308   SourceLocation SpellingLoc = Loc;
3309   if (getSourceManager().isMacroArgExpansion(Loc))
3310     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3311   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3312   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3313       return;
3314 
3315   if (MD->size_overridden_methods() > 0) {
3316     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3317       unsigned DiagID =
3318           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3319               ? DiagInconsistent
3320               : DiagSuggest;
3321       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3322       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3323       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3324     };
3325     if (isa<CXXDestructorDecl>(MD))
3326       EmitDiag(
3327           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3328           diag::warn_suggest_destructor_marked_not_override_overriding);
3329     else
3330       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3331                diag::warn_suggest_function_marked_not_override_overriding);
3332   }
3333 }
3334 
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)3335 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3336                                                   const CXXMethodDecl *Old) {
3337   FinalAttr *FA = Old->getAttr<FinalAttr>();
3338   if (!FA)
3339     return false;
3340 
3341   Diag(New->getLocation(), diag::err_final_function_overridden)
3342     << New->getDeclName()
3343     << FA->isSpelledAsSealed();
3344   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3345   return true;
3346 }
3347 
InitializationHasSideEffects(const FieldDecl & FD)3348 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3349   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3350   // FIXME: Destruction of ObjC lifetime types has side-effects.
3351   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3352     return !RD->isCompleteDefinition() ||
3353            !RD->hasTrivialDefaultConstructor() ||
3354            !RD->hasTrivialDestructor();
3355   return false;
3356 }
3357 
CheckShadowInheritedFields(const SourceLocation & Loc,DeclarationName FieldName,const CXXRecordDecl * RD,bool DeclIsField)3358 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3359                                       DeclarationName FieldName,
3360                                       const CXXRecordDecl *RD,
3361                                       bool DeclIsField) {
3362   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3363     return;
3364 
3365   // To record a shadowed field in a base
3366   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3367   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3368                            CXXBasePath &Path) {
3369     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3370     // Record an ambiguous path directly
3371     if (Bases.find(Base) != Bases.end())
3372       return true;
3373     for (const auto Field : Base->lookup(FieldName)) {
3374       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3375           Field->getAccess() != AS_private) {
3376         assert(Field->getAccess() != AS_none);
3377         assert(Bases.find(Base) == Bases.end());
3378         Bases[Base] = Field;
3379         return true;
3380       }
3381     }
3382     return false;
3383   };
3384 
3385   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3386                      /*DetectVirtual=*/true);
3387   if (!RD->lookupInBases(FieldShadowed, Paths))
3388     return;
3389 
3390   for (const auto &P : Paths) {
3391     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3392     auto It = Bases.find(Base);
3393     // Skip duplicated bases
3394     if (It == Bases.end())
3395       continue;
3396     auto BaseField = It->second;
3397     assert(BaseField->getAccess() != AS_private);
3398     if (AS_none !=
3399         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3400       Diag(Loc, diag::warn_shadow_field)
3401         << FieldName << RD << Base << DeclIsField;
3402       Diag(BaseField->getLocation(), diag::note_shadow_field);
3403       Bases.erase(It);
3404     }
3405   }
3406 }
3407 
3408 template <typename AttrType>
HasAttribute(const QualType & T)3409 inline static bool HasAttribute(const QualType &T) {
3410   if (const TagDecl *TD = T->getAsTagDecl())
3411     return TD->hasAttr<AttrType>();
3412   if (const TypedefType *TDT = T->getAs<TypedefType>())
3413     return TDT->getDecl()->hasAttr<AttrType>();
3414   return false;
3415 }
3416 
IsUnusedPrivateField(const FieldDecl * FD)3417 static bool IsUnusedPrivateField(const FieldDecl *FD) {
3418   if (FD->getAccess() == AS_private && FD->getDeclName()) {
3419     QualType FieldType = FD->getType();
3420     if (HasAttribute<WarnUnusedAttr>(FieldType))
3421       return true;
3422 
3423     return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3424            !FD->getParent()->isDependentContext() &&
3425            !HasAttribute<UnusedAttr>(FieldType) &&
3426            !InitializationHasSideEffects(*FD);
3427   }
3428   return false;
3429 }
3430 
3431 NamedDecl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BitWidth,const VirtSpecifiers & VS,InClassInitStyle InitStyle)3432 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3433                                MultiTemplateParamsArg TemplateParameterLists,
3434                                Expr *BitWidth, const VirtSpecifiers &VS,
3435                                InClassInitStyle InitStyle) {
3436   const DeclSpec &DS = D.getDeclSpec();
3437   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3438   DeclarationName Name = NameInfo.getName();
3439   SourceLocation Loc = NameInfo.getLoc();
3440 
3441   // For anonymous bitfields, the location should point to the type.
3442   if (Loc.isInvalid())
3443     Loc = D.getBeginLoc();
3444 
3445   assert(isa<CXXRecordDecl>(CurContext));
3446   assert(!DS.isFriendSpecified());
3447 
3448   bool isFunc = D.isDeclarationOfFunction();
3449   const ParsedAttr *MSPropertyAttr =
3450       D.getDeclSpec().getAttributes().getMSPropertyAttr();
3451 
3452   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3453     // The Microsoft extension __interface only permits public member functions
3454     // and prohibits constructors, destructors, operators, non-public member
3455     // functions, static methods and data members.
3456     unsigned InvalidDecl;
3457     bool ShowDeclName = true;
3458     if (!isFunc &&
3459         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3460       InvalidDecl = 0;
3461     else if (!isFunc)
3462       InvalidDecl = 1;
3463     else if (AS != AS_public)
3464       InvalidDecl = 2;
3465     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3466       InvalidDecl = 3;
3467     else switch (Name.getNameKind()) {
3468       case DeclarationName::CXXConstructorName:
3469         InvalidDecl = 4;
3470         ShowDeclName = false;
3471         break;
3472 
3473       case DeclarationName::CXXDestructorName:
3474         InvalidDecl = 5;
3475         ShowDeclName = false;
3476         break;
3477 
3478       case DeclarationName::CXXOperatorName:
3479       case DeclarationName::CXXConversionFunctionName:
3480         InvalidDecl = 6;
3481         break;
3482 
3483       default:
3484         InvalidDecl = 0;
3485         break;
3486     }
3487 
3488     if (InvalidDecl) {
3489       if (ShowDeclName)
3490         Diag(Loc, diag::err_invalid_member_in_interface)
3491           << (InvalidDecl-1) << Name;
3492       else
3493         Diag(Loc, diag::err_invalid_member_in_interface)
3494           << (InvalidDecl-1) << "";
3495       return nullptr;
3496     }
3497   }
3498 
3499   // C++ 9.2p6: A member shall not be declared to have automatic storage
3500   // duration (auto, register) or with the extern storage-class-specifier.
3501   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3502   // data members and cannot be applied to names declared const or static,
3503   // and cannot be applied to reference members.
3504   switch (DS.getStorageClassSpec()) {
3505   case DeclSpec::SCS_unspecified:
3506   case DeclSpec::SCS_typedef:
3507   case DeclSpec::SCS_static:
3508     break;
3509   case DeclSpec::SCS_mutable:
3510     if (isFunc) {
3511       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3512 
3513       // FIXME: It would be nicer if the keyword was ignored only for this
3514       // declarator. Otherwise we could get follow-up errors.
3515       D.getMutableDeclSpec().ClearStorageClassSpecs();
3516     }
3517     break;
3518   default:
3519     Diag(DS.getStorageClassSpecLoc(),
3520          diag::err_storageclass_invalid_for_member);
3521     D.getMutableDeclSpec().ClearStorageClassSpecs();
3522     break;
3523   }
3524 
3525   bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3526                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3527                      !isFunc && TemplateParameterLists.empty();
3528 
3529   if (DS.hasConstexprSpecifier() && isInstField) {
3530     SemaDiagnosticBuilder B =
3531         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3532     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3533     if (InitStyle == ICIS_NoInit) {
3534       B << 0 << 0;
3535       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3536         B << FixItHint::CreateRemoval(ConstexprLoc);
3537       else {
3538         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3539         D.getMutableDeclSpec().ClearConstexprSpec();
3540         const char *PrevSpec;
3541         unsigned DiagID;
3542         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3543             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3544         (void)Failed;
3545         assert(!Failed && "Making a constexpr member const shouldn't fail");
3546       }
3547     } else {
3548       B << 1;
3549       const char *PrevSpec;
3550       unsigned DiagID;
3551       if (D.getMutableDeclSpec().SetStorageClassSpec(
3552           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3553           Context.getPrintingPolicy())) {
3554         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3555                "This is the only DeclSpec that should fail to be applied");
3556         B << 1;
3557       } else {
3558         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3559         isInstField = false;
3560       }
3561     }
3562   }
3563 
3564   NamedDecl *Member;
3565   if (isInstField) {
3566     CXXScopeSpec &SS = D.getCXXScopeSpec();
3567 
3568     // Data members must have identifiers for names.
3569     if (!Name.isIdentifier()) {
3570       Diag(Loc, diag::err_bad_variable_name)
3571         << Name;
3572       return nullptr;
3573     }
3574 
3575     IdentifierInfo *II = Name.getAsIdentifierInfo();
3576     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3577       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3578           << II
3579           << SourceRange(D.getName().TemplateId->LAngleLoc,
3580                          D.getName().TemplateId->RAngleLoc)
3581           << D.getName().TemplateId->LAngleLoc;
3582       D.SetIdentifier(II, Loc);
3583     }
3584 
3585     if (SS.isSet() && !SS.isInvalid()) {
3586       // The user provided a superfluous scope specifier inside a class
3587       // definition:
3588       //
3589       // class X {
3590       //   int X::member;
3591       // };
3592       if (DeclContext *DC = computeDeclContext(SS, false)) {
3593         TemplateIdAnnotation *TemplateId =
3594             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3595                 ? D.getName().TemplateId
3596                 : nullptr;
3597         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3598                                      TemplateId,
3599                                      /*IsMemberSpecialization=*/false);
3600       } else {
3601         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3602           << Name << SS.getRange();
3603       }
3604       SS.clear();
3605     }
3606 
3607     if (MSPropertyAttr) {
3608       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3609                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3610       if (!Member)
3611         return nullptr;
3612       isInstField = false;
3613     } else {
3614       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3615                                 BitWidth, InitStyle, AS);
3616       if (!Member)
3617         return nullptr;
3618     }
3619 
3620     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3621   } else {
3622     Member = HandleDeclarator(S, D, TemplateParameterLists);
3623     if (!Member)
3624       return nullptr;
3625 
3626     // Non-instance-fields can't have a bitfield.
3627     if (BitWidth) {
3628       if (Member->isInvalidDecl()) {
3629         // don't emit another diagnostic.
3630       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3631         // C++ 9.6p3: A bit-field shall not be a static member.
3632         // "static member 'A' cannot be a bit-field"
3633         Diag(Loc, diag::err_static_not_bitfield)
3634           << Name << BitWidth->getSourceRange();
3635       } else if (isa<TypedefDecl>(Member)) {
3636         // "typedef member 'x' cannot be a bit-field"
3637         Diag(Loc, diag::err_typedef_not_bitfield)
3638           << Name << BitWidth->getSourceRange();
3639       } else {
3640         // A function typedef ("typedef int f(); f a;").
3641         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3642         Diag(Loc, diag::err_not_integral_type_bitfield)
3643           << Name << cast<ValueDecl>(Member)->getType()
3644           << BitWidth->getSourceRange();
3645       }
3646 
3647       BitWidth = nullptr;
3648       Member->setInvalidDecl();
3649     }
3650 
3651     NamedDecl *NonTemplateMember = Member;
3652     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3653       NonTemplateMember = FunTmpl->getTemplatedDecl();
3654     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3655       NonTemplateMember = VarTmpl->getTemplatedDecl();
3656 
3657     Member->setAccess(AS);
3658 
3659     // If we have declared a member function template or static data member
3660     // template, set the access of the templated declaration as well.
3661     if (NonTemplateMember != Member)
3662       NonTemplateMember->setAccess(AS);
3663 
3664     // C++ [temp.deduct.guide]p3:
3665     //   A deduction guide [...] for a member class template [shall be
3666     //   declared] with the same access [as the template].
3667     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3668       auto *TD = DG->getDeducedTemplate();
3669       // Access specifiers are only meaningful if both the template and the
3670       // deduction guide are from the same scope.
3671       if (AS != TD->getAccess() &&
3672           TD->getDeclContext()->getRedeclContext()->Equals(
3673               DG->getDeclContext()->getRedeclContext())) {
3674         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3675         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3676             << TD->getAccess();
3677         const AccessSpecDecl *LastAccessSpec = nullptr;
3678         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3679           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3680             LastAccessSpec = AccessSpec;
3681         }
3682         assert(LastAccessSpec && "differing access with no access specifier");
3683         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3684             << AS;
3685       }
3686     }
3687   }
3688 
3689   if (VS.isOverrideSpecified())
3690     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3691   if (VS.isFinalSpecified())
3692     Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3693                                       VS.isFinalSpelledSealed()
3694                                           ? FinalAttr::Keyword_sealed
3695                                           : FinalAttr::Keyword_final));
3696 
3697   if (VS.getLastLocation().isValid()) {
3698     // Update the end location of a method that has a virt-specifiers.
3699     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3700       MD->setRangeEnd(VS.getLastLocation());
3701   }
3702 
3703   CheckOverrideControl(Member);
3704 
3705   assert((Name || isInstField) && "No identifier for non-field ?");
3706 
3707   if (isInstField) {
3708     FieldDecl *FD = cast<FieldDecl>(Member);
3709     FieldCollector->Add(FD);
3710 
3711     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3712         IsUnusedPrivateField(FD)) {
3713       // Remember all explicit private FieldDecls that have a name, no side
3714       // effects and are not part of a dependent type declaration.
3715       UnusedPrivateFields.insert(FD);
3716     }
3717   }
3718 
3719   return Member;
3720 }
3721 
3722 namespace {
3723   class UninitializedFieldVisitor
3724       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3725     Sema &S;
3726     // List of Decls to generate a warning on.  Also remove Decls that become
3727     // initialized.
3728     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3729     // List of base classes of the record.  Classes are removed after their
3730     // initializers.
3731     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3732     // Vector of decls to be removed from the Decl set prior to visiting the
3733     // nodes.  These Decls may have been initialized in the prior initializer.
3734     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3735     // If non-null, add a note to the warning pointing back to the constructor.
3736     const CXXConstructorDecl *Constructor;
3737     // Variables to hold state when processing an initializer list.  When
3738     // InitList is true, special case initialization of FieldDecls matching
3739     // InitListFieldDecl.
3740     bool InitList;
3741     FieldDecl *InitListFieldDecl;
3742     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3743 
3744   public:
3745     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,llvm::SmallPtrSetImpl<ValueDecl * > & Decls,llvm::SmallPtrSetImpl<QualType> & BaseClasses)3746     UninitializedFieldVisitor(Sema &S,
3747                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3748                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3749       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3750         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3751 
3752     // Returns true if the use of ME is not an uninitialized use.
IsInitListMemberExprInitialized(MemberExpr * ME,bool CheckReferenceOnly)3753     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3754                                          bool CheckReferenceOnly) {
3755       llvm::SmallVector<FieldDecl*, 4> Fields;
3756       bool ReferenceField = false;
3757       while (ME) {
3758         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3759         if (!FD)
3760           return false;
3761         Fields.push_back(FD);
3762         if (FD->getType()->isReferenceType())
3763           ReferenceField = true;
3764         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3765       }
3766 
3767       // Binding a reference to an uninitialized field is not an
3768       // uninitialized use.
3769       if (CheckReferenceOnly && !ReferenceField)
3770         return true;
3771 
3772       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3773       // Discard the first field since it is the field decl that is being
3774       // initialized.
3775       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3776         UsedFieldIndex.push_back(FD->getFieldIndex());
3777 
3778       for (auto UsedIter = UsedFieldIndex.begin(),
3779                 UsedEnd = UsedFieldIndex.end(),
3780                 OrigIter = InitFieldIndex.begin(),
3781                 OrigEnd = InitFieldIndex.end();
3782            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3783         if (*UsedIter < *OrigIter)
3784           return true;
3785         if (*UsedIter > *OrigIter)
3786           break;
3787       }
3788 
3789       return false;
3790     }
3791 
HandleMemberExpr(MemberExpr * ME,bool CheckReferenceOnly,bool AddressOf)3792     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3793                           bool AddressOf) {
3794       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3795         return;
3796 
3797       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3798       // or union.
3799       MemberExpr *FieldME = ME;
3800 
3801       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3802 
3803       Expr *Base = ME;
3804       while (MemberExpr *SubME =
3805                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3806 
3807         if (isa<VarDecl>(SubME->getMemberDecl()))
3808           return;
3809 
3810         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3811           if (!FD->isAnonymousStructOrUnion())
3812             FieldME = SubME;
3813 
3814         if (!FieldME->getType().isPODType(S.Context))
3815           AllPODFields = false;
3816 
3817         Base = SubME->getBase();
3818       }
3819 
3820       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3821         Visit(Base);
3822         return;
3823       }
3824 
3825       if (AddressOf && AllPODFields)
3826         return;
3827 
3828       ValueDecl* FoundVD = FieldME->getMemberDecl();
3829 
3830       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3831         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3832           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3833         }
3834 
3835         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3836           QualType T = BaseCast->getType();
3837           if (T->isPointerType() &&
3838               BaseClasses.count(T->getPointeeType())) {
3839             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3840                 << T->getPointeeType() << FoundVD;
3841           }
3842         }
3843       }
3844 
3845       if (!Decls.count(FoundVD))
3846         return;
3847 
3848       const bool IsReference = FoundVD->getType()->isReferenceType();
3849 
3850       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3851         // Special checking for initializer lists.
3852         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3853           return;
3854         }
3855       } else {
3856         // Prevent double warnings on use of unbounded references.
3857         if (CheckReferenceOnly && !IsReference)
3858           return;
3859       }
3860 
3861       unsigned diag = IsReference
3862           ? diag::warn_reference_field_is_uninit
3863           : diag::warn_field_is_uninit;
3864       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3865       if (Constructor)
3866         S.Diag(Constructor->getLocation(),
3867                diag::note_uninit_in_this_constructor)
3868           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3869 
3870     }
3871 
HandleValue(Expr * E,bool AddressOf)3872     void HandleValue(Expr *E, bool AddressOf) {
3873       E = E->IgnoreParens();
3874 
3875       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3876         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3877                          AddressOf /*AddressOf*/);
3878         return;
3879       }
3880 
3881       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3882         Visit(CO->getCond());
3883         HandleValue(CO->getTrueExpr(), AddressOf);
3884         HandleValue(CO->getFalseExpr(), AddressOf);
3885         return;
3886       }
3887 
3888       if (BinaryConditionalOperator *BCO =
3889               dyn_cast<BinaryConditionalOperator>(E)) {
3890         Visit(BCO->getCond());
3891         HandleValue(BCO->getFalseExpr(), AddressOf);
3892         return;
3893       }
3894 
3895       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3896         HandleValue(OVE->getSourceExpr(), AddressOf);
3897         return;
3898       }
3899 
3900       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3901         switch (BO->getOpcode()) {
3902         default:
3903           break;
3904         case(BO_PtrMemD):
3905         case(BO_PtrMemI):
3906           HandleValue(BO->getLHS(), AddressOf);
3907           Visit(BO->getRHS());
3908           return;
3909         case(BO_Comma):
3910           Visit(BO->getLHS());
3911           HandleValue(BO->getRHS(), AddressOf);
3912           return;
3913         }
3914       }
3915 
3916       Visit(E);
3917     }
3918 
CheckInitListExpr(InitListExpr * ILE)3919     void CheckInitListExpr(InitListExpr *ILE) {
3920       InitFieldIndex.push_back(0);
3921       for (auto *Child : ILE->children()) {
3922         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3923           CheckInitListExpr(SubList);
3924         } else {
3925           Visit(Child);
3926         }
3927         ++InitFieldIndex.back();
3928       }
3929       InitFieldIndex.pop_back();
3930     }
3931 
CheckInitializer(Expr * E,const CXXConstructorDecl * FieldConstructor,FieldDecl * Field,const Type * BaseClass)3932     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3933                           FieldDecl *Field, const Type *BaseClass) {
3934       // Remove Decls that may have been initialized in the previous
3935       // initializer.
3936       for (ValueDecl* VD : DeclsToRemove)
3937         Decls.erase(VD);
3938       DeclsToRemove.clear();
3939 
3940       Constructor = FieldConstructor;
3941       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3942 
3943       if (ILE && Field) {
3944         InitList = true;
3945         InitListFieldDecl = Field;
3946         InitFieldIndex.clear();
3947         CheckInitListExpr(ILE);
3948       } else {
3949         InitList = false;
3950         Visit(E);
3951       }
3952 
3953       if (Field)
3954         Decls.erase(Field);
3955       if (BaseClass)
3956         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3957     }
3958 
VisitMemberExpr(MemberExpr * ME)3959     void VisitMemberExpr(MemberExpr *ME) {
3960       // All uses of unbounded reference fields will warn.
3961       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3962     }
3963 
VisitImplicitCastExpr(ImplicitCastExpr * E)3964     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3965       if (E->getCastKind() == CK_LValueToRValue) {
3966         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3967         return;
3968       }
3969 
3970       Inherited::VisitImplicitCastExpr(E);
3971     }
3972 
VisitCXXConstructExpr(CXXConstructExpr * E)3973     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3974       if (E->getConstructor()->isCopyConstructor()) {
3975         Expr *ArgExpr = E->getArg(0);
3976         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3977           if (ILE->getNumInits() == 1)
3978             ArgExpr = ILE->getInit(0);
3979         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3980           if (ICE->getCastKind() == CK_NoOp)
3981             ArgExpr = ICE->getSubExpr();
3982         HandleValue(ArgExpr, false /*AddressOf*/);
3983         return;
3984       }
3985       Inherited::VisitCXXConstructExpr(E);
3986     }
3987 
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)3988     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3989       Expr *Callee = E->getCallee();
3990       if (isa<MemberExpr>(Callee)) {
3991         HandleValue(Callee, false /*AddressOf*/);
3992         for (auto *Arg : E->arguments())
3993           Visit(Arg);
3994         return;
3995       }
3996 
3997       Inherited::VisitCXXMemberCallExpr(E);
3998     }
3999 
VisitCallExpr(CallExpr * E)4000     void VisitCallExpr(CallExpr *E) {
4001       // Treat std::move as a use.
4002       if (E->isCallToStdMove()) {
4003         HandleValue(E->getArg(0), /*AddressOf=*/false);
4004         return;
4005       }
4006 
4007       Inherited::VisitCallExpr(E);
4008     }
4009 
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)4010     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4011       Expr *Callee = E->getCallee();
4012 
4013       if (isa<UnresolvedLookupExpr>(Callee))
4014         return Inherited::VisitCXXOperatorCallExpr(E);
4015 
4016       Visit(Callee);
4017       for (auto *Arg : E->arguments())
4018         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4019     }
4020 
VisitBinaryOperator(BinaryOperator * E)4021     void VisitBinaryOperator(BinaryOperator *E) {
4022       // If a field assignment is detected, remove the field from the
4023       // uninitiailized field set.
4024       if (E->getOpcode() == BO_Assign)
4025         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4026           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4027             if (!FD->getType()->isReferenceType())
4028               DeclsToRemove.push_back(FD);
4029 
4030       if (E->isCompoundAssignmentOp()) {
4031         HandleValue(E->getLHS(), false /*AddressOf*/);
4032         Visit(E->getRHS());
4033         return;
4034       }
4035 
4036       Inherited::VisitBinaryOperator(E);
4037     }
4038 
VisitUnaryOperator(UnaryOperator * E)4039     void VisitUnaryOperator(UnaryOperator *E) {
4040       if (E->isIncrementDecrementOp()) {
4041         HandleValue(E->getSubExpr(), false /*AddressOf*/);
4042         return;
4043       }
4044       if (E->getOpcode() == UO_AddrOf) {
4045         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4046           HandleValue(ME->getBase(), true /*AddressOf*/);
4047           return;
4048         }
4049       }
4050 
4051       Inherited::VisitUnaryOperator(E);
4052     }
4053   };
4054 
4055   // Diagnose value-uses of fields to initialize themselves, e.g.
4056   //   foo(foo)
4057   // where foo is not also a parameter to the constructor.
4058   // Also diagnose across field uninitialized use such as
4059   //   x(y), y(x)
4060   // TODO: implement -Wuninitialized and fold this into that framework.
DiagnoseUninitializedFields(Sema & SemaRef,const CXXConstructorDecl * Constructor)4061   static void DiagnoseUninitializedFields(
4062       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4063 
4064     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4065                                            Constructor->getLocation())) {
4066       return;
4067     }
4068 
4069     if (Constructor->isInvalidDecl())
4070       return;
4071 
4072     const CXXRecordDecl *RD = Constructor->getParent();
4073 
4074     if (RD->isDependentContext())
4075       return;
4076 
4077     // Holds fields that are uninitialized.
4078     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4079 
4080     // At the beginning, all fields are uninitialized.
4081     for (auto *I : RD->decls()) {
4082       if (auto *FD = dyn_cast<FieldDecl>(I)) {
4083         UninitializedFields.insert(FD);
4084       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4085         UninitializedFields.insert(IFD->getAnonField());
4086       }
4087     }
4088 
4089     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4090     for (const auto &I : RD->bases())
4091       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4092 
4093     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4094       return;
4095 
4096     UninitializedFieldVisitor UninitializedChecker(SemaRef,
4097                                                    UninitializedFields,
4098                                                    UninitializedBaseClasses);
4099 
4100     for (const auto *FieldInit : Constructor->inits()) {
4101       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4102         break;
4103 
4104       Expr *InitExpr = FieldInit->getInit();
4105       if (!InitExpr)
4106         continue;
4107 
4108       if (CXXDefaultInitExpr *Default =
4109               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4110         InitExpr = Default->getExpr();
4111         if (!InitExpr)
4112           continue;
4113         // In class initializers will point to the constructor.
4114         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4115                                               FieldInit->getAnyMember(),
4116                                               FieldInit->getBaseClass());
4117       } else {
4118         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4119                                               FieldInit->getAnyMember(),
4120                                               FieldInit->getBaseClass());
4121       }
4122     }
4123   }
4124 } // namespace
4125 
ActOnStartCXXInClassMemberInitializer()4126 void Sema::ActOnStartCXXInClassMemberInitializer() {
4127   // Create a synthetic function scope to represent the call to the constructor
4128   // that notionally surrounds a use of this initializer.
4129   PushFunctionScope();
4130 }
4131 
ActOnStartTrailingRequiresClause(Scope * S,Declarator & D)4132 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4133   if (!D.isFunctionDeclarator())
4134     return;
4135   auto &FTI = D.getFunctionTypeInfo();
4136   if (!FTI.Params)
4137     return;
4138   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4139                                                           FTI.NumParams)) {
4140     auto *ParamDecl = cast<NamedDecl>(Param.Param);
4141     if (ParamDecl->getDeclName())
4142       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4143   }
4144 }
4145 
ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)4146 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4147   return ActOnRequiresClause(ConstraintExpr);
4148 }
4149 
ActOnRequiresClause(ExprResult ConstraintExpr)4150 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4151   if (ConstraintExpr.isInvalid())
4152     return ExprError();
4153 
4154   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4155                                       UPPC_RequiresClause))
4156     return ExprError();
4157 
4158   return ConstraintExpr;
4159 }
4160 
ConvertMemberDefaultInitExpression(FieldDecl * FD,Expr * InitExpr,SourceLocation InitLoc)4161 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4162                                                     Expr *InitExpr,
4163                                                     SourceLocation InitLoc) {
4164   InitializedEntity Entity =
4165       InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4166   InitializationKind Kind =
4167       FD->getInClassInitStyle() == ICIS_ListInit
4168           ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4169                                                  InitExpr->getBeginLoc(),
4170                                                  InitExpr->getEndLoc())
4171           : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4172   InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4173   return Seq.Perform(*this, Entity, Kind, InitExpr);
4174 }
4175 
ActOnFinishCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,ExprResult InitExpr)4176 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4177                                                   SourceLocation InitLoc,
4178                                                   ExprResult InitExpr) {
4179   // Pop the notional constructor scope we created earlier.
4180   PopFunctionScopeInfo(nullptr, D);
4181 
4182   // Microsoft C++'s property declaration cannot have a default member
4183   // initializer.
4184   if (isa<MSPropertyDecl>(D)) {
4185     D->setInvalidDecl();
4186     return;
4187   }
4188 
4189   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4190   assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4191          "must set init style when field is created");
4192 
4193   if (!InitExpr.isUsable() ||
4194       DiagnoseUnexpandedParameterPack(InitExpr.get(), UPPC_Initializer)) {
4195     FD->setInvalidDecl();
4196     ExprResult RecoveryInit =
4197         CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4198     if (RecoveryInit.isUsable())
4199       FD->setInClassInitializer(RecoveryInit.get());
4200     return;
4201   }
4202 
4203   if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4204     InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4205     // C++11 [class.base.init]p7:
4206     //   The initialization of each base and member constitutes a
4207     //   full-expression.
4208     if (!InitExpr.isInvalid())
4209       InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4210     if (InitExpr.isInvalid()) {
4211       FD->setInvalidDecl();
4212       return;
4213     }
4214   }
4215 
4216   FD->setInClassInitializer(InitExpr.get());
4217 }
4218 
4219 /// Find the direct and/or virtual base specifiers that
4220 /// correspond to the given base type, for use in base initialization
4221 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)4222 static bool FindBaseInitializer(Sema &SemaRef,
4223                                 CXXRecordDecl *ClassDecl,
4224                                 QualType BaseType,
4225                                 const CXXBaseSpecifier *&DirectBaseSpec,
4226                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4227   // First, check for a direct base class.
4228   DirectBaseSpec = nullptr;
4229   for (const auto &Base : ClassDecl->bases()) {
4230     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4231       // We found a direct base of this type. That's what we're
4232       // initializing.
4233       DirectBaseSpec = &Base;
4234       break;
4235     }
4236   }
4237 
4238   // Check for a virtual base class.
4239   // FIXME: We might be able to short-circuit this if we know in advance that
4240   // there are no virtual bases.
4241   VirtualBaseSpec = nullptr;
4242   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4243     // We haven't found a base yet; search the class hierarchy for a
4244     // virtual base class.
4245     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4246                        /*DetectVirtual=*/false);
4247     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4248                               SemaRef.Context.getTypeDeclType(ClassDecl),
4249                               BaseType, Paths)) {
4250       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4251            Path != Paths.end(); ++Path) {
4252         if (Path->back().Base->isVirtual()) {
4253           VirtualBaseSpec = Path->back().Base;
4254           break;
4255         }
4256       }
4257     }
4258   }
4259 
4260   return DirectBaseSpec || VirtualBaseSpec;
4261 }
4262 
4263 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)4264 Sema::ActOnMemInitializer(Decl *ConstructorD,
4265                           Scope *S,
4266                           CXXScopeSpec &SS,
4267                           IdentifierInfo *MemberOrBase,
4268                           ParsedType TemplateTypeTy,
4269                           const DeclSpec &DS,
4270                           SourceLocation IdLoc,
4271                           Expr *InitList,
4272                           SourceLocation EllipsisLoc) {
4273   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4274                              DS, IdLoc, InitList,
4275                              EllipsisLoc);
4276 }
4277 
4278 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,SourceLocation EllipsisLoc)4279 Sema::ActOnMemInitializer(Decl *ConstructorD,
4280                           Scope *S,
4281                           CXXScopeSpec &SS,
4282                           IdentifierInfo *MemberOrBase,
4283                           ParsedType TemplateTypeTy,
4284                           const DeclSpec &DS,
4285                           SourceLocation IdLoc,
4286                           SourceLocation LParenLoc,
4287                           ArrayRef<Expr *> Args,
4288                           SourceLocation RParenLoc,
4289                           SourceLocation EllipsisLoc) {
4290   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4291   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4292                              DS, IdLoc, List, EllipsisLoc);
4293 }
4294 
4295 namespace {
4296 
4297 // Callback to only accept typo corrections that can be a valid C++ member
4298 // initializer: either a non-static field member or a base class.
4299 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4300 public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)4301   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4302       : ClassDecl(ClassDecl) {}
4303 
ValidateCandidate(const TypoCorrection & candidate)4304   bool ValidateCandidate(const TypoCorrection &candidate) override {
4305     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4306       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4307         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4308       return isa<TypeDecl>(ND);
4309     }
4310     return false;
4311   }
4312 
clone()4313   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4314     return std::make_unique<MemInitializerValidatorCCC>(*this);
4315   }
4316 
4317 private:
4318   CXXRecordDecl *ClassDecl;
4319 };
4320 
4321 }
4322 
DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,RecordDecl * ClassDecl,const IdentifierInfo * Name)4323 bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4324                                              RecordDecl *ClassDecl,
4325                                              const IdentifierInfo *Name) {
4326   DeclContextLookupResult Result = ClassDecl->lookup(Name);
4327   DeclContextLookupResult::iterator Found =
4328       llvm::find_if(Result, [this](const NamedDecl *Elem) {
4329         return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4330                Elem->isPlaceholderVar(getLangOpts());
4331       });
4332   // We did not find a placeholder variable
4333   if (Found == Result.end())
4334     return false;
4335   Diag(Loc, diag::err_using_placeholder_variable) << Name;
4336   for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4337     const NamedDecl *ND = *It;
4338     if (ND->getDeclContext() != ND->getDeclContext())
4339       break;
4340     if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4341         ND->isPlaceholderVar(getLangOpts()))
4342       Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4343   }
4344   return true;
4345 }
4346 
4347 ValueDecl *
tryLookupUnambiguousFieldDecl(RecordDecl * ClassDecl,const IdentifierInfo * MemberOrBase)4348 Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4349                                     const IdentifierInfo *MemberOrBase) {
4350   ValueDecl *ND = nullptr;
4351   for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4352     if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4353       bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4354       if (ND) {
4355         if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4356           return nullptr;
4357         break;
4358       }
4359       if (!IsPlaceholder)
4360         return cast<ValueDecl>(D);
4361       ND = cast<ValueDecl>(D);
4362     }
4363   }
4364   return ND;
4365 }
4366 
tryLookupCtorInitMemberDecl(CXXRecordDecl * ClassDecl,CXXScopeSpec & SS,ParsedType TemplateTypeTy,IdentifierInfo * MemberOrBase)4367 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4368                                              CXXScopeSpec &SS,
4369                                              ParsedType TemplateTypeTy,
4370                                              IdentifierInfo *MemberOrBase) {
4371   if (SS.getScopeRep() || TemplateTypeTy)
4372     return nullptr;
4373   return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4374 }
4375 
4376 MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)4377 Sema::BuildMemInitializer(Decl *ConstructorD,
4378                           Scope *S,
4379                           CXXScopeSpec &SS,
4380                           IdentifierInfo *MemberOrBase,
4381                           ParsedType TemplateTypeTy,
4382                           const DeclSpec &DS,
4383                           SourceLocation IdLoc,
4384                           Expr *Init,
4385                           SourceLocation EllipsisLoc) {
4386   if (!ConstructorD || !Init)
4387     return true;
4388 
4389   AdjustDeclIfTemplate(ConstructorD);
4390 
4391   CXXConstructorDecl *Constructor
4392     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4393   if (!Constructor) {
4394     // The user wrote a constructor initializer on a function that is
4395     // not a C++ constructor. Ignore the error for now, because we may
4396     // have more member initializers coming; we'll diagnose it just
4397     // once in ActOnMemInitializers.
4398     return true;
4399   }
4400 
4401   CXXRecordDecl *ClassDecl = Constructor->getParent();
4402 
4403   // C++ [class.base.init]p2:
4404   //   Names in a mem-initializer-id are looked up in the scope of the
4405   //   constructor's class and, if not found in that scope, are looked
4406   //   up in the scope containing the constructor's definition.
4407   //   [Note: if the constructor's class contains a member with the
4408   //   same name as a direct or virtual base class of the class, a
4409   //   mem-initializer-id naming the member or base class and composed
4410   //   of a single identifier refers to the class member. A
4411   //   mem-initializer-id for the hidden base class may be specified
4412   //   using a qualified name. ]
4413 
4414   // Look for a member, first.
4415   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4416           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4417     if (EllipsisLoc.isValid())
4418       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4419           << MemberOrBase
4420           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4421 
4422     return BuildMemberInitializer(Member, Init, IdLoc);
4423   }
4424   // It didn't name a member, so see if it names a class.
4425   QualType BaseType;
4426   TypeSourceInfo *TInfo = nullptr;
4427 
4428   if (TemplateTypeTy) {
4429     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4430     if (BaseType.isNull())
4431       return true;
4432   } else if (DS.getTypeSpecType() == TST_decltype) {
4433     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4434   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4435     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4436     return true;
4437   } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4438     BaseType =
4439         BuildPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),
4440                               DS.getBeginLoc(), DS.getEllipsisLoc());
4441   } else {
4442     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4443     LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4444 
4445     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4446     if (!TyD) {
4447       if (R.isAmbiguous()) return true;
4448 
4449       // We don't want access-control diagnostics here.
4450       R.suppressDiagnostics();
4451 
4452       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4453         bool NotUnknownSpecialization = false;
4454         DeclContext *DC = computeDeclContext(SS, false);
4455         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4456           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4457 
4458         if (!NotUnknownSpecialization) {
4459           // When the scope specifier can refer to a member of an unknown
4460           // specialization, we take it as a type name.
4461           BaseType = CheckTypenameType(
4462               ElaboratedTypeKeyword::None, SourceLocation(),
4463               SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4464           if (BaseType.isNull())
4465             return true;
4466 
4467           TInfo = Context.CreateTypeSourceInfo(BaseType);
4468           DependentNameTypeLoc TL =
4469               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4470           if (!TL.isNull()) {
4471             TL.setNameLoc(IdLoc);
4472             TL.setElaboratedKeywordLoc(SourceLocation());
4473             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4474           }
4475 
4476           R.clear();
4477           R.setLookupName(MemberOrBase);
4478         }
4479       }
4480 
4481       if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4482         if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4483           auto *TempSpec = cast<TemplateSpecializationType>(
4484               UnqualifiedBase->getInjectedClassNameSpecialization());
4485           TemplateName TN = TempSpec->getTemplateName();
4486           for (auto const &Base : ClassDecl->bases()) {
4487             auto BaseTemplate =
4488                 Base.getType()->getAs<TemplateSpecializationType>();
4489             if (BaseTemplate &&
4490                 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4491                                             /*IgnoreDeduced=*/true)) {
4492               Diag(IdLoc, diag::ext_unqualified_base_class)
4493                   << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4494               BaseType = Base.getType();
4495               break;
4496             }
4497           }
4498         }
4499       }
4500 
4501       // If no results were found, try to correct typos.
4502       TypoCorrection Corr;
4503       MemInitializerValidatorCCC CCC(ClassDecl);
4504       if (R.empty() && BaseType.isNull() &&
4505           (Corr =
4506                CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4507                            CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4508         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4509           // We have found a non-static data member with a similar
4510           // name to what was typed; complain and initialize that
4511           // member.
4512           diagnoseTypo(Corr,
4513                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4514                          << MemberOrBase << true);
4515           return BuildMemberInitializer(Member, Init, IdLoc);
4516         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4517           const CXXBaseSpecifier *DirectBaseSpec;
4518           const CXXBaseSpecifier *VirtualBaseSpec;
4519           if (FindBaseInitializer(*this, ClassDecl,
4520                                   Context.getTypeDeclType(Type),
4521                                   DirectBaseSpec, VirtualBaseSpec)) {
4522             // We have found a direct or virtual base class with a
4523             // similar name to what was typed; complain and initialize
4524             // that base class.
4525             diagnoseTypo(Corr,
4526                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4527                            << MemberOrBase << false,
4528                          PDiag() /*Suppress note, we provide our own.*/);
4529 
4530             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4531                                                               : VirtualBaseSpec;
4532             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4533                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4534 
4535             TyD = Type;
4536           }
4537         }
4538       }
4539 
4540       if (!TyD && BaseType.isNull()) {
4541         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4542           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4543         return true;
4544       }
4545     }
4546 
4547     if (BaseType.isNull()) {
4548       BaseType = getElaboratedType(ElaboratedTypeKeyword::None, SS,
4549                                    Context.getTypeDeclType(TyD));
4550       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4551       TInfo = Context.CreateTypeSourceInfo(BaseType);
4552       ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4553       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4554       TL.setElaboratedKeywordLoc(SourceLocation());
4555       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4556     }
4557   }
4558 
4559   if (!TInfo)
4560     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4561 
4562   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4563 }
4564 
4565 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)4566 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4567                              SourceLocation IdLoc) {
4568   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4569   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4570   assert((DirectMember || IndirectMember) &&
4571          "Member must be a FieldDecl or IndirectFieldDecl");
4572 
4573   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4574     return true;
4575 
4576   if (Member->isInvalidDecl())
4577     return true;
4578 
4579   MultiExprArg Args;
4580   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4581     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4582   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4583     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4584   } else {
4585     // Template instantiation doesn't reconstruct ParenListExprs for us.
4586     Args = Init;
4587   }
4588 
4589   SourceRange InitRange = Init->getSourceRange();
4590 
4591   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4592     // Can't check initialization for a member of dependent type or when
4593     // any of the arguments are type-dependent expressions.
4594     DiscardCleanupsInEvaluationContext();
4595   } else {
4596     bool InitList = false;
4597     if (isa<InitListExpr>(Init)) {
4598       InitList = true;
4599       Args = Init;
4600     }
4601 
4602     // Initialize the member.
4603     InitializedEntity MemberEntity =
4604       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4605                    : InitializedEntity::InitializeMember(IndirectMember,
4606                                                          nullptr);
4607     InitializationKind Kind =
4608         InitList ? InitializationKind::CreateDirectList(
4609                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4610                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4611                                                     InitRange.getEnd());
4612 
4613     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4614     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4615                                             nullptr);
4616     if (!MemberInit.isInvalid()) {
4617       // C++11 [class.base.init]p7:
4618       //   The initialization of each base and member constitutes a
4619       //   full-expression.
4620       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4621                                        /*DiscardedValue*/ false);
4622     }
4623 
4624     if (MemberInit.isInvalid()) {
4625       // Args were sensible expressions but we couldn't initialize the member
4626       // from them. Preserve them in a RecoveryExpr instead.
4627       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4628                                 Member->getType())
4629                  .get();
4630       if (!Init)
4631         return true;
4632     } else {
4633       Init = MemberInit.get();
4634     }
4635   }
4636 
4637   if (DirectMember) {
4638     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4639                                             InitRange.getBegin(), Init,
4640                                             InitRange.getEnd());
4641   } else {
4642     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4643                                             InitRange.getBegin(), Init,
4644                                             InitRange.getEnd());
4645   }
4646 }
4647 
4648 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)4649 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4650                                  CXXRecordDecl *ClassDecl) {
4651   SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4652   if (!LangOpts.CPlusPlus11)
4653     return Diag(NameLoc, diag::err_delegating_ctor)
4654            << TInfo->getTypeLoc().getSourceRange();
4655   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4656 
4657   bool InitList = true;
4658   MultiExprArg Args = Init;
4659   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4660     InitList = false;
4661     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4662   }
4663 
4664   SourceRange InitRange = Init->getSourceRange();
4665   // Initialize the object.
4666   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4667                                      QualType(ClassDecl->getTypeForDecl(), 0));
4668   InitializationKind Kind =
4669       InitList ? InitializationKind::CreateDirectList(
4670                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4671                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4672                                                   InitRange.getEnd());
4673   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4674   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4675                                               Args, nullptr);
4676   if (!DelegationInit.isInvalid()) {
4677     assert((DelegationInit.get()->containsErrors() ||
4678             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4679            "Delegating constructor with no target?");
4680 
4681     // C++11 [class.base.init]p7:
4682     //   The initialization of each base and member constitutes a
4683     //   full-expression.
4684     DelegationInit = ActOnFinishFullExpr(
4685         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4686   }
4687 
4688   if (DelegationInit.isInvalid()) {
4689     DelegationInit =
4690         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4691                            QualType(ClassDecl->getTypeForDecl(), 0));
4692     if (DelegationInit.isInvalid())
4693       return true;
4694   } else {
4695     // If we are in a dependent context, template instantiation will
4696     // perform this type-checking again. Just save the arguments that we
4697     // received in a ParenListExpr.
4698     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4699     // of the information that we have about the base
4700     // initializer. However, deconstructing the ASTs is a dicey process,
4701     // and this approach is far more likely to get the corner cases right.
4702     if (CurContext->isDependentContext())
4703       DelegationInit = Init;
4704   }
4705 
4706   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4707                                           DelegationInit.getAs<Expr>(),
4708                                           InitRange.getEnd());
4709 }
4710 
4711 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)4712 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4713                            Expr *Init, CXXRecordDecl *ClassDecl,
4714                            SourceLocation EllipsisLoc) {
4715   SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4716 
4717   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4718     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4719            << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4720 
4721   // C++ [class.base.init]p2:
4722   //   [...] Unless the mem-initializer-id names a nonstatic data
4723   //   member of the constructor's class or a direct or virtual base
4724   //   of that class, the mem-initializer is ill-formed. A
4725   //   mem-initializer-list can initialize a base class using any
4726   //   name that denotes that base class type.
4727 
4728   // We can store the initializers in "as-written" form and delay analysis until
4729   // instantiation if the constructor is dependent. But not for dependent
4730   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4731   bool Dependent = CurContext->isDependentContext() &&
4732                    (BaseType->isDependentType() || Init->isTypeDependent());
4733 
4734   SourceRange InitRange = Init->getSourceRange();
4735   if (EllipsisLoc.isValid()) {
4736     // This is a pack expansion.
4737     if (!BaseType->containsUnexpandedParameterPack())  {
4738       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4739         << SourceRange(BaseLoc, InitRange.getEnd());
4740 
4741       EllipsisLoc = SourceLocation();
4742     }
4743   } else {
4744     // Check for any unexpanded parameter packs.
4745     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4746       return true;
4747 
4748     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4749       return true;
4750   }
4751 
4752   // Check for direct and virtual base classes.
4753   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4754   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4755   if (!Dependent) {
4756     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4757                                        BaseType))
4758       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4759 
4760     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4761                         VirtualBaseSpec);
4762 
4763     // C++ [base.class.init]p2:
4764     // Unless the mem-initializer-id names a nonstatic data member of the
4765     // constructor's class or a direct or virtual base of that class, the
4766     // mem-initializer is ill-formed.
4767     if (!DirectBaseSpec && !VirtualBaseSpec) {
4768       // If the class has any dependent bases, then it's possible that
4769       // one of those types will resolve to the same type as
4770       // BaseType. Therefore, just treat this as a dependent base
4771       // class initialization.  FIXME: Should we try to check the
4772       // initialization anyway? It seems odd.
4773       if (ClassDecl->hasAnyDependentBases())
4774         Dependent = true;
4775       else
4776         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4777                << BaseType << Context.getTypeDeclType(ClassDecl)
4778                << BaseTInfo->getTypeLoc().getSourceRange();
4779     }
4780   }
4781 
4782   if (Dependent) {
4783     DiscardCleanupsInEvaluationContext();
4784 
4785     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4786                                             /*IsVirtual=*/false,
4787                                             InitRange.getBegin(), Init,
4788                                             InitRange.getEnd(), EllipsisLoc);
4789   }
4790 
4791   // C++ [base.class.init]p2:
4792   //   If a mem-initializer-id is ambiguous because it designates both
4793   //   a direct non-virtual base class and an inherited virtual base
4794   //   class, the mem-initializer is ill-formed.
4795   if (DirectBaseSpec && VirtualBaseSpec)
4796     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4797       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4798 
4799   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4800   if (!BaseSpec)
4801     BaseSpec = VirtualBaseSpec;
4802 
4803   // Initialize the base.
4804   bool InitList = true;
4805   MultiExprArg Args = Init;
4806   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4807     InitList = false;
4808     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4809   }
4810 
4811   InitializedEntity BaseEntity =
4812     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4813   InitializationKind Kind =
4814       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4815                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4816                                                   InitRange.getEnd());
4817   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4818   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4819   if (!BaseInit.isInvalid()) {
4820     // C++11 [class.base.init]p7:
4821     //   The initialization of each base and member constitutes a
4822     //   full-expression.
4823     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4824                                    /*DiscardedValue*/ false);
4825   }
4826 
4827   if (BaseInit.isInvalid()) {
4828     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4829                                   Args, BaseType);
4830     if (BaseInit.isInvalid())
4831       return true;
4832   } else {
4833     // If we are in a dependent context, template instantiation will
4834     // perform this type-checking again. Just save the arguments that we
4835     // received in a ParenListExpr.
4836     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4837     // of the information that we have about the base
4838     // initializer. However, deconstructing the ASTs is a dicey process,
4839     // and this approach is far more likely to get the corner cases right.
4840     if (CurContext->isDependentContext())
4841       BaseInit = Init;
4842   }
4843 
4844   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4845                                           BaseSpec->isVirtual(),
4846                                           InitRange.getBegin(),
4847                                           BaseInit.getAs<Expr>(),
4848                                           InitRange.getEnd(), EllipsisLoc);
4849 }
4850 
4851 // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E)4852 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4853   QualType TargetType =
4854       SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4855                                  SourceLocation(), DeclarationName());
4856   SourceLocation ExprLoc = E->getBeginLoc();
4857   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4858       TargetType, ExprLoc);
4859 
4860   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4861                                    SourceRange(ExprLoc, ExprLoc),
4862                                    E->getSourceRange()).get();
4863 }
4864 
4865 /// ImplicitInitializerKind - How an implicit base or member initializer should
4866 /// initialize its base or member.
4867 enum ImplicitInitializerKind {
4868   IIK_Default,
4869   IIK_Copy,
4870   IIK_Move,
4871   IIK_Inherit
4872 };
4873 
4874 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)4875 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4876                              ImplicitInitializerKind ImplicitInitKind,
4877                              CXXBaseSpecifier *BaseSpec,
4878                              bool IsInheritedVirtualBase,
4879                              CXXCtorInitializer *&CXXBaseInit) {
4880   InitializedEntity InitEntity
4881     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4882                                         IsInheritedVirtualBase);
4883 
4884   ExprResult BaseInit;
4885 
4886   switch (ImplicitInitKind) {
4887   case IIK_Inherit:
4888   case IIK_Default: {
4889     InitializationKind InitKind
4890       = InitializationKind::CreateDefault(Constructor->getLocation());
4891     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4892     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4893     break;
4894   }
4895 
4896   case IIK_Move:
4897   case IIK_Copy: {
4898     bool Moving = ImplicitInitKind == IIK_Move;
4899     ParmVarDecl *Param = Constructor->getParamDecl(0);
4900     QualType ParamType = Param->getType().getNonReferenceType();
4901 
4902     Expr *CopyCtorArg =
4903       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4904                           SourceLocation(), Param, false,
4905                           Constructor->getLocation(), ParamType,
4906                           VK_LValue, nullptr);
4907 
4908     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4909 
4910     // Cast to the base class to avoid ambiguities.
4911     QualType ArgTy =
4912       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4913                                        ParamType.getQualifiers());
4914 
4915     if (Moving) {
4916       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4917     }
4918 
4919     CXXCastPath BasePath;
4920     BasePath.push_back(BaseSpec);
4921     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4922                                             CK_UncheckedDerivedToBase,
4923                                             Moving ? VK_XValue : VK_LValue,
4924                                             &BasePath).get();
4925 
4926     InitializationKind InitKind
4927       = InitializationKind::CreateDirect(Constructor->getLocation(),
4928                                          SourceLocation(), SourceLocation());
4929     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4930     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4931     break;
4932   }
4933   }
4934 
4935   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4936   if (BaseInit.isInvalid())
4937     return true;
4938 
4939   CXXBaseInit =
4940     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4941                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4942                                                         SourceLocation()),
4943                                              BaseSpec->isVirtual(),
4944                                              SourceLocation(),
4945                                              BaseInit.getAs<Expr>(),
4946                                              SourceLocation(),
4947                                              SourceLocation());
4948 
4949   return false;
4950 }
4951 
RefersToRValueRef(Expr * MemRef)4952 static bool RefersToRValueRef(Expr *MemRef) {
4953   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4954   return Referenced->getType()->isRValueReferenceType();
4955 }
4956 
4957 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)4958 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4959                                ImplicitInitializerKind ImplicitInitKind,
4960                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4961                                CXXCtorInitializer *&CXXMemberInit) {
4962   if (Field->isInvalidDecl())
4963     return true;
4964 
4965   SourceLocation Loc = Constructor->getLocation();
4966 
4967   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4968     bool Moving = ImplicitInitKind == IIK_Move;
4969     ParmVarDecl *Param = Constructor->getParamDecl(0);
4970     QualType ParamType = Param->getType().getNonReferenceType();
4971 
4972     // Suppress copying zero-width bitfields.
4973     if (Field->isZeroLengthBitField())
4974       return false;
4975 
4976     Expr *MemberExprBase =
4977       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4978                           SourceLocation(), Param, false,
4979                           Loc, ParamType, VK_LValue, nullptr);
4980 
4981     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4982 
4983     if (Moving) {
4984       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4985     }
4986 
4987     // Build a reference to this field within the parameter.
4988     CXXScopeSpec SS;
4989     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4990                               Sema::LookupMemberName);
4991     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4992                                   : cast<ValueDecl>(Field), AS_public);
4993     MemberLookup.resolveKind();
4994     ExprResult CtorArg
4995       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4996                                          ParamType, Loc,
4997                                          /*IsArrow=*/false,
4998                                          SS,
4999                                          /*TemplateKWLoc=*/SourceLocation(),
5000                                          /*FirstQualifierInScope=*/nullptr,
5001                                          MemberLookup,
5002                                          /*TemplateArgs=*/nullptr,
5003                                          /*S*/nullptr);
5004     if (CtorArg.isInvalid())
5005       return true;
5006 
5007     // C++11 [class.copy]p15:
5008     //   - if a member m has rvalue reference type T&&, it is direct-initialized
5009     //     with static_cast<T&&>(x.m);
5010     if (RefersToRValueRef(CtorArg.get())) {
5011       CtorArg = CastForMoving(SemaRef, CtorArg.get());
5012     }
5013 
5014     InitializedEntity Entity =
5015         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5016                                                        /*Implicit*/ true)
5017                  : InitializedEntity::InitializeMember(Field, nullptr,
5018                                                        /*Implicit*/ true);
5019 
5020     // Direct-initialize to use the copy constructor.
5021     InitializationKind InitKind =
5022       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
5023 
5024     Expr *CtorArgE = CtorArg.getAs<Expr>();
5025     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5026     ExprResult MemberInit =
5027         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5028     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5029     if (MemberInit.isInvalid())
5030       return true;
5031 
5032     if (Indirect)
5033       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5034           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5035     else
5036       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5037           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5038     return false;
5039   }
5040 
5041   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5042          "Unhandled implicit init kind!");
5043 
5044   QualType FieldBaseElementType =
5045     SemaRef.Context.getBaseElementType(Field->getType());
5046 
5047   if (FieldBaseElementType->isRecordType()) {
5048     InitializedEntity InitEntity =
5049         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5050                                                        /*Implicit*/ true)
5051                  : InitializedEntity::InitializeMember(Field, nullptr,
5052                                                        /*Implicit*/ true);
5053     InitializationKind InitKind =
5054       InitializationKind::CreateDefault(Loc);
5055 
5056     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5057     ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5058 
5059     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5060     if (MemberInit.isInvalid())
5061       return true;
5062 
5063     if (Indirect)
5064       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5065                                                                Indirect, Loc,
5066                                                                Loc,
5067                                                                MemberInit.get(),
5068                                                                Loc);
5069     else
5070       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5071                                                                Field, Loc, Loc,
5072                                                                MemberInit.get(),
5073                                                                Loc);
5074     return false;
5075   }
5076 
5077   if (!Field->getParent()->isUnion()) {
5078     if (FieldBaseElementType->isReferenceType()) {
5079       SemaRef.Diag(Constructor->getLocation(),
5080                    diag::err_uninitialized_member_in_ctor)
5081       << (int)Constructor->isImplicit()
5082       << SemaRef.Context.getTagDeclType(Constructor->getParent())
5083       << 0 << Field->getDeclName();
5084       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5085       return true;
5086     }
5087 
5088     if (FieldBaseElementType.isConstQualified()) {
5089       SemaRef.Diag(Constructor->getLocation(),
5090                    diag::err_uninitialized_member_in_ctor)
5091       << (int)Constructor->isImplicit()
5092       << SemaRef.Context.getTagDeclType(Constructor->getParent())
5093       << 1 << Field->getDeclName();
5094       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5095       return true;
5096     }
5097   }
5098 
5099   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5100     // ARC and Weak:
5101     //   Default-initialize Objective-C pointers to NULL.
5102     CXXMemberInit
5103       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5104                                                  Loc, Loc,
5105                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5106                                                  Loc);
5107     return false;
5108   }
5109 
5110   // Nothing to initialize.
5111   CXXMemberInit = nullptr;
5112   return false;
5113 }
5114 
5115 namespace {
5116 struct BaseAndFieldInfo {
5117   Sema &S;
5118   CXXConstructorDecl *Ctor;
5119   bool AnyErrorsInInits;
5120   ImplicitInitializerKind IIK;
5121   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5122   SmallVector<CXXCtorInitializer*, 8> AllToInit;
5123   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5124 
BaseAndFieldInfo__anon42c808801211::BaseAndFieldInfo5125   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5126     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5127     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5128     if (Ctor->getInheritedConstructor())
5129       IIK = IIK_Inherit;
5130     else if (Generated && Ctor->isCopyConstructor())
5131       IIK = IIK_Copy;
5132     else if (Generated && Ctor->isMoveConstructor())
5133       IIK = IIK_Move;
5134     else
5135       IIK = IIK_Default;
5136   }
5137 
isImplicitCopyOrMove__anon42c808801211::BaseAndFieldInfo5138   bool isImplicitCopyOrMove() const {
5139     switch (IIK) {
5140     case IIK_Copy:
5141     case IIK_Move:
5142       return true;
5143 
5144     case IIK_Default:
5145     case IIK_Inherit:
5146       return false;
5147     }
5148 
5149     llvm_unreachable("Invalid ImplicitInitializerKind!");
5150   }
5151 
addFieldInitializer__anon42c808801211::BaseAndFieldInfo5152   bool addFieldInitializer(CXXCtorInitializer *Init) {
5153     AllToInit.push_back(Init);
5154 
5155     // Check whether this initializer makes the field "used".
5156     if (Init->getInit()->HasSideEffects(S.Context))
5157       S.UnusedPrivateFields.remove(Init->getAnyMember());
5158 
5159     return false;
5160   }
5161 
isInactiveUnionMember__anon42c808801211::BaseAndFieldInfo5162   bool isInactiveUnionMember(FieldDecl *Field) {
5163     RecordDecl *Record = Field->getParent();
5164     if (!Record->isUnion())
5165       return false;
5166 
5167     if (FieldDecl *Active =
5168             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5169       return Active != Field->getCanonicalDecl();
5170 
5171     // In an implicit copy or move constructor, ignore any in-class initializer.
5172     if (isImplicitCopyOrMove())
5173       return true;
5174 
5175     // If there's no explicit initialization, the field is active only if it
5176     // has an in-class initializer...
5177     if (Field->hasInClassInitializer())
5178       return false;
5179     // ... or it's an anonymous struct or union whose class has an in-class
5180     // initializer.
5181     if (!Field->isAnonymousStructOrUnion())
5182       return true;
5183     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5184     return !FieldRD->hasInClassInitializer();
5185   }
5186 
5187   /// Determine whether the given field is, or is within, a union member
5188   /// that is inactive (because there was an initializer given for a different
5189   /// member of the union, or because the union was not initialized at all).
isWithinInactiveUnionMember__anon42c808801211::BaseAndFieldInfo5190   bool isWithinInactiveUnionMember(FieldDecl *Field,
5191                                    IndirectFieldDecl *Indirect) {
5192     if (!Indirect)
5193       return isInactiveUnionMember(Field);
5194 
5195     for (auto *C : Indirect->chain()) {
5196       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5197       if (Field && isInactiveUnionMember(Field))
5198         return true;
5199     }
5200     return false;
5201   }
5202 };
5203 }
5204 
5205 /// Determine whether the given type is an incomplete or zero-lenfgth
5206 /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)5207 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5208   if (T->isIncompleteArrayType())
5209     return true;
5210 
5211   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5212     if (ArrayT->isZeroSize())
5213       return true;
5214 
5215     T = ArrayT->getElementType();
5216   }
5217 
5218   return false;
5219 }
5220 
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=nullptr)5221 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5222                                     FieldDecl *Field,
5223                                     IndirectFieldDecl *Indirect = nullptr) {
5224   if (Field->isInvalidDecl())
5225     return false;
5226 
5227   // Overwhelmingly common case: we have a direct initializer for this field.
5228   if (CXXCtorInitializer *Init =
5229           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5230     return Info.addFieldInitializer(Init);
5231 
5232   // C++11 [class.base.init]p8:
5233   //   if the entity is a non-static data member that has a
5234   //   brace-or-equal-initializer and either
5235   //   -- the constructor's class is a union and no other variant member of that
5236   //      union is designated by a mem-initializer-id or
5237   //   -- the constructor's class is not a union, and, if the entity is a member
5238   //      of an anonymous union, no other member of that union is designated by
5239   //      a mem-initializer-id,
5240   //   the entity is initialized as specified in [dcl.init].
5241   //
5242   // We also apply the same rules to handle anonymous structs within anonymous
5243   // unions.
5244   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5245     return false;
5246 
5247   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5248     ExprResult DIE =
5249         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5250     if (DIE.isInvalid())
5251       return true;
5252 
5253     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5254     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5255 
5256     CXXCtorInitializer *Init;
5257     if (Indirect)
5258       Init = new (SemaRef.Context)
5259           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5260                              SourceLocation(), DIE.get(), SourceLocation());
5261     else
5262       Init = new (SemaRef.Context)
5263           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5264                              SourceLocation(), DIE.get(), SourceLocation());
5265     return Info.addFieldInitializer(Init);
5266   }
5267 
5268   // Don't initialize incomplete or zero-length arrays.
5269   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5270     return false;
5271 
5272   // Don't try to build an implicit initializer if there were semantic
5273   // errors in any of the initializers (and therefore we might be
5274   // missing some that the user actually wrote).
5275   if (Info.AnyErrorsInInits)
5276     return false;
5277 
5278   CXXCtorInitializer *Init = nullptr;
5279   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5280                                      Indirect, Init))
5281     return true;
5282 
5283   if (!Init)
5284     return false;
5285 
5286   return Info.addFieldInitializer(Init);
5287 }
5288 
5289 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)5290 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5291                                CXXCtorInitializer *Initializer) {
5292   assert(Initializer->isDelegatingInitializer());
5293   Constructor->setNumCtorInitializers(1);
5294   CXXCtorInitializer **initializer =
5295     new (Context) CXXCtorInitializer*[1];
5296   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5297   Constructor->setCtorInitializers(initializer);
5298 
5299   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5300     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5301     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5302   }
5303 
5304   DelegatingCtorDecls.push_back(Constructor);
5305 
5306   DiagnoseUninitializedFields(*this, Constructor);
5307 
5308   return false;
5309 }
5310 
LookupDestructorIfRelevant(Sema & S,CXXRecordDecl * Class)5311 static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5312                                                      CXXRecordDecl *Class) {
5313   if (Class->isInvalidDecl())
5314     return nullptr;
5315   if (Class->hasIrrelevantDestructor())
5316     return nullptr;
5317 
5318   // Dtor might still be missing, e.g because it's invalid.
5319   return S.LookupDestructor(Class);
5320 }
5321 
MarkFieldDestructorReferenced(Sema & S,SourceLocation Location,FieldDecl * Field)5322 static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5323                                           FieldDecl *Field) {
5324   if (Field->isInvalidDecl())
5325     return;
5326 
5327   // Don't destroy incomplete or zero-length arrays.
5328   if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5329     return;
5330 
5331   QualType FieldType = S.Context.getBaseElementType(Field->getType());
5332 
5333   auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5334   if (!FieldClassDecl)
5335     return;
5336 
5337   // The destructor for an implicit anonymous union member is never invoked.
5338   if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5339     return;
5340 
5341   auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5342   if (!Dtor)
5343     return;
5344 
5345   S.CheckDestructorAccess(Field->getLocation(), Dtor,
5346                           S.PDiag(diag::err_access_dtor_field)
5347                               << Field->getDeclName() << FieldType);
5348 
5349   S.MarkFunctionReferenced(Location, Dtor);
5350   S.DiagnoseUseOfDecl(Dtor, Location);
5351 }
5352 
MarkBaseDestructorsReferenced(Sema & S,SourceLocation Location,CXXRecordDecl * ClassDecl)5353 static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5354                                           CXXRecordDecl *ClassDecl) {
5355   if (ClassDecl->isDependentContext())
5356     return;
5357 
5358   // We only potentially invoke the destructors of potentially constructed
5359   // subobjects.
5360   bool VisitVirtualBases = !ClassDecl->isAbstract();
5361 
5362   // If the destructor exists and has already been marked used in the MS ABI,
5363   // then virtual base destructors have already been checked and marked used.
5364   // Skip checking them again to avoid duplicate diagnostics.
5365   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5366     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5367     if (Dtor && Dtor->isUsed())
5368       VisitVirtualBases = false;
5369   }
5370 
5371   llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5372 
5373   // Bases.
5374   for (const auto &Base : ClassDecl->bases()) {
5375     auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5376     if (!BaseClassDecl)
5377       continue;
5378 
5379     // Remember direct virtual bases.
5380     if (Base.isVirtual()) {
5381       if (!VisitVirtualBases)
5382         continue;
5383       DirectVirtualBases.insert(BaseClassDecl);
5384     }
5385 
5386     auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5387     if (!Dtor)
5388       continue;
5389 
5390     // FIXME: caret should be on the start of the class name
5391     S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5392                             S.PDiag(diag::err_access_dtor_base)
5393                                 << Base.getType() << Base.getSourceRange(),
5394                             S.Context.getTypeDeclType(ClassDecl));
5395 
5396     S.MarkFunctionReferenced(Location, Dtor);
5397     S.DiagnoseUseOfDecl(Dtor, Location);
5398   }
5399 
5400   if (VisitVirtualBases)
5401     S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5402                                            &DirectVirtualBases);
5403 }
5404 
SetCtorInitializers(CXXConstructorDecl * Constructor,bool AnyErrors,ArrayRef<CXXCtorInitializer * > Initializers)5405 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5406                                ArrayRef<CXXCtorInitializer *> Initializers) {
5407   if (Constructor->isDependentContext()) {
5408     // Just store the initializers as written, they will be checked during
5409     // instantiation.
5410     if (!Initializers.empty()) {
5411       Constructor->setNumCtorInitializers(Initializers.size());
5412       CXXCtorInitializer **baseOrMemberInitializers =
5413         new (Context) CXXCtorInitializer*[Initializers.size()];
5414       memcpy(baseOrMemberInitializers, Initializers.data(),
5415              Initializers.size() * sizeof(CXXCtorInitializer*));
5416       Constructor->setCtorInitializers(baseOrMemberInitializers);
5417     }
5418 
5419     // Let template instantiation know whether we had errors.
5420     if (AnyErrors)
5421       Constructor->setInvalidDecl();
5422 
5423     return false;
5424   }
5425 
5426   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5427 
5428   // We need to build the initializer AST according to order of construction
5429   // and not what user specified in the Initializers list.
5430   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5431   if (!ClassDecl)
5432     return true;
5433 
5434   bool HadError = false;
5435 
5436   for (unsigned i = 0; i < Initializers.size(); i++) {
5437     CXXCtorInitializer *Member = Initializers[i];
5438 
5439     if (Member->isBaseInitializer())
5440       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5441     else {
5442       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5443 
5444       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5445         for (auto *C : F->chain()) {
5446           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5447           if (FD && FD->getParent()->isUnion())
5448             Info.ActiveUnionMember.insert(std::make_pair(
5449                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5450         }
5451       } else if (FieldDecl *FD = Member->getMember()) {
5452         if (FD->getParent()->isUnion())
5453           Info.ActiveUnionMember.insert(std::make_pair(
5454               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5455       }
5456     }
5457   }
5458 
5459   // Keep track of the direct virtual bases.
5460   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5461   for (auto &I : ClassDecl->bases()) {
5462     if (I.isVirtual())
5463       DirectVBases.insert(&I);
5464   }
5465 
5466   // Push virtual bases before others.
5467   for (auto &VBase : ClassDecl->vbases()) {
5468     if (CXXCtorInitializer *Value
5469         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5470       // [class.base.init]p7, per DR257:
5471       //   A mem-initializer where the mem-initializer-id names a virtual base
5472       //   class is ignored during execution of a constructor of any class that
5473       //   is not the most derived class.
5474       if (ClassDecl->isAbstract()) {
5475         // FIXME: Provide a fixit to remove the base specifier. This requires
5476         // tracking the location of the associated comma for a base specifier.
5477         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5478           << VBase.getType() << ClassDecl;
5479         DiagnoseAbstractType(ClassDecl);
5480       }
5481 
5482       Info.AllToInit.push_back(Value);
5483     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5484       // [class.base.init]p8, per DR257:
5485       //   If a given [...] base class is not named by a mem-initializer-id
5486       //   [...] and the entity is not a virtual base class of an abstract
5487       //   class, then [...] the entity is default-initialized.
5488       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5489       CXXCtorInitializer *CXXBaseInit;
5490       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5491                                        &VBase, IsInheritedVirtualBase,
5492                                        CXXBaseInit)) {
5493         HadError = true;
5494         continue;
5495       }
5496 
5497       Info.AllToInit.push_back(CXXBaseInit);
5498     }
5499   }
5500 
5501   // Non-virtual bases.
5502   for (auto &Base : ClassDecl->bases()) {
5503     // Virtuals are in the virtual base list and already constructed.
5504     if (Base.isVirtual())
5505       continue;
5506 
5507     if (CXXCtorInitializer *Value
5508           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5509       Info.AllToInit.push_back(Value);
5510     } else if (!AnyErrors) {
5511       CXXCtorInitializer *CXXBaseInit;
5512       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5513                                        &Base, /*IsInheritedVirtualBase=*/false,
5514                                        CXXBaseInit)) {
5515         HadError = true;
5516         continue;
5517       }
5518 
5519       Info.AllToInit.push_back(CXXBaseInit);
5520     }
5521   }
5522 
5523   // Fields.
5524   for (auto *Mem : ClassDecl->decls()) {
5525     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5526       // C++ [class.bit]p2:
5527       //   A declaration for a bit-field that omits the identifier declares an
5528       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5529       //   initialized.
5530       if (F->isUnnamedBitField())
5531         continue;
5532 
5533       // If we're not generating the implicit copy/move constructor, then we'll
5534       // handle anonymous struct/union fields based on their individual
5535       // indirect fields.
5536       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5537         continue;
5538 
5539       if (CollectFieldInitializer(*this, Info, F))
5540         HadError = true;
5541       continue;
5542     }
5543 
5544     // Beyond this point, we only consider default initialization.
5545     if (Info.isImplicitCopyOrMove())
5546       continue;
5547 
5548     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5549       if (F->getType()->isIncompleteArrayType()) {
5550         assert(ClassDecl->hasFlexibleArrayMember() &&
5551                "Incomplete array type is not valid");
5552         continue;
5553       }
5554 
5555       // Initialize each field of an anonymous struct individually.
5556       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5557         HadError = true;
5558 
5559       continue;
5560     }
5561   }
5562 
5563   unsigned NumInitializers = Info.AllToInit.size();
5564   if (NumInitializers > 0) {
5565     Constructor->setNumCtorInitializers(NumInitializers);
5566     CXXCtorInitializer **baseOrMemberInitializers =
5567       new (Context) CXXCtorInitializer*[NumInitializers];
5568     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5569            NumInitializers * sizeof(CXXCtorInitializer*));
5570     Constructor->setCtorInitializers(baseOrMemberInitializers);
5571 
5572     SourceLocation Location = Constructor->getLocation();
5573 
5574     // Constructors implicitly reference the base and member
5575     // destructors.
5576 
5577     for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5578       FieldDecl *Field = Initializer->getAnyMember();
5579       if (!Field)
5580         continue;
5581 
5582       // C++ [class.base.init]p12:
5583       //   In a non-delegating constructor, the destructor for each
5584       //   potentially constructed subobject of class type is potentially
5585       //   invoked.
5586       MarkFieldDestructorReferenced(*this, Location, Field);
5587     }
5588 
5589     MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5590   }
5591 
5592   return HadError;
5593 }
5594 
PopulateKeysForFields(FieldDecl * Field,SmallVectorImpl<const void * > & IdealInits)5595 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5596   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5597     const RecordDecl *RD = RT->getDecl();
5598     if (RD->isAnonymousStructOrUnion()) {
5599       for (auto *Field : RD->fields())
5600         PopulateKeysForFields(Field, IdealInits);
5601       return;
5602     }
5603   }
5604   IdealInits.push_back(Field->getCanonicalDecl());
5605 }
5606 
GetKeyForBase(ASTContext & Context,QualType BaseType)5607 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5608   return Context.getCanonicalType(BaseType).getTypePtr();
5609 }
5610 
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)5611 static const void *GetKeyForMember(ASTContext &Context,
5612                                    CXXCtorInitializer *Member) {
5613   if (!Member->isAnyMemberInitializer())
5614     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5615 
5616   return Member->getAnyMember()->getCanonicalDecl();
5617 }
5618 
AddInitializerToDiag(const Sema::SemaDiagnosticBuilder & Diag,const CXXCtorInitializer * Previous,const CXXCtorInitializer * Current)5619 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5620                                  const CXXCtorInitializer *Previous,
5621                                  const CXXCtorInitializer *Current) {
5622   if (Previous->isAnyMemberInitializer())
5623     Diag << 0 << Previous->getAnyMember();
5624   else
5625     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5626 
5627   if (Current->isAnyMemberInitializer())
5628     Diag << 0 << Current->getAnyMember();
5629   else
5630     Diag << 1 << Current->getTypeSourceInfo()->getType();
5631 }
5632 
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,ArrayRef<CXXCtorInitializer * > Inits)5633 static void DiagnoseBaseOrMemInitializerOrder(
5634     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5635     ArrayRef<CXXCtorInitializer *> Inits) {
5636   if (Constructor->getDeclContext()->isDependentContext())
5637     return;
5638 
5639   // Don't check initializers order unless the warning is enabled at the
5640   // location of at least one initializer.
5641   bool ShouldCheckOrder = false;
5642   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5643     CXXCtorInitializer *Init = Inits[InitIndex];
5644     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5645                                  Init->getSourceLocation())) {
5646       ShouldCheckOrder = true;
5647       break;
5648     }
5649   }
5650   if (!ShouldCheckOrder)
5651     return;
5652 
5653   // Build the list of bases and members in the order that they'll
5654   // actually be initialized.  The explicit initializers should be in
5655   // this same order but may be missing things.
5656   SmallVector<const void*, 32> IdealInitKeys;
5657 
5658   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5659 
5660   // 1. Virtual bases.
5661   for (const auto &VBase : ClassDecl->vbases())
5662     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5663 
5664   // 2. Non-virtual bases.
5665   for (const auto &Base : ClassDecl->bases()) {
5666     if (Base.isVirtual())
5667       continue;
5668     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5669   }
5670 
5671   // 3. Direct fields.
5672   for (auto *Field : ClassDecl->fields()) {
5673     if (Field->isUnnamedBitField())
5674       continue;
5675 
5676     PopulateKeysForFields(Field, IdealInitKeys);
5677   }
5678 
5679   unsigned NumIdealInits = IdealInitKeys.size();
5680   unsigned IdealIndex = 0;
5681 
5682   // Track initializers that are in an incorrect order for either a warning or
5683   // note if multiple ones occur.
5684   SmallVector<unsigned> WarnIndexes;
5685   // Correlates the index of an initializer in the init-list to the index of
5686   // the field/base in the class.
5687   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5688 
5689   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5690     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5691 
5692     // Scan forward to try to find this initializer in the idealized
5693     // initializers list.
5694     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5695       if (InitKey == IdealInitKeys[IdealIndex])
5696         break;
5697 
5698     // If we didn't find this initializer, it must be because we
5699     // scanned past it on a previous iteration.  That can only
5700     // happen if we're out of order;  emit a warning.
5701     if (IdealIndex == NumIdealInits && InitIndex) {
5702       WarnIndexes.push_back(InitIndex);
5703 
5704       // Move back to the initializer's location in the ideal list.
5705       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5706         if (InitKey == IdealInitKeys[IdealIndex])
5707           break;
5708 
5709       assert(IdealIndex < NumIdealInits &&
5710              "initializer not found in initializer list");
5711     }
5712     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5713   }
5714 
5715   if (WarnIndexes.empty())
5716     return;
5717 
5718   // Sort based on the ideal order, first in the pair.
5719   llvm::sort(CorrelatedInitOrder, llvm::less_first());
5720 
5721   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5722   // emit the diagnostic before we can try adding notes.
5723   {
5724     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5725         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5726         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5727                                 : diag::warn_some_initializers_out_of_order);
5728 
5729     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5730       if (CorrelatedInitOrder[I].second == I)
5731         continue;
5732       // Ideally we would be using InsertFromRange here, but clang doesn't
5733       // appear to handle InsertFromRange correctly when the source range is
5734       // modified by another fix-it.
5735       D << FixItHint::CreateReplacement(
5736           Inits[I]->getSourceRange(),
5737           Lexer::getSourceText(
5738               CharSourceRange::getTokenRange(
5739                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5740               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5741     }
5742 
5743     // If there is only 1 item out of order, the warning expects the name and
5744     // type of each being added to it.
5745     if (WarnIndexes.size() == 1) {
5746       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5747                            Inits[WarnIndexes.front()]);
5748       return;
5749     }
5750   }
5751   // More than 1 item to warn, create notes letting the user know which ones
5752   // are bad.
5753   for (unsigned WarnIndex : WarnIndexes) {
5754     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5755     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5756                           diag::note_initializer_out_of_order);
5757     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5758     D << PrevInit->getSourceRange();
5759   }
5760 }
5761 
5762 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)5763 bool CheckRedundantInit(Sema &S,
5764                         CXXCtorInitializer *Init,
5765                         CXXCtorInitializer *&PrevInit) {
5766   if (!PrevInit) {
5767     PrevInit = Init;
5768     return false;
5769   }
5770 
5771   if (FieldDecl *Field = Init->getAnyMember())
5772     S.Diag(Init->getSourceLocation(),
5773            diag::err_multiple_mem_initialization)
5774       << Field->getDeclName()
5775       << Init->getSourceRange();
5776   else {
5777     const Type *BaseClass = Init->getBaseClass();
5778     assert(BaseClass && "neither field nor base");
5779     S.Diag(Init->getSourceLocation(),
5780            diag::err_multiple_base_initialization)
5781       << QualType(BaseClass, 0)
5782       << Init->getSourceRange();
5783   }
5784   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5785     << 0 << PrevInit->getSourceRange();
5786 
5787   return true;
5788 }
5789 
5790 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5791 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5792 
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)5793 bool CheckRedundantUnionInit(Sema &S,
5794                              CXXCtorInitializer *Init,
5795                              RedundantUnionMap &Unions) {
5796   FieldDecl *Field = Init->getAnyMember();
5797   RecordDecl *Parent = Field->getParent();
5798   NamedDecl *Child = Field;
5799 
5800   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5801     if (Parent->isUnion()) {
5802       UnionEntry &En = Unions[Parent];
5803       if (En.first && En.first != Child) {
5804         S.Diag(Init->getSourceLocation(),
5805                diag::err_multiple_mem_union_initialization)
5806           << Field->getDeclName()
5807           << Init->getSourceRange();
5808         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5809           << 0 << En.second->getSourceRange();
5810         return true;
5811       }
5812       if (!En.first) {
5813         En.first = Child;
5814         En.second = Init;
5815       }
5816       if (!Parent->isAnonymousStructOrUnion())
5817         return false;
5818     }
5819 
5820     Child = Parent;
5821     Parent = cast<RecordDecl>(Parent->getDeclContext());
5822   }
5823 
5824   return false;
5825 }
5826 } // namespace
5827 
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,ArrayRef<CXXCtorInitializer * > MemInits,bool AnyErrors)5828 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5829                                 SourceLocation ColonLoc,
5830                                 ArrayRef<CXXCtorInitializer*> MemInits,
5831                                 bool AnyErrors) {
5832   if (!ConstructorDecl)
5833     return;
5834 
5835   AdjustDeclIfTemplate(ConstructorDecl);
5836 
5837   CXXConstructorDecl *Constructor
5838     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5839 
5840   if (!Constructor) {
5841     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5842     return;
5843   }
5844 
5845   // Mapping for the duplicate initializers check.
5846   // For member initializers, this is keyed with a FieldDecl*.
5847   // For base initializers, this is keyed with a Type*.
5848   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5849 
5850   // Mapping for the inconsistent anonymous-union initializers check.
5851   RedundantUnionMap MemberUnions;
5852 
5853   bool HadError = false;
5854   for (unsigned i = 0; i < MemInits.size(); i++) {
5855     CXXCtorInitializer *Init = MemInits[i];
5856 
5857     // Set the source order index.
5858     Init->setSourceOrder(i);
5859 
5860     if (Init->isAnyMemberInitializer()) {
5861       const void *Key = GetKeyForMember(Context, Init);
5862       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5863           CheckRedundantUnionInit(*this, Init, MemberUnions))
5864         HadError = true;
5865     } else if (Init->isBaseInitializer()) {
5866       const void *Key = GetKeyForMember(Context, Init);
5867       if (CheckRedundantInit(*this, Init, Members[Key]))
5868         HadError = true;
5869     } else {
5870       assert(Init->isDelegatingInitializer());
5871       // This must be the only initializer
5872       if (MemInits.size() != 1) {
5873         Diag(Init->getSourceLocation(),
5874              diag::err_delegating_initializer_alone)
5875           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5876         // We will treat this as being the only initializer.
5877       }
5878       SetDelegatingInitializer(Constructor, MemInits[i]);
5879       // Return immediately as the initializer is set.
5880       return;
5881     }
5882   }
5883 
5884   if (HadError)
5885     return;
5886 
5887   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5888 
5889   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5890 
5891   DiagnoseUninitializedFields(*this, Constructor);
5892 }
5893 
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)5894 void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5895                                                   CXXRecordDecl *ClassDecl) {
5896   // Ignore dependent contexts. Also ignore unions, since their members never
5897   // have destructors implicitly called.
5898   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5899     return;
5900 
5901   // FIXME: all the access-control diagnostics are positioned on the
5902   // field/base declaration.  That's probably good; that said, the
5903   // user might reasonably want to know why the destructor is being
5904   // emitted, and we currently don't say.
5905 
5906   // Non-static data members.
5907   for (auto *Field : ClassDecl->fields()) {
5908     MarkFieldDestructorReferenced(*this, Location, Field);
5909   }
5910 
5911   MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5912 }
5913 
MarkVirtualBaseDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl,llvm::SmallPtrSetImpl<const CXXRecordDecl * > * DirectVirtualBases)5914 void Sema::MarkVirtualBaseDestructorsReferenced(
5915     SourceLocation Location, CXXRecordDecl *ClassDecl,
5916     llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5917   // Virtual bases.
5918   for (const auto &VBase : ClassDecl->vbases()) {
5919     auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5920     if (!BaseClassDecl)
5921       continue;
5922 
5923     // Ignore already visited direct virtual bases.
5924     if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5925       continue;
5926 
5927     auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5928     if (!Dtor)
5929       continue;
5930 
5931     if (CheckDestructorAccess(
5932             ClassDecl->getLocation(), Dtor,
5933             PDiag(diag::err_access_dtor_vbase)
5934                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5935             Context.getTypeDeclType(ClassDecl)) ==
5936         AR_accessible) {
5937       CheckDerivedToBaseConversion(
5938           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5939           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5940           SourceRange(), DeclarationName(), nullptr);
5941     }
5942 
5943     MarkFunctionReferenced(Location, Dtor);
5944     DiagnoseUseOfDecl(Dtor, Location);
5945   }
5946 }
5947 
ActOnDefaultCtorInitializers(Decl * CDtorDecl)5948 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5949   if (!CDtorDecl)
5950     return;
5951 
5952   if (CXXConstructorDecl *Constructor
5953       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5954     if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5955         !ClassDecl || ClassDecl->isInvalidDecl()) {
5956       return;
5957     }
5958     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5959     DiagnoseUninitializedFields(*this, Constructor);
5960   }
5961 }
5962 
isAbstractType(SourceLocation Loc,QualType T)5963 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5964   if (!getLangOpts().CPlusPlus)
5965     return false;
5966 
5967   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5968   if (!RD)
5969     return false;
5970 
5971   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5972   // class template specialization here, but doing so breaks a lot of code.
5973 
5974   // We can't answer whether something is abstract until it has a
5975   // definition. If it's currently being defined, we'll walk back
5976   // over all the declarations when we have a full definition.
5977   const CXXRecordDecl *Def = RD->getDefinition();
5978   if (!Def || Def->isBeingDefined())
5979     return false;
5980 
5981   return RD->isAbstract();
5982 }
5983 
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5984 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5985                                   TypeDiagnoser &Diagnoser) {
5986   if (!isAbstractType(Loc, T))
5987     return false;
5988 
5989   T = Context.getBaseElementType(T);
5990   Diagnoser.diagnose(*this, Loc, T);
5991   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5992   return true;
5993 }
5994 
DiagnoseAbstractType(const CXXRecordDecl * RD)5995 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5996   // Check if we've already emitted the list of pure virtual functions
5997   // for this class.
5998   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5999     return;
6000 
6001   // If the diagnostic is suppressed, don't emit the notes. We're only
6002   // going to emit them once, so try to attach them to a diagnostic we're
6003   // actually going to show.
6004   if (Diags.isLastDiagnosticIgnored())
6005     return;
6006 
6007   CXXFinalOverriderMap FinalOverriders;
6008   RD->getFinalOverriders(FinalOverriders);
6009 
6010   // Keep a set of seen pure methods so we won't diagnose the same method
6011   // more than once.
6012   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6013 
6014   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6015                                    MEnd = FinalOverriders.end();
6016        M != MEnd;
6017        ++M) {
6018     for (OverridingMethods::iterator SO = M->second.begin(),
6019                                   SOEnd = M->second.end();
6020          SO != SOEnd; ++SO) {
6021       // C++ [class.abstract]p4:
6022       //   A class is abstract if it contains or inherits at least one
6023       //   pure virtual function for which the final overrider is pure
6024       //   virtual.
6025 
6026       //
6027       if (SO->second.size() != 1)
6028         continue;
6029 
6030       if (!SO->second.front().Method->isPureVirtual())
6031         continue;
6032 
6033       if (!SeenPureMethods.insert(SO->second.front().Method).second)
6034         continue;
6035 
6036       Diag(SO->second.front().Method->getLocation(),
6037            diag::note_pure_virtual_function)
6038         << SO->second.front().Method->getDeclName() << RD->getDeclName();
6039     }
6040   }
6041 
6042   if (!PureVirtualClassDiagSet)
6043     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
6044   PureVirtualClassDiagSet->insert(RD);
6045 }
6046 
6047 namespace {
6048 struct AbstractUsageInfo {
6049   Sema &S;
6050   CXXRecordDecl *Record;
6051   CanQualType AbstractType;
6052   bool Invalid;
6053 
AbstractUsageInfo__anon42c808801411::AbstractUsageInfo6054   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6055     : S(S), Record(Record),
6056       AbstractType(S.Context.getCanonicalType(
6057                    S.Context.getTypeDeclType(Record))),
6058       Invalid(false) {}
6059 
DiagnoseAbstractType__anon42c808801411::AbstractUsageInfo6060   void DiagnoseAbstractType() {
6061     if (Invalid) return;
6062     S.DiagnoseAbstractType(Record);
6063     Invalid = true;
6064   }
6065 
6066   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6067 };
6068 
6069 struct CheckAbstractUsage {
6070   AbstractUsageInfo &Info;
6071   const NamedDecl *Ctx;
6072 
CheckAbstractUsage__anon42c808801411::CheckAbstractUsage6073   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6074     : Info(Info), Ctx(Ctx) {}
6075 
Visit__anon42c808801411::CheckAbstractUsage6076   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6077     switch (TL.getTypeLocClass()) {
6078 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6079 #define TYPELOC(CLASS, PARENT) \
6080     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6081 #include "clang/AST/TypeLocNodes.def"
6082     }
6083   }
6084 
Check__anon42c808801411::CheckAbstractUsage6085   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6086     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
6087     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6088       if (!TL.getParam(I))
6089         continue;
6090 
6091       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6092       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6093     }
6094   }
6095 
Check__anon42c808801411::CheckAbstractUsage6096   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6097     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
6098   }
6099 
Check__anon42c808801411::CheckAbstractUsage6100   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6101     // Visit the type parameters from a permissive context.
6102     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6103       TemplateArgumentLoc TAL = TL.getArgLoc(I);
6104       if (TAL.getArgument().getKind() == TemplateArgument::Type)
6105         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6106           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6107       // TODO: other template argument types?
6108     }
6109   }
6110 
6111   // Visit pointee types from a permissive context.
6112 #define CheckPolymorphic(Type) \
6113   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6114     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6115   }
6116   CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon42c808801411::CheckAbstractUsage6117   CheckPolymorphic(ReferenceTypeLoc)
6118   CheckPolymorphic(MemberPointerTypeLoc)
6119   CheckPolymorphic(BlockPointerTypeLoc)
6120   CheckPolymorphic(AtomicTypeLoc)
6121 
6122   /// Handle all the types we haven't given a more specific
6123   /// implementation for above.
6124   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6125     // Every other kind of type that we haven't called out already
6126     // that has an inner type is either (1) sugar or (2) contains that
6127     // inner type in some way as a subobject.
6128     if (TypeLoc Next = TL.getNextTypeLoc())
6129       return Visit(Next, Sel);
6130 
6131     // If there's no inner type and we're in a permissive context,
6132     // don't diagnose.
6133     if (Sel == Sema::AbstractNone) return;
6134 
6135     // Check whether the type matches the abstract type.
6136     QualType T = TL.getType();
6137     if (T->isArrayType()) {
6138       Sel = Sema::AbstractArrayType;
6139       T = Info.S.Context.getBaseElementType(T);
6140     }
6141     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6142     if (CT != Info.AbstractType) return;
6143 
6144     // It matched; do some magic.
6145     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6146     if (Sel == Sema::AbstractArrayType) {
6147       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6148         << T << TL.getSourceRange();
6149     } else {
6150       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6151         << Sel << T << TL.getSourceRange();
6152     }
6153     Info.DiagnoseAbstractType();
6154   }
6155 };
6156 
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)6157 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6158                                   Sema::AbstractDiagSelID Sel) {
6159   CheckAbstractUsage(*this, D).Visit(TL, Sel);
6160 }
6161 
6162 }
6163 
6164 /// Check for invalid uses of an abstract type in a function declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,FunctionDecl * FD)6165 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6166                                     FunctionDecl *FD) {
6167   // Only definitions are required to refer to complete and
6168   // non-abstract types.
6169   if (!FD->doesThisDeclarationHaveABody())
6170     return;
6171 
6172   // For safety's sake, just ignore it if we don't have type source
6173   // information.  This should never happen for non-implicit methods,
6174   // but...
6175   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6176     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6177 }
6178 
6179 /// Check for invalid uses of an abstract type in a variable0 declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,VarDecl * VD)6180 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6181                                     VarDecl *VD) {
6182   // No need to do the check on definitions, which require that
6183   // the type is complete.
6184   if (VD->isThisDeclarationADefinition())
6185     return;
6186 
6187   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6188                  Sema::AbstractVariableType);
6189 }
6190 
6191 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)6192 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6193                                     CXXRecordDecl *RD) {
6194   for (auto *D : RD->decls()) {
6195     if (D->isImplicit()) continue;
6196 
6197     // Step through friends to the befriended declaration.
6198     if (auto *FD = dyn_cast<FriendDecl>(D)) {
6199       D = FD->getFriendDecl();
6200       if (!D) continue;
6201     }
6202 
6203     // Functions and function templates.
6204     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6205       CheckAbstractClassUsage(Info, FD);
6206     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6207       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6208 
6209     // Fields and static variables.
6210     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6211       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6212         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6213     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6214       CheckAbstractClassUsage(Info, VD);
6215     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6216       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6217 
6218     // Nested classes and class templates.
6219     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6220       CheckAbstractClassUsage(Info, RD);
6221     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6222       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6223     }
6224   }
6225 }
6226 
ReferenceDllExportedMembers(Sema & S,CXXRecordDecl * Class)6227 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6228   Attr *ClassAttr = getDLLAttr(Class);
6229   if (!ClassAttr)
6230     return;
6231 
6232   assert(ClassAttr->getKind() == attr::DLLExport);
6233 
6234   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6235 
6236   if (TSK == TSK_ExplicitInstantiationDeclaration)
6237     // Don't go any further if this is just an explicit instantiation
6238     // declaration.
6239     return;
6240 
6241   // Add a context note to explain how we got to any diagnostics produced below.
6242   struct MarkingClassDllexported {
6243     Sema &S;
6244     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6245                             SourceLocation AttrLoc)
6246         : S(S) {
6247       Sema::CodeSynthesisContext Ctx;
6248       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6249       Ctx.PointOfInstantiation = AttrLoc;
6250       Ctx.Entity = Class;
6251       S.pushCodeSynthesisContext(Ctx);
6252     }
6253     ~MarkingClassDllexported() {
6254       S.popCodeSynthesisContext();
6255     }
6256   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6257 
6258   if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6259     S.MarkVTableUsed(Class->getLocation(), Class, true);
6260 
6261   for (Decl *Member : Class->decls()) {
6262     // Skip members that were not marked exported.
6263     if (!Member->hasAttr<DLLExportAttr>())
6264       continue;
6265 
6266     // Defined static variables that are members of an exported base
6267     // class must be marked export too.
6268     auto *VD = dyn_cast<VarDecl>(Member);
6269     if (VD && VD->getStorageClass() == SC_Static &&
6270         TSK == TSK_ImplicitInstantiation)
6271       S.MarkVariableReferenced(VD->getLocation(), VD);
6272 
6273     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6274     if (!MD)
6275       continue;
6276 
6277     if (MD->isUserProvided()) {
6278       // Instantiate non-default class member functions ...
6279 
6280       // .. except for certain kinds of template specializations.
6281       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6282         continue;
6283 
6284       // If this is an MS ABI dllexport default constructor, instantiate any
6285       // default arguments.
6286       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6287         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6288         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6289           S.InstantiateDefaultCtorDefaultArgs(CD);
6290         }
6291       }
6292 
6293       S.MarkFunctionReferenced(Class->getLocation(), MD);
6294 
6295       // The function will be passed to the consumer when its definition is
6296       // encountered.
6297     } else if (MD->isExplicitlyDefaulted()) {
6298       // Synthesize and instantiate explicitly defaulted methods.
6299       S.MarkFunctionReferenced(Class->getLocation(), MD);
6300 
6301       if (TSK != TSK_ExplicitInstantiationDefinition) {
6302         // Except for explicit instantiation defs, we will not see the
6303         // definition again later, so pass it to the consumer now.
6304         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6305       }
6306     } else if (!MD->isTrivial() ||
6307                MD->isCopyAssignmentOperator() ||
6308                MD->isMoveAssignmentOperator()) {
6309       // Synthesize and instantiate non-trivial implicit methods, and the copy
6310       // and move assignment operators. The latter are exported even if they
6311       // are trivial, because the address of an operator can be taken and
6312       // should compare equal across libraries.
6313       S.MarkFunctionReferenced(Class->getLocation(), MD);
6314 
6315       // There is no later point when we will see the definition of this
6316       // function, so pass it to the consumer now.
6317       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6318     }
6319   }
6320 }
6321 
checkForMultipleExportedDefaultConstructors(Sema & S,CXXRecordDecl * Class)6322 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6323                                                         CXXRecordDecl *Class) {
6324   // Only the MS ABI has default constructor closures, so we don't need to do
6325   // this semantic checking anywhere else.
6326   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6327     return;
6328 
6329   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6330   for (Decl *Member : Class->decls()) {
6331     // Look for exported default constructors.
6332     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6333     if (!CD || !CD->isDefaultConstructor())
6334       continue;
6335     auto *Attr = CD->getAttr<DLLExportAttr>();
6336     if (!Attr)
6337       continue;
6338 
6339     // If the class is non-dependent, mark the default arguments as ODR-used so
6340     // that we can properly codegen the constructor closure.
6341     if (!Class->isDependentContext()) {
6342       for (ParmVarDecl *PD : CD->parameters()) {
6343         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6344         S.DiscardCleanupsInEvaluationContext();
6345       }
6346     }
6347 
6348     if (LastExportedDefaultCtor) {
6349       S.Diag(LastExportedDefaultCtor->getLocation(),
6350              diag::err_attribute_dll_ambiguous_default_ctor)
6351           << Class;
6352       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6353           << CD->getDeclName();
6354       return;
6355     }
6356     LastExportedDefaultCtor = CD;
6357   }
6358 }
6359 
checkCUDADeviceBuiltinSurfaceClassTemplate(Sema & S,CXXRecordDecl * Class)6360 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6361                                                        CXXRecordDecl *Class) {
6362   bool ErrorReported = false;
6363   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6364                                                      ClassTemplateDecl *TD) {
6365     if (ErrorReported)
6366       return;
6367     S.Diag(TD->getLocation(),
6368            diag::err_cuda_device_builtin_surftex_cls_template)
6369         << /*surface*/ 0 << TD;
6370     ErrorReported = true;
6371   };
6372 
6373   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6374   if (!TD) {
6375     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6376     if (!SD) {
6377       S.Diag(Class->getLocation(),
6378              diag::err_cuda_device_builtin_surftex_ref_decl)
6379           << /*surface*/ 0 << Class;
6380       S.Diag(Class->getLocation(),
6381              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6382           << Class;
6383       return;
6384     }
6385     TD = SD->getSpecializedTemplate();
6386   }
6387 
6388   TemplateParameterList *Params = TD->getTemplateParameters();
6389   unsigned N = Params->size();
6390 
6391   if (N != 2) {
6392     reportIllegalClassTemplate(S, TD);
6393     S.Diag(TD->getLocation(),
6394            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6395         << TD << 2;
6396   }
6397   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6398     reportIllegalClassTemplate(S, TD);
6399     S.Diag(TD->getLocation(),
6400            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6401         << TD << /*1st*/ 0 << /*type*/ 0;
6402   }
6403   if (N > 1) {
6404     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6405     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6406       reportIllegalClassTemplate(S, TD);
6407       S.Diag(TD->getLocation(),
6408              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6409           << TD << /*2nd*/ 1 << /*integer*/ 1;
6410     }
6411   }
6412 }
6413 
checkCUDADeviceBuiltinTextureClassTemplate(Sema & S,CXXRecordDecl * Class)6414 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6415                                                        CXXRecordDecl *Class) {
6416   bool ErrorReported = false;
6417   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6418                                                      ClassTemplateDecl *TD) {
6419     if (ErrorReported)
6420       return;
6421     S.Diag(TD->getLocation(),
6422            diag::err_cuda_device_builtin_surftex_cls_template)
6423         << /*texture*/ 1 << TD;
6424     ErrorReported = true;
6425   };
6426 
6427   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6428   if (!TD) {
6429     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6430     if (!SD) {
6431       S.Diag(Class->getLocation(),
6432              diag::err_cuda_device_builtin_surftex_ref_decl)
6433           << /*texture*/ 1 << Class;
6434       S.Diag(Class->getLocation(),
6435              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6436           << Class;
6437       return;
6438     }
6439     TD = SD->getSpecializedTemplate();
6440   }
6441 
6442   TemplateParameterList *Params = TD->getTemplateParameters();
6443   unsigned N = Params->size();
6444 
6445   if (N != 3) {
6446     reportIllegalClassTemplate(S, TD);
6447     S.Diag(TD->getLocation(),
6448            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6449         << TD << 3;
6450   }
6451   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6452     reportIllegalClassTemplate(S, TD);
6453     S.Diag(TD->getLocation(),
6454            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6455         << TD << /*1st*/ 0 << /*type*/ 0;
6456   }
6457   if (N > 1) {
6458     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6459     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6460       reportIllegalClassTemplate(S, TD);
6461       S.Diag(TD->getLocation(),
6462              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6463           << TD << /*2nd*/ 1 << /*integer*/ 1;
6464     }
6465   }
6466   if (N > 2) {
6467     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6468     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6469       reportIllegalClassTemplate(S, TD);
6470       S.Diag(TD->getLocation(),
6471              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6472           << TD << /*3rd*/ 2 << /*integer*/ 1;
6473     }
6474   }
6475 }
6476 
checkClassLevelCodeSegAttribute(CXXRecordDecl * Class)6477 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6478   // Mark any compiler-generated routines with the implicit code_seg attribute.
6479   for (auto *Method : Class->methods()) {
6480     if (Method->isUserProvided())
6481       continue;
6482     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6483       Method->addAttr(A);
6484   }
6485 }
6486 
checkClassLevelDLLAttribute(CXXRecordDecl * Class)6487 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6488   Attr *ClassAttr = getDLLAttr(Class);
6489 
6490   // MSVC inherits DLL attributes to partial class template specializations.
6491   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6492     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6493       if (Attr *TemplateAttr =
6494               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6495         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6496         A->setInherited(true);
6497         ClassAttr = A;
6498       }
6499     }
6500   }
6501 
6502   if (!ClassAttr)
6503     return;
6504 
6505   // MSVC allows imported or exported template classes that have UniqueExternal
6506   // linkage. This occurs when the template class has been instantiated with
6507   // a template parameter which itself has internal linkage.
6508   // We drop the attribute to avoid exporting or importing any members.
6509   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6510        Context.getTargetInfo().getTriple().isPS()) &&
6511       (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6512     Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6513     return;
6514   }
6515 
6516   if (!Class->isExternallyVisible()) {
6517     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6518         << Class << ClassAttr;
6519     return;
6520   }
6521 
6522   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6523       !ClassAttr->isInherited()) {
6524     // Diagnose dll attributes on members of class with dll attribute.
6525     for (Decl *Member : Class->decls()) {
6526       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6527         continue;
6528       InheritableAttr *MemberAttr = getDLLAttr(Member);
6529       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6530         continue;
6531 
6532       Diag(MemberAttr->getLocation(),
6533              diag::err_attribute_dll_member_of_dll_class)
6534           << MemberAttr << ClassAttr;
6535       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6536       Member->setInvalidDecl();
6537     }
6538   }
6539 
6540   if (Class->getDescribedClassTemplate())
6541     // Don't inherit dll attribute until the template is instantiated.
6542     return;
6543 
6544   // The class is either imported or exported.
6545   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6546 
6547   // Check if this was a dllimport attribute propagated from a derived class to
6548   // a base class template specialization. We don't apply these attributes to
6549   // static data members.
6550   const bool PropagatedImport =
6551       !ClassExported &&
6552       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6553 
6554   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6555 
6556   // Ignore explicit dllexport on explicit class template instantiation
6557   // declarations, except in MinGW mode.
6558   if (ClassExported && !ClassAttr->isInherited() &&
6559       TSK == TSK_ExplicitInstantiationDeclaration &&
6560       !Context.getTargetInfo().getTriple().isOSCygMing()) {
6561     Class->dropAttr<DLLExportAttr>();
6562     return;
6563   }
6564 
6565   // Force declaration of implicit members so they can inherit the attribute.
6566   ForceDeclarationOfImplicitMembers(Class);
6567 
6568   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6569   // seem to be true in practice?
6570 
6571   for (Decl *Member : Class->decls()) {
6572     VarDecl *VD = dyn_cast<VarDecl>(Member);
6573     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6574 
6575     // Only methods and static fields inherit the attributes.
6576     if (!VD && !MD)
6577       continue;
6578 
6579     if (MD) {
6580       // Don't process deleted methods.
6581       if (MD->isDeleted())
6582         continue;
6583 
6584       if (MD->isInlined()) {
6585         // MinGW does not import or export inline methods. But do it for
6586         // template instantiations.
6587         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6588             TSK != TSK_ExplicitInstantiationDeclaration &&
6589             TSK != TSK_ExplicitInstantiationDefinition)
6590           continue;
6591 
6592         // MSVC versions before 2015 don't export the move assignment operators
6593         // and move constructor, so don't attempt to import/export them if
6594         // we have a definition.
6595         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6596         if ((MD->isMoveAssignmentOperator() ||
6597              (Ctor && Ctor->isMoveConstructor())) &&
6598             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6599           continue;
6600 
6601         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6602         // operator is exported anyway.
6603         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6604             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6605           continue;
6606       }
6607     }
6608 
6609     // Don't apply dllimport attributes to static data members of class template
6610     // instantiations when the attribute is propagated from a derived class.
6611     if (VD && PropagatedImport)
6612       continue;
6613 
6614     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6615       continue;
6616 
6617     if (!getDLLAttr(Member)) {
6618       InheritableAttr *NewAttr = nullptr;
6619 
6620       // Do not export/import inline function when -fno-dllexport-inlines is
6621       // passed. But add attribute for later local static var check.
6622       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6623           TSK != TSK_ExplicitInstantiationDeclaration &&
6624           TSK != TSK_ExplicitInstantiationDefinition) {
6625         if (ClassExported) {
6626           NewAttr = ::new (getASTContext())
6627               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6628         } else {
6629           NewAttr = ::new (getASTContext())
6630               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6631         }
6632       } else {
6633         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6634       }
6635 
6636       NewAttr->setInherited(true);
6637       Member->addAttr(NewAttr);
6638 
6639       if (MD) {
6640         // Propagate DLLAttr to friend re-declarations of MD that have already
6641         // been constructed.
6642         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6643              FD = FD->getPreviousDecl()) {
6644           if (FD->getFriendObjectKind() == Decl::FOK_None)
6645             continue;
6646           assert(!getDLLAttr(FD) &&
6647                  "friend re-decl should not already have a DLLAttr");
6648           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6649           NewAttr->setInherited(true);
6650           FD->addAttr(NewAttr);
6651         }
6652       }
6653     }
6654   }
6655 
6656   if (ClassExported)
6657     DelayedDllExportClasses.push_back(Class);
6658 }
6659 
propagateDLLAttrToBaseClassTemplate(CXXRecordDecl * Class,Attr * ClassAttr,ClassTemplateSpecializationDecl * BaseTemplateSpec,SourceLocation BaseLoc)6660 void Sema::propagateDLLAttrToBaseClassTemplate(
6661     CXXRecordDecl *Class, Attr *ClassAttr,
6662     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6663   if (getDLLAttr(
6664           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6665     // If the base class template has a DLL attribute, don't try to change it.
6666     return;
6667   }
6668 
6669   auto TSK = BaseTemplateSpec->getSpecializationKind();
6670   if (!getDLLAttr(BaseTemplateSpec) &&
6671       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6672        TSK == TSK_ImplicitInstantiation)) {
6673     // The template hasn't been instantiated yet (or it has, but only as an
6674     // explicit instantiation declaration or implicit instantiation, which means
6675     // we haven't codegenned any members yet), so propagate the attribute.
6676     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6677     NewAttr->setInherited(true);
6678     BaseTemplateSpec->addAttr(NewAttr);
6679 
6680     // If this was an import, mark that we propagated it from a derived class to
6681     // a base class template specialization.
6682     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6683       ImportAttr->setPropagatedToBaseTemplate();
6684 
6685     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6686     // needs to be run again to work see the new attribute. Otherwise this will
6687     // get run whenever the template is instantiated.
6688     if (TSK != TSK_Undeclared)
6689       checkClassLevelDLLAttribute(BaseTemplateSpec);
6690 
6691     return;
6692   }
6693 
6694   if (getDLLAttr(BaseTemplateSpec)) {
6695     // The template has already been specialized or instantiated with an
6696     // attribute, explicitly or through propagation. We should not try to change
6697     // it.
6698     return;
6699   }
6700 
6701   // The template was previously instantiated or explicitly specialized without
6702   // a dll attribute, It's too late for us to add an attribute, so warn that
6703   // this is unsupported.
6704   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6705       << BaseTemplateSpec->isExplicitSpecialization();
6706   Diag(ClassAttr->getLocation(), diag::note_attribute);
6707   if (BaseTemplateSpec->isExplicitSpecialization()) {
6708     Diag(BaseTemplateSpec->getLocation(),
6709            diag::note_template_class_explicit_specialization_was_here)
6710         << BaseTemplateSpec;
6711   } else {
6712     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6713            diag::note_template_class_instantiation_was_here)
6714         << BaseTemplateSpec;
6715   }
6716 }
6717 
6718 Sema::DefaultedFunctionKind
getDefaultedFunctionKind(const FunctionDecl * FD)6719 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6720   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6721     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6722       if (Ctor->isDefaultConstructor())
6723         return CXXSpecialMemberKind::DefaultConstructor;
6724 
6725       if (Ctor->isCopyConstructor())
6726         return CXXSpecialMemberKind::CopyConstructor;
6727 
6728       if (Ctor->isMoveConstructor())
6729         return CXXSpecialMemberKind::MoveConstructor;
6730     }
6731 
6732     if (MD->isCopyAssignmentOperator())
6733       return CXXSpecialMemberKind::CopyAssignment;
6734 
6735     if (MD->isMoveAssignmentOperator())
6736       return CXXSpecialMemberKind::MoveAssignment;
6737 
6738     if (isa<CXXDestructorDecl>(FD))
6739       return CXXSpecialMemberKind::Destructor;
6740   }
6741 
6742   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6743   case OO_EqualEqual:
6744     return DefaultedComparisonKind::Equal;
6745 
6746   case OO_ExclaimEqual:
6747     return DefaultedComparisonKind::NotEqual;
6748 
6749   case OO_Spaceship:
6750     // No point allowing this if <=> doesn't exist in the current language mode.
6751     if (!getLangOpts().CPlusPlus20)
6752       break;
6753     return DefaultedComparisonKind::ThreeWay;
6754 
6755   case OO_Less:
6756   case OO_LessEqual:
6757   case OO_Greater:
6758   case OO_GreaterEqual:
6759     // No point allowing this if <=> doesn't exist in the current language mode.
6760     if (!getLangOpts().CPlusPlus20)
6761       break;
6762     return DefaultedComparisonKind::Relational;
6763 
6764   default:
6765     break;
6766   }
6767 
6768   // Not defaultable.
6769   return DefaultedFunctionKind();
6770 }
6771 
DefineDefaultedFunction(Sema & S,FunctionDecl * FD,SourceLocation DefaultLoc)6772 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6773                                     SourceLocation DefaultLoc) {
6774   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6775   if (DFK.isComparison())
6776     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6777 
6778   switch (DFK.asSpecialMember()) {
6779   case CXXSpecialMemberKind::DefaultConstructor:
6780     S.DefineImplicitDefaultConstructor(DefaultLoc,
6781                                        cast<CXXConstructorDecl>(FD));
6782     break;
6783   case CXXSpecialMemberKind::CopyConstructor:
6784     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6785     break;
6786   case CXXSpecialMemberKind::CopyAssignment:
6787     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6788     break;
6789   case CXXSpecialMemberKind::Destructor:
6790     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6791     break;
6792   case CXXSpecialMemberKind::MoveConstructor:
6793     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6794     break;
6795   case CXXSpecialMemberKind::MoveAssignment:
6796     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6797     break;
6798   case CXXSpecialMemberKind::Invalid:
6799     llvm_unreachable("Invalid special member.");
6800   }
6801 }
6802 
6803 /// Determine whether a type is permitted to be passed or returned in
6804 /// registers, per C++ [class.temporary]p3.
canPassInRegisters(Sema & S,CXXRecordDecl * D,TargetInfo::CallingConvKind CCK)6805 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6806                                TargetInfo::CallingConvKind CCK) {
6807   if (D->isDependentType() || D->isInvalidDecl())
6808     return false;
6809 
6810   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6811   // The PS4 platform ABI follows the behavior of Clang 3.2.
6812   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6813     return !D->hasNonTrivialDestructorForCall() &&
6814            !D->hasNonTrivialCopyConstructorForCall();
6815 
6816   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6817     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6818     bool DtorIsTrivialForCall = false;
6819 
6820     // If a class has at least one eligible, trivial copy constructor, it
6821     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6822     //
6823     // Note: This permits classes with non-trivial copy or move ctors to be
6824     // passed in registers, so long as they *also* have a trivial copy ctor,
6825     // which is non-conforming.
6826     if (D->needsImplicitCopyConstructor()) {
6827       if (!D->defaultedCopyConstructorIsDeleted()) {
6828         if (D->hasTrivialCopyConstructor())
6829           CopyCtorIsTrivial = true;
6830         if (D->hasTrivialCopyConstructorForCall())
6831           CopyCtorIsTrivialForCall = true;
6832       }
6833     } else {
6834       for (const CXXConstructorDecl *CD : D->ctors()) {
6835         if (CD->isCopyConstructor() && !CD->isDeleted() &&
6836             !CD->isIneligibleOrNotSelected()) {
6837           if (CD->isTrivial())
6838             CopyCtorIsTrivial = true;
6839           if (CD->isTrivialForCall())
6840             CopyCtorIsTrivialForCall = true;
6841         }
6842       }
6843     }
6844 
6845     if (D->needsImplicitDestructor()) {
6846       if (!D->defaultedDestructorIsDeleted() &&
6847           D->hasTrivialDestructorForCall())
6848         DtorIsTrivialForCall = true;
6849     } else if (const auto *DD = D->getDestructor()) {
6850       if (!DD->isDeleted() && DD->isTrivialForCall())
6851         DtorIsTrivialForCall = true;
6852     }
6853 
6854     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6855     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6856       return true;
6857 
6858     // If a class has a destructor, we'd really like to pass it indirectly
6859     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6860     // impossible for small types, which it will pass in a single register or
6861     // stack slot. Most objects with dtors are large-ish, so handle that early.
6862     // We can't call out all large objects as being indirect because there are
6863     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6864     // how we pass large POD types.
6865 
6866     // Note: This permits small classes with nontrivial destructors to be
6867     // passed in registers, which is non-conforming.
6868     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6869     uint64_t TypeSize = isAArch64 ? 128 : 64;
6870 
6871     if (CopyCtorIsTrivial &&
6872         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6873       return true;
6874     return false;
6875   }
6876 
6877   // Per C++ [class.temporary]p3, the relevant condition is:
6878   //   each copy constructor, move constructor, and destructor of X is
6879   //   either trivial or deleted, and X has at least one non-deleted copy
6880   //   or move constructor
6881   bool HasNonDeletedCopyOrMove = false;
6882 
6883   if (D->needsImplicitCopyConstructor() &&
6884       !D->defaultedCopyConstructorIsDeleted()) {
6885     if (!D->hasTrivialCopyConstructorForCall())
6886       return false;
6887     HasNonDeletedCopyOrMove = true;
6888   }
6889 
6890   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6891       !D->defaultedMoveConstructorIsDeleted()) {
6892     if (!D->hasTrivialMoveConstructorForCall())
6893       return false;
6894     HasNonDeletedCopyOrMove = true;
6895   }
6896 
6897   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6898       !D->hasTrivialDestructorForCall())
6899     return false;
6900 
6901   for (const CXXMethodDecl *MD : D->methods()) {
6902     if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6903       continue;
6904 
6905     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6906     if (CD && CD->isCopyOrMoveConstructor())
6907       HasNonDeletedCopyOrMove = true;
6908     else if (!isa<CXXDestructorDecl>(MD))
6909       continue;
6910 
6911     if (!MD->isTrivialForCall())
6912       return false;
6913   }
6914 
6915   return HasNonDeletedCopyOrMove;
6916 }
6917 
6918 /// Report an error regarding overriding, along with any relevant
6919 /// overridden methods.
6920 ///
6921 /// \param DiagID the primary error to report.
6922 /// \param MD the overriding method.
6923 static bool
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,llvm::function_ref<bool (const CXXMethodDecl *)> Report)6924 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6925                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6926   bool IssuedDiagnostic = false;
6927   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6928     if (Report(O)) {
6929       if (!IssuedDiagnostic) {
6930         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6931         IssuedDiagnostic = true;
6932       }
6933       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6934     }
6935   }
6936   return IssuedDiagnostic;
6937 }
6938 
CheckCompletedCXXClass(Scope * S,CXXRecordDecl * Record)6939 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6940   if (!Record)
6941     return;
6942 
6943   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6944     AbstractUsageInfo Info(*this, Record);
6945     CheckAbstractClassUsage(Info, Record);
6946   }
6947 
6948   // If this is not an aggregate type and has no user-declared constructor,
6949   // complain about any non-static data members of reference or const scalar
6950   // type, since they will never get initializers.
6951   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6952       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6953       !Record->isLambda()) {
6954     bool Complained = false;
6955     for (const auto *F : Record->fields()) {
6956       if (F->hasInClassInitializer() || F->isUnnamedBitField())
6957         continue;
6958 
6959       if (F->getType()->isReferenceType() ||
6960           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6961         if (!Complained) {
6962           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6963               << Record->getTagKind() << Record;
6964           Complained = true;
6965         }
6966 
6967         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6968           << F->getType()->isReferenceType()
6969           << F->getDeclName();
6970       }
6971     }
6972   }
6973 
6974   if (Record->getIdentifier()) {
6975     // C++ [class.mem]p13:
6976     //   If T is the name of a class, then each of the following shall have a
6977     //   name different from T:
6978     //     - every member of every anonymous union that is a member of class T.
6979     //
6980     // C++ [class.mem]p14:
6981     //   In addition, if class T has a user-declared constructor (12.1), every
6982     //   non-static data member of class T shall have a name different from T.
6983     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6984     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6985          ++I) {
6986       NamedDecl *D = (*I)->getUnderlyingDecl();
6987       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6988            Record->hasUserDeclaredConstructor()) ||
6989           isa<IndirectFieldDecl>(D)) {
6990         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6991           << D->getDeclName();
6992         break;
6993       }
6994     }
6995   }
6996 
6997   // Warn if the class has virtual methods but non-virtual public destructor.
6998   if (Record->isPolymorphic() && !Record->isDependentType()) {
6999     CXXDestructorDecl *dtor = Record->getDestructor();
7000     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7001         !Record->hasAttr<FinalAttr>())
7002       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7003            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7004   }
7005 
7006   if (Record->isAbstract()) {
7007     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7008       Diag(Record->getLocation(), diag::warn_abstract_final_class)
7009         << FA->isSpelledAsSealed();
7010       DiagnoseAbstractType(Record);
7011     }
7012   }
7013 
7014   // Warn if the class has a final destructor but is not itself marked final.
7015   if (!Record->hasAttr<FinalAttr>()) {
7016     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7017       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7018         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7019             << FA->isSpelledAsSealed()
7020             << FixItHint::CreateInsertion(
7021                    getLocForEndOfToken(Record->getLocation()),
7022                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
7023         Diag(Record->getLocation(),
7024              diag::note_final_dtor_non_final_class_silence)
7025             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7026       }
7027     }
7028   }
7029 
7030   // See if trivial_abi has to be dropped.
7031   if (Record->hasAttr<TrivialABIAttr>())
7032     checkIllFormedTrivialABIStruct(*Record);
7033 
7034   // Set HasTrivialSpecialMemberForCall if the record has attribute
7035   // "trivial_abi".
7036   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7037 
7038   if (HasTrivialABI)
7039     Record->setHasTrivialSpecialMemberForCall();
7040 
7041   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7042   // We check these last because they can depend on the properties of the
7043   // primary comparison functions (==, <=>).
7044   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7045 
7046   // Perform checks that can't be done until we know all the properties of a
7047   // member function (whether it's defaulted, deleted, virtual, overriding,
7048   // ...).
7049   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7050     // A static function cannot override anything.
7051     if (MD->getStorageClass() == SC_Static) {
7052       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7053                           [](const CXXMethodDecl *) { return true; }))
7054         return;
7055     }
7056 
7057     // A deleted function cannot override a non-deleted function and vice
7058     // versa.
7059     if (ReportOverrides(*this,
7060                         MD->isDeleted() ? diag::err_deleted_override
7061                                         : diag::err_non_deleted_override,
7062                         MD, [&](const CXXMethodDecl *V) {
7063                           return MD->isDeleted() != V->isDeleted();
7064                         })) {
7065       if (MD->isDefaulted() && MD->isDeleted())
7066         // Explain why this defaulted function was deleted.
7067         DiagnoseDeletedDefaultedFunction(MD);
7068       return;
7069     }
7070 
7071     // A consteval function cannot override a non-consteval function and vice
7072     // versa.
7073     if (ReportOverrides(*this,
7074                         MD->isConsteval() ? diag::err_consteval_override
7075                                           : diag::err_non_consteval_override,
7076                         MD, [&](const CXXMethodDecl *V) {
7077                           return MD->isConsteval() != V->isConsteval();
7078                         })) {
7079       if (MD->isDefaulted() && MD->isDeleted())
7080         // Explain why this defaulted function was deleted.
7081         DiagnoseDeletedDefaultedFunction(MD);
7082       return;
7083     }
7084   };
7085 
7086   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7087     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7088       return false;
7089 
7090     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7091     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7092         DFK.asComparison() == DefaultedComparisonKind::Relational) {
7093       DefaultedSecondaryComparisons.push_back(FD);
7094       return true;
7095     }
7096 
7097     CheckExplicitlyDefaultedFunction(S, FD);
7098     return false;
7099   };
7100 
7101   if (!Record->isInvalidDecl() &&
7102       Record->hasAttr<VTablePointerAuthenticationAttr>())
7103     checkIncorrectVTablePointerAuthenticationAttribute(*Record);
7104 
7105   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7106     // Check whether the explicitly-defaulted members are valid.
7107     bool Incomplete = CheckForDefaultedFunction(M);
7108 
7109     // Skip the rest of the checks for a member of a dependent class.
7110     if (Record->isDependentType())
7111       return;
7112 
7113     // For an explicitly defaulted or deleted special member, we defer
7114     // determining triviality until the class is complete. That time is now!
7115     CXXSpecialMemberKind CSM = getSpecialMember(M);
7116     if (!M->isImplicit() && !M->isUserProvided()) {
7117       if (CSM != CXXSpecialMemberKind::Invalid) {
7118         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7119         // Inform the class that we've finished declaring this member.
7120         Record->finishedDefaultedOrDeletedMember(M);
7121         M->setTrivialForCall(
7122             HasTrivialABI ||
7123             SpecialMemberIsTrivial(M, CSM,
7124                                    TrivialABIHandling::ConsiderTrivialABI));
7125         Record->setTrivialForCallFlags(M);
7126       }
7127     }
7128 
7129     // Set triviality for the purpose of calls if this is a user-provided
7130     // copy/move constructor or destructor.
7131     if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7132          CSM == CXXSpecialMemberKind::MoveConstructor ||
7133          CSM == CXXSpecialMemberKind::Destructor) &&
7134         M->isUserProvided()) {
7135       M->setTrivialForCall(HasTrivialABI);
7136       Record->setTrivialForCallFlags(M);
7137     }
7138 
7139     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7140         M->hasAttr<DLLExportAttr>()) {
7141       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7142           M->isTrivial() &&
7143           (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7144            CSM == CXXSpecialMemberKind::CopyConstructor ||
7145            CSM == CXXSpecialMemberKind::Destructor))
7146         M->dropAttr<DLLExportAttr>();
7147 
7148       if (M->hasAttr<DLLExportAttr>()) {
7149         // Define after any fields with in-class initializers have been parsed.
7150         DelayedDllExportMemberFunctions.push_back(M);
7151       }
7152     }
7153 
7154     bool EffectivelyConstexprDestructor = true;
7155     // Avoid triggering vtable instantiation due to a dtor that is not
7156     // "effectively constexpr" for better compatibility.
7157     // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7158     if (isa<CXXDestructorDecl>(M)) {
7159       llvm::SmallDenseSet<QualType> Visited;
7160       auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7161         if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7162           return false;
7163         const CXXRecordDecl *RD =
7164             T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7165         if (!RD || !RD->isCompleteDefinition())
7166           return true;
7167 
7168         if (!RD->hasConstexprDestructor())
7169           return false;
7170 
7171         for (const CXXBaseSpecifier &B : RD->bases())
7172           if (!Check(B.getType(), Check))
7173             return false;
7174         for (const FieldDecl *FD : RD->fields())
7175           if (!Check(FD->getType(), Check))
7176             return false;
7177         return true;
7178       };
7179       EffectivelyConstexprDestructor =
7180           Check(QualType(Record->getTypeForDecl(), 0), Check);
7181     }
7182 
7183     // Define defaulted constexpr virtual functions that override a base class
7184     // function right away.
7185     // FIXME: We can defer doing this until the vtable is marked as used.
7186     if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7187         M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7188         EffectivelyConstexprDestructor)
7189       DefineDefaultedFunction(*this, M, M->getLocation());
7190 
7191     if (!Incomplete)
7192       CheckCompletedMemberFunction(M);
7193   };
7194 
7195   // Check the destructor before any other member function. We need to
7196   // determine whether it's trivial in order to determine whether the claas
7197   // type is a literal type, which is a prerequisite for determining whether
7198   // other special member functions are valid and whether they're implicitly
7199   // 'constexpr'.
7200   if (CXXDestructorDecl *Dtor = Record->getDestructor())
7201     CompleteMemberFunction(Dtor);
7202 
7203   bool HasMethodWithOverrideControl = false,
7204        HasOverridingMethodWithoutOverrideControl = false;
7205   for (auto *D : Record->decls()) {
7206     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7207       // FIXME: We could do this check for dependent types with non-dependent
7208       // bases.
7209       if (!Record->isDependentType()) {
7210         // See if a method overloads virtual methods in a base
7211         // class without overriding any.
7212         if (!M->isStatic())
7213           DiagnoseHiddenVirtualMethods(M);
7214 
7215         if (M->hasAttr<OverrideAttr>()) {
7216           HasMethodWithOverrideControl = true;
7217         } else if (M->size_overridden_methods() > 0) {
7218           HasOverridingMethodWithoutOverrideControl = true;
7219         } else {
7220           // Warn on newly-declared virtual methods in `final` classes
7221           if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7222             Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7223                 << M;
7224           }
7225         }
7226       }
7227 
7228       if (!isa<CXXDestructorDecl>(M))
7229         CompleteMemberFunction(M);
7230     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7231       CheckForDefaultedFunction(
7232           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7233     }
7234   }
7235 
7236   if (HasOverridingMethodWithoutOverrideControl) {
7237     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7238     for (auto *M : Record->methods())
7239       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7240   }
7241 
7242   // Check the defaulted secondary comparisons after any other member functions.
7243   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7244     CheckExplicitlyDefaultedFunction(S, FD);
7245 
7246     // If this is a member function, we deferred checking it until now.
7247     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7248       CheckCompletedMemberFunction(MD);
7249   }
7250 
7251   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7252   // whether this class uses any C++ features that are implemented
7253   // completely differently in MSVC, and if so, emit a diagnostic.
7254   // That diagnostic defaults to an error, but we allow projects to
7255   // map it down to a warning (or ignore it).  It's a fairly common
7256   // practice among users of the ms_struct pragma to mass-annotate
7257   // headers, sweeping up a bunch of types that the project doesn't
7258   // really rely on MSVC-compatible layout for.  We must therefore
7259   // support "ms_struct except for C++ stuff" as a secondary ABI.
7260   // Don't emit this diagnostic if the feature was enabled as a
7261   // language option (as opposed to via a pragma or attribute), as
7262   // the option -mms-bitfields otherwise essentially makes it impossible
7263   // to build C++ code, unless this diagnostic is turned off.
7264   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7265       (Record->isPolymorphic() || Record->getNumBases())) {
7266     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7267   }
7268 
7269   checkClassLevelDLLAttribute(Record);
7270   checkClassLevelCodeSegAttribute(Record);
7271 
7272   bool ClangABICompat4 =
7273       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7274   TargetInfo::CallingConvKind CCK =
7275       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7276   bool CanPass = canPassInRegisters(*this, Record, CCK);
7277 
7278   // Do not change ArgPassingRestrictions if it has already been set to
7279   // RecordArgPassingKind::CanNeverPassInRegs.
7280   if (Record->getArgPassingRestrictions() !=
7281       RecordArgPassingKind::CanNeverPassInRegs)
7282     Record->setArgPassingRestrictions(
7283         CanPass ? RecordArgPassingKind::CanPassInRegs
7284                 : RecordArgPassingKind::CannotPassInRegs);
7285 
7286   // If canPassInRegisters returns true despite the record having a non-trivial
7287   // destructor, the record is destructed in the callee. This happens only when
7288   // the record or one of its subobjects has a field annotated with trivial_abi
7289   // or a field qualified with ObjC __strong/__weak.
7290   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7291     Record->setParamDestroyedInCallee(true);
7292   else if (Record->hasNonTrivialDestructor())
7293     Record->setParamDestroyedInCallee(CanPass);
7294 
7295   if (getLangOpts().ForceEmitVTables) {
7296     // If we want to emit all the vtables, we need to mark it as used.  This
7297     // is especially required for cases like vtable assumption loads.
7298     MarkVTableUsed(Record->getInnerLocStart(), Record);
7299   }
7300 
7301   if (getLangOpts().CUDA) {
7302     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7303       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7304     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7305       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7306   }
7307 
7308   llvm::SmallDenseMap<OverloadedOperatorKind,
7309                       llvm::SmallVector<const FunctionDecl *, 2>, 4>
7310       TypeAwareDecls{{OO_New, {}},
7311                      {OO_Array_New, {}},
7312                      {OO_Delete, {}},
7313                      {OO_Array_New, {}}};
7314   for (auto *D : Record->decls()) {
7315     const FunctionDecl *FnDecl = D->getAsFunction();
7316     if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7317       continue;
7318     assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7319     TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7320   }
7321   auto CheckMismatchedTypeAwareAllocators =
7322       [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7323                                       OverloadedOperatorKind DeleteKind) {
7324         auto &NewDecls = TypeAwareDecls[NewKind];
7325         auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7326         if (NewDecls.empty() == DeleteDecls.empty())
7327           return;
7328         DeclarationName FoundOperator =
7329             Context.DeclarationNames.getCXXOperatorName(
7330                 NewDecls.empty() ? DeleteKind : NewKind);
7331         DeclarationName MissingOperator =
7332             Context.DeclarationNames.getCXXOperatorName(
7333                 NewDecls.empty() ? NewKind : DeleteKind);
7334         Diag(Record->getLocation(),
7335              diag::err_type_aware_allocator_missing_matching_operator)
7336             << FoundOperator << Context.getRecordType(Record)
7337             << MissingOperator;
7338         for (auto MD : NewDecls)
7339           Diag(MD->getLocation(),
7340                diag::note_unmatched_type_aware_allocator_declared)
7341               << MD;
7342         for (auto MD : DeleteDecls)
7343           Diag(MD->getLocation(),
7344                diag::note_unmatched_type_aware_allocator_declared)
7345               << MD;
7346       };
7347   CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7348   CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7349 }
7350 
7351 /// Look up the special member function that would be called by a special
7352 /// member function for a subobject of class type.
7353 ///
7354 /// \param Class The class type of the subobject.
7355 /// \param CSM The kind of special member function.
7356 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7357 /// \param ConstRHS True if this is a copy operation with a const object
7358 ///        on its RHS, that is, if the argument to the outer special member
7359 ///        function is 'const' and this is not a field marked 'mutable'.
7360 static Sema::SpecialMemberOverloadResult
lookupCallFromSpecialMember(Sema & S,CXXRecordDecl * Class,CXXSpecialMemberKind CSM,unsigned FieldQuals,bool ConstRHS)7361 lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7362                             CXXSpecialMemberKind CSM, unsigned FieldQuals,
7363                             bool ConstRHS) {
7364   unsigned LHSQuals = 0;
7365   if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7366       CSM == CXXSpecialMemberKind::MoveAssignment)
7367     LHSQuals = FieldQuals;
7368 
7369   unsigned RHSQuals = FieldQuals;
7370   if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7371       CSM == CXXSpecialMemberKind::Destructor)
7372     RHSQuals = 0;
7373   else if (ConstRHS)
7374     RHSQuals |= Qualifiers::Const;
7375 
7376   return S.LookupSpecialMember(Class, CSM,
7377                                RHSQuals & Qualifiers::Const,
7378                                RHSQuals & Qualifiers::Volatile,
7379                                false,
7380                                LHSQuals & Qualifiers::Const,
7381                                LHSQuals & Qualifiers::Volatile);
7382 }
7383 
7384 class Sema::InheritedConstructorInfo {
7385   Sema &S;
7386   SourceLocation UseLoc;
7387 
7388   /// A mapping from the base classes through which the constructor was
7389   /// inherited to the using shadow declaration in that base class (or a null
7390   /// pointer if the constructor was declared in that base class).
7391   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7392       InheritedFromBases;
7393 
7394 public:
InheritedConstructorInfo(Sema & S,SourceLocation UseLoc,ConstructorUsingShadowDecl * Shadow)7395   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7396                            ConstructorUsingShadowDecl *Shadow)
7397       : S(S), UseLoc(UseLoc) {
7398     bool DiagnosedMultipleConstructedBases = false;
7399     CXXRecordDecl *ConstructedBase = nullptr;
7400     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7401 
7402     // Find the set of such base class subobjects and check that there's a
7403     // unique constructed subobject.
7404     for (auto *D : Shadow->redecls()) {
7405       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7406       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7407       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7408 
7409       InheritedFromBases.insert(
7410           std::make_pair(DNominatedBase->getCanonicalDecl(),
7411                          DShadow->getNominatedBaseClassShadowDecl()));
7412       if (DShadow->constructsVirtualBase())
7413         InheritedFromBases.insert(
7414             std::make_pair(DConstructedBase->getCanonicalDecl(),
7415                            DShadow->getConstructedBaseClassShadowDecl()));
7416       else
7417         assert(DNominatedBase == DConstructedBase);
7418 
7419       // [class.inhctor.init]p2:
7420       //   If the constructor was inherited from multiple base class subobjects
7421       //   of type B, the program is ill-formed.
7422       if (!ConstructedBase) {
7423         ConstructedBase = DConstructedBase;
7424         ConstructedBaseIntroducer = D->getIntroducer();
7425       } else if (ConstructedBase != DConstructedBase &&
7426                  !Shadow->isInvalidDecl()) {
7427         if (!DiagnosedMultipleConstructedBases) {
7428           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7429               << Shadow->getTargetDecl();
7430           S.Diag(ConstructedBaseIntroducer->getLocation(),
7431                  diag::note_ambiguous_inherited_constructor_using)
7432               << ConstructedBase;
7433           DiagnosedMultipleConstructedBases = true;
7434         }
7435         S.Diag(D->getIntroducer()->getLocation(),
7436                diag::note_ambiguous_inherited_constructor_using)
7437             << DConstructedBase;
7438       }
7439     }
7440 
7441     if (DiagnosedMultipleConstructedBases)
7442       Shadow->setInvalidDecl();
7443   }
7444 
7445   /// Find the constructor to use for inherited construction of a base class,
7446   /// and whether that base class constructor inherits the constructor from a
7447   /// virtual base class (in which case it won't actually invoke it).
7448   std::pair<CXXConstructorDecl *, bool>
findConstructorForBase(CXXRecordDecl * Base,CXXConstructorDecl * Ctor) const7449   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7450     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7451     if (It == InheritedFromBases.end())
7452       return std::make_pair(nullptr, false);
7453 
7454     // This is an intermediary class.
7455     if (It->second)
7456       return std::make_pair(
7457           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7458           It->second->constructsVirtualBase());
7459 
7460     // This is the base class from which the constructor was inherited.
7461     return std::make_pair(Ctor, false);
7462   }
7463 };
7464 
7465 /// Is the special member function which would be selected to perform the
7466 /// specified operation on the specified class type a constexpr constructor?
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,CXXSpecialMemberKind CSM,unsigned Quals,bool ConstRHS,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)7467 static bool specialMemberIsConstexpr(
7468     Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7469     bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7470     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7471   // Suppress duplicate constraint checking here, in case a constraint check
7472   // caused us to decide to do this.  Any truely recursive checks will get
7473   // caught during these checks anyway.
7474   Sema::SatisfactionStackResetRAII SSRAII{S};
7475 
7476   // If we're inheriting a constructor, see if we need to call it for this base
7477   // class.
7478   if (InheritedCtor) {
7479     assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7480     auto BaseCtor =
7481         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7482     if (BaseCtor)
7483       return BaseCtor->isConstexpr();
7484   }
7485 
7486   if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7487     return ClassDecl->hasConstexprDefaultConstructor();
7488   if (CSM == CXXSpecialMemberKind::Destructor)
7489     return ClassDecl->hasConstexprDestructor();
7490 
7491   Sema::SpecialMemberOverloadResult SMOR =
7492       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7493   if (!SMOR.getMethod())
7494     // A constructor we wouldn't select can't be "involved in initializing"
7495     // anything.
7496     return true;
7497   return SMOR.getMethod()->isConstexpr();
7498 }
7499 
7500 /// Determine whether the specified special member function would be constexpr
7501 /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,CXXSpecialMemberKind CSM,bool ConstArg,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)7502 static bool defaultedSpecialMemberIsConstexpr(
7503     Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7504     CXXConstructorDecl *InheritedCtor = nullptr,
7505     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7506   if (!S.getLangOpts().CPlusPlus11)
7507     return false;
7508 
7509   // C++11 [dcl.constexpr]p4:
7510   // In the definition of a constexpr constructor [...]
7511   bool Ctor = true;
7512   switch (CSM) {
7513   case CXXSpecialMemberKind::DefaultConstructor:
7514     if (Inherited)
7515       break;
7516     // Since default constructor lookup is essentially trivial (and cannot
7517     // involve, for instance, template instantiation), we compute whether a
7518     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7519     //
7520     // This is important for performance; we need to know whether the default
7521     // constructor is constexpr to determine whether the type is a literal type.
7522     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7523 
7524   case CXXSpecialMemberKind::CopyConstructor:
7525   case CXXSpecialMemberKind::MoveConstructor:
7526     // For copy or move constructors, we need to perform overload resolution.
7527     break;
7528 
7529   case CXXSpecialMemberKind::CopyAssignment:
7530   case CXXSpecialMemberKind::MoveAssignment:
7531     if (!S.getLangOpts().CPlusPlus14)
7532       return false;
7533     // In C++1y, we need to perform overload resolution.
7534     Ctor = false;
7535     break;
7536 
7537   case CXXSpecialMemberKind::Destructor:
7538     return ClassDecl->defaultedDestructorIsConstexpr();
7539 
7540   case CXXSpecialMemberKind::Invalid:
7541     return false;
7542   }
7543 
7544   //   -- if the class is a non-empty union, or for each non-empty anonymous
7545   //      union member of a non-union class, exactly one non-static data member
7546   //      shall be initialized; [DR1359]
7547   //
7548   // If we squint, this is guaranteed, since exactly one non-static data member
7549   // will be initialized (if the constructor isn't deleted), we just don't know
7550   // which one.
7551   if (Ctor && ClassDecl->isUnion())
7552     return CSM == CXXSpecialMemberKind::DefaultConstructor
7553                ? ClassDecl->hasInClassInitializer() ||
7554                      !ClassDecl->hasVariantMembers()
7555                : true;
7556 
7557   //   -- the class shall not have any virtual base classes;
7558   if (Ctor && ClassDecl->getNumVBases())
7559     return false;
7560 
7561   // C++1y [class.copy]p26:
7562   //   -- [the class] is a literal type, and
7563   if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7564     return false;
7565 
7566   //   -- every constructor involved in initializing [...] base class
7567   //      sub-objects shall be a constexpr constructor;
7568   //   -- the assignment operator selected to copy/move each direct base
7569   //      class is a constexpr function, and
7570   if (!S.getLangOpts().CPlusPlus23) {
7571     for (const auto &B : ClassDecl->bases()) {
7572       const RecordType *BaseType = B.getType()->getAs<RecordType>();
7573       if (!BaseType)
7574         continue;
7575       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7576       if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7577                                     InheritedCtor, Inherited))
7578         return false;
7579     }
7580   }
7581 
7582   //   -- every constructor involved in initializing non-static data members
7583   //      [...] shall be a constexpr constructor;
7584   //   -- every non-static data member and base class sub-object shall be
7585   //      initialized
7586   //   -- for each non-static data member of X that is of class type (or array
7587   //      thereof), the assignment operator selected to copy/move that member is
7588   //      a constexpr function
7589   if (!S.getLangOpts().CPlusPlus23) {
7590     for (const auto *F : ClassDecl->fields()) {
7591       if (F->isInvalidDecl())
7592         continue;
7593       if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7594           F->hasInClassInitializer())
7595         continue;
7596       QualType BaseType = S.Context.getBaseElementType(F->getType());
7597       if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7598         CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7599         if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7600                                       BaseType.getCVRQualifiers(),
7601                                       ConstArg && !F->isMutable()))
7602           return false;
7603       } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7604         return false;
7605       }
7606     }
7607   }
7608 
7609   // All OK, it's constexpr!
7610   return true;
7611 }
7612 
7613 namespace {
7614 /// RAII object to register a defaulted function as having its exception
7615 /// specification computed.
7616 struct ComputingExceptionSpec {
7617   Sema &S;
7618 
ComputingExceptionSpec__anon42c808801f11::ComputingExceptionSpec7619   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7620       : S(S) {
7621     Sema::CodeSynthesisContext Ctx;
7622     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7623     Ctx.PointOfInstantiation = Loc;
7624     Ctx.Entity = FD;
7625     S.pushCodeSynthesisContext(Ctx);
7626   }
~ComputingExceptionSpec__anon42c808801f11::ComputingExceptionSpec7627   ~ComputingExceptionSpec() {
7628     S.popCodeSynthesisContext();
7629   }
7630 };
7631 }
7632 
7633 static Sema::ImplicitExceptionSpecification
7634 ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7635                                            CXXMethodDecl *MD,
7636                                            CXXSpecialMemberKind CSM,
7637                                            Sema::InheritedConstructorInfo *ICI);
7638 
7639 static Sema::ImplicitExceptionSpecification
7640 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7641                                         FunctionDecl *FD,
7642                                         Sema::DefaultedComparisonKind DCK);
7643 
7644 static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,FunctionDecl * FD)7645 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7646   auto DFK = S.getDefaultedFunctionKind(FD);
7647   if (DFK.isSpecialMember())
7648     return ComputeDefaultedSpecialMemberExceptionSpec(
7649         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7650   if (DFK.isComparison())
7651     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7652                                                    DFK.asComparison());
7653 
7654   auto *CD = cast<CXXConstructorDecl>(FD);
7655   assert(CD->getInheritedConstructor() &&
7656          "only defaulted functions and inherited constructors have implicit "
7657          "exception specs");
7658   Sema::InheritedConstructorInfo ICI(
7659       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7660   return ComputeDefaultedSpecialMemberExceptionSpec(
7661       S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);
7662 }
7663 
getImplicitMethodEPI(Sema & S,CXXMethodDecl * MD)7664 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7665                                                             CXXMethodDecl *MD) {
7666   FunctionProtoType::ExtProtoInfo EPI;
7667 
7668   // Build an exception specification pointing back at this member.
7669   EPI.ExceptionSpec.Type = EST_Unevaluated;
7670   EPI.ExceptionSpec.SourceDecl = MD;
7671 
7672   // Set the calling convention to the default for C++ instance methods.
7673   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7674       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7675                                             /*IsCXXMethod=*/true));
7676   return EPI;
7677 }
7678 
EvaluateImplicitExceptionSpec(SourceLocation Loc,FunctionDecl * FD)7679 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7680   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7681   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7682     return;
7683 
7684   // Evaluate the exception specification.
7685   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7686   auto ESI = IES.getExceptionSpec();
7687 
7688   // Update the type of the special member to use it.
7689   UpdateExceptionSpec(FD, ESI);
7690 }
7691 
CheckExplicitlyDefaultedFunction(Scope * S,FunctionDecl * FD)7692 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7693   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7694 
7695   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7696   if (!DefKind) {
7697     assert(FD->getDeclContext()->isDependentContext());
7698     return;
7699   }
7700 
7701   if (DefKind.isComparison()) {
7702     auto PT = FD->getParamDecl(0)->getType();
7703     if (const CXXRecordDecl *RD =
7704             PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7705       for (FieldDecl *Field : RD->fields()) {
7706         UnusedPrivateFields.remove(Field);
7707       }
7708     }
7709   }
7710 
7711   if (DefKind.isSpecialMember()
7712           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7713                                                   DefKind.asSpecialMember(),
7714                                                   FD->getDefaultLoc())
7715           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7716     FD->setInvalidDecl();
7717 }
7718 
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD,CXXSpecialMemberKind CSM,SourceLocation DefaultLoc)7719 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7720                                                  CXXSpecialMemberKind CSM,
7721                                                  SourceLocation DefaultLoc) {
7722   CXXRecordDecl *RD = MD->getParent();
7723 
7724   assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7725          "not an explicitly-defaulted special member");
7726 
7727   // Defer all checking for special members of a dependent type.
7728   if (RD->isDependentType())
7729     return false;
7730 
7731   // Whether this was the first-declared instance of the constructor.
7732   // This affects whether we implicitly add an exception spec and constexpr.
7733   bool First = MD == MD->getCanonicalDecl();
7734 
7735   bool HadError = false;
7736 
7737   // C++11 [dcl.fct.def.default]p1:
7738   //   A function that is explicitly defaulted shall
7739   //     -- be a special member function [...] (checked elsewhere),
7740   //     -- have the same type (except for ref-qualifiers, and except that a
7741   //        copy operation can take a non-const reference) as an implicit
7742   //        declaration, and
7743   //     -- not have default arguments.
7744   // C++2a changes the second bullet to instead delete the function if it's
7745   // defaulted on its first declaration, unless it's "an assignment operator,
7746   // and its return type differs or its parameter type is not a reference".
7747   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7748   bool ShouldDeleteForTypeMismatch = false;
7749   unsigned ExpectedParams = 1;
7750   if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7751       CSM == CXXSpecialMemberKind::Destructor)
7752     ExpectedParams = 0;
7753   if (MD->getNumExplicitParams() != ExpectedParams) {
7754     // This checks for default arguments: a copy or move constructor with a
7755     // default argument is classified as a default constructor, and assignment
7756     // operations and destructors can't have default arguments.
7757     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7758         << CSM << MD->getSourceRange();
7759     HadError = true;
7760   } else if (MD->isVariadic()) {
7761     if (DeleteOnTypeMismatch)
7762       ShouldDeleteForTypeMismatch = true;
7763     else {
7764       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7765           << CSM << MD->getSourceRange();
7766       HadError = true;
7767     }
7768   }
7769 
7770   const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7771 
7772   bool CanHaveConstParam = false;
7773   if (CSM == CXXSpecialMemberKind::CopyConstructor)
7774     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7775   else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7776     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7777 
7778   QualType ReturnType = Context.VoidTy;
7779   if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7780       CSM == CXXSpecialMemberKind::MoveAssignment) {
7781     // Check for return type matching.
7782     ReturnType = Type->getReturnType();
7783     QualType ThisType = MD->getFunctionObjectParameterType();
7784 
7785     QualType DeclType = Context.getTypeDeclType(RD);
7786     DeclType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
7787                                          DeclType, nullptr);
7788     DeclType = Context.getAddrSpaceQualType(
7789         DeclType, ThisType.getQualifiers().getAddressSpace());
7790     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7791 
7792     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7793       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7794           << (CSM == CXXSpecialMemberKind::MoveAssignment)
7795           << ExpectedReturnType;
7796       HadError = true;
7797     }
7798 
7799     // A defaulted special member cannot have cv-qualifiers.
7800     if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7801       if (DeleteOnTypeMismatch)
7802         ShouldDeleteForTypeMismatch = true;
7803       else {
7804         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7805             << (CSM == CXXSpecialMemberKind::MoveAssignment)
7806             << getLangOpts().CPlusPlus14;
7807         HadError = true;
7808       }
7809     }
7810     // [C++23][dcl.fct.def.default]/p2.2
7811     // if F2 has an implicit object parameter of type “reference to C”,
7812     // F1 may be an explicit object member function whose explicit object
7813     // parameter is of (possibly different) type “reference to C”,
7814     // in which case the type of F1 would differ from the type of F2
7815     // in that the type of F1 has an additional parameter;
7816     QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7817                                            ? MD->getParamDecl(0)->getType()
7818                                            : QualType();
7819     if (!ExplicitObjectParameter.isNull() &&
7820         (!ExplicitObjectParameter->isReferenceType() ||
7821          !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7822                               Context.getRecordType(RD)))) {
7823       if (DeleteOnTypeMismatch)
7824         ShouldDeleteForTypeMismatch = true;
7825       else {
7826         Diag(MD->getLocation(),
7827              diag::err_defaulted_special_member_explicit_object_mismatch)
7828             << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7829             << MD->getSourceRange();
7830         HadError = true;
7831       }
7832     }
7833   }
7834 
7835   // Check for parameter type matching.
7836   QualType ArgType =
7837       ExpectedParams
7838           ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7839           : QualType();
7840   bool HasConstParam = false;
7841   if (ExpectedParams && ArgType->isReferenceType()) {
7842     // Argument must be reference to possibly-const T.
7843     QualType ReferentType = ArgType->getPointeeType();
7844     HasConstParam = ReferentType.isConstQualified();
7845 
7846     if (ReferentType.isVolatileQualified()) {
7847       if (DeleteOnTypeMismatch)
7848         ShouldDeleteForTypeMismatch = true;
7849       else {
7850         Diag(MD->getLocation(),
7851              diag::err_defaulted_special_member_volatile_param)
7852             << CSM;
7853         HadError = true;
7854       }
7855     }
7856 
7857     if (HasConstParam && !CanHaveConstParam) {
7858       if (DeleteOnTypeMismatch)
7859         ShouldDeleteForTypeMismatch = true;
7860       else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7861                CSM == CXXSpecialMemberKind::CopyAssignment) {
7862         Diag(MD->getLocation(),
7863              diag::err_defaulted_special_member_copy_const_param)
7864             << (CSM == CXXSpecialMemberKind::CopyAssignment);
7865         // FIXME: Explain why this special member can't be const.
7866         HadError = true;
7867       } else {
7868         Diag(MD->getLocation(),
7869              diag::err_defaulted_special_member_move_const_param)
7870             << (CSM == CXXSpecialMemberKind::MoveAssignment);
7871         HadError = true;
7872       }
7873     }
7874   } else if (ExpectedParams) {
7875     // A copy assignment operator can take its argument by value, but a
7876     // defaulted one cannot.
7877     assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7878            "unexpected non-ref argument");
7879     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7880     HadError = true;
7881   }
7882 
7883   // C++11 [dcl.fct.def.default]p2:
7884   //   An explicitly-defaulted function may be declared constexpr only if it
7885   //   would have been implicitly declared as constexpr,
7886   // Do not apply this rule to members of class templates, since core issue 1358
7887   // makes such functions always instantiate to constexpr functions. For
7888   // functions which cannot be constexpr (for non-constructors in C++11 and for
7889   // destructors in C++14 and C++17), this is checked elsewhere.
7890   //
7891   // FIXME: This should not apply if the member is deleted.
7892   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7893                                                      HasConstParam);
7894 
7895   // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7896   //   If the instantiated template specialization of a constexpr function
7897   //   template or member function of a class template would fail to satisfy
7898   //   the requirements for a constexpr function or constexpr constructor, that
7899   //   specialization is still a constexpr function or constexpr constructor,
7900   //   even though a call to such a function cannot appear in a constant
7901   //   expression.
7902   if (MD->isTemplateInstantiation() && MD->isConstexpr())
7903     Constexpr = true;
7904 
7905   if ((getLangOpts().CPlusPlus20 ||
7906        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7907                                   : isa<CXXConstructorDecl>(MD))) &&
7908       MD->isConstexpr() && !Constexpr &&
7909       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7910         if (!MD->isConsteval() && RD->getNumVBases()) {
7911           Diag(MD->getBeginLoc(),
7912                diag::err_incorrect_defaulted_constexpr_with_vb)
7913               << CSM;
7914           for (const auto &I : RD->vbases())
7915             Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7916         } else {
7917           Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7918               << CSM << MD->isConsteval();
7919         }
7920         HadError = true;
7921         // FIXME: Explain why the special member can't be constexpr.
7922   }
7923 
7924   if (First) {
7925     // C++2a [dcl.fct.def.default]p3:
7926     //   If a function is explicitly defaulted on its first declaration, it is
7927     //   implicitly considered to be constexpr if the implicit declaration
7928     //   would be.
7929     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7930                                           ? ConstexprSpecKind::Consteval
7931                                           : ConstexprSpecKind::Constexpr)
7932                                    : ConstexprSpecKind::Unspecified);
7933 
7934     if (!Type->hasExceptionSpec()) {
7935       // C++2a [except.spec]p3:
7936       //   If a declaration of a function does not have a noexcept-specifier
7937       //   [and] is defaulted on its first declaration, [...] the exception
7938       //   specification is as specified below
7939       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7940       EPI.ExceptionSpec.Type = EST_Unevaluated;
7941       EPI.ExceptionSpec.SourceDecl = MD;
7942       MD->setType(
7943           Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7944     }
7945   }
7946 
7947   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7948     if (First) {
7949       SetDeclDeleted(MD, MD->getLocation());
7950       if (!inTemplateInstantiation() && !HadError) {
7951         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7952         if (ShouldDeleteForTypeMismatch) {
7953           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7954         } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7955                                              /*Diagnose*/ true) &&
7956                    DefaultLoc.isValid()) {
7957           Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7958               << FixItHint::CreateReplacement(DefaultLoc, "delete");
7959         }
7960       }
7961       if (ShouldDeleteForTypeMismatch && !HadError) {
7962         Diag(MD->getLocation(),
7963              diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7964             << CSM;
7965       }
7966     } else {
7967       // C++11 [dcl.fct.def.default]p4:
7968       //   [For a] user-provided explicitly-defaulted function [...] if such a
7969       //   function is implicitly defined as deleted, the program is ill-formed.
7970       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7971       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7972       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7973       HadError = true;
7974     }
7975   }
7976 
7977   return HadError;
7978 }
7979 
7980 namespace {
7981 /// Helper class for building and checking a defaulted comparison.
7982 ///
7983 /// Defaulted functions are built in two phases:
7984 ///
7985 ///  * First, the set of operations that the function will perform are
7986 ///    identified, and some of them are checked. If any of the checked
7987 ///    operations is invalid in certain ways, the comparison function is
7988 ///    defined as deleted and no body is built.
7989 ///  * Then, if the function is not defined as deleted, the body is built.
7990 ///
7991 /// This is accomplished by performing two visitation steps over the eventual
7992 /// body of the function.
7993 template<typename Derived, typename ResultList, typename Result,
7994          typename Subobject>
7995 class DefaultedComparisonVisitor {
7996 public:
7997   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7998 
DefaultedComparisonVisitor(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK)7999   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8000                              DefaultedComparisonKind DCK)
8001       : S(S), RD(RD), FD(FD), DCK(DCK) {
8002     if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
8003       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8004       // UnresolvedSet to avoid this copy.
8005       Fns.assign(Info->getUnqualifiedLookups().begin(),
8006                  Info->getUnqualifiedLookups().end());
8007     }
8008   }
8009 
visit()8010   ResultList visit() {
8011     // The type of an lvalue naming a parameter of this function.
8012     QualType ParamLvalType =
8013         FD->getParamDecl(0)->getType().getNonReferenceType();
8014 
8015     ResultList Results;
8016 
8017     switch (DCK) {
8018     case DefaultedComparisonKind::None:
8019       llvm_unreachable("not a defaulted comparison");
8020 
8021     case DefaultedComparisonKind::Equal:
8022     case DefaultedComparisonKind::ThreeWay:
8023       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8024       return Results;
8025 
8026     case DefaultedComparisonKind::NotEqual:
8027     case DefaultedComparisonKind::Relational:
8028       Results.add(getDerived().visitExpandedSubobject(
8029           ParamLvalType, getDerived().getCompleteObject()));
8030       return Results;
8031     }
8032     llvm_unreachable("");
8033   }
8034 
8035 protected:
getDerived()8036   Derived &getDerived() { return static_cast<Derived&>(*this); }
8037 
8038   /// Visit the expanded list of subobjects of the given type, as specified in
8039   /// C++2a [class.compare.default].
8040   ///
8041   /// \return \c true if the ResultList object said we're done, \c false if not.
visitSubobjects(ResultList & Results,CXXRecordDecl * Record,Qualifiers Quals)8042   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8043                        Qualifiers Quals) {
8044     // C++2a [class.compare.default]p4:
8045     //   The direct base class subobjects of C
8046     for (CXXBaseSpecifier &Base : Record->bases())
8047       if (Results.add(getDerived().visitSubobject(
8048               S.Context.getQualifiedType(Base.getType(), Quals),
8049               getDerived().getBase(&Base))))
8050         return true;
8051 
8052     //   followed by the non-static data members of C
8053     for (FieldDecl *Field : Record->fields()) {
8054       // C++23 [class.bit]p2:
8055       //   Unnamed bit-fields are not members ...
8056       if (Field->isUnnamedBitField())
8057         continue;
8058       // Recursively expand anonymous structs.
8059       if (Field->isAnonymousStructOrUnion()) {
8060         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8061                             Quals))
8062           return true;
8063         continue;
8064       }
8065 
8066       // Figure out the type of an lvalue denoting this field.
8067       Qualifiers FieldQuals = Quals;
8068       if (Field->isMutable())
8069         FieldQuals.removeConst();
8070       QualType FieldType =
8071           S.Context.getQualifiedType(Field->getType(), FieldQuals);
8072 
8073       if (Results.add(getDerived().visitSubobject(
8074               FieldType, getDerived().getField(Field))))
8075         return true;
8076     }
8077 
8078     //   form a list of subobjects.
8079     return false;
8080   }
8081 
visitSubobject(QualType Type,Subobject Subobj)8082   Result visitSubobject(QualType Type, Subobject Subobj) {
8083     //   In that list, any subobject of array type is recursively expanded
8084     const ArrayType *AT = S.Context.getAsArrayType(Type);
8085     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8086       return getDerived().visitSubobjectArray(CAT->getElementType(),
8087                                               CAT->getSize(), Subobj);
8088     return getDerived().visitExpandedSubobject(Type, Subobj);
8089   }
8090 
visitSubobjectArray(QualType Type,const llvm::APInt & Size,Subobject Subobj)8091   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8092                              Subobject Subobj) {
8093     return getDerived().visitSubobject(Type, Subobj);
8094   }
8095 
8096 protected:
8097   Sema &S;
8098   CXXRecordDecl *RD;
8099   FunctionDecl *FD;
8100   DefaultedComparisonKind DCK;
8101   UnresolvedSet<16> Fns;
8102 };
8103 
8104 /// Information about a defaulted comparison, as determined by
8105 /// DefaultedComparisonAnalyzer.
8106 struct DefaultedComparisonInfo {
8107   bool Deleted = false;
8108   bool Constexpr = true;
8109   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8110 
deleted__anon42c808802011::DefaultedComparisonInfo8111   static DefaultedComparisonInfo deleted() {
8112     DefaultedComparisonInfo Deleted;
8113     Deleted.Deleted = true;
8114     return Deleted;
8115   }
8116 
add__anon42c808802011::DefaultedComparisonInfo8117   bool add(const DefaultedComparisonInfo &R) {
8118     Deleted |= R.Deleted;
8119     Constexpr &= R.Constexpr;
8120     Category = commonComparisonType(Category, R.Category);
8121     return Deleted;
8122   }
8123 };
8124 
8125 /// An element in the expanded list of subobjects of a defaulted comparison, as
8126 /// specified in C++2a [class.compare.default]p4.
8127 struct DefaultedComparisonSubobject {
8128   enum { CompleteObject, Member, Base } Kind;
8129   NamedDecl *Decl;
8130   SourceLocation Loc;
8131 };
8132 
8133 /// A visitor over the notional body of a defaulted comparison that determines
8134 /// whether that body would be deleted or constexpr.
8135 class DefaultedComparisonAnalyzer
8136     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8137                                         DefaultedComparisonInfo,
8138                                         DefaultedComparisonInfo,
8139                                         DefaultedComparisonSubobject> {
8140 public:
8141   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8142 
8143 private:
8144   DiagnosticKind Diagnose;
8145 
8146 public:
8147   using Base = DefaultedComparisonVisitor;
8148   using Result = DefaultedComparisonInfo;
8149   using Subobject = DefaultedComparisonSubobject;
8150 
8151   friend Base;
8152 
DefaultedComparisonAnalyzer(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK,DiagnosticKind Diagnose=NoDiagnostics)8153   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8154                               DefaultedComparisonKind DCK,
8155                               DiagnosticKind Diagnose = NoDiagnostics)
8156       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8157 
visit()8158   Result visit() {
8159     if ((DCK == DefaultedComparisonKind::Equal ||
8160          DCK == DefaultedComparisonKind::ThreeWay) &&
8161         RD->hasVariantMembers()) {
8162       // C++2a [class.compare.default]p2 [P2002R0]:
8163       //   A defaulted comparison operator function for class C is defined as
8164       //   deleted if [...] C has variant members.
8165       if (Diagnose == ExplainDeleted) {
8166         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8167           << FD << RD->isUnion() << RD;
8168       }
8169       return Result::deleted();
8170     }
8171 
8172     return Base::visit();
8173   }
8174 
8175 private:
getCompleteObject()8176   Subobject getCompleteObject() {
8177     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8178   }
8179 
getBase(CXXBaseSpecifier * Base)8180   Subobject getBase(CXXBaseSpecifier *Base) {
8181     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8182                      Base->getBaseTypeLoc()};
8183   }
8184 
getField(FieldDecl * Field)8185   Subobject getField(FieldDecl *Field) {
8186     return Subobject{Subobject::Member, Field, Field->getLocation()};
8187   }
8188 
visitExpandedSubobject(QualType Type,Subobject Subobj)8189   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8190     // C++2a [class.compare.default]p2 [P2002R0]:
8191     //   A defaulted <=> or == operator function for class C is defined as
8192     //   deleted if any non-static data member of C is of reference type
8193     if (Type->isReferenceType()) {
8194       if (Diagnose == ExplainDeleted) {
8195         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8196             << FD << RD;
8197       }
8198       return Result::deleted();
8199     }
8200 
8201     // [...] Let xi be an lvalue denoting the ith element [...]
8202     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8203     Expr *Args[] = {&Xi, &Xi};
8204 
8205     // All operators start by trying to apply that same operator recursively.
8206     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8207     assert(OO != OO_None && "not an overloaded operator!");
8208     return visitBinaryOperator(OO, Args, Subobj);
8209   }
8210 
8211   Result
visitBinaryOperator(OverloadedOperatorKind OO,ArrayRef<Expr * > Args,Subobject Subobj,OverloadCandidateSet * SpaceshipCandidates=nullptr)8212   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8213                       Subobject Subobj,
8214                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8215     // Note that there is no need to consider rewritten candidates here if
8216     // we've already found there is no viable 'operator<=>' candidate (and are
8217     // considering synthesizing a '<=>' from '==' and '<').
8218     OverloadCandidateSet CandidateSet(
8219         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8220         OverloadCandidateSet::OperatorRewriteInfo(
8221             OO, FD->getLocation(),
8222             /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8223 
8224     /// C++2a [class.compare.default]p1 [P2002R0]:
8225     ///   [...] the defaulted function itself is never a candidate for overload
8226     ///   resolution [...]
8227     CandidateSet.exclude(FD);
8228 
8229     if (Args[0]->getType()->isOverloadableType())
8230       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8231     else
8232       // FIXME: We determine whether this is a valid expression by checking to
8233       // see if there's a viable builtin operator candidate for it. That isn't
8234       // really what the rules ask us to do, but should give the right results.
8235       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8236 
8237     Result R;
8238 
8239     OverloadCandidateSet::iterator Best;
8240     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8241     case OR_Success: {
8242       // C++2a [class.compare.secondary]p2 [P2002R0]:
8243       //   The operator function [...] is defined as deleted if [...] the
8244       //   candidate selected by overload resolution is not a rewritten
8245       //   candidate.
8246       if ((DCK == DefaultedComparisonKind::NotEqual ||
8247            DCK == DefaultedComparisonKind::Relational) &&
8248           !Best->RewriteKind) {
8249         if (Diagnose == ExplainDeleted) {
8250           if (Best->Function) {
8251             S.Diag(Best->Function->getLocation(),
8252                    diag::note_defaulted_comparison_not_rewritten_callee)
8253                 << FD;
8254           } else {
8255             assert(Best->Conversions.size() == 2 &&
8256                    Best->Conversions[0].isUserDefined() &&
8257                    "non-user-defined conversion from class to built-in "
8258                    "comparison");
8259             S.Diag(Best->Conversions[0]
8260                        .UserDefined.FoundConversionFunction.getDecl()
8261                        ->getLocation(),
8262                    diag::note_defaulted_comparison_not_rewritten_conversion)
8263                 << FD;
8264           }
8265         }
8266         return Result::deleted();
8267       }
8268 
8269       // Throughout C++2a [class.compare]: if overload resolution does not
8270       // result in a usable function, the candidate function is defined as
8271       // deleted. This requires that we selected an accessible function.
8272       //
8273       // Note that this only considers the access of the function when named
8274       // within the type of the subobject, and not the access path for any
8275       // derived-to-base conversion.
8276       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8277       if (ArgClass && Best->FoundDecl.getDecl() &&
8278           Best->FoundDecl.getDecl()->isCXXClassMember()) {
8279         QualType ObjectType = Subobj.Kind == Subobject::Member
8280                                   ? Args[0]->getType()
8281                                   : S.Context.getRecordType(RD);
8282         if (!S.isMemberAccessibleForDeletion(
8283                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8284                 Diagnose == ExplainDeleted
8285                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8286                           << FD << Subobj.Kind << Subobj.Decl
8287                     : S.PDiag()))
8288           return Result::deleted();
8289       }
8290 
8291       bool NeedsDeducing =
8292           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8293 
8294       if (FunctionDecl *BestFD = Best->Function) {
8295         // C++2a [class.compare.default]p3 [P2002R0]:
8296         //   A defaulted comparison function is constexpr-compatible if
8297         //   [...] no overlod resolution performed [...] results in a
8298         //   non-constexpr function.
8299         assert(!BestFD->isDeleted() && "wrong overload resolution result");
8300         // If it's not constexpr, explain why not.
8301         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8302           if (Subobj.Kind != Subobject::CompleteObject)
8303             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8304               << Subobj.Kind << Subobj.Decl;
8305           S.Diag(BestFD->getLocation(),
8306                  diag::note_defaulted_comparison_not_constexpr_here);
8307           // Bail out after explaining; we don't want any more notes.
8308           return Result::deleted();
8309         }
8310         R.Constexpr &= BestFD->isConstexpr();
8311 
8312         if (NeedsDeducing) {
8313           // If any callee has an undeduced return type, deduce it now.
8314           // FIXME: It's not clear how a failure here should be handled. For
8315           // now, we produce an eager diagnostic, because that is forward
8316           // compatible with most (all?) other reasonable options.
8317           if (BestFD->getReturnType()->isUndeducedType() &&
8318               S.DeduceReturnType(BestFD, FD->getLocation(),
8319                                  /*Diagnose=*/false)) {
8320             // Don't produce a duplicate error when asked to explain why the
8321             // comparison is deleted: we diagnosed that when initially checking
8322             // the defaulted operator.
8323             if (Diagnose == NoDiagnostics) {
8324               S.Diag(
8325                   FD->getLocation(),
8326                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8327                   << Subobj.Kind << Subobj.Decl;
8328               S.Diag(
8329                   Subobj.Loc,
8330                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8331                   << Subobj.Kind << Subobj.Decl;
8332               S.Diag(BestFD->getLocation(),
8333                      diag::note_defaulted_comparison_cannot_deduce_callee)
8334                   << Subobj.Kind << Subobj.Decl;
8335             }
8336             return Result::deleted();
8337           }
8338           auto *Info = S.Context.CompCategories.lookupInfoForType(
8339               BestFD->getCallResultType());
8340           if (!Info) {
8341             if (Diagnose == ExplainDeleted) {
8342               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8343                   << Subobj.Kind << Subobj.Decl
8344                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
8345               S.Diag(BestFD->getLocation(),
8346                      diag::note_defaulted_comparison_cannot_deduce_callee)
8347                   << Subobj.Kind << Subobj.Decl;
8348             }
8349             return Result::deleted();
8350           }
8351           R.Category = Info->Kind;
8352         }
8353       } else {
8354         QualType T = Best->BuiltinParamTypes[0];
8355         assert(T == Best->BuiltinParamTypes[1] &&
8356                "builtin comparison for different types?");
8357         assert(Best->BuiltinParamTypes[2].isNull() &&
8358                "invalid builtin comparison");
8359 
8360         // FIXME: If the type we deduced is a vector type, we mark the
8361         // comparison as deleted because we don't yet support this.
8362         if (isa<VectorType>(T)) {
8363           if (Diagnose == ExplainDeleted) {
8364             S.Diag(FD->getLocation(),
8365                    diag::note_defaulted_comparison_vector_types)
8366                 << FD;
8367             S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8368           }
8369           return Result::deleted();
8370         }
8371 
8372         if (NeedsDeducing) {
8373           std::optional<ComparisonCategoryType> Cat =
8374               getComparisonCategoryForBuiltinCmp(T);
8375           assert(Cat && "no category for builtin comparison?");
8376           R.Category = *Cat;
8377         }
8378       }
8379 
8380       // Note that we might be rewriting to a different operator. That call is
8381       // not considered until we come to actually build the comparison function.
8382       break;
8383     }
8384 
8385     case OR_Ambiguous:
8386       if (Diagnose == ExplainDeleted) {
8387         unsigned Kind = 0;
8388         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8389           Kind = OO == OO_EqualEqual ? 1 : 2;
8390         CandidateSet.NoteCandidates(
8391             PartialDiagnosticAt(
8392                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8393                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8394             S, OCD_AmbiguousCandidates, Args);
8395       }
8396       R = Result::deleted();
8397       break;
8398 
8399     case OR_Deleted:
8400       if (Diagnose == ExplainDeleted) {
8401         if ((DCK == DefaultedComparisonKind::NotEqual ||
8402              DCK == DefaultedComparisonKind::Relational) &&
8403             !Best->RewriteKind) {
8404           S.Diag(Best->Function->getLocation(),
8405                  diag::note_defaulted_comparison_not_rewritten_callee)
8406               << FD;
8407         } else {
8408           S.Diag(Subobj.Loc,
8409                  diag::note_defaulted_comparison_calls_deleted)
8410               << FD << Subobj.Kind << Subobj.Decl;
8411           S.NoteDeletedFunction(Best->Function);
8412         }
8413       }
8414       R = Result::deleted();
8415       break;
8416 
8417     case OR_No_Viable_Function:
8418       // If there's no usable candidate, we're done unless we can rewrite a
8419       // '<=>' in terms of '==' and '<'.
8420       if (OO == OO_Spaceship &&
8421           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8422         // For any kind of comparison category return type, we need a usable
8423         // '==' and a usable '<'.
8424         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8425                                        &CandidateSet)))
8426           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8427         break;
8428       }
8429 
8430       if (Diagnose == ExplainDeleted) {
8431         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8432             << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8433             << Subobj.Kind << Subobj.Decl;
8434 
8435         // For a three-way comparison, list both the candidates for the
8436         // original operator and the candidates for the synthesized operator.
8437         if (SpaceshipCandidates) {
8438           SpaceshipCandidates->NoteCandidates(
8439               S, Args,
8440               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8441                                                       Args, FD->getLocation()));
8442           S.Diag(Subobj.Loc,
8443                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8444               << (OO == OO_EqualEqual ? 0 : 1);
8445         }
8446 
8447         CandidateSet.NoteCandidates(
8448             S, Args,
8449             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8450                                             FD->getLocation()));
8451       }
8452       R = Result::deleted();
8453       break;
8454     }
8455 
8456     return R;
8457   }
8458 };
8459 
8460 /// A list of statements.
8461 struct StmtListResult {
8462   bool IsInvalid = false;
8463   llvm::SmallVector<Stmt*, 16> Stmts;
8464 
add__anon42c808802011::StmtListResult8465   bool add(const StmtResult &S) {
8466     IsInvalid |= S.isInvalid();
8467     if (IsInvalid)
8468       return true;
8469     Stmts.push_back(S.get());
8470     return false;
8471   }
8472 };
8473 
8474 /// A visitor over the notional body of a defaulted comparison that synthesizes
8475 /// the actual body.
8476 class DefaultedComparisonSynthesizer
8477     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8478                                         StmtListResult, StmtResult,
8479                                         std::pair<ExprResult, ExprResult>> {
8480   SourceLocation Loc;
8481   unsigned ArrayDepth = 0;
8482 
8483 public:
8484   using Base = DefaultedComparisonVisitor;
8485   using ExprPair = std::pair<ExprResult, ExprResult>;
8486 
8487   friend Base;
8488 
DefaultedComparisonSynthesizer(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK,SourceLocation BodyLoc)8489   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8490                                  DefaultedComparisonKind DCK,
8491                                  SourceLocation BodyLoc)
8492       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8493 
8494   /// Build a suitable function body for this defaulted comparison operator.
build()8495   StmtResult build() {
8496     Sema::CompoundScopeRAII CompoundScope(S);
8497 
8498     StmtListResult Stmts = visit();
8499     if (Stmts.IsInvalid)
8500       return StmtError();
8501 
8502     ExprResult RetVal;
8503     switch (DCK) {
8504     case DefaultedComparisonKind::None:
8505       llvm_unreachable("not a defaulted comparison");
8506 
8507     case DefaultedComparisonKind::Equal: {
8508       // C++2a [class.eq]p3:
8509       //   [...] compar[e] the corresponding elements [...] until the first
8510       //   index i where xi == yi yields [...] false. If no such index exists,
8511       //   V is true. Otherwise, V is false.
8512       //
8513       // Join the comparisons with '&&'s and return the result. Use a right
8514       // fold (traversing the conditions right-to-left), because that
8515       // short-circuits more naturally.
8516       auto OldStmts = std::move(Stmts.Stmts);
8517       Stmts.Stmts.clear();
8518       ExprResult CmpSoFar;
8519       // Finish a particular comparison chain.
8520       auto FinishCmp = [&] {
8521         if (Expr *Prior = CmpSoFar.get()) {
8522           // Convert the last expression to 'return ...;'
8523           if (RetVal.isUnset() && Stmts.Stmts.empty())
8524             RetVal = CmpSoFar;
8525           // Convert any prior comparison to 'if (!(...)) return false;'
8526           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8527             return true;
8528           CmpSoFar = ExprResult();
8529         }
8530         return false;
8531       };
8532       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8533         Expr *E = dyn_cast<Expr>(EAsStmt);
8534         if (!E) {
8535           // Found an array comparison.
8536           if (FinishCmp() || Stmts.add(EAsStmt))
8537             return StmtError();
8538           continue;
8539         }
8540 
8541         if (CmpSoFar.isUnset()) {
8542           CmpSoFar = E;
8543           continue;
8544         }
8545         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8546         if (CmpSoFar.isInvalid())
8547           return StmtError();
8548       }
8549       if (FinishCmp())
8550         return StmtError();
8551       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8552       //   If no such index exists, V is true.
8553       if (RetVal.isUnset())
8554         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8555       break;
8556     }
8557 
8558     case DefaultedComparisonKind::ThreeWay: {
8559       // Per C++2a [class.spaceship]p3, as a fallback add:
8560       // return static_cast<R>(std::strong_ordering::equal);
8561       QualType StrongOrdering = S.CheckComparisonCategoryType(
8562           ComparisonCategoryType::StrongOrdering, Loc,
8563           Sema::ComparisonCategoryUsage::DefaultedOperator);
8564       if (StrongOrdering.isNull())
8565         return StmtError();
8566       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8567                              .getValueInfo(ComparisonCategoryResult::Equal)
8568                              ->VD;
8569       RetVal = getDecl(EqualVD);
8570       if (RetVal.isInvalid())
8571         return StmtError();
8572       RetVal = buildStaticCastToR(RetVal.get());
8573       break;
8574     }
8575 
8576     case DefaultedComparisonKind::NotEqual:
8577     case DefaultedComparisonKind::Relational:
8578       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8579       break;
8580     }
8581 
8582     // Build the final return statement.
8583     if (RetVal.isInvalid())
8584       return StmtError();
8585     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8586     if (ReturnStmt.isInvalid())
8587       return StmtError();
8588     Stmts.Stmts.push_back(ReturnStmt.get());
8589 
8590     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8591   }
8592 
8593 private:
getDecl(ValueDecl * VD)8594   ExprResult getDecl(ValueDecl *VD) {
8595     return S.BuildDeclarationNameExpr(
8596         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8597   }
8598 
getParam(unsigned I)8599   ExprResult getParam(unsigned I) {
8600     ParmVarDecl *PD = FD->getParamDecl(I);
8601     return getDecl(PD);
8602   }
8603 
getCompleteObject()8604   ExprPair getCompleteObject() {
8605     unsigned Param = 0;
8606     ExprResult LHS;
8607     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8608         MD && MD->isImplicitObjectMemberFunction()) {
8609       // LHS is '*this'.
8610       LHS = S.ActOnCXXThis(Loc);
8611       if (!LHS.isInvalid())
8612         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8613     } else {
8614       LHS = getParam(Param++);
8615     }
8616     ExprResult RHS = getParam(Param++);
8617     assert(Param == FD->getNumParams());
8618     return {LHS, RHS};
8619   }
8620 
getBase(CXXBaseSpecifier * Base)8621   ExprPair getBase(CXXBaseSpecifier *Base) {
8622     ExprPair Obj = getCompleteObject();
8623     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8624       return {ExprError(), ExprError()};
8625     CXXCastPath Path = {Base};
8626     const auto CastToBase = [&](Expr *E) {
8627       QualType ToType = S.Context.getQualifiedType(
8628           Base->getType(), E->getType().getQualifiers());
8629       return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8630     };
8631     return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8632   }
8633 
getField(FieldDecl * Field)8634   ExprPair getField(FieldDecl *Field) {
8635     ExprPair Obj = getCompleteObject();
8636     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8637       return {ExprError(), ExprError()};
8638 
8639     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8640     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8641     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8642                                       CXXScopeSpec(), Field, Found, NameInfo),
8643             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8644                                       CXXScopeSpec(), Field, Found, NameInfo)};
8645   }
8646 
8647   // FIXME: When expanding a subobject, register a note in the code synthesis
8648   // stack to say which subobject we're comparing.
8649 
buildIfNotCondReturnFalse(ExprResult Cond)8650   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8651     if (Cond.isInvalid())
8652       return StmtError();
8653 
8654     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8655     if (NotCond.isInvalid())
8656       return StmtError();
8657 
8658     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8659     assert(!False.isInvalid() && "should never fail");
8660     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8661     if (ReturnFalse.isInvalid())
8662       return StmtError();
8663 
8664     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8665                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8666                                           Sema::ConditionKind::Boolean),
8667                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8668   }
8669 
visitSubobjectArray(QualType Type,llvm::APInt Size,ExprPair Subobj)8670   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8671                                  ExprPair Subobj) {
8672     QualType SizeType = S.Context.getSizeType();
8673     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8674 
8675     // Build 'size_t i$n = 0'.
8676     IdentifierInfo *IterationVarName = nullptr;
8677     {
8678       SmallString<8> Str;
8679       llvm::raw_svector_ostream OS(Str);
8680       OS << "i" << ArrayDepth;
8681       IterationVarName = &S.Context.Idents.get(OS.str());
8682     }
8683     VarDecl *IterationVar = VarDecl::Create(
8684         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8685         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8686     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8687     IterationVar->setInit(
8688         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8689     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8690 
8691     auto IterRef = [&] {
8692       ExprResult Ref = S.BuildDeclarationNameExpr(
8693           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8694           IterationVar);
8695       assert(!Ref.isInvalid() && "can't reference our own variable?");
8696       return Ref.get();
8697     };
8698 
8699     // Build 'i$n != Size'.
8700     ExprResult Cond = S.CreateBuiltinBinOp(
8701         Loc, BO_NE, IterRef(),
8702         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8703     assert(!Cond.isInvalid() && "should never fail");
8704 
8705     // Build '++i$n'.
8706     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8707     assert(!Inc.isInvalid() && "should never fail");
8708 
8709     // Build 'a[i$n]' and 'b[i$n]'.
8710     auto Index = [&](ExprResult E) {
8711       if (E.isInvalid())
8712         return ExprError();
8713       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8714     };
8715     Subobj.first = Index(Subobj.first);
8716     Subobj.second = Index(Subobj.second);
8717 
8718     // Compare the array elements.
8719     ++ArrayDepth;
8720     StmtResult Substmt = visitSubobject(Type, Subobj);
8721     --ArrayDepth;
8722 
8723     if (Substmt.isInvalid())
8724       return StmtError();
8725 
8726     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8727     // For outer levels or for an 'operator<=>' we already have a suitable
8728     // statement that returns as necessary.
8729     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8730       assert(DCK == DefaultedComparisonKind::Equal &&
8731              "should have non-expression statement");
8732       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8733       if (Substmt.isInvalid())
8734         return StmtError();
8735     }
8736 
8737     // Build 'for (...) ...'
8738     return S.ActOnForStmt(Loc, Loc, Init,
8739                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8740                                            Sema::ConditionKind::Boolean),
8741                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8742                           Substmt.get());
8743   }
8744 
visitExpandedSubobject(QualType Type,ExprPair Obj)8745   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8746     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8747       return StmtError();
8748 
8749     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8750     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8751     ExprResult Op;
8752     if (Type->isOverloadableType())
8753       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8754                                    Obj.second.get(), /*PerformADL=*/true,
8755                                    /*AllowRewrittenCandidates=*/true, FD);
8756     else
8757       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8758     if (Op.isInvalid())
8759       return StmtError();
8760 
8761     switch (DCK) {
8762     case DefaultedComparisonKind::None:
8763       llvm_unreachable("not a defaulted comparison");
8764 
8765     case DefaultedComparisonKind::Equal:
8766       // Per C++2a [class.eq]p2, each comparison is individually contextually
8767       // converted to bool.
8768       Op = S.PerformContextuallyConvertToBool(Op.get());
8769       if (Op.isInvalid())
8770         return StmtError();
8771       return Op.get();
8772 
8773     case DefaultedComparisonKind::ThreeWay: {
8774       // Per C++2a [class.spaceship]p3, form:
8775       //   if (R cmp = static_cast<R>(op); cmp != 0)
8776       //     return cmp;
8777       QualType R = FD->getReturnType();
8778       Op = buildStaticCastToR(Op.get());
8779       if (Op.isInvalid())
8780         return StmtError();
8781 
8782       // R cmp = ...;
8783       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8784       VarDecl *VD =
8785           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8786                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8787       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8788       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8789 
8790       // cmp != 0
8791       ExprResult VDRef = getDecl(VD);
8792       if (VDRef.isInvalid())
8793         return StmtError();
8794       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8795       Expr *Zero =
8796           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8797       ExprResult Comp;
8798       if (VDRef.get()->getType()->isOverloadableType())
8799         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8800                                        true, FD);
8801       else
8802         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8803       if (Comp.isInvalid())
8804         return StmtError();
8805       Sema::ConditionResult Cond = S.ActOnCondition(
8806           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8807       if (Cond.isInvalid())
8808         return StmtError();
8809 
8810       // return cmp;
8811       VDRef = getDecl(VD);
8812       if (VDRef.isInvalid())
8813         return StmtError();
8814       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8815       if (ReturnStmt.isInvalid())
8816         return StmtError();
8817 
8818       // if (...)
8819       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8820                            Loc, ReturnStmt.get(),
8821                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8822     }
8823 
8824     case DefaultedComparisonKind::NotEqual:
8825     case DefaultedComparisonKind::Relational:
8826       // C++2a [class.compare.secondary]p2:
8827       //   Otherwise, the operator function yields x @ y.
8828       return Op.get();
8829     }
8830     llvm_unreachable("");
8831   }
8832 
8833   /// Build "static_cast<R>(E)".
buildStaticCastToR(Expr * E)8834   ExprResult buildStaticCastToR(Expr *E) {
8835     QualType R = FD->getReturnType();
8836     assert(!R->isUndeducedType() && "type should have been deduced already");
8837 
8838     // Don't bother forming a no-op cast in the common case.
8839     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8840       return E;
8841     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8842                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8843                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8844   }
8845 };
8846 }
8847 
8848 /// Perform the unqualified lookups that might be needed to form a defaulted
8849 /// comparison function for the given operator.
lookupOperatorsForDefaultedComparison(Sema & Self,Scope * S,UnresolvedSetImpl & Operators,OverloadedOperatorKind Op)8850 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8851                                                   UnresolvedSetImpl &Operators,
8852                                                   OverloadedOperatorKind Op) {
8853   auto Lookup = [&](OverloadedOperatorKind OO) {
8854     Self.LookupOverloadedOperatorName(OO, S, Operators);
8855   };
8856 
8857   // Every defaulted operator looks up itself.
8858   Lookup(Op);
8859   // ... and the rewritten form of itself, if any.
8860   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8861     Lookup(ExtraOp);
8862 
8863   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8864   // synthesize a three-way comparison from '<' and '=='. In a dependent
8865   // context, we also need to look up '==' in case we implicitly declare a
8866   // defaulted 'operator=='.
8867   if (Op == OO_Spaceship) {
8868     Lookup(OO_ExclaimEqual);
8869     Lookup(OO_Less);
8870     Lookup(OO_EqualEqual);
8871   }
8872 }
8873 
CheckExplicitlyDefaultedComparison(Scope * S,FunctionDecl * FD,DefaultedComparisonKind DCK)8874 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8875                                               DefaultedComparisonKind DCK) {
8876   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8877 
8878   // Perform any unqualified lookups we're going to need to default this
8879   // function.
8880   if (S) {
8881     UnresolvedSet<32> Operators;
8882     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8883                                           FD->getOverloadedOperator());
8884     FD->setDefaultedOrDeletedInfo(
8885         FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
8886             Context, Operators.pairs()));
8887   }
8888 
8889   // C++2a [class.compare.default]p1:
8890   //   A defaulted comparison operator function for some class C shall be a
8891   //   non-template function declared in the member-specification of C that is
8892   //    -- a non-static const non-volatile member of C having one parameter of
8893   //       type const C& and either no ref-qualifier or the ref-qualifier &, or
8894   //    -- a friend of C having two parameters of type const C& or two
8895   //       parameters of type C.
8896 
8897   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8898   bool IsMethod = isa<CXXMethodDecl>(FD);
8899   if (IsMethod) {
8900     auto *MD = cast<CXXMethodDecl>(FD);
8901     assert(!MD->isStatic() && "comparison function cannot be a static member");
8902 
8903     if (MD->getRefQualifier() == RQ_RValue) {
8904       Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8905 
8906       // Remove the ref qualifier to recover.
8907       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8908       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8909       EPI.RefQualifier = RQ_None;
8910       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8911                                           FPT->getParamTypes(), EPI));
8912     }
8913 
8914     // If we're out-of-class, this is the class we're comparing.
8915     if (!RD)
8916       RD = MD->getParent();
8917     QualType T = MD->getFunctionObjectParameterReferenceType();
8918     if (!T.getNonReferenceType().isConstQualified() &&
8919         (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
8920       SourceLocation Loc, InsertLoc;
8921       if (MD->isExplicitObjectMemberFunction()) {
8922         Loc = MD->getParamDecl(0)->getBeginLoc();
8923         InsertLoc = getLocForEndOfToken(
8924             MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8925       } else {
8926         Loc = MD->getLocation();
8927         if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8928           InsertLoc = Loc.getRParenLoc();
8929       }
8930       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8931       // corresponding defaulted 'operator<=>' already.
8932       if (!MD->isImplicit()) {
8933         Diag(Loc, diag::err_defaulted_comparison_non_const)
8934             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8935       }
8936 
8937       // Add the 'const' to the type to recover.
8938       if (MD->isExplicitObjectMemberFunction()) {
8939         assert(T->isLValueReferenceType());
8940         MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
8941             T.getNonReferenceType().withConst()));
8942       } else {
8943         const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8944         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8945         EPI.TypeQuals.addConst();
8946         MD->setType(Context.getFunctionType(FPT->getReturnType(),
8947                                             FPT->getParamTypes(), EPI));
8948       }
8949     }
8950 
8951     if (MD->isVolatile()) {
8952       Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8953 
8954       // Remove the 'volatile' from the type to recover.
8955       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8956       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8957       EPI.TypeQuals.removeVolatile();
8958       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8959                                           FPT->getParamTypes(), EPI));
8960     }
8961   }
8962 
8963   if ((FD->getNumParams() -
8964        (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8965       (IsMethod ? 1 : 2)) {
8966     // Let's not worry about using a variadic template pack here -- who would do
8967     // such a thing?
8968     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8969         << int(IsMethod) << int(DCK);
8970     return true;
8971   }
8972 
8973   const ParmVarDecl *KnownParm = nullptr;
8974   for (const ParmVarDecl *Param : FD->parameters()) {
8975     QualType ParmTy = Param->getType();
8976     if (!KnownParm) {
8977       auto CTy = ParmTy;
8978       // Is it `T const &`?
8979       bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8980       QualType ExpectedTy;
8981       if (RD)
8982         ExpectedTy = Context.getRecordType(RD);
8983       if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
8984         CTy = Ref->getPointeeType();
8985         if (RD)
8986           ExpectedTy.addConst();
8987         Ok = true;
8988       }
8989 
8990       // Is T a class?
8991       if (RD) {
8992         Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
8993       } else {
8994         RD = CTy->getAsCXXRecordDecl();
8995         Ok &= RD != nullptr;
8996       }
8997 
8998       if (Ok) {
8999         KnownParm = Param;
9000       } else {
9001         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9002         // corresponding defaulted 'operator<=>' already.
9003         if (!FD->isImplicit()) {
9004           if (RD) {
9005             QualType PlainTy = Context.getRecordType(RD);
9006             QualType RefTy =
9007                 Context.getLValueReferenceType(PlainTy.withConst());
9008             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9009                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9010                 << Param->getSourceRange();
9011           } else {
9012             assert(!IsMethod && "should know expected type for method");
9013             Diag(FD->getLocation(),
9014                  diag::err_defaulted_comparison_param_unknown)
9015                 << int(DCK) << ParmTy << Param->getSourceRange();
9016           }
9017         }
9018         return true;
9019       }
9020     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9021       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9022           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9023           << ParmTy << Param->getSourceRange();
9024       return true;
9025     }
9026   }
9027 
9028   assert(RD && "must have determined class");
9029   if (IsMethod) {
9030   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9031     // In-class, must be a friend decl.
9032     assert(FD->getFriendObjectKind() && "expected a friend declaration");
9033   } else {
9034     // Out of class, require the defaulted comparison to be a friend (of a
9035     // complete type, per CWG2547).
9036     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
9037                             diag::err_defaulted_comparison_not_friend, int(DCK),
9038                             int(1)))
9039       return true;
9040 
9041     if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9042           return declaresSameEntity(F->getFriendDecl(), FD);
9043         })) {
9044       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9045           << int(DCK) << int(0) << RD;
9046       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9047       return true;
9048     }
9049   }
9050 
9051   // C++2a [class.eq]p1, [class.rel]p1:
9052   //   A [defaulted comparison other than <=>] shall have a declared return
9053   //   type bool.
9054   if (DCK != DefaultedComparisonKind::ThreeWay &&
9055       !FD->getDeclaredReturnType()->isDependentType() &&
9056       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9057     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9058         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9059         << FD->getReturnTypeSourceRange();
9060     return true;
9061   }
9062   // C++2a [class.spaceship]p2 [P2002R0]:
9063   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9064   //   R shall not contain a placeholder type.
9065   if (QualType RT = FD->getDeclaredReturnType();
9066       DCK == DefaultedComparisonKind::ThreeWay &&
9067       RT->getContainedDeducedType() &&
9068       (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9069        RT->getContainedAutoType()->isConstrained())) {
9070     Diag(FD->getLocation(),
9071          diag::err_defaulted_comparison_deduced_return_type_not_auto)
9072         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9073         << FD->getReturnTypeSourceRange();
9074     return true;
9075   }
9076 
9077   // For a defaulted function in a dependent class, defer all remaining checks
9078   // until instantiation.
9079   if (RD->isDependentType())
9080     return false;
9081 
9082   // Determine whether the function should be defined as deleted.
9083   DefaultedComparisonInfo Info =
9084       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9085 
9086   bool First = FD == FD->getCanonicalDecl();
9087 
9088   if (!First) {
9089     if (Info.Deleted) {
9090       // C++11 [dcl.fct.def.default]p4:
9091       //   [For a] user-provided explicitly-defaulted function [...] if such a
9092       //   function is implicitly defined as deleted, the program is ill-formed.
9093       //
9094       // This is really just a consequence of the general rule that you can
9095       // only delete a function on its first declaration.
9096       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9097           << FD->isImplicit() << (int)DCK;
9098       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9099                                   DefaultedComparisonAnalyzer::ExplainDeleted)
9100           .visit();
9101       return true;
9102     }
9103     if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9104       // C++20 [class.compare.default]p1:
9105       //   [...] A definition of a comparison operator as defaulted that appears
9106       //   in a class shall be the first declaration of that function.
9107       Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9108           << (int)DCK;
9109       Diag(FD->getCanonicalDecl()->getLocation(),
9110            diag::note_previous_declaration);
9111       return true;
9112     }
9113   }
9114 
9115   // If we want to delete the function, then do so; there's nothing else to
9116   // check in that case.
9117   if (Info.Deleted) {
9118     SetDeclDeleted(FD, FD->getLocation());
9119     if (!inTemplateInstantiation() && !FD->isImplicit()) {
9120       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9121           << (int)DCK;
9122       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9123                                   DefaultedComparisonAnalyzer::ExplainDeleted)
9124           .visit();
9125       if (FD->getDefaultLoc().isValid())
9126         Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9127             << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9128     }
9129     return false;
9130   }
9131 
9132   // C++2a [class.spaceship]p2:
9133   //   The return type is deduced as the common comparison type of R0, R1, ...
9134   if (DCK == DefaultedComparisonKind::ThreeWay &&
9135       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9136     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9137     if (RetLoc.isInvalid())
9138       RetLoc = FD->getBeginLoc();
9139     // FIXME: Should we really care whether we have the complete type and the
9140     // 'enumerator' constants here? A forward declaration seems sufficient.
9141     QualType Cat = CheckComparisonCategoryType(
9142         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9143     if (Cat.isNull())
9144       return true;
9145     Context.adjustDeducedFunctionResultType(
9146         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9147   }
9148 
9149   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9150   //   An explicitly-defaulted function that is not defined as deleted may be
9151   //   declared constexpr or consteval only if it is constexpr-compatible.
9152   // C++2a [class.compare.default]p3 [P2002R0]:
9153   //   A defaulted comparison function is constexpr-compatible if it satisfies
9154   //   the requirements for a constexpr function [...]
9155   // The only relevant requirements are that the parameter and return types are
9156   // literal types. The remaining conditions are checked by the analyzer.
9157   //
9158   // We support P2448R2 in language modes earlier than C++23 as an extension.
9159   // The concept of constexpr-compatible was removed.
9160   // C++23 [dcl.fct.def.default]p3 [P2448R2]
9161   //  A function explicitly defaulted on its first declaration is implicitly
9162   //  inline, and is implicitly constexpr if it is constexpr-suitable.
9163   // C++23 [dcl.constexpr]p3
9164   //   A function is constexpr-suitable if
9165   //    - it is not a coroutine, and
9166   //    - if the function is a constructor or destructor, its class does not
9167   //      have any virtual base classes.
9168   if (FD->isConstexpr()) {
9169     if (!getLangOpts().CPlusPlus23 &&
9170         CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
9171         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
9172         !Info.Constexpr) {
9173       Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9174           << FD->isImplicit() << (int)DCK << FD->isConsteval();
9175       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9176                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
9177           .visit();
9178     }
9179   }
9180 
9181   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9182   //   If a constexpr-compatible function is explicitly defaulted on its first
9183   //   declaration, it is implicitly considered to be constexpr.
9184   // FIXME: Only applying this to the first declaration seems problematic, as
9185   // simple reorderings can affect the meaning of the program.
9186   if (First && !FD->isConstexpr() && Info.Constexpr)
9187     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9188 
9189   // C++2a [except.spec]p3:
9190   //   If a declaration of a function does not have a noexcept-specifier
9191   //   [and] is defaulted on its first declaration, [...] the exception
9192   //   specification is as specified below
9193   if (FD->getExceptionSpecType() == EST_None) {
9194     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9195     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9196     EPI.ExceptionSpec.Type = EST_Unevaluated;
9197     EPI.ExceptionSpec.SourceDecl = FD;
9198     FD->setType(Context.getFunctionType(FPT->getReturnType(),
9199                                         FPT->getParamTypes(), EPI));
9200   }
9201 
9202   return false;
9203 }
9204 
DeclareImplicitEqualityComparison(CXXRecordDecl * RD,FunctionDecl * Spaceship)9205 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9206                                              FunctionDecl *Spaceship) {
9207   Sema::CodeSynthesisContext Ctx;
9208   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9209   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9210   Ctx.Entity = Spaceship;
9211   pushCodeSynthesisContext(Ctx);
9212 
9213   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9214     EqualEqual->setImplicit();
9215 
9216   popCodeSynthesisContext();
9217 }
9218 
DefineDefaultedComparison(SourceLocation UseLoc,FunctionDecl * FD,DefaultedComparisonKind DCK)9219 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9220                                      DefaultedComparisonKind DCK) {
9221   assert(FD->isDefaulted() && !FD->isDeleted() &&
9222          !FD->doesThisDeclarationHaveABody());
9223   if (FD->willHaveBody() || FD->isInvalidDecl())
9224     return;
9225 
9226   SynthesizedFunctionScope Scope(*this, FD);
9227 
9228   // Add a context note for diagnostics produced after this point.
9229   Scope.addContextNote(UseLoc);
9230 
9231   {
9232     // Build and set up the function body.
9233     // The first parameter has type maybe-ref-to maybe-const T, use that to get
9234     // the type of the class being compared.
9235     auto PT = FD->getParamDecl(0)->getType();
9236     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9237     SourceLocation BodyLoc =
9238         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9239     StmtResult Body =
9240         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9241     if (Body.isInvalid()) {
9242       FD->setInvalidDecl();
9243       return;
9244     }
9245     FD->setBody(Body.get());
9246     FD->markUsed(Context);
9247   }
9248 
9249   // The exception specification is needed because we are defining the
9250   // function. Note that this will reuse the body we just built.
9251   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9252 
9253   if (ASTMutationListener *L = getASTMutationListener())
9254     L->CompletedImplicitDefinition(FD);
9255 }
9256 
9257 static Sema::ImplicitExceptionSpecification
ComputeDefaultedComparisonExceptionSpec(Sema & S,SourceLocation Loc,FunctionDecl * FD,Sema::DefaultedComparisonKind DCK)9258 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9259                                         FunctionDecl *FD,
9260                                         Sema::DefaultedComparisonKind DCK) {
9261   ComputingExceptionSpec CES(S, FD, Loc);
9262   Sema::ImplicitExceptionSpecification ExceptSpec(S);
9263 
9264   if (FD->isInvalidDecl())
9265     return ExceptSpec;
9266 
9267   // The common case is that we just defined the comparison function. In that
9268   // case, just look at whether the body can throw.
9269   if (FD->hasBody()) {
9270     ExceptSpec.CalledStmt(FD->getBody());
9271   } else {
9272     // Otherwise, build a body so we can check it. This should ideally only
9273     // happen when we're not actually marking the function referenced. (This is
9274     // only really important for efficiency: we don't want to build and throw
9275     // away bodies for comparison functions more than we strictly need to.)
9276 
9277     // Pretend to synthesize the function body in an unevaluated context.
9278     // Note that we can't actually just go ahead and define the function here:
9279     // we are not permitted to mark its callees as referenced.
9280     Sema::SynthesizedFunctionScope Scope(S, FD);
9281     EnterExpressionEvaluationContext Context(
9282         S, Sema::ExpressionEvaluationContext::Unevaluated);
9283 
9284     CXXRecordDecl *RD =
9285         cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9286                                 ? FD->getDeclContext()
9287                                 : FD->getLexicalDeclContext());
9288     SourceLocation BodyLoc =
9289         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9290     StmtResult Body =
9291         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9292     if (!Body.isInvalid())
9293       ExceptSpec.CalledStmt(Body.get());
9294 
9295     // FIXME: Can we hold onto this body and just transform it to potentially
9296     // evaluated when we're asked to define the function rather than rebuilding
9297     // it? Either that, or we should only build the bits of the body that we
9298     // need (the expressions, not the statements).
9299   }
9300 
9301   return ExceptSpec;
9302 }
9303 
CheckDelayedMemberExceptionSpecs()9304 void Sema::CheckDelayedMemberExceptionSpecs() {
9305   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9306   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9307 
9308   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9309   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9310 
9311   // Perform any deferred checking of exception specifications for virtual
9312   // destructors.
9313   for (auto &Check : Overriding)
9314     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9315 
9316   // Perform any deferred checking of exception specifications for befriended
9317   // special members.
9318   for (auto &Check : Equivalent)
9319     CheckEquivalentExceptionSpec(Check.second, Check.first);
9320 }
9321 
9322 namespace {
9323 /// CRTP base class for visiting operations performed by a special member
9324 /// function (or inherited constructor).
9325 template<typename Derived>
9326 struct SpecialMemberVisitor {
9327   Sema &S;
9328   CXXMethodDecl *MD;
9329   CXXSpecialMemberKind CSM;
9330   Sema::InheritedConstructorInfo *ICI;
9331 
9332   // Properties of the special member, computed for convenience.
9333   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9334 
SpecialMemberVisitor__anon42c808802811::SpecialMemberVisitor9335   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9336                        Sema::InheritedConstructorInfo *ICI)
9337       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9338     switch (CSM) {
9339     case CXXSpecialMemberKind::DefaultConstructor:
9340     case CXXSpecialMemberKind::CopyConstructor:
9341     case CXXSpecialMemberKind::MoveConstructor:
9342       IsConstructor = true;
9343       break;
9344     case CXXSpecialMemberKind::CopyAssignment:
9345     case CXXSpecialMemberKind::MoveAssignment:
9346       IsAssignment = true;
9347       break;
9348     case CXXSpecialMemberKind::Destructor:
9349       break;
9350     case CXXSpecialMemberKind::Invalid:
9351       llvm_unreachable("invalid special member kind");
9352     }
9353 
9354     if (MD->getNumExplicitParams()) {
9355       if (const ReferenceType *RT =
9356               MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9357         ConstArg = RT->getPointeeType().isConstQualified();
9358     }
9359   }
9360 
getDerived__anon42c808802811::SpecialMemberVisitor9361   Derived &getDerived() { return static_cast<Derived&>(*this); }
9362 
9363   /// Is this a "move" special member?
isMove__anon42c808802811::SpecialMemberVisitor9364   bool isMove() const {
9365     return CSM == CXXSpecialMemberKind::MoveConstructor ||
9366            CSM == CXXSpecialMemberKind::MoveAssignment;
9367   }
9368 
9369   /// Look up the corresponding special member in the given class.
lookupIn__anon42c808802811::SpecialMemberVisitor9370   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9371                                              unsigned Quals, bool IsMutable) {
9372     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9373                                        ConstArg && !IsMutable);
9374   }
9375 
9376   /// Look up the constructor for the specified base class to see if it's
9377   /// overridden due to this being an inherited constructor.
lookupInheritedCtor__anon42c808802811::SpecialMemberVisitor9378   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9379     if (!ICI)
9380       return {};
9381     assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9382     auto *BaseCtor =
9383       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9384     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9385       return MD;
9386     return {};
9387   }
9388 
9389   /// A base or member subobject.
9390   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9391 
9392   /// Get the location to use for a subobject in diagnostics.
getSubobjectLoc__anon42c808802811::SpecialMemberVisitor9393   static SourceLocation getSubobjectLoc(Subobject Subobj) {
9394     // FIXME: For an indirect virtual base, the direct base leading to
9395     // the indirect virtual base would be a more useful choice.
9396     if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9397       return B->getBaseTypeLoc();
9398     else
9399       return cast<FieldDecl *>(Subobj)->getLocation();
9400   }
9401 
9402   enum BasesToVisit {
9403     /// Visit all non-virtual (direct) bases.
9404     VisitNonVirtualBases,
9405     /// Visit all direct bases, virtual or not.
9406     VisitDirectBases,
9407     /// Visit all non-virtual bases, and all virtual bases if the class
9408     /// is not abstract.
9409     VisitPotentiallyConstructedBases,
9410     /// Visit all direct or virtual bases.
9411     VisitAllBases
9412   };
9413 
9414   // Visit the bases and members of the class.
visit__anon42c808802811::SpecialMemberVisitor9415   bool visit(BasesToVisit Bases) {
9416     CXXRecordDecl *RD = MD->getParent();
9417 
9418     if (Bases == VisitPotentiallyConstructedBases)
9419       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9420 
9421     for (auto &B : RD->bases())
9422       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9423           getDerived().visitBase(&B))
9424         return true;
9425 
9426     if (Bases == VisitAllBases)
9427       for (auto &B : RD->vbases())
9428         if (getDerived().visitBase(&B))
9429           return true;
9430 
9431     for (auto *F : RD->fields())
9432       if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9433           getDerived().visitField(F))
9434         return true;
9435 
9436     return false;
9437   }
9438 };
9439 }
9440 
9441 namespace {
9442 struct SpecialMemberDeletionInfo
9443     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9444   bool Diagnose;
9445 
9446   SourceLocation Loc;
9447 
9448   bool AllFieldsAreConst;
9449 
SpecialMemberDeletionInfo__anon42c808802911::SpecialMemberDeletionInfo9450   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9451                             CXXSpecialMemberKind CSM,
9452                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9453       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9454         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9455 
inUnion__anon42c808802911::SpecialMemberDeletionInfo9456   bool inUnion() const { return MD->getParent()->isUnion(); }
9457 
getEffectiveCSM__anon42c808802911::SpecialMemberDeletionInfo9458   CXXSpecialMemberKind getEffectiveCSM() {
9459     return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9460   }
9461 
9462   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9463 
9464   bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9465 
visitBase__anon42c808802911::SpecialMemberDeletionInfo9466   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
visitField__anon42c808802911::SpecialMemberDeletionInfo9467   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9468 
9469   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9470   bool shouldDeleteForField(FieldDecl *FD);
9471   bool shouldDeleteForAllConstMembers();
9472 
9473   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9474                                      unsigned Quals);
9475   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9476                                     Sema::SpecialMemberOverloadResult SMOR,
9477                                     bool IsDtorCallInCtor);
9478 
9479   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9480 };
9481 }
9482 
9483 /// Is the given special member inaccessible when used on the given
9484 /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)9485 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9486                                              CXXMethodDecl *target) {
9487   /// If we're operating on a base class, the object type is the
9488   /// type of this special member.
9489   QualType objectTy;
9490   AccessSpecifier access = target->getAccess();
9491   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9492     objectTy = S.Context.getTypeDeclType(MD->getParent());
9493     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9494 
9495   // If we're operating on a field, the object type is the type of the field.
9496   } else {
9497     objectTy = S.Context.getTypeDeclType(target->getParent());
9498   }
9499 
9500   return S.isMemberAccessibleForDeletion(
9501       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9502 }
9503 
9504 /// Check whether we should delete a special member due to the implicit
9505 /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult SMOR,bool IsDtorCallInCtor)9506 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9507     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9508     bool IsDtorCallInCtor) {
9509   CXXMethodDecl *Decl = SMOR.getMethod();
9510   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9511 
9512   int DiagKind = -1;
9513 
9514   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9515     DiagKind = !Decl ? 0 : 1;
9516   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9517     DiagKind = 2;
9518   else if (!isAccessible(Subobj, Decl))
9519     DiagKind = 3;
9520   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9521            !Decl->isTrivial()) {
9522     // A member of a union must have a trivial corresponding special member.
9523     // As a weird special case, a destructor call from a union's constructor
9524     // must be accessible and non-deleted, but need not be trivial. Such a
9525     // destructor is never actually called, but is semantically checked as
9526     // if it were.
9527     if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9528       // [class.default.ctor]p2:
9529       //   A defaulted default constructor for class X is defined as deleted if
9530       //   - X is a union that has a variant member with a non-trivial default
9531       //     constructor and no variant member of X has a default member
9532       //     initializer
9533       const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9534       if (!RD->hasInClassInitializer())
9535         DiagKind = 4;
9536     } else {
9537       DiagKind = 4;
9538     }
9539   }
9540 
9541   if (DiagKind == -1)
9542     return false;
9543 
9544   if (Diagnose) {
9545     if (Field) {
9546       S.Diag(Field->getLocation(),
9547              diag::note_deleted_special_member_class_subobject)
9548           << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9549           << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9550     } else {
9551       CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9552       S.Diag(Base->getBeginLoc(),
9553              diag::note_deleted_special_member_class_subobject)
9554           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9555           << Base->getType() << DiagKind << IsDtorCallInCtor
9556           << /*IsObjCPtr*/ false;
9557     }
9558 
9559     if (DiagKind == 1)
9560       S.NoteDeletedFunction(Decl);
9561     // FIXME: Explain inaccessibility if DiagKind == 3.
9562   }
9563 
9564   return true;
9565 }
9566 
9567 /// Check whether we should delete a special member function due to having a
9568 /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)9569 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9570     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9571   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9572   bool IsMutable = Field && Field->isMutable();
9573 
9574   // C++11 [class.ctor]p5:
9575   // -- any direct or virtual base class, or non-static data member with no
9576   //    brace-or-equal-initializer, has class type M (or array thereof) and
9577   //    either M has no default constructor or overload resolution as applied
9578   //    to M's default constructor results in an ambiguity or in a function
9579   //    that is deleted or inaccessible
9580   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9581   // -- a direct or virtual base class B that cannot be copied/moved because
9582   //    overload resolution, as applied to B's corresponding special member,
9583   //    results in an ambiguity or a function that is deleted or inaccessible
9584   //    from the defaulted special member
9585   // C++11 [class.dtor]p5:
9586   // -- any direct or virtual base class [...] has a type with a destructor
9587   //    that is deleted or inaccessible
9588   if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9589         Field->hasInClassInitializer()) &&
9590       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9591                                    false))
9592     return true;
9593 
9594   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9595   // -- any direct or virtual base class or non-static data member has a
9596   //    type with a destructor that is deleted or inaccessible
9597   if (IsConstructor) {
9598     Sema::SpecialMemberOverloadResult SMOR =
9599         S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9600                               false, false, false, false);
9601     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9602       return true;
9603   }
9604 
9605   return false;
9606 }
9607 
shouldDeleteForVariantObjCPtrMember(FieldDecl * FD,QualType FieldType)9608 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9609     FieldDecl *FD, QualType FieldType) {
9610   // The defaulted special functions are defined as deleted if this is a variant
9611   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9612   // type under ARC.
9613   if (!FieldType.hasNonTrivialObjCLifetime())
9614     return false;
9615 
9616   // Don't make the defaulted default constructor defined as deleted if the
9617   // member has an in-class initializer.
9618   if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9619       FD->hasInClassInitializer())
9620     return false;
9621 
9622   if (Diagnose) {
9623     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9624     S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9625         << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9626         << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9627   }
9628 
9629   return true;
9630 }
9631 
shouldDeleteForVariantPtrAuthMember(const FieldDecl * FD)9632 bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9633     const FieldDecl *FD) {
9634   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9635   // Copy/move constructors/assignment operators are deleted if the field has an
9636   // address-discriminated ptrauth qualifier.
9637   PointerAuthQualifier Q = FieldType.getPointerAuth();
9638 
9639   if (!Q || !Q.isAddressDiscriminated())
9640     return false;
9641 
9642   if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9643       CSM == CXXSpecialMemberKind::Destructor)
9644     return false;
9645 
9646   if (Diagnose) {
9647     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9648     S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9649         << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9650         << /*IsDtorCallInCtor*/ false << 2;
9651   }
9652 
9653   return true;
9654 }
9655 
9656 /// Check whether we should delete a special member function due to the class
9657 /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)9658 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9659   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9660   // If program is correct, BaseClass cannot be null, but if it is, the error
9661   // must be reported elsewhere.
9662   if (!BaseClass)
9663     return false;
9664   // If we have an inheriting constructor, check whether we're calling an
9665   // inherited constructor instead of a default constructor.
9666   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9667   if (auto *BaseCtor = SMOR.getMethod()) {
9668     // Note that we do not check access along this path; other than that,
9669     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9670     // FIXME: Check that the base has a usable destructor! Sink this into
9671     // shouldDeleteForClassSubobject.
9672     if (BaseCtor->isDeleted() && Diagnose) {
9673       S.Diag(Base->getBeginLoc(),
9674              diag::note_deleted_special_member_class_subobject)
9675           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9676           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9677           << /*IsObjCPtr*/ false;
9678       S.NoteDeletedFunction(BaseCtor);
9679     }
9680     return BaseCtor->isDeleted();
9681   }
9682   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9683 }
9684 
9685 /// Check whether we should delete a special member function due to the class
9686 /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)9687 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9688   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9689   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9690 
9691   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9692     return true;
9693 
9694   if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9695     return true;
9696 
9697   if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9698     // For a default constructor, all references must be initialized in-class
9699     // and, if a union, it must have a non-const member.
9700     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9701       if (Diagnose)
9702         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9703           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9704       return true;
9705     }
9706     // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9707     // data member of const-qualified type (or array thereof) with no
9708     // brace-or-equal-initializer is not const-default-constructible.
9709     if (!inUnion() && FieldType.isConstQualified() &&
9710         !FD->hasInClassInitializer() &&
9711         (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9712       if (Diagnose)
9713         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9714           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9715       return true;
9716     }
9717 
9718     if (inUnion() && !FieldType.isConstQualified())
9719       AllFieldsAreConst = false;
9720   } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9721     // For a copy constructor, data members must not be of rvalue reference
9722     // type.
9723     if (FieldType->isRValueReferenceType()) {
9724       if (Diagnose)
9725         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9726           << MD->getParent() << FD << FieldType;
9727       return true;
9728     }
9729   } else if (IsAssignment) {
9730     // For an assignment operator, data members must not be of reference type.
9731     if (FieldType->isReferenceType()) {
9732       if (Diagnose)
9733         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9734           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9735       return true;
9736     }
9737     if (!FieldRecord && FieldType.isConstQualified()) {
9738       // C++11 [class.copy]p23:
9739       // -- a non-static data member of const non-class type (or array thereof)
9740       if (Diagnose)
9741         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9742           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9743       return true;
9744     }
9745   }
9746 
9747   if (FieldRecord) {
9748     // Some additional restrictions exist on the variant members.
9749     if (!inUnion() && FieldRecord->isUnion() &&
9750         FieldRecord->isAnonymousStructOrUnion()) {
9751       bool AllVariantFieldsAreConst = true;
9752 
9753       // FIXME: Handle anonymous unions declared within anonymous unions.
9754       for (auto *UI : FieldRecord->fields()) {
9755         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9756 
9757         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9758           return true;
9759 
9760         if (shouldDeleteForVariantPtrAuthMember(&*UI))
9761           return true;
9762 
9763         if (!UnionFieldType.isConstQualified())
9764           AllVariantFieldsAreConst = false;
9765 
9766         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9767         if (UnionFieldRecord &&
9768             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9769                                           UnionFieldType.getCVRQualifiers()))
9770           return true;
9771       }
9772 
9773       // At least one member in each anonymous union must be non-const
9774       if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9775           AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9776         if (Diagnose)
9777           S.Diag(FieldRecord->getLocation(),
9778                  diag::note_deleted_default_ctor_all_const)
9779             << !!ICI << MD->getParent() << /*anonymous union*/1;
9780         return true;
9781       }
9782 
9783       // Don't check the implicit member of the anonymous union type.
9784       // This is technically non-conformant but supported, and we have a
9785       // diagnostic for this elsewhere.
9786       return false;
9787     }
9788 
9789     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9790                                       FieldType.getCVRQualifiers()))
9791       return true;
9792   }
9793 
9794   return false;
9795 }
9796 
9797 /// C++11 [class.ctor] p5:
9798 ///   A defaulted default constructor for a class X is defined as deleted if
9799 /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()9800 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9801   // This is a silly definition, because it gives an empty union a deleted
9802   // default constructor. Don't do that.
9803   if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9804       AllFieldsAreConst) {
9805     bool AnyFields = false;
9806     for (auto *F : MD->getParent()->fields())
9807       if ((AnyFields = !F->isUnnamedBitField()))
9808         break;
9809     if (!AnyFields)
9810       return false;
9811     if (Diagnose)
9812       S.Diag(MD->getParent()->getLocation(),
9813              diag::note_deleted_default_ctor_all_const)
9814         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9815     return true;
9816   }
9817   return false;
9818 }
9819 
9820 /// Determine whether a defaulted special member function should be defined as
9821 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9822 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMemberKind CSM,InheritedConstructorInfo * ICI,bool Diagnose)9823 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9824                                      CXXSpecialMemberKind CSM,
9825                                      InheritedConstructorInfo *ICI,
9826                                      bool Diagnose) {
9827   if (MD->isInvalidDecl())
9828     return false;
9829   CXXRecordDecl *RD = MD->getParent();
9830   assert(!RD->isDependentType() && "do deletion after instantiation");
9831   if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9832       RD->isInvalidDecl())
9833     return false;
9834 
9835   // C++11 [expr.lambda.prim]p19:
9836   //   The closure type associated with a lambda-expression has a
9837   //   deleted (8.4.3) default constructor and a deleted copy
9838   //   assignment operator.
9839   // C++2a adds back these operators if the lambda has no lambda-capture.
9840   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9841       (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9842        CSM == CXXSpecialMemberKind::CopyAssignment)) {
9843     if (Diagnose)
9844       Diag(RD->getLocation(), diag::note_lambda_decl);
9845     return true;
9846   }
9847 
9848   // For an anonymous struct or union, the copy and assignment special members
9849   // will never be used, so skip the check. For an anonymous union declared at
9850   // namespace scope, the constructor and destructor are used.
9851   if (CSM != CXXSpecialMemberKind::DefaultConstructor &&
9852       CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion())
9853     return false;
9854 
9855   // C++11 [class.copy]p7, p18:
9856   //   If the class definition declares a move constructor or move assignment
9857   //   operator, an implicitly declared copy constructor or copy assignment
9858   //   operator is defined as deleted.
9859   if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9860                            CSM == CXXSpecialMemberKind::CopyAssignment)) {
9861     CXXMethodDecl *UserDeclaredMove = nullptr;
9862 
9863     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9864     // deletion of the corresponding copy operation, not both copy operations.
9865     // MSVC 2015 has adopted the standards conforming behavior.
9866     bool DeletesOnlyMatchingCopy =
9867         getLangOpts().MSVCCompat &&
9868         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9869 
9870     if (RD->hasUserDeclaredMoveConstructor() &&
9871         (!DeletesOnlyMatchingCopy ||
9872          CSM == CXXSpecialMemberKind::CopyConstructor)) {
9873       if (!Diagnose) return true;
9874 
9875       // Find any user-declared move constructor.
9876       for (auto *I : RD->ctors()) {
9877         if (I->isMoveConstructor()) {
9878           UserDeclaredMove = I;
9879           break;
9880         }
9881       }
9882       assert(UserDeclaredMove);
9883     } else if (RD->hasUserDeclaredMoveAssignment() &&
9884                (!DeletesOnlyMatchingCopy ||
9885                 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9886       if (!Diagnose) return true;
9887 
9888       // Find any user-declared move assignment operator.
9889       for (auto *I : RD->methods()) {
9890         if (I->isMoveAssignmentOperator()) {
9891           UserDeclaredMove = I;
9892           break;
9893         }
9894       }
9895       assert(UserDeclaredMove);
9896     }
9897 
9898     if (UserDeclaredMove) {
9899       Diag(UserDeclaredMove->getLocation(),
9900            diag::note_deleted_copy_user_declared_move)
9901           << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9902           << UserDeclaredMove->isMoveAssignmentOperator();
9903       return true;
9904     }
9905   }
9906 
9907   // Do access control from the special member function
9908   ContextRAII MethodContext(*this, MD);
9909 
9910   // C++11 [class.dtor]p5:
9911   // -- for a virtual destructor, lookup of the non-array deallocation function
9912   //    results in an ambiguity or in a function that is deleted or inaccessible
9913   if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9914     FunctionDecl *OperatorDelete = nullptr;
9915     QualType DeallocType = Context.getRecordType(RD);
9916     DeclarationName Name =
9917       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9918     ImplicitDeallocationParameters IDP = {
9919         DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
9920         AlignedAllocationMode::No, SizedDeallocationMode::No};
9921     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9922                                  OperatorDelete, IDP,
9923                                  /*Diagnose=*/false)) {
9924       if (Diagnose)
9925         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9926       return true;
9927     }
9928   }
9929 
9930   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9931 
9932   // Per DR1611, do not consider virtual bases of constructors of abstract
9933   // classes, since we are not going to construct them.
9934   // Per DR1658, do not consider virtual bases of destructors of abstract
9935   // classes either.
9936   // Per DR2180, for assignment operators we only assign (and thus only
9937   // consider) direct bases.
9938   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9939                                  : SMI.VisitPotentiallyConstructedBases))
9940     return true;
9941 
9942   if (SMI.shouldDeleteForAllConstMembers())
9943     return true;
9944 
9945   if (getLangOpts().CUDA) {
9946     // We should delete the special member in CUDA mode if target inference
9947     // failed.
9948     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9949     // is treated as certain special member, which may not reflect what special
9950     // member MD really is. However inferTargetForImplicitSpecialMember
9951     // expects CSM to match MD, therefore recalculate CSM.
9952     assert(ICI || CSM == getSpecialMember(MD));
9953     auto RealCSM = CSM;
9954     if (ICI)
9955       RealCSM = getSpecialMember(MD);
9956 
9957     return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9958                                                       SMI.ConstArg, Diagnose);
9959   }
9960 
9961   return false;
9962 }
9963 
DiagnoseDeletedDefaultedFunction(FunctionDecl * FD)9964 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9965   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9966   assert(DFK && "not a defaultable function");
9967   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9968 
9969   if (DFK.isSpecialMember()) {
9970     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9971                               nullptr, /*Diagnose=*/true);
9972   } else {
9973     DefaultedComparisonAnalyzer(
9974         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9975         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9976         .visit();
9977   }
9978 }
9979 
9980 /// Perform lookup for a special member of the specified kind, and determine
9981 /// whether it is trivial. If the triviality can be determined without the
9982 /// lookup, skip it. This is intended for use when determining whether a
9983 /// special member of a containing object is trivial, and thus does not ever
9984 /// perform overload resolution for default constructors.
9985 ///
9986 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9987 /// member that was most likely to be intended to be trivial, if any.
9988 ///
9989 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9990 /// determine whether the special member is trivial.
findTrivialSpecialMember(Sema & S,CXXRecordDecl * RD,CXXSpecialMemberKind CSM,unsigned Quals,bool ConstRHS,TrivialABIHandling TAH,CXXMethodDecl ** Selected)9991 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9992                                      CXXSpecialMemberKind CSM, unsigned Quals,
9993                                      bool ConstRHS, TrivialABIHandling TAH,
9994                                      CXXMethodDecl **Selected) {
9995   if (Selected)
9996     *Selected = nullptr;
9997 
9998   switch (CSM) {
9999   case CXXSpecialMemberKind::Invalid:
10000     llvm_unreachable("not a special member");
10001 
10002   case CXXSpecialMemberKind::DefaultConstructor:
10003     // C++11 [class.ctor]p5:
10004     //   A default constructor is trivial if:
10005     //    - all the [direct subobjects] have trivial default constructors
10006     //
10007     // Note, no overload resolution is performed in this case.
10008     if (RD->hasTrivialDefaultConstructor())
10009       return true;
10010 
10011     if (Selected) {
10012       // If there's a default constructor which could have been trivial, dig it
10013       // out. Otherwise, if there's any user-provided default constructor, point
10014       // to that as an example of why there's not a trivial one.
10015       CXXConstructorDecl *DefCtor = nullptr;
10016       if (RD->needsImplicitDefaultConstructor())
10017         S.DeclareImplicitDefaultConstructor(RD);
10018       for (auto *CI : RD->ctors()) {
10019         if (!CI->isDefaultConstructor())
10020           continue;
10021         DefCtor = CI;
10022         if (!DefCtor->isUserProvided())
10023           break;
10024       }
10025 
10026       *Selected = DefCtor;
10027     }
10028 
10029     return false;
10030 
10031   case CXXSpecialMemberKind::Destructor:
10032     // C++11 [class.dtor]p5:
10033     //   A destructor is trivial if:
10034     //    - all the direct [subobjects] have trivial destructors
10035     if (RD->hasTrivialDestructor() ||
10036         (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10037          RD->hasTrivialDestructorForCall()))
10038       return true;
10039 
10040     if (Selected) {
10041       if (RD->needsImplicitDestructor())
10042         S.DeclareImplicitDestructor(RD);
10043       *Selected = RD->getDestructor();
10044     }
10045 
10046     return false;
10047 
10048   case CXXSpecialMemberKind::CopyConstructor:
10049     // C++11 [class.copy]p12:
10050     //   A copy constructor is trivial if:
10051     //    - the constructor selected to copy each direct [subobject] is trivial
10052     if (RD->hasTrivialCopyConstructor() ||
10053         (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10054          RD->hasTrivialCopyConstructorForCall())) {
10055       if (Quals == Qualifiers::Const)
10056         // We must either select the trivial copy constructor or reach an
10057         // ambiguity; no need to actually perform overload resolution.
10058         return true;
10059     } else if (!Selected) {
10060       return false;
10061     }
10062     // In C++98, we are not supposed to perform overload resolution here, but we
10063     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10064     // cases like B as having a non-trivial copy constructor:
10065     //   struct A { template<typename T> A(T&); };
10066     //   struct B { mutable A a; };
10067     goto NeedOverloadResolution;
10068 
10069   case CXXSpecialMemberKind::CopyAssignment:
10070     // C++11 [class.copy]p25:
10071     //   A copy assignment operator is trivial if:
10072     //    - the assignment operator selected to copy each direct [subobject] is
10073     //      trivial
10074     if (RD->hasTrivialCopyAssignment()) {
10075       if (Quals == Qualifiers::Const)
10076         return true;
10077     } else if (!Selected) {
10078       return false;
10079     }
10080     // In C++98, we are not supposed to perform overload resolution here, but we
10081     // treat that as a language defect.
10082     goto NeedOverloadResolution;
10083 
10084   case CXXSpecialMemberKind::MoveConstructor:
10085   case CXXSpecialMemberKind::MoveAssignment:
10086   NeedOverloadResolution:
10087     Sema::SpecialMemberOverloadResult SMOR =
10088         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10089 
10090     // The standard doesn't describe how to behave if the lookup is ambiguous.
10091     // We treat it as not making the member non-trivial, just like the standard
10092     // mandates for the default constructor. This should rarely matter, because
10093     // the member will also be deleted.
10094     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10095       return true;
10096 
10097     if (!SMOR.getMethod()) {
10098       assert(SMOR.getKind() ==
10099              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10100       return false;
10101     }
10102 
10103     // We deliberately don't check if we found a deleted special member. We're
10104     // not supposed to!
10105     if (Selected)
10106       *Selected = SMOR.getMethod();
10107 
10108     if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10109         (CSM == CXXSpecialMemberKind::CopyConstructor ||
10110          CSM == CXXSpecialMemberKind::MoveConstructor))
10111       return SMOR.getMethod()->isTrivialForCall();
10112     return SMOR.getMethod()->isTrivial();
10113   }
10114 
10115   llvm_unreachable("unknown special method kind");
10116 }
10117 
findUserDeclaredCtor(CXXRecordDecl * RD)10118 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10119   for (auto *CI : RD->ctors())
10120     if (!CI->isImplicit())
10121       return CI;
10122 
10123   // Look for constructor templates.
10124   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10125   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10126     if (CXXConstructorDecl *CD =
10127           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10128       return CD;
10129   }
10130 
10131   return nullptr;
10132 }
10133 
10134 /// The kind of subobject we are checking for triviality. The values of this
10135 /// enumeration are used in diagnostics.
10136 enum TrivialSubobjectKind {
10137   /// The subobject is a base class.
10138   TSK_BaseClass,
10139   /// The subobject is a non-static data member.
10140   TSK_Field,
10141   /// The object is actually the complete object.
10142   TSK_CompleteObject
10143 };
10144 
10145 /// Check whether the special member selected for a given type would be trivial.
checkTrivialSubobjectCall(Sema & S,SourceLocation SubobjLoc,QualType SubType,bool ConstRHS,CXXSpecialMemberKind CSM,TrivialSubobjectKind Kind,TrivialABIHandling TAH,bool Diagnose)10146 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10147                                       QualType SubType, bool ConstRHS,
10148                                       CXXSpecialMemberKind CSM,
10149                                       TrivialSubobjectKind Kind,
10150                                       TrivialABIHandling TAH, bool Diagnose) {
10151   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10152   if (!SubRD)
10153     return true;
10154 
10155   CXXMethodDecl *Selected;
10156   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10157                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10158     return true;
10159 
10160   if (Diagnose) {
10161     if (ConstRHS)
10162       SubType.addConst();
10163 
10164     if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10165       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10166         << Kind << SubType.getUnqualifiedType();
10167       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10168         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10169     } else if (!Selected)
10170       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10171           << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10172     else if (Selected->isUserProvided()) {
10173       if (Kind == TSK_CompleteObject)
10174         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10175             << Kind << SubType.getUnqualifiedType() << CSM;
10176       else {
10177         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10178             << Kind << SubType.getUnqualifiedType() << CSM;
10179         S.Diag(Selected->getLocation(), diag::note_declared_at);
10180       }
10181     } else {
10182       if (Kind != TSK_CompleteObject)
10183         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10184             << Kind << SubType.getUnqualifiedType() << CSM;
10185 
10186       // Explain why the defaulted or deleted special member isn't trivial.
10187       S.SpecialMemberIsTrivial(Selected, CSM,
10188                                TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10189     }
10190   }
10191 
10192   return false;
10193 }
10194 
10195 /// Check whether the members of a class type allow a special member to be
10196 /// trivial.
checkTrivialClassMembers(Sema & S,CXXRecordDecl * RD,CXXSpecialMemberKind CSM,bool ConstArg,TrivialABIHandling TAH,bool Diagnose)10197 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10198                                      CXXSpecialMemberKind CSM, bool ConstArg,
10199                                      TrivialABIHandling TAH, bool Diagnose) {
10200   for (const auto *FI : RD->fields()) {
10201     if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10202       continue;
10203 
10204     QualType FieldType = S.Context.getBaseElementType(FI->getType());
10205 
10206     // Pretend anonymous struct or union members are members of this class.
10207     if (FI->isAnonymousStructOrUnion()) {
10208       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10209                                     CSM, ConstArg, TAH, Diagnose))
10210         return false;
10211       continue;
10212     }
10213 
10214     // C++11 [class.ctor]p5:
10215     //   A default constructor is trivial if [...]
10216     //    -- no non-static data member of its class has a
10217     //       brace-or-equal-initializer
10218     if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10219         FI->hasInClassInitializer()) {
10220       if (Diagnose)
10221         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10222             << FI;
10223       return false;
10224     }
10225 
10226     // Objective C ARC 4.3.5:
10227     //   [...] nontrivally ownership-qualified types are [...] not trivially
10228     //   default constructible, copy constructible, move constructible, copy
10229     //   assignable, move assignable, or destructible [...]
10230     if (FieldType.hasNonTrivialObjCLifetime()) {
10231       if (Diagnose)
10232         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10233           << RD << FieldType.getObjCLifetime();
10234       return false;
10235     }
10236 
10237     bool ConstRHS = ConstArg && !FI->isMutable();
10238     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10239                                    CSM, TSK_Field, TAH, Diagnose))
10240       return false;
10241   }
10242 
10243   return true;
10244 }
10245 
DiagnoseNontrivial(const CXXRecordDecl * RD,CXXSpecialMemberKind CSM)10246 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10247                               CXXSpecialMemberKind CSM) {
10248   QualType Ty = Context.getRecordType(RD);
10249 
10250   bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10251                    CSM == CXXSpecialMemberKind::CopyAssignment);
10252   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10253                             TSK_CompleteObject,
10254                             TrivialABIHandling::IgnoreTrivialABI,
10255                             /*Diagnose*/ true);
10256 }
10257 
SpecialMemberIsTrivial(CXXMethodDecl * MD,CXXSpecialMemberKind CSM,TrivialABIHandling TAH,bool Diagnose)10258 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10259                                   TrivialABIHandling TAH, bool Diagnose) {
10260   assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10261          "not special enough");
10262 
10263   CXXRecordDecl *RD = MD->getParent();
10264 
10265   bool ConstArg = false;
10266 
10267   // C++11 [class.copy]p12, p25: [DR1593]
10268   //   A [special member] is trivial if [...] its parameter-type-list is
10269   //   equivalent to the parameter-type-list of an implicit declaration [...]
10270   switch (CSM) {
10271   case CXXSpecialMemberKind::DefaultConstructor:
10272   case CXXSpecialMemberKind::Destructor:
10273     // Trivial default constructors and destructors cannot have parameters.
10274     break;
10275 
10276   case CXXSpecialMemberKind::CopyConstructor:
10277   case CXXSpecialMemberKind::CopyAssignment: {
10278     const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10279     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10280 
10281     // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10282     // if they are not user-provided and their parameter-type-list is equivalent
10283     // to the parameter-type-list of an implicit declaration. This maintains the
10284     // behavior before dr2171 was implemented.
10285     //
10286     // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10287     // trivial, if they are not user-provided, regardless of the qualifiers on
10288     // the reference type.
10289     const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10290                                   LangOptions::ClangABI::Ver14;
10291     if (!RT ||
10292         ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10293          ClangABICompat14)) {
10294       if (Diagnose)
10295         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10296           << Param0->getSourceRange() << Param0->getType()
10297           << Context.getLValueReferenceType(
10298                Context.getRecordType(RD).withConst());
10299       return false;
10300     }
10301 
10302     ConstArg = RT->getPointeeType().isConstQualified();
10303     break;
10304   }
10305 
10306   case CXXSpecialMemberKind::MoveConstructor:
10307   case CXXSpecialMemberKind::MoveAssignment: {
10308     // Trivial move operations always have non-cv-qualified parameters.
10309     const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10310     const RValueReferenceType *RT =
10311       Param0->getType()->getAs<RValueReferenceType>();
10312     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10313       if (Diagnose)
10314         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10315           << Param0->getSourceRange() << Param0->getType()
10316           << Context.getRValueReferenceType(Context.getRecordType(RD));
10317       return false;
10318     }
10319     break;
10320   }
10321 
10322   case CXXSpecialMemberKind::Invalid:
10323     llvm_unreachable("not a special member");
10324   }
10325 
10326   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10327     if (Diagnose)
10328       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10329            diag::note_nontrivial_default_arg)
10330         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10331     return false;
10332   }
10333   if (MD->isVariadic()) {
10334     if (Diagnose)
10335       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10336     return false;
10337   }
10338 
10339   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10340   //   A copy/move [constructor or assignment operator] is trivial if
10341   //    -- the [member] selected to copy/move each direct base class subobject
10342   //       is trivial
10343   //
10344   // C++11 [class.copy]p12, C++11 [class.copy]p25:
10345   //   A [default constructor or destructor] is trivial if
10346   //    -- all the direct base classes have trivial [default constructors or
10347   //       destructors]
10348   for (const auto &BI : RD->bases())
10349     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10350                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10351       return false;
10352 
10353   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10354   //   A copy/move [constructor or assignment operator] for a class X is
10355   //   trivial if
10356   //    -- for each non-static data member of X that is of class type (or array
10357   //       thereof), the constructor selected to copy/move that member is
10358   //       trivial
10359   //
10360   // C++11 [class.copy]p12, C++11 [class.copy]p25:
10361   //   A [default constructor or destructor] is trivial if
10362   //    -- for all of the non-static data members of its class that are of class
10363   //       type (or array thereof), each such class has a trivial [default
10364   //       constructor or destructor]
10365   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10366     return false;
10367 
10368   // C++11 [class.dtor]p5:
10369   //   A destructor is trivial if [...]
10370   //    -- the destructor is not virtual
10371   if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10372     if (Diagnose)
10373       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10374     return false;
10375   }
10376 
10377   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10378   //   A [special member] for class X is trivial if [...]
10379   //    -- class X has no virtual functions and no virtual base classes
10380   if (CSM != CXXSpecialMemberKind::Destructor &&
10381       MD->getParent()->isDynamicClass()) {
10382     if (!Diagnose)
10383       return false;
10384 
10385     if (RD->getNumVBases()) {
10386       // Check for virtual bases. We already know that the corresponding
10387       // member in all bases is trivial, so vbases must all be direct.
10388       CXXBaseSpecifier &BS = *RD->vbases_begin();
10389       assert(BS.isVirtual());
10390       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10391       return false;
10392     }
10393 
10394     // Must have a virtual method.
10395     for (const auto *MI : RD->methods()) {
10396       if (MI->isVirtual()) {
10397         SourceLocation MLoc = MI->getBeginLoc();
10398         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10399         return false;
10400       }
10401     }
10402 
10403     llvm_unreachable("dynamic class with no vbases and no virtual functions");
10404   }
10405 
10406   // Looks like it's trivial!
10407   return true;
10408 }
10409 
10410 namespace {
10411 struct FindHiddenVirtualMethod {
10412   Sema *S;
10413   CXXMethodDecl *Method;
10414   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10415   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10416 
10417 private:
10418   /// Check whether any most overridden method from MD in Methods
CheckMostOverridenMethods__anon42c808802a11::FindHiddenVirtualMethod10419   static bool CheckMostOverridenMethods(
10420       const CXXMethodDecl *MD,
10421       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10422     if (MD->size_overridden_methods() == 0)
10423       return Methods.count(MD->getCanonicalDecl());
10424     for (const CXXMethodDecl *O : MD->overridden_methods())
10425       if (CheckMostOverridenMethods(O, Methods))
10426         return true;
10427     return false;
10428   }
10429 
10430 public:
10431   /// Member lookup function that determines whether a given C++
10432   /// method overloads virtual methods in a base class without overriding any,
10433   /// to be used with CXXRecordDecl::lookupInBases().
operator ()__anon42c808802a11::FindHiddenVirtualMethod10434   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10435     RecordDecl *BaseRecord =
10436         Specifier->getType()->castAs<RecordType>()->getDecl();
10437 
10438     DeclarationName Name = Method->getDeclName();
10439     assert(Name.getNameKind() == DeclarationName::Identifier);
10440 
10441     bool foundSameNameMethod = false;
10442     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10443     for (Path.Decls = BaseRecord->lookup(Name).begin();
10444          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10445       NamedDecl *D = *Path.Decls;
10446       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10447         MD = MD->getCanonicalDecl();
10448         foundSameNameMethod = true;
10449         // Interested only in hidden virtual methods.
10450         if (!MD->isVirtual())
10451           continue;
10452         // If the method we are checking overrides a method from its base
10453         // don't warn about the other overloaded methods. Clang deviates from
10454         // GCC by only diagnosing overloads of inherited virtual functions that
10455         // do not override any other virtual functions in the base. GCC's
10456         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10457         // function from a base class. These cases may be better served by a
10458         // warning (not specific to virtual functions) on call sites when the
10459         // call would select a different function from the base class, were it
10460         // visible.
10461         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10462         if (!S->IsOverload(Method, MD, false))
10463           return true;
10464         // Collect the overload only if its hidden.
10465         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10466           overloadedMethods.push_back(MD);
10467       }
10468     }
10469 
10470     if (foundSameNameMethod)
10471       OverloadedMethods.append(overloadedMethods.begin(),
10472                                overloadedMethods.end());
10473     return foundSameNameMethod;
10474   }
10475 };
10476 } // end anonymous namespace
10477 
10478 /// Add the most overridden methods from MD to Methods
AddMostOverridenMethods(const CXXMethodDecl * MD,llvm::SmallPtrSetImpl<const CXXMethodDecl * > & Methods)10479 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10480                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10481   if (MD->size_overridden_methods() == 0)
10482     Methods.insert(MD->getCanonicalDecl());
10483   else
10484     for (const CXXMethodDecl *O : MD->overridden_methods())
10485       AddMostOverridenMethods(O, Methods);
10486 }
10487 
FindHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)10488 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10489                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10490   if (!MD->getDeclName().isIdentifier())
10491     return;
10492 
10493   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10494                      /*bool RecordPaths=*/false,
10495                      /*bool DetectVirtual=*/false);
10496   FindHiddenVirtualMethod FHVM;
10497   FHVM.Method = MD;
10498   FHVM.S = this;
10499 
10500   // Keep the base methods that were overridden or introduced in the subclass
10501   // by 'using' in a set. A base method not in this set is hidden.
10502   CXXRecordDecl *DC = MD->getParent();
10503   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10504   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10505     NamedDecl *ND = *I;
10506     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10507       ND = shad->getTargetDecl();
10508     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10509       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10510   }
10511 
10512   if (DC->lookupInBases(FHVM, Paths))
10513     OverloadedMethods = FHVM.OverloadedMethods;
10514 }
10515 
NoteHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)10516 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10517                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10518   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10519     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10520     PartialDiagnostic PD = PDiag(
10521          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10522     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10523     Diag(overloadedMD->getLocation(), PD);
10524   }
10525 }
10526 
DiagnoseHiddenVirtualMethods(CXXMethodDecl * MD)10527 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10528   if (MD->isInvalidDecl())
10529     return;
10530 
10531   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10532     return;
10533 
10534   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10535   FindHiddenVirtualMethods(MD, OverloadedMethods);
10536   if (!OverloadedMethods.empty()) {
10537     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10538       << MD << (OverloadedMethods.size() > 1);
10539 
10540     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10541   }
10542 }
10543 
checkIllFormedTrivialABIStruct(CXXRecordDecl & RD)10544 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10545   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10546     // No diagnostics if this is a template instantiation.
10547     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10548       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10549            diag::ext_cannot_use_trivial_abi) << &RD;
10550       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10551            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10552     }
10553     RD.dropAttr<TrivialABIAttr>();
10554   };
10555 
10556   // Ill-formed if the struct has virtual functions.
10557   if (RD.isPolymorphic()) {
10558     PrintDiagAndRemoveAttr(1);
10559     return;
10560   }
10561 
10562   for (const auto &B : RD.bases()) {
10563     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10564     // virtual base.
10565     if (!B.getType()->isDependentType() &&
10566         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10567       PrintDiagAndRemoveAttr(2);
10568       return;
10569     }
10570 
10571     if (B.isVirtual()) {
10572       PrintDiagAndRemoveAttr(3);
10573       return;
10574     }
10575   }
10576 
10577   for (const auto *FD : RD.fields()) {
10578     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10579     // non-trivial for the purpose of calls.
10580     QualType FT = FD->getType();
10581     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10582       PrintDiagAndRemoveAttr(4);
10583       return;
10584     }
10585 
10586     // Ill-formed if the field is an address-discriminated value.
10587     if (FT.hasAddressDiscriminatedPointerAuth()) {
10588       PrintDiagAndRemoveAttr(6);
10589       return;
10590     }
10591 
10592     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10593       if (!RT->isDependentType() &&
10594           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10595         PrintDiagAndRemoveAttr(5);
10596         return;
10597       }
10598   }
10599 
10600   if (IsCXXTriviallyRelocatableType(RD))
10601     return;
10602 
10603   // Ill-formed if the copy and move constructors are deleted.
10604   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10605     // If the type is dependent, then assume it might have
10606     // implicit copy or move ctor because we won't know yet at this point.
10607     if (RD.isDependentType())
10608       return true;
10609     if (RD.needsImplicitCopyConstructor() &&
10610         !RD.defaultedCopyConstructorIsDeleted())
10611       return true;
10612     if (RD.needsImplicitMoveConstructor() &&
10613         !RD.defaultedMoveConstructorIsDeleted())
10614       return true;
10615     for (const CXXConstructorDecl *CD : RD.ctors())
10616       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10617         return true;
10618     return false;
10619   };
10620 
10621   if (!HasNonDeletedCopyOrMoveConstructor()) {
10622     PrintDiagAndRemoveAttr(0);
10623     return;
10624   }
10625 }
10626 
checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl & RD)10627 void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10628     CXXRecordDecl &RD) {
10629   if (RequireCompleteType(RD.getLocation(), Context.getRecordType(&RD),
10630                           diag::err_incomplete_type_vtable_pointer_auth))
10631     return;
10632 
10633   const CXXRecordDecl *PrimaryBase = &RD;
10634   if (PrimaryBase->hasAnyDependentBases())
10635     return;
10636 
10637   while (1) {
10638     assert(PrimaryBase);
10639     const CXXRecordDecl *Base = nullptr;
10640     for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10641       if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10642         continue;
10643       Base = BasePtr.getType()->getAsCXXRecordDecl();
10644       break;
10645     }
10646     if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10647       break;
10648     Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10649          diag::err_non_top_level_vtable_pointer_auth)
10650         << &RD << Base;
10651     PrimaryBase = Base;
10652   }
10653 
10654   if (!RD.isPolymorphic())
10655     Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10656          diag::err_non_polymorphic_vtable_pointer_auth)
10657         << &RD;
10658 }
10659 
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & AttrList)10660 void Sema::ActOnFinishCXXMemberSpecification(
10661     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10662     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10663   if (!TagDecl)
10664     return;
10665 
10666   AdjustDeclIfTemplate(TagDecl);
10667 
10668   for (const ParsedAttr &AL : AttrList) {
10669     if (AL.getKind() != ParsedAttr::AT_Visibility)
10670       continue;
10671     AL.setInvalid();
10672     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10673   }
10674 
10675   ActOnFields(S, RLoc, TagDecl,
10676               llvm::ArrayRef(
10677                   // strict aliasing violation!
10678                   reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10679                   FieldCollector->getCurNumFields()),
10680               LBrac, RBrac, AttrList);
10681 
10682   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10683 }
10684 
10685 /// Find the equality comparison functions that should be implicitly declared
10686 /// in a given class definition, per C++2a [class.compare.default]p3.
findImplicitlyDeclaredEqualityComparisons(ASTContext & Ctx,CXXRecordDecl * RD,llvm::SmallVectorImpl<FunctionDecl * > & Spaceships)10687 static void findImplicitlyDeclaredEqualityComparisons(
10688     ASTContext &Ctx, CXXRecordDecl *RD,
10689     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10690   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10691   if (!RD->lookup(EqEq).empty())
10692     // Member operator== explicitly declared: no implicit operator==s.
10693     return;
10694 
10695   // Traverse friends looking for an '==' or a '<=>'.
10696   for (FriendDecl *Friend : RD->friends()) {
10697     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10698     if (!FD) continue;
10699 
10700     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10701       // Friend operator== explicitly declared: no implicit operator==s.
10702       Spaceships.clear();
10703       return;
10704     }
10705 
10706     if (FD->getOverloadedOperator() == OO_Spaceship &&
10707         FD->isExplicitlyDefaulted())
10708       Spaceships.push_back(FD);
10709   }
10710 
10711   // Look for members named 'operator<=>'.
10712   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10713   for (NamedDecl *ND : RD->lookup(Cmp)) {
10714     // Note that we could find a non-function here (either a function template
10715     // or a using-declaration). Neither case results in an implicit
10716     // 'operator=='.
10717     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10718       if (FD->isExplicitlyDefaulted())
10719         Spaceships.push_back(FD);
10720   }
10721 }
10722 
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)10723 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10724   // Don't add implicit special members to templated classes.
10725   // FIXME: This means unqualified lookups for 'operator=' within a class
10726   // template don't work properly.
10727   if (!ClassDecl->isDependentType()) {
10728     if (ClassDecl->needsImplicitDefaultConstructor()) {
10729       ++getASTContext().NumImplicitDefaultConstructors;
10730 
10731       if (ClassDecl->hasInheritedConstructor())
10732         DeclareImplicitDefaultConstructor(ClassDecl);
10733     }
10734 
10735     if (ClassDecl->needsImplicitCopyConstructor()) {
10736       ++getASTContext().NumImplicitCopyConstructors;
10737 
10738       // If the properties or semantics of the copy constructor couldn't be
10739       // determined while the class was being declared, force a declaration
10740       // of it now.
10741       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10742           ClassDecl->hasInheritedConstructor())
10743         DeclareImplicitCopyConstructor(ClassDecl);
10744       // For the MS ABI we need to know whether the copy ctor is deleted. A
10745       // prerequisite for deleting the implicit copy ctor is that the class has
10746       // a move ctor or move assignment that is either user-declared or whose
10747       // semantics are inherited from a subobject. FIXME: We should provide a
10748       // more direct way for CodeGen to ask whether the constructor was deleted.
10749       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10750                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10751                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10752                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10753                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10754         DeclareImplicitCopyConstructor(ClassDecl);
10755     }
10756 
10757     if (getLangOpts().CPlusPlus11 &&
10758         ClassDecl->needsImplicitMoveConstructor()) {
10759       ++getASTContext().NumImplicitMoveConstructors;
10760 
10761       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10762           ClassDecl->hasInheritedConstructor())
10763         DeclareImplicitMoveConstructor(ClassDecl);
10764     }
10765 
10766     if (ClassDecl->needsImplicitCopyAssignment()) {
10767       ++getASTContext().NumImplicitCopyAssignmentOperators;
10768 
10769       // If we have a dynamic class, then the copy assignment operator may be
10770       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10771       // it shows up in the right place in the vtable and that we diagnose
10772       // problems with the implicit exception specification.
10773       if (ClassDecl->isDynamicClass() ||
10774           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10775           ClassDecl->hasInheritedAssignment())
10776         DeclareImplicitCopyAssignment(ClassDecl);
10777     }
10778 
10779     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10780       ++getASTContext().NumImplicitMoveAssignmentOperators;
10781 
10782       // Likewise for the move assignment operator.
10783       if (ClassDecl->isDynamicClass() ||
10784           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10785           ClassDecl->hasInheritedAssignment())
10786         DeclareImplicitMoveAssignment(ClassDecl);
10787     }
10788 
10789     if (ClassDecl->needsImplicitDestructor()) {
10790       ++getASTContext().NumImplicitDestructors;
10791 
10792       // If we have a dynamic class, then the destructor may be virtual, so we
10793       // have to declare the destructor immediately. This ensures that, e.g., it
10794       // shows up in the right place in the vtable and that we diagnose problems
10795       // with the implicit exception specification.
10796       if (ClassDecl->isDynamicClass() ||
10797           ClassDecl->needsOverloadResolutionForDestructor())
10798         DeclareImplicitDestructor(ClassDecl);
10799     }
10800   }
10801 
10802   // C++2a [class.compare.default]p3:
10803   //   If the member-specification does not explicitly declare any member or
10804   //   friend named operator==, an == operator function is declared implicitly
10805   //   for each defaulted three-way comparison operator function defined in
10806   //   the member-specification
10807   // FIXME: Consider doing this lazily.
10808   // We do this during the initial parse for a class template, not during
10809   // instantiation, so that we can handle unqualified lookups for 'operator=='
10810   // when parsing the template.
10811   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10812     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10813     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10814                                               DefaultedSpaceships);
10815     for (auto *FD : DefaultedSpaceships)
10816       DeclareImplicitEqualityComparison(ClassDecl, FD);
10817   }
10818 }
10819 
10820 unsigned
ActOnReenterTemplateScope(Decl * D,llvm::function_ref<Scope * ()> EnterScope)10821 Sema::ActOnReenterTemplateScope(Decl *D,
10822                                 llvm::function_ref<Scope *()> EnterScope) {
10823   if (!D)
10824     return 0;
10825   AdjustDeclIfTemplate(D);
10826 
10827   // In order to get name lookup right, reenter template scopes in order from
10828   // outermost to innermost.
10829   SmallVector<TemplateParameterList *, 4> ParameterLists;
10830   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10831 
10832   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10833     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10834       ParameterLists.push_back(DD->getTemplateParameterList(i));
10835 
10836     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10837       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10838         ParameterLists.push_back(FTD->getTemplateParameters());
10839     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10840       LookupDC = VD->getDeclContext();
10841 
10842       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10843         ParameterLists.push_back(VTD->getTemplateParameters());
10844       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10845         ParameterLists.push_back(PSD->getTemplateParameters());
10846     }
10847   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10848     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10849       ParameterLists.push_back(TD->getTemplateParameterList(i));
10850 
10851     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10852       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10853         ParameterLists.push_back(CTD->getTemplateParameters());
10854       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10855         ParameterLists.push_back(PSD->getTemplateParameters());
10856     }
10857   }
10858   // FIXME: Alias declarations and concepts.
10859 
10860   unsigned Count = 0;
10861   Scope *InnermostTemplateScope = nullptr;
10862   for (TemplateParameterList *Params : ParameterLists) {
10863     // Ignore explicit specializations; they don't contribute to the template
10864     // depth.
10865     if (Params->size() == 0)
10866       continue;
10867 
10868     InnermostTemplateScope = EnterScope();
10869     for (NamedDecl *Param : *Params) {
10870       if (Param->getDeclName()) {
10871         InnermostTemplateScope->AddDecl(Param);
10872         IdResolver.AddDecl(Param);
10873       }
10874     }
10875     ++Count;
10876   }
10877 
10878   // Associate the new template scopes with the corresponding entities.
10879   if (InnermostTemplateScope) {
10880     assert(LookupDC && "no enclosing DeclContext for template lookup");
10881     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10882   }
10883 
10884   return Count;
10885 }
10886 
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)10887 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10888   if (!RecordD) return;
10889   AdjustDeclIfTemplate(RecordD);
10890   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10891   PushDeclContext(S, Record);
10892 }
10893 
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)10894 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10895   if (!RecordD) return;
10896   PopDeclContext();
10897 }
10898 
ActOnReenterCXXMethodParameter(Scope * S,ParmVarDecl * Param)10899 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10900   if (!Param)
10901     return;
10902 
10903   S->AddDecl(Param);
10904   if (Param->getDeclName())
10905     IdResolver.AddDecl(Param);
10906 }
10907 
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)10908 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10909 }
10910 
10911 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10912 /// C++ method declaration. We're (re-)introducing the given
10913 /// function parameter into scope for use in parsing later parts of
10914 /// the method declaration. For example, we could see an
10915 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)10916 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10917   if (!ParamD)
10918     return;
10919 
10920   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10921 
10922   S->AddDecl(Param);
10923   if (Param->getDeclName())
10924     IdResolver.AddDecl(Param);
10925 }
10926 
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)10927 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10928   if (!MethodD)
10929     return;
10930 
10931   AdjustDeclIfTemplate(MethodD);
10932 
10933   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10934 
10935   // Now that we have our default arguments, check the constructor
10936   // again. It could produce additional diagnostics or affect whether
10937   // the class has implicitly-declared destructors, among other
10938   // things.
10939   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10940     CheckConstructor(Constructor);
10941 
10942   // Check the default arguments, which we may have added.
10943   if (!Method->isInvalidDecl())
10944     CheckCXXDefaultArguments(Method);
10945 }
10946 
10947 // Emit the given diagnostic for each non-address-space qualifier.
10948 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
checkMethodTypeQualifiers(Sema & S,Declarator & D,unsigned DiagID)10949 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10950   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10951   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10952     bool DiagOccured = false;
10953     FTI.MethodQualifiers->forEachQualifier(
10954         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10955                                    SourceLocation SL) {
10956           // This diagnostic should be emitted on any qualifier except an addr
10957           // space qualifier. However, forEachQualifier currently doesn't visit
10958           // addr space qualifiers, so there's no way to write this condition
10959           // right now; we just diagnose on everything.
10960           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10961           DiagOccured = true;
10962         });
10963     if (DiagOccured)
10964       D.setInvalidType();
10965   }
10966 }
10967 
diagnoseInvalidDeclaratorChunks(Sema & S,Declarator & D,unsigned Kind)10968 static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
10969                                             unsigned Kind) {
10970   if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
10971     return;
10972 
10973   DeclaratorChunk &Chunk = D.getTypeObject(D.getNumTypeObjects() - 1);
10974   if (Chunk.Kind == DeclaratorChunk::Paren ||
10975       Chunk.Kind == DeclaratorChunk::Function)
10976     return;
10977 
10978   SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
10979   S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
10980       << Kind << Chunk.getSourceRange();
10981   D.setInvalidType();
10982 }
10983 
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)10984 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10985                                           StorageClass &SC) {
10986   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10987 
10988   // C++ [class.ctor]p3:
10989   //   A constructor shall not be virtual (10.3) or static (9.4). A
10990   //   constructor can be invoked for a const, volatile or const
10991   //   volatile object. A constructor shall not be declared const,
10992   //   volatile, or const volatile (9.3.2).
10993   if (isVirtual) {
10994     if (!D.isInvalidType())
10995       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10996         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10997         << SourceRange(D.getIdentifierLoc());
10998     D.setInvalidType();
10999   }
11000   if (SC == SC_Static) {
11001     if (!D.isInvalidType())
11002       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11003         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11004         << SourceRange(D.getIdentifierLoc());
11005     D.setInvalidType();
11006     SC = SC_None;
11007   }
11008 
11009   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11010     diagnoseIgnoredQualifiers(
11011         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11012         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
11013         D.getDeclSpec().getRestrictSpecLoc(),
11014         D.getDeclSpec().getAtomicSpecLoc());
11015     D.setInvalidType();
11016   }
11017 
11018   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11019   diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11020 
11021   // C++0x [class.ctor]p4:
11022   //   A constructor shall not be declared with a ref-qualifier.
11023   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11024   if (FTI.hasRefQualifier()) {
11025     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11026       << FTI.RefQualifierIsLValueRef
11027       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11028     D.setInvalidType();
11029   }
11030 
11031   // Rebuild the function type "R" without any type qualifiers (in
11032   // case any of the errors above fired) and with "void" as the
11033   // return type, since constructors don't have return types.
11034   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11035   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11036     return R;
11037 
11038   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11039   EPI.TypeQuals = Qualifiers();
11040   EPI.RefQualifier = RQ_None;
11041 
11042   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11043 }
11044 
CheckConstructor(CXXConstructorDecl * Constructor)11045 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11046   CXXRecordDecl *ClassDecl
11047     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11048   if (!ClassDecl)
11049     return Constructor->setInvalidDecl();
11050 
11051   // C++ [class.copy]p3:
11052   //   A declaration of a constructor for a class X is ill-formed if
11053   //   its first parameter is of type (optionally cv-qualified) X and
11054   //   either there are no other parameters or else all other
11055   //   parameters have default arguments.
11056   if (!Constructor->isInvalidDecl() &&
11057       Constructor->hasOneParamOrDefaultArgs() &&
11058       !Constructor->isFunctionTemplateSpecialization()) {
11059     QualType ParamType = Constructor->getParamDecl(0)->getType();
11060     QualType ClassTy = Context.getTagDeclType(ClassDecl);
11061     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
11062       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11063       const char *ConstRef
11064         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11065                                                         : " const &";
11066       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11067         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11068 
11069       // FIXME: Rather that making the constructor invalid, we should endeavor
11070       // to fix the type.
11071       Constructor->setInvalidDecl();
11072     }
11073   }
11074 }
11075 
CheckDestructor(CXXDestructorDecl * Destructor)11076 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11077   CXXRecordDecl *RD = Destructor->getParent();
11078 
11079   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11080     SourceLocation Loc;
11081 
11082     if (!Destructor->isImplicit())
11083       Loc = Destructor->getLocation();
11084     else
11085       Loc = RD->getLocation();
11086 
11087     // If we have a virtual destructor, look up the deallocation function
11088     if (FunctionDecl *OperatorDelete =
11089             FindDeallocationFunctionForDestructor(Loc, RD)) {
11090       Expr *ThisArg = nullptr;
11091 
11092       // If the notional 'delete this' expression requires a non-trivial
11093       // conversion from 'this' to the type of a destroying operator delete's
11094       // first parameter, perform that conversion now.
11095       if (OperatorDelete->isDestroyingOperatorDelete()) {
11096         unsigned AddressParamIndex = 0;
11097         if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11098           ++AddressParamIndex;
11099         QualType ParamType =
11100             OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11101         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11102           // C++ [class.dtor]p13:
11103           //   ... as if for the expression 'delete this' appearing in a
11104           //   non-virtual destructor of the destructor's class.
11105           ContextRAII SwitchContext(*this, Destructor);
11106           ExprResult This = ActOnCXXThis(
11107               OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11108           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11109           This = PerformImplicitConversion(This.get(), ParamType,
11110                                            AssignmentAction::Passing);
11111           if (This.isInvalid()) {
11112             // FIXME: Register this as a context note so that it comes out
11113             // in the right order.
11114             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11115             return true;
11116           }
11117           ThisArg = This.get();
11118         }
11119       }
11120 
11121       DiagnoseUseOfDecl(OperatorDelete, Loc);
11122       MarkFunctionReferenced(Loc, OperatorDelete);
11123       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11124     }
11125   }
11126 
11127   return false;
11128 }
11129 
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)11130 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11131                                          StorageClass& SC) {
11132   // C++ [class.dtor]p1:
11133   //   [...] A typedef-name that names a class is a class-name
11134   //   (7.1.3); however, a typedef-name that names a class shall not
11135   //   be used as the identifier in the declarator for a destructor
11136   //   declaration.
11137   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11138   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11139     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11140       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11141   else if (const TemplateSpecializationType *TST =
11142              DeclaratorType->getAs<TemplateSpecializationType>())
11143     if (TST->isTypeAlias())
11144       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11145         << DeclaratorType << 1;
11146 
11147   // C++ [class.dtor]p2:
11148   //   A destructor is used to destroy objects of its class type. A
11149   //   destructor takes no parameters, and no return type can be
11150   //   specified for it (not even void). The address of a destructor
11151   //   shall not be taken. A destructor shall not be static. A
11152   //   destructor can be invoked for a const, volatile or const
11153   //   volatile object. A destructor shall not be declared const,
11154   //   volatile or const volatile (9.3.2).
11155   if (SC == SC_Static) {
11156     if (!D.isInvalidType())
11157       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11158         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11159         << SourceRange(D.getIdentifierLoc())
11160         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11161 
11162     SC = SC_None;
11163   }
11164   if (!D.isInvalidType()) {
11165     // Destructors don't have return types, but the parser will
11166     // happily parse something like:
11167     //
11168     //   class X {
11169     //     float ~X();
11170     //   };
11171     //
11172     // The return type will be eliminated later.
11173     if (D.getDeclSpec().hasTypeSpecifier())
11174       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11175         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11176         << SourceRange(D.getIdentifierLoc());
11177     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11178       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11179                                 SourceLocation(),
11180                                 D.getDeclSpec().getConstSpecLoc(),
11181                                 D.getDeclSpec().getVolatileSpecLoc(),
11182                                 D.getDeclSpec().getRestrictSpecLoc(),
11183                                 D.getDeclSpec().getAtomicSpecLoc());
11184       D.setInvalidType();
11185     }
11186   }
11187 
11188   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11189   diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11190 
11191   // C++0x [class.dtor]p2:
11192   //   A destructor shall not be declared with a ref-qualifier.
11193   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11194   if (FTI.hasRefQualifier()) {
11195     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11196       << FTI.RefQualifierIsLValueRef
11197       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11198     D.setInvalidType();
11199   }
11200 
11201   // Make sure we don't have any parameters.
11202   if (FTIHasNonVoidParameters(FTI)) {
11203     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11204 
11205     // Delete the parameters.
11206     FTI.freeParams();
11207     D.setInvalidType();
11208   }
11209 
11210   // Make sure the destructor isn't variadic.
11211   if (FTI.isVariadic) {
11212     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11213     D.setInvalidType();
11214   }
11215 
11216   // Rebuild the function type "R" without any type qualifiers or
11217   // parameters (in case any of the errors above fired) and with
11218   // "void" as the return type, since destructors don't have return
11219   // types.
11220   if (!D.isInvalidType())
11221     return R;
11222 
11223   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11224   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11225   EPI.Variadic = false;
11226   EPI.TypeQuals = Qualifiers();
11227   EPI.RefQualifier = RQ_None;
11228   return Context.getFunctionType(Context.VoidTy, {}, EPI);
11229 }
11230 
extendLeft(SourceRange & R,SourceRange Before)11231 static void extendLeft(SourceRange &R, SourceRange Before) {
11232   if (Before.isInvalid())
11233     return;
11234   R.setBegin(Before.getBegin());
11235   if (R.getEnd().isInvalid())
11236     R.setEnd(Before.getEnd());
11237 }
11238 
extendRight(SourceRange & R,SourceRange After)11239 static void extendRight(SourceRange &R, SourceRange After) {
11240   if (After.isInvalid())
11241     return;
11242   if (R.getBegin().isInvalid())
11243     R.setBegin(After.getBegin());
11244   R.setEnd(After.getEnd());
11245 }
11246 
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)11247 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11248                                      StorageClass& SC) {
11249   // C++ [class.conv.fct]p1:
11250   //   Neither parameter types nor return type can be specified. The
11251   //   type of a conversion function (8.3.5) is "function taking no
11252   //   parameter returning conversion-type-id."
11253   if (SC == SC_Static) {
11254     if (!D.isInvalidType())
11255       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11256         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11257         << D.getName().getSourceRange();
11258     D.setInvalidType();
11259     SC = SC_None;
11260   }
11261 
11262   TypeSourceInfo *ConvTSI = nullptr;
11263   QualType ConvType =
11264       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11265 
11266   const DeclSpec &DS = D.getDeclSpec();
11267   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11268     // Conversion functions don't have return types, but the parser will
11269     // happily parse something like:
11270     //
11271     //   class X {
11272     //     float operator bool();
11273     //   };
11274     //
11275     // The return type will be changed later anyway.
11276     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11277       << SourceRange(DS.getTypeSpecTypeLoc())
11278       << SourceRange(D.getIdentifierLoc());
11279     D.setInvalidType();
11280   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11281     // It's also plausible that the user writes type qualifiers in the wrong
11282     // place, such as:
11283     //   struct S { const operator int(); };
11284     // FIXME: we could provide a fixit to move the qualifiers onto the
11285     // conversion type.
11286     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11287         << SourceRange(D.getIdentifierLoc()) << 0;
11288     D.setInvalidType();
11289   }
11290   const auto *Proto = R->castAs<FunctionProtoType>();
11291   // Make sure we don't have any parameters.
11292   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11293   unsigned NumParam = Proto->getNumParams();
11294 
11295   // [C++2b]
11296   // A conversion function shall have no non-object parameters.
11297   if (NumParam == 1) {
11298     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11299     if (const auto *First =
11300             dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11301         First && First->isExplicitObjectParameter())
11302       NumParam--;
11303   }
11304 
11305   if (NumParam != 0) {
11306     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11307     // Delete the parameters.
11308     FTI.freeParams();
11309     D.setInvalidType();
11310   } else if (Proto->isVariadic()) {
11311     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11312     D.setInvalidType();
11313   }
11314 
11315   // Diagnose "&operator bool()" and other such nonsense.  This
11316   // is actually a gcc extension which we don't support.
11317   if (Proto->getReturnType() != ConvType) {
11318     bool NeedsTypedef = false;
11319     SourceRange Before, After;
11320 
11321     // Walk the chunks and extract information on them for our diagnostic.
11322     bool PastFunctionChunk = false;
11323     for (auto &Chunk : D.type_objects()) {
11324       switch (Chunk.Kind) {
11325       case DeclaratorChunk::Function:
11326         if (!PastFunctionChunk) {
11327           if (Chunk.Fun.HasTrailingReturnType) {
11328             TypeSourceInfo *TRT = nullptr;
11329             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11330             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11331           }
11332           PastFunctionChunk = true;
11333           break;
11334         }
11335         [[fallthrough]];
11336       case DeclaratorChunk::Array:
11337         NeedsTypedef = true;
11338         extendRight(After, Chunk.getSourceRange());
11339         break;
11340 
11341       case DeclaratorChunk::Pointer:
11342       case DeclaratorChunk::BlockPointer:
11343       case DeclaratorChunk::Reference:
11344       case DeclaratorChunk::MemberPointer:
11345       case DeclaratorChunk::Pipe:
11346         extendLeft(Before, Chunk.getSourceRange());
11347         break;
11348 
11349       case DeclaratorChunk::Paren:
11350         extendLeft(Before, Chunk.Loc);
11351         extendRight(After, Chunk.EndLoc);
11352         break;
11353       }
11354     }
11355 
11356     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11357                          After.isValid()  ? After.getBegin() :
11358                                             D.getIdentifierLoc();
11359     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11360     DB << Before << After;
11361 
11362     if (!NeedsTypedef) {
11363       DB << /*don't need a typedef*/0;
11364 
11365       // If we can provide a correct fix-it hint, do so.
11366       if (After.isInvalid() && ConvTSI) {
11367         SourceLocation InsertLoc =
11368             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11369         DB << FixItHint::CreateInsertion(InsertLoc, " ")
11370            << FixItHint::CreateInsertionFromRange(
11371                   InsertLoc, CharSourceRange::getTokenRange(Before))
11372            << FixItHint::CreateRemoval(Before);
11373       }
11374     } else if (!Proto->getReturnType()->isDependentType()) {
11375       DB << /*typedef*/1 << Proto->getReturnType();
11376     } else if (getLangOpts().CPlusPlus11) {
11377       DB << /*alias template*/2 << Proto->getReturnType();
11378     } else {
11379       DB << /*might not be fixable*/3;
11380     }
11381 
11382     // Recover by incorporating the other type chunks into the result type.
11383     // Note, this does *not* change the name of the function. This is compatible
11384     // with the GCC extension:
11385     //   struct S { &operator int(); } s;
11386     //   int &r = s.operator int(); // ok in GCC
11387     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
11388     ConvType = Proto->getReturnType();
11389   }
11390 
11391   // C++ [class.conv.fct]p4:
11392   //   The conversion-type-id shall not represent a function type nor
11393   //   an array type.
11394   if (ConvType->isArrayType()) {
11395     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11396     ConvType = Context.getPointerType(ConvType);
11397     D.setInvalidType();
11398   } else if (ConvType->isFunctionType()) {
11399     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11400     ConvType = Context.getPointerType(ConvType);
11401     D.setInvalidType();
11402   }
11403 
11404   // Rebuild the function type "R" without any parameters (in case any
11405   // of the errors above fired) and with the conversion type as the
11406   // return type.
11407   if (D.isInvalidType())
11408     R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11409 
11410   // C++0x explicit conversion operators.
11411   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11412     Diag(DS.getExplicitSpecLoc(),
11413          getLangOpts().CPlusPlus11
11414              ? diag::warn_cxx98_compat_explicit_conversion_functions
11415              : diag::ext_explicit_conversion_functions)
11416         << SourceRange(DS.getExplicitSpecRange());
11417 }
11418 
ActOnConversionDeclarator(CXXConversionDecl * Conversion)11419 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11420   assert(Conversion && "Expected to receive a conversion function declaration");
11421 
11422   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11423 
11424   // Make sure we aren't redeclaring the conversion function.
11425   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11426   // C++ [class.conv.fct]p1:
11427   //   [...] A conversion function is never used to convert a
11428   //   (possibly cv-qualified) object to the (possibly cv-qualified)
11429   //   same object type (or a reference to it), to a (possibly
11430   //   cv-qualified) base class of that type (or a reference to it),
11431   //   or to (possibly cv-qualified) void.
11432   QualType ClassType
11433     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11434   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11435     ConvType = ConvTypeRef->getPointeeType();
11436   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11437       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11438     /* Suppress diagnostics for instantiations. */;
11439   else if (Conversion->size_overridden_methods() != 0)
11440     /* Suppress diagnostics for overriding virtual function in a base class. */;
11441   else if (ConvType->isRecordType()) {
11442     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11443     if (ConvType == ClassType)
11444       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11445         << ClassType;
11446     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11447       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11448         <<  ClassType << ConvType;
11449   } else if (ConvType->isVoidType()) {
11450     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11451       << ClassType << ConvType;
11452   }
11453 
11454   if (FunctionTemplateDecl *ConversionTemplate =
11455           Conversion->getDescribedFunctionTemplate()) {
11456     if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11457       ConvType = ConvTypePtr->getPointeeType();
11458     }
11459     if (ConvType->isUndeducedAutoType()) {
11460       Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11461           << getReturnTypeLoc(Conversion).getSourceRange()
11462           << ConvType->castAs<AutoType>()->getKeyword()
11463           << /* in declaration of conversion function template= */ 24;
11464     }
11465 
11466     return ConversionTemplate;
11467   }
11468 
11469   return Conversion;
11470 }
11471 
CheckExplicitObjectMemberFunction(DeclContext * DC,Declarator & D,DeclarationName Name,QualType R)11472 void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11473                                              DeclarationName Name, QualType R) {
11474   CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11475 }
11476 
CheckExplicitObjectLambda(Declarator & D)11477 void Sema::CheckExplicitObjectLambda(Declarator &D) {
11478   CheckExplicitObjectMemberFunction(D, {}, {}, true);
11479 }
11480 
CheckExplicitObjectMemberFunction(Declarator & D,DeclarationName Name,QualType R,bool IsLambda,DeclContext * DC)11481 void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11482                                              DeclarationName Name, QualType R,
11483                                              bool IsLambda, DeclContext *DC) {
11484   if (!D.isFunctionDeclarator())
11485     return;
11486 
11487   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11488   if (FTI.NumParams == 0)
11489     return;
11490   ParmVarDecl *ExplicitObjectParam = nullptr;
11491   for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11492     const auto &ParamInfo = FTI.Params[Idx];
11493     if (!ParamInfo.Param)
11494       continue;
11495     ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11496     if (!Param->isExplicitObjectParameter())
11497       continue;
11498     if (Idx == 0) {
11499       ExplicitObjectParam = Param;
11500       continue;
11501     } else {
11502       Diag(Param->getLocation(),
11503            diag::err_explicit_object_parameter_must_be_first)
11504           << IsLambda << Param->getSourceRange();
11505     }
11506   }
11507   if (!ExplicitObjectParam)
11508     return;
11509 
11510   if (ExplicitObjectParam->hasDefaultArg()) {
11511     Diag(ExplicitObjectParam->getLocation(),
11512          diag::err_explicit_object_default_arg)
11513         << ExplicitObjectParam->getSourceRange();
11514   }
11515 
11516   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11517       (D.getContext() == clang::DeclaratorContext::Member &&
11518        D.isStaticMember())) {
11519     Diag(ExplicitObjectParam->getBeginLoc(),
11520          diag::err_explicit_object_parameter_nonmember)
11521         << D.getSourceRange() << /*static=*/0 << IsLambda;
11522     D.setInvalidType();
11523   }
11524 
11525   if (D.getDeclSpec().isVirtualSpecified()) {
11526     Diag(ExplicitObjectParam->getBeginLoc(),
11527          diag::err_explicit_object_parameter_nonmember)
11528         << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11529     D.setInvalidType();
11530   }
11531 
11532   // Friend declarations require some care. Consider:
11533   //
11534   // namespace N {
11535   // struct A{};
11536   // int f(A);
11537   // }
11538   //
11539   // struct S {
11540   //   struct T {
11541   //     int f(this T);
11542   //   };
11543   //
11544   //   friend int T::f(this T); // Allow this.
11545   //   friend int f(this S);    // But disallow this.
11546   //   friend int N::f(this A); // And disallow this.
11547   // };
11548   //
11549   // Here, it seems to suffice to check whether the scope
11550   // specifier designates a class type.
11551   if (D.getDeclSpec().isFriendSpecified() &&
11552       !isa_and_present<CXXRecordDecl>(
11553           computeDeclContext(D.getCXXScopeSpec()))) {
11554     Diag(ExplicitObjectParam->getBeginLoc(),
11555          diag::err_explicit_object_parameter_nonmember)
11556         << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11557     D.setInvalidType();
11558   }
11559 
11560   if (IsLambda && FTI.hasMutableQualifier()) {
11561     Diag(ExplicitObjectParam->getBeginLoc(),
11562          diag::err_explicit_object_parameter_mutable)
11563         << D.getSourceRange();
11564   }
11565 
11566   if (IsLambda)
11567     return;
11568 
11569   if (!DC || !DC->isRecord()) {
11570     assert(D.isInvalidType() && "Explicit object parameter in non-member "
11571                                 "should have been diagnosed already");
11572     return;
11573   }
11574 
11575   // CWG2674: constructors and destructors cannot have explicit parameters.
11576   if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11577       Name.getNameKind() == DeclarationName::CXXDestructorName) {
11578     Diag(ExplicitObjectParam->getBeginLoc(),
11579          diag::err_explicit_object_parameter_constructor)
11580         << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11581         << D.getSourceRange();
11582     D.setInvalidType();
11583   }
11584 }
11585 
11586 namespace {
11587 /// Utility class to accumulate and print a diagnostic listing the invalid
11588 /// specifier(s) on a declaration.
11589 struct BadSpecifierDiagnoser {
BadSpecifierDiagnoser__anon42c808802e11::BadSpecifierDiagnoser11590   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11591       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
~BadSpecifierDiagnoser__anon42c808802e11::BadSpecifierDiagnoser11592   ~BadSpecifierDiagnoser() {
11593     Diagnostic << Specifiers;
11594   }
11595 
check__anon42c808802e11::BadSpecifierDiagnoser11596   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11597     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11598   }
check__anon42c808802e11::BadSpecifierDiagnoser11599   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11600     return check(SpecLoc,
11601                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11602   }
check__anon42c808802e11::BadSpecifierDiagnoser11603   void check(SourceLocation SpecLoc, const char *Spec) {
11604     if (SpecLoc.isInvalid()) return;
11605     Diagnostic << SourceRange(SpecLoc, SpecLoc);
11606     if (!Specifiers.empty()) Specifiers += " ";
11607     Specifiers += Spec;
11608   }
11609 
11610   Sema &S;
11611   Sema::SemaDiagnosticBuilder Diagnostic;
11612   std::string Specifiers;
11613 };
11614 }
11615 
CheckDeductionGuideDeclarator(Declarator & D,QualType & R,StorageClass & SC)11616 bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11617                                          StorageClass &SC) {
11618   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11619   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11620   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11621 
11622   // C++ [temp.deduct.guide]p3:
11623   //   A deduction-gide shall be declared in the same scope as the
11624   //   corresponding class template.
11625   if (!CurContext->getRedeclContext()->Equals(
11626           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11627     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11628       << GuidedTemplateDecl;
11629     NoteTemplateLocation(*GuidedTemplateDecl);
11630   }
11631 
11632   auto &DS = D.getMutableDeclSpec();
11633   // We leave 'friend' and 'virtual' to be rejected in the normal way.
11634   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11635       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11636       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11637     BadSpecifierDiagnoser Diagnoser(
11638         *this, D.getIdentifierLoc(),
11639         diag::err_deduction_guide_invalid_specifier);
11640 
11641     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11642     DS.ClearStorageClassSpecs();
11643     SC = SC_None;
11644 
11645     // 'explicit' is permitted.
11646     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11647     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11648     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11649     DS.ClearConstexprSpec();
11650 
11651     Diagnoser.check(DS.getConstSpecLoc(), "const");
11652     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11653     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11654     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11655     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11656     DS.ClearTypeQualifiers();
11657 
11658     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11659     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11660     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11661     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11662     DS.ClearTypeSpecType();
11663   }
11664 
11665   if (D.isInvalidType())
11666     return true;
11667 
11668   // Check the declarator is simple enough.
11669   bool FoundFunction = false;
11670   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11671     if (Chunk.Kind == DeclaratorChunk::Paren)
11672       continue;
11673     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11674       Diag(D.getDeclSpec().getBeginLoc(),
11675            diag::err_deduction_guide_with_complex_decl)
11676           << D.getSourceRange();
11677       break;
11678     }
11679     if (!Chunk.Fun.hasTrailingReturnType())
11680       return Diag(D.getName().getBeginLoc(),
11681                   diag::err_deduction_guide_no_trailing_return_type);
11682 
11683     // Check that the return type is written as a specialization of
11684     // the template specified as the deduction-guide's name.
11685     // The template name may not be qualified. [temp.deduct.guide]
11686     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11687     TypeSourceInfo *TSI = nullptr;
11688     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11689     assert(TSI && "deduction guide has valid type but invalid return type?");
11690     bool AcceptableReturnType = false;
11691     bool MightInstantiateToSpecialization = false;
11692     if (auto RetTST =
11693             TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11694       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11695       bool TemplateMatches = Context.hasSameTemplateName(
11696           SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11697 
11698       const QualifiedTemplateName *Qualifiers =
11699           SpecifiedName.getAsQualifiedTemplateName();
11700       assert(Qualifiers && "expected QualifiedTemplate");
11701       bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11702                            Qualifiers->getQualifier() == nullptr;
11703       if (SimplyWritten && TemplateMatches)
11704         AcceptableReturnType = true;
11705       else {
11706         // This could still instantiate to the right type, unless we know it
11707         // names the wrong class template.
11708         auto *TD = SpecifiedName.getAsTemplateDecl();
11709         MightInstantiateToSpecialization =
11710             !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11711       }
11712     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11713       MightInstantiateToSpecialization = true;
11714     }
11715 
11716     if (!AcceptableReturnType)
11717       return Diag(TSI->getTypeLoc().getBeginLoc(),
11718                   diag::err_deduction_guide_bad_trailing_return_type)
11719              << GuidedTemplate << TSI->getType()
11720              << MightInstantiateToSpecialization
11721              << TSI->getTypeLoc().getSourceRange();
11722 
11723     // Keep going to check that we don't have any inner declarator pieces (we
11724     // could still have a function returning a pointer to a function).
11725     FoundFunction = true;
11726   }
11727 
11728   if (D.isFunctionDefinition())
11729     // we can still create a valid deduction guide here.
11730     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11731   return false;
11732 }
11733 
11734 //===----------------------------------------------------------------------===//
11735 // Namespace Handling
11736 //===----------------------------------------------------------------------===//
11737 
11738 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11739 /// reopened.
DiagnoseNamespaceInlineMismatch(Sema & S,SourceLocation KeywordLoc,SourceLocation Loc,IdentifierInfo * II,bool * IsInline,NamespaceDecl * PrevNS)11740 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11741                                             SourceLocation Loc,
11742                                             IdentifierInfo *II, bool *IsInline,
11743                                             NamespaceDecl *PrevNS) {
11744   assert(*IsInline != PrevNS->isInline());
11745 
11746   // 'inline' must appear on the original definition, but not necessarily
11747   // on all extension definitions, so the note should point to the first
11748   // definition to avoid confusion.
11749   PrevNS = PrevNS->getFirstDecl();
11750 
11751   if (PrevNS->isInline())
11752     // The user probably just forgot the 'inline', so suggest that it
11753     // be added back.
11754     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11755       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11756   else
11757     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11758 
11759   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11760   *IsInline = PrevNS->isInline();
11761 }
11762 
11763 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11764 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,const ParsedAttributesView & AttrList,UsingDirectiveDecl * & UD,bool IsNested)11765 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11766                                    SourceLocation InlineLoc,
11767                                    SourceLocation NamespaceLoc,
11768                                    SourceLocation IdentLoc, IdentifierInfo *II,
11769                                    SourceLocation LBrace,
11770                                    const ParsedAttributesView &AttrList,
11771                                    UsingDirectiveDecl *&UD, bool IsNested) {
11772   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11773   // For anonymous namespace, take the location of the left brace.
11774   SourceLocation Loc = II ? IdentLoc : LBrace;
11775   bool IsInline = InlineLoc.isValid();
11776   bool IsInvalid = false;
11777   bool IsStd = false;
11778   bool AddToKnown = false;
11779   Scope *DeclRegionScope = NamespcScope->getParent();
11780 
11781   NamespaceDecl *PrevNS = nullptr;
11782   if (II) {
11783     // C++ [namespace.std]p7:
11784     //   A translation unit shall not declare namespace std to be an inline
11785     //   namespace (9.8.2).
11786     //
11787     // Precondition: the std namespace is in the file scope and is declared to
11788     // be inline
11789     auto DiagnoseInlineStdNS = [&]() {
11790       assert(IsInline && II->isStr("std") &&
11791              CurContext->getRedeclContext()->isTranslationUnit() &&
11792              "Precondition of DiagnoseInlineStdNS not met");
11793       Diag(InlineLoc, diag::err_inline_namespace_std)
11794           << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11795       IsInline = false;
11796     };
11797     // C++ [namespace.def]p2:
11798     //   The identifier in an original-namespace-definition shall not
11799     //   have been previously defined in the declarative region in
11800     //   which the original-namespace-definition appears. The
11801     //   identifier in an original-namespace-definition is the name of
11802     //   the namespace. Subsequently in that declarative region, it is
11803     //   treated as an original-namespace-name.
11804     //
11805     // Since namespace names are unique in their scope, and we don't
11806     // look through using directives, just look for any ordinary names
11807     // as if by qualified name lookup.
11808     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11809                    RedeclarationKind::ForExternalRedeclaration);
11810     LookupQualifiedName(R, CurContext->getRedeclContext());
11811     NamedDecl *PrevDecl =
11812         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11813     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11814 
11815     if (PrevNS) {
11816       // This is an extended namespace definition.
11817       if (IsInline && II->isStr("std") &&
11818           CurContext->getRedeclContext()->isTranslationUnit())
11819         DiagnoseInlineStdNS();
11820       else if (IsInline != PrevNS->isInline())
11821         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11822                                         &IsInline, PrevNS);
11823     } else if (PrevDecl) {
11824       // This is an invalid name redefinition.
11825       Diag(Loc, diag::err_redefinition_different_kind)
11826         << II;
11827       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11828       IsInvalid = true;
11829       // Continue on to push Namespc as current DeclContext and return it.
11830     } else if (II->isStr("std") &&
11831                CurContext->getRedeclContext()->isTranslationUnit()) {
11832       if (IsInline)
11833         DiagnoseInlineStdNS();
11834       // This is the first "real" definition of the namespace "std", so update
11835       // our cache of the "std" namespace to point at this definition.
11836       PrevNS = getStdNamespace();
11837       IsStd = true;
11838       AddToKnown = !IsInline;
11839     } else {
11840       // We've seen this namespace for the first time.
11841       AddToKnown = !IsInline;
11842     }
11843   } else {
11844     // Anonymous namespaces.
11845 
11846     // Determine whether the parent already has an anonymous namespace.
11847     DeclContext *Parent = CurContext->getRedeclContext();
11848     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11849       PrevNS = TU->getAnonymousNamespace();
11850     } else {
11851       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11852       PrevNS = ND->getAnonymousNamespace();
11853     }
11854 
11855     if (PrevNS && IsInline != PrevNS->isInline())
11856       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11857                                       &IsInline, PrevNS);
11858   }
11859 
11860   NamespaceDecl *Namespc = NamespaceDecl::Create(
11861       Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11862   if (IsInvalid)
11863     Namespc->setInvalidDecl();
11864 
11865   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11866   AddPragmaAttributes(DeclRegionScope, Namespc);
11867   ProcessAPINotes(Namespc);
11868 
11869   // FIXME: Should we be merging attributes?
11870   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11871     PushNamespaceVisibilityAttr(Attr, Loc);
11872 
11873   if (IsStd)
11874     StdNamespace = Namespc;
11875   if (AddToKnown)
11876     KnownNamespaces[Namespc] = false;
11877 
11878   if (II) {
11879     PushOnScopeChains(Namespc, DeclRegionScope);
11880   } else {
11881     // Link the anonymous namespace into its parent.
11882     DeclContext *Parent = CurContext->getRedeclContext();
11883     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11884       TU->setAnonymousNamespace(Namespc);
11885     } else {
11886       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11887     }
11888 
11889     CurContext->addDecl(Namespc);
11890 
11891     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11892     //   behaves as if it were replaced by
11893     //     namespace unique { /* empty body */ }
11894     //     using namespace unique;
11895     //     namespace unique { namespace-body }
11896     //   where all occurrences of 'unique' in a translation unit are
11897     //   replaced by the same identifier and this identifier differs
11898     //   from all other identifiers in the entire program.
11899 
11900     // We just create the namespace with an empty name and then add an
11901     // implicit using declaration, just like the standard suggests.
11902     //
11903     // CodeGen enforces the "universally unique" aspect by giving all
11904     // declarations semantically contained within an anonymous
11905     // namespace internal linkage.
11906 
11907     if (!PrevNS) {
11908       UD = UsingDirectiveDecl::Create(Context, Parent,
11909                                       /* 'using' */ LBrace,
11910                                       /* 'namespace' */ SourceLocation(),
11911                                       /* qualifier */ NestedNameSpecifierLoc(),
11912                                       /* identifier */ SourceLocation(),
11913                                       Namespc,
11914                                       /* Ancestor */ Parent);
11915       UD->setImplicit();
11916       Parent->addDecl(UD);
11917     }
11918   }
11919 
11920   ActOnDocumentableDecl(Namespc);
11921 
11922   // Although we could have an invalid decl (i.e. the namespace name is a
11923   // redefinition), push it as current DeclContext and try to continue parsing.
11924   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11925   // for the namespace has the declarations that showed up in that particular
11926   // namespace definition.
11927   PushDeclContext(NamespcScope, Namespc);
11928   return Namespc;
11929 }
11930 
11931 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11932 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)11933 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11934   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11935     return AD->getNamespace();
11936   return dyn_cast_or_null<NamespaceDecl>(D);
11937 }
11938 
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)11939 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11940   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11941   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11942   Namespc->setRBraceLoc(RBrace);
11943   PopDeclContext();
11944   if (Namespc->hasAttr<VisibilityAttr>())
11945     PopPragmaVisibility(true, RBrace);
11946   // If this namespace contains an export-declaration, export it now.
11947   if (DeferredExportedNamespaces.erase(Namespc))
11948     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11949 }
11950 
getStdBadAlloc() const11951 CXXRecordDecl *Sema::getStdBadAlloc() const {
11952   return cast_or_null<CXXRecordDecl>(
11953                                   StdBadAlloc.get(Context.getExternalSource()));
11954 }
11955 
getStdAlignValT() const11956 EnumDecl *Sema::getStdAlignValT() const {
11957   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11958 }
11959 
getStdNamespace() const11960 NamespaceDecl *Sema::getStdNamespace() const {
11961   return cast_or_null<NamespaceDecl>(
11962                                  StdNamespace.get(Context.getExternalSource()));
11963 }
11964 
11965 namespace {
11966 
11967 enum UnsupportedSTLSelect {
11968   USS_InvalidMember,
11969   USS_MissingMember,
11970   USS_NonTrivial,
11971   USS_Other
11972 };
11973 
11974 struct InvalidSTLDiagnoser {
11975   Sema &S;
11976   SourceLocation Loc;
11977   QualType TyForDiags;
11978 
operator ()__anon42c808803011::InvalidSTLDiagnoser11979   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11980                       const VarDecl *VD = nullptr) {
11981     {
11982       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11983                << TyForDiags << ((int)Sel);
11984       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11985         assert(!Name.empty());
11986         D << Name;
11987       }
11988     }
11989     if (Sel == USS_InvalidMember) {
11990       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11991           << VD << VD->getSourceRange();
11992     }
11993     return QualType();
11994   }
11995 };
11996 } // namespace
11997 
CheckComparisonCategoryType(ComparisonCategoryType Kind,SourceLocation Loc,ComparisonCategoryUsage Usage)11998 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11999                                            SourceLocation Loc,
12000                                            ComparisonCategoryUsage Usage) {
12001   assert(getLangOpts().CPlusPlus &&
12002          "Looking for comparison category type outside of C++.");
12003 
12004   // Use an elaborated type for diagnostics which has a name containing the
12005   // prepended 'std' namespace but not any inline namespace names.
12006   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12007     auto *NNS =
12008         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
12009     return Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,
12010                                      Info->getType());
12011   };
12012 
12013   // Check if we've already successfully checked the comparison category type
12014   // before. If so, skip checking it again.
12015   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12016   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12017     // The only thing we need to check is that the type has a reachable
12018     // definition in the current context.
12019     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12020       return QualType();
12021 
12022     return Info->getType();
12023   }
12024 
12025   // If lookup failed
12026   if (!Info) {
12027     std::string NameForDiags = "std::";
12028     NameForDiags += ComparisonCategories::getCategoryString(Kind);
12029     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12030         << NameForDiags << (int)Usage;
12031     return QualType();
12032   }
12033 
12034   assert(Info->Kind == Kind);
12035   assert(Info->Record);
12036 
12037   // Update the Record decl in case we encountered a forward declaration on our
12038   // first pass. FIXME: This is a bit of a hack.
12039   if (Info->Record->hasDefinition())
12040     Info->Record = Info->Record->getDefinition();
12041 
12042   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12043     return QualType();
12044 
12045   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12046 
12047   if (!Info->Record->isTriviallyCopyable())
12048     return UnsupportedSTLError(USS_NonTrivial);
12049 
12050   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12051     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12052     // Tolerate empty base classes.
12053     if (Base->isEmpty())
12054       continue;
12055     // Reject STL implementations which have at least one non-empty base.
12056     return UnsupportedSTLError();
12057   }
12058 
12059   // Check that the STL has implemented the types using a single integer field.
12060   // This expectation allows better codegen for builtin operators. We require:
12061   //   (1) The class has exactly one field.
12062   //   (2) The field is an integral or enumeration type.
12063   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12064   if (std::distance(FIt, FEnd) != 1 ||
12065       !FIt->getType()->isIntegralOrEnumerationType()) {
12066     return UnsupportedSTLError();
12067   }
12068 
12069   // Build each of the require values and store them in Info.
12070   for (ComparisonCategoryResult CCR :
12071        ComparisonCategories::getPossibleResultsForType(Kind)) {
12072     StringRef MemName = ComparisonCategories::getResultString(CCR);
12073     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12074 
12075     if (!ValInfo)
12076       return UnsupportedSTLError(USS_MissingMember, MemName);
12077 
12078     VarDecl *VD = ValInfo->VD;
12079     assert(VD && "should not be null!");
12080 
12081     // Attempt to diagnose reasons why the STL definition of this type
12082     // might be foobar, including it failing to be a constant expression.
12083     // TODO Handle more ways the lookup or result can be invalid.
12084     if (!VD->isStaticDataMember() ||
12085         !VD->isUsableInConstantExpressions(Context))
12086       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12087 
12088     // Attempt to evaluate the var decl as a constant expression and extract
12089     // the value of its first field as a ICE. If this fails, the STL
12090     // implementation is not supported.
12091     if (!ValInfo->hasValidIntValue())
12092       return UnsupportedSTLError();
12093 
12094     MarkVariableReferenced(Loc, VD);
12095   }
12096 
12097   // We've successfully built the required types and expressions. Update
12098   // the cache and return the newly cached value.
12099   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12100   return Info->getType();
12101 }
12102 
getOrCreateStdNamespace()12103 NamespaceDecl *Sema::getOrCreateStdNamespace() {
12104   if (!StdNamespace) {
12105     // The "std" namespace has not yet been defined, so build one implicitly.
12106     StdNamespace = NamespaceDecl::Create(
12107         Context, Context.getTranslationUnitDecl(),
12108         /*Inline=*/false, SourceLocation(), SourceLocation(),
12109         &PP.getIdentifierTable().get("std"),
12110         /*PrevDecl=*/nullptr, /*Nested=*/false);
12111     getStdNamespace()->setImplicit(true);
12112     // We want the created NamespaceDecl to be available for redeclaration
12113     // lookups, but not for regular name lookups.
12114     Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12115     getStdNamespace()->clearIdentifierNamespace();
12116   }
12117 
12118   return getStdNamespace();
12119 }
12120 
isStdClassTemplate(Sema & S,QualType SugaredType,QualType * TypeArg,const char * ClassName,ClassTemplateDecl ** CachedDecl,const Decl ** MalformedDecl)12121 static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12122                                const char *ClassName,
12123                                ClassTemplateDecl **CachedDecl,
12124                                const Decl **MalformedDecl) {
12125   // We're looking for implicit instantiations of
12126   // template <typename U> class std::{ClassName}.
12127 
12128   if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12129                        // it.
12130     return false;
12131 
12132   auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12133     if (!MalformedDecl)
12134       return;
12135     if (!D)
12136       D = SugaredType->getAsTagDecl();
12137     if (!D || !D->isInStdNamespace())
12138       return;
12139     IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12140     if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12141       *MalformedDecl = D;
12142   };
12143 
12144   ClassTemplateDecl *Template = nullptr;
12145   ArrayRef<TemplateArgument> Arguments;
12146   {
12147     const TemplateSpecializationType *TST =
12148         SugaredType->getAsNonAliasTemplateSpecializationType();
12149     if (!TST)
12150       if (const auto *ICN = SugaredType->getAs<InjectedClassNameType>())
12151         TST = ICN->getInjectedTST();
12152     if (TST) {
12153       Template = dyn_cast_or_null<ClassTemplateDecl>(
12154           TST->getTemplateName().getAsTemplateDecl());
12155       Arguments = TST->template_arguments();
12156     } else if (const RecordType *RT = SugaredType->getAs<RecordType>()) {
12157       ClassTemplateSpecializationDecl *Specialization =
12158           dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
12159       if (!Specialization) {
12160         ReportMatchingNameAsMalformed(RT->getDecl());
12161         return false;
12162       }
12163       Template = Specialization->getSpecializedTemplate();
12164       Arguments = Specialization->getTemplateArgs().asArray();
12165     }
12166   }
12167 
12168   if (!Template) {
12169     ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12170     return false;
12171   }
12172 
12173   if (!*CachedDecl) {
12174     // Haven't recognized std::{ClassName} yet, maybe this is it.
12175     // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12176     // semantics of this are slightly different, most notably the existing
12177     // "lookup" semantics explicitly diagnose an invalid definition as an
12178     // error.
12179     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12180     if (TemplateClass->getIdentifier() !=
12181             &S.PP.getIdentifierTable().get(ClassName) ||
12182         !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12183             TemplateClass->getNonTransparentDeclContext()))
12184       return false;
12185     // This is a template called std::{ClassName}, but is it the right
12186     // template?
12187     TemplateParameterList *Params = Template->getTemplateParameters();
12188     if (Params->getMinRequiredArguments() != 1 ||
12189         !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12190         Params->getParam(0)->isTemplateParameterPack()) {
12191       if (MalformedDecl)
12192         *MalformedDecl = TemplateClass;
12193       return false;
12194     }
12195 
12196     // It's the right template.
12197     *CachedDecl = Template;
12198   }
12199 
12200   if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12201     return false;
12202 
12203   // This is an instance of std::{ClassName}. Find the argument type.
12204   if (TypeArg) {
12205     QualType ArgType = Arguments[0].getAsType();
12206     // FIXME: Since TST only has as-written arguments, we have to perform the
12207     // only kind of conversion applicable to type arguments; in Objective-C ARC:
12208     // - If an explicitly-specified template argument type is a lifetime type
12209     //   with no lifetime qualifier, the __strong lifetime qualifier is
12210     //   inferred.
12211     if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12212         !ArgType.getObjCLifetime()) {
12213       Qualifiers Qs;
12214       Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12215       ArgType = S.Context.getQualifiedType(ArgType, Qs);
12216     }
12217     *TypeArg = ArgType;
12218   }
12219 
12220   return true;
12221 }
12222 
isStdInitializerList(QualType Ty,QualType * Element)12223 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12224   assert(getLangOpts().CPlusPlus &&
12225          "Looking for std::initializer_list outside of C++.");
12226 
12227   // We're looking for implicit instantiations of
12228   // template <typename E> class std::initializer_list.
12229 
12230   return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12231                             &StdInitializerList, /*MalformedDecl=*/nullptr);
12232 }
12233 
isStdTypeIdentity(QualType Ty,QualType * Element,const Decl ** MalformedDecl)12234 bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12235                              const Decl **MalformedDecl) {
12236   assert(getLangOpts().CPlusPlus &&
12237          "Looking for std::type_identity outside of C++.");
12238 
12239   // We're looking for implicit instantiations of
12240   // template <typename T> struct std::type_identity.
12241 
12242   return isStdClassTemplate(*this, Ty, Element, "type_identity",
12243                             &StdTypeIdentity, MalformedDecl);
12244 }
12245 
LookupStdClassTemplate(Sema & S,SourceLocation Loc,const char * ClassName,bool * WasMalformed)12246 static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12247                                                  const char *ClassName,
12248                                                  bool *WasMalformed) {
12249   if (!S.StdNamespace)
12250     return nullptr;
12251 
12252   LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12253                       Sema::LookupOrdinaryName);
12254   if (!S.LookupQualifiedName(Result, S.getStdNamespace()))
12255     return nullptr;
12256 
12257   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12258   if (!Template) {
12259     Result.suppressDiagnostics();
12260     // We found something weird. Complain about the first thing we found.
12261     NamedDecl *Found = *Result.begin();
12262     S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12263         << ClassName;
12264     if (WasMalformed)
12265       *WasMalformed = true;
12266     return nullptr;
12267   }
12268 
12269   // We found some template with the correct name. Now verify that it's
12270   // correct.
12271   TemplateParameterList *Params = Template->getTemplateParameters();
12272   if (Params->getMinRequiredArguments() != 1 ||
12273       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12274     S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12275         << ClassName;
12276     if (WasMalformed)
12277       *WasMalformed = true;
12278     return nullptr;
12279   }
12280 
12281   return Template;
12282 }
12283 
BuildStdClassTemplate(Sema & S,ClassTemplateDecl * CTD,QualType TypeParam,SourceLocation Loc)12284 static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12285                                       QualType TypeParam, SourceLocation Loc) {
12286   assert(S.getStdNamespace());
12287   TemplateArgumentListInfo Args(Loc, Loc);
12288   auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12289   Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12290 
12291   QualType T = S.CheckTemplateIdType(TemplateName(CTD), Loc, Args);
12292   if (T.isNull())
12293     return QualType();
12294 
12295   return S.Context.getElaboratedType(
12296       ElaboratedTypeKeyword::None,
12297       NestedNameSpecifier::Create(S.Context, nullptr, S.getStdNamespace()), T);
12298 }
12299 
BuildStdInitializerList(QualType Element,SourceLocation Loc)12300 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12301   if (!StdInitializerList) {
12302     bool WasMalformed = false;
12303     StdInitializerList =
12304         LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12305     if (!StdInitializerList) {
12306       if (!WasMalformed)
12307         Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12308       return QualType();
12309     }
12310   }
12311   return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12312 }
12313 
tryBuildStdTypeIdentity(QualType Type,SourceLocation Loc)12314 QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12315   if (!StdTypeIdentity) {
12316     StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12317                                              /*WasMalformed=*/nullptr);
12318     if (!StdTypeIdentity)
12319       return QualType();
12320   }
12321   return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12322 }
12323 
isInitListConstructor(const FunctionDecl * Ctor)12324 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12325   // C++ [dcl.init.list]p2:
12326   //   A constructor is an initializer-list constructor if its first parameter
12327   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
12328   //   std::initializer_list<E> for some type E, and either there are no other
12329   //   parameters or else all other parameters have default arguments.
12330   if (!Ctor->hasOneParamOrDefaultArgs())
12331     return false;
12332 
12333   QualType ArgType = Ctor->getParamDecl(0)->getType();
12334   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12335     ArgType = RT->getPointeeType().getUnqualifiedType();
12336 
12337   return isStdInitializerList(ArgType, nullptr);
12338 }
12339 
12340 /// Determine whether a using statement is in a context where it will be
12341 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)12342 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12343   switch (CurContext->getDeclKind()) {
12344     case Decl::TranslationUnit:
12345       return true;
12346     case Decl::LinkageSpec:
12347       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12348     default:
12349       return false;
12350   }
12351 }
12352 
12353 namespace {
12354 
12355 // Callback to only accept typo corrections that are namespaces.
12356 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12357 public:
ValidateCandidate(const TypoCorrection & candidate)12358   bool ValidateCandidate(const TypoCorrection &candidate) override {
12359     if (NamedDecl *ND = candidate.getCorrectionDecl())
12360       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12361     return false;
12362   }
12363 
clone()12364   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12365     return std::make_unique<NamespaceValidatorCCC>(*this);
12366   }
12367 };
12368 
12369 }
12370 
DiagnoseInvisibleNamespace(const TypoCorrection & Corrected,Sema & S)12371 static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12372                                        Sema &S) {
12373   auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12374   Module *M = ND->getOwningModule();
12375   assert(M && "hidden namespace definition not in a module?");
12376 
12377   if (M->isExplicitGlobalModule())
12378     S.Diag(Corrected.getCorrectionRange().getBegin(),
12379            diag::err_module_unimported_use_header)
12380         << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12381         << /*Header Name*/ false;
12382   else
12383     S.Diag(Corrected.getCorrectionRange().getBegin(),
12384            diag::err_module_unimported_use)
12385         << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12386         << M->getTopLevelModuleName();
12387 }
12388 
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)12389 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12390                                        CXXScopeSpec &SS,
12391                                        SourceLocation IdentLoc,
12392                                        IdentifierInfo *Ident) {
12393   R.clear();
12394   NamespaceValidatorCCC CCC{};
12395   if (TypoCorrection Corrected =
12396           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12397                         CorrectTypoKind::ErrorRecovery)) {
12398     // Generally we find it is confusing more than helpful to diagnose the
12399     // invisible namespace.
12400     // See https://github.com/llvm/llvm-project/issues/73893.
12401     //
12402     // However, we should diagnose when the users are trying to using an
12403     // invisible namespace. So we handle the case specially here.
12404     if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12405         Corrected.requiresImport()) {
12406       DiagnoseInvisibleNamespace(Corrected, S);
12407     } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12408       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12409       bool DroppedSpecifier =
12410           Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12411       S.diagnoseTypo(Corrected,
12412                      S.PDiag(diag::err_using_directive_member_suggest)
12413                        << Ident << DC << DroppedSpecifier << SS.getRange(),
12414                      S.PDiag(diag::note_namespace_defined_here));
12415     } else {
12416       S.diagnoseTypo(Corrected,
12417                      S.PDiag(diag::err_using_directive_suggest) << Ident,
12418                      S.PDiag(diag::note_namespace_defined_here));
12419     }
12420     R.addDecl(Corrected.getFoundDecl());
12421     return true;
12422   }
12423   return false;
12424 }
12425 
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,const ParsedAttributesView & AttrList)12426 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12427                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12428                                 SourceLocation IdentLoc,
12429                                 IdentifierInfo *NamespcName,
12430                                 const ParsedAttributesView &AttrList) {
12431   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12432   assert(NamespcName && "Invalid NamespcName.");
12433   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12434 
12435   // Get the innermost enclosing declaration scope.
12436   S = S->getDeclParent();
12437 
12438   UsingDirectiveDecl *UDir = nullptr;
12439   NestedNameSpecifier *Qualifier = nullptr;
12440   if (SS.isSet())
12441     Qualifier = SS.getScopeRep();
12442 
12443   // Lookup namespace name.
12444   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12445   LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12446   if (R.isAmbiguous())
12447     return nullptr;
12448 
12449   if (R.empty()) {
12450     R.clear();
12451     // Allow "using namespace std;" or "using namespace ::std;" even if
12452     // "std" hasn't been defined yet, for GCC compatibility.
12453     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12454         NamespcName->isStr("std")) {
12455       Diag(IdentLoc, diag::ext_using_undefined_std);
12456       R.addDecl(getOrCreateStdNamespace());
12457       R.resolveKind();
12458     }
12459     // Otherwise, attempt typo correction.
12460     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12461   }
12462 
12463   if (!R.empty()) {
12464     NamedDecl *Named = R.getRepresentativeDecl();
12465     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12466     assert(NS && "expected namespace decl");
12467 
12468     // The use of a nested name specifier may trigger deprecation warnings.
12469     DiagnoseUseOfDecl(Named, IdentLoc);
12470 
12471     // C++ [namespace.udir]p1:
12472     //   A using-directive specifies that the names in the nominated
12473     //   namespace can be used in the scope in which the
12474     //   using-directive appears after the using-directive. During
12475     //   unqualified name lookup (3.4.1), the names appear as if they
12476     //   were declared in the nearest enclosing namespace which
12477     //   contains both the using-directive and the nominated
12478     //   namespace. [Note: in this context, "contains" means "contains
12479     //   directly or indirectly". ]
12480 
12481     // Find enclosing context containing both using-directive and
12482     // nominated namespace.
12483     DeclContext *CommonAncestor = NS;
12484     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12485       CommonAncestor = CommonAncestor->getParent();
12486 
12487     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12488                                       SS.getWithLocInContext(Context),
12489                                       IdentLoc, Named, CommonAncestor);
12490 
12491     if (IsUsingDirectiveInToplevelContext(CurContext) &&
12492         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12493       Diag(IdentLoc, diag::warn_using_directive_in_header);
12494     }
12495 
12496     PushUsingDirective(S, UDir);
12497   } else {
12498     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12499   }
12500 
12501   if (UDir) {
12502     ProcessDeclAttributeList(S, UDir, AttrList);
12503     ProcessAPINotes(UDir);
12504   }
12505 
12506   return UDir;
12507 }
12508 
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)12509 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12510   // If the scope has an associated entity and the using directive is at
12511   // namespace or translation unit scope, add the UsingDirectiveDecl into
12512   // its lookup structure so qualified name lookup can find it.
12513   DeclContext *Ctx = S->getEntity();
12514   if (Ctx && !Ctx->isFunctionOrMethod())
12515     Ctx->addDecl(UDir);
12516   else
12517     // Otherwise, it is at block scope. The using-directives will affect lookup
12518     // only to the end of the scope.
12519     S->PushUsingDirective(UDir);
12520 }
12521 
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation TypenameLoc,CXXScopeSpec & SS,UnqualifiedId & Name,SourceLocation EllipsisLoc,const ParsedAttributesView & AttrList)12522 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12523                                   SourceLocation UsingLoc,
12524                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
12525                                   UnqualifiedId &Name,
12526                                   SourceLocation EllipsisLoc,
12527                                   const ParsedAttributesView &AttrList) {
12528   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12529 
12530   if (SS.isEmpty()) {
12531     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12532     return nullptr;
12533   }
12534 
12535   switch (Name.getKind()) {
12536   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12537   case UnqualifiedIdKind::IK_Identifier:
12538   case UnqualifiedIdKind::IK_OperatorFunctionId:
12539   case UnqualifiedIdKind::IK_LiteralOperatorId:
12540   case UnqualifiedIdKind::IK_ConversionFunctionId:
12541     break;
12542 
12543   case UnqualifiedIdKind::IK_ConstructorName:
12544   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12545     // C++11 inheriting constructors.
12546     Diag(Name.getBeginLoc(),
12547          getLangOpts().CPlusPlus11
12548              ? diag::warn_cxx98_compat_using_decl_constructor
12549              : diag::err_using_decl_constructor)
12550         << SS.getRange();
12551 
12552     if (getLangOpts().CPlusPlus11) break;
12553 
12554     return nullptr;
12555 
12556   case UnqualifiedIdKind::IK_DestructorName:
12557     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12558     return nullptr;
12559 
12560   case UnqualifiedIdKind::IK_TemplateId:
12561     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12562         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12563     return nullptr;
12564 
12565   case UnqualifiedIdKind::IK_DeductionGuideName:
12566     llvm_unreachable("cannot parse qualified deduction guide name");
12567   }
12568 
12569   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12570   DeclarationName TargetName = TargetNameInfo.getName();
12571   if (!TargetName)
12572     return nullptr;
12573 
12574   // Warn about access declarations.
12575   if (UsingLoc.isInvalid()) {
12576     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12577                                  ? diag::err_access_decl
12578                                  : diag::warn_access_decl_deprecated)
12579         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12580   }
12581 
12582   if (EllipsisLoc.isInvalid()) {
12583     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12584         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12585       return nullptr;
12586   } else {
12587     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12588         !TargetNameInfo.containsUnexpandedParameterPack()) {
12589       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12590         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12591       EllipsisLoc = SourceLocation();
12592     }
12593   }
12594 
12595   NamedDecl *UD =
12596       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12597                             SS, TargetNameInfo, EllipsisLoc, AttrList,
12598                             /*IsInstantiation*/ false,
12599                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12600   if (UD)
12601     PushOnScopeChains(UD, S, /*AddToContext*/ false);
12602 
12603   return UD;
12604 }
12605 
ActOnUsingEnumDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation EnumLoc,SourceRange TyLoc,const IdentifierInfo & II,ParsedType Ty,CXXScopeSpec * SS)12606 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12607                                       SourceLocation UsingLoc,
12608                                       SourceLocation EnumLoc, SourceRange TyLoc,
12609                                       const IdentifierInfo &II, ParsedType Ty,
12610                                       CXXScopeSpec *SS) {
12611   assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12612   TypeSourceInfo *TSI = nullptr;
12613   SourceLocation IdentLoc = TyLoc.getBegin();
12614   QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12615   if (EnumTy.isNull()) {
12616     Diag(IdentLoc, isDependentScopeSpecifier(*SS)
12617                        ? diag::err_using_enum_is_dependent
12618                        : diag::err_unknown_typename)
12619         << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12620     return nullptr;
12621   }
12622 
12623   if (EnumTy->isDependentType()) {
12624     Diag(IdentLoc, diag::err_using_enum_is_dependent);
12625     return nullptr;
12626   }
12627 
12628   auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12629   if (!Enum) {
12630     Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12631     return nullptr;
12632   }
12633 
12634   if (auto *Def = Enum->getDefinition())
12635     Enum = Def;
12636 
12637   if (TSI == nullptr)
12638     TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12639 
12640   auto *UD =
12641       BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12642 
12643   if (UD)
12644     PushOnScopeChains(UD, S, /*AddToContext*/ false);
12645 
12646   return UD;
12647 }
12648 
12649 /// Determine whether a using declaration considers the given
12650 /// declarations as "equivalent", e.g., if they are redeclarations of
12651 /// the same entity or are both typedefs of the same type.
12652 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2)12653 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12654   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12655     return true;
12656 
12657   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12658     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12659       return Context.hasSameType(TD1->getUnderlyingType(),
12660                                  TD2->getUnderlyingType());
12661 
12662   // Two using_if_exists using-declarations are equivalent if both are
12663   // unresolved.
12664   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12665       isa<UnresolvedUsingIfExistsDecl>(D2))
12666     return true;
12667 
12668   return false;
12669 }
12670 
CheckUsingShadowDecl(BaseUsingDecl * BUD,NamedDecl * Orig,const LookupResult & Previous,UsingShadowDecl * & PrevShadow)12671 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12672                                 const LookupResult &Previous,
12673                                 UsingShadowDecl *&PrevShadow) {
12674   // Diagnose finding a decl which is not from a base class of the
12675   // current class.  We do this now because there are cases where this
12676   // function will silently decide not to build a shadow decl, which
12677   // will pre-empt further diagnostics.
12678   //
12679   // We don't need to do this in C++11 because we do the check once on
12680   // the qualifier.
12681   //
12682   // FIXME: diagnose the following if we care enough:
12683   //   struct A { int foo; };
12684   //   struct B : A { using A::foo; };
12685   //   template <class T> struct C : A {};
12686   //   template <class T> struct D : C<T> { using B::foo; } // <---
12687   // This is invalid (during instantiation) in C++03 because B::foo
12688   // resolves to the using decl in B, which is not a base class of D<T>.
12689   // We can't diagnose it immediately because C<T> is an unknown
12690   // specialization. The UsingShadowDecl in D<T> then points directly
12691   // to A::foo, which will look well-formed when we instantiate.
12692   // The right solution is to not collapse the shadow-decl chain.
12693   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12694     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12695       DeclContext *OrigDC = Orig->getDeclContext();
12696 
12697       // Handle enums and anonymous structs.
12698       if (isa<EnumDecl>(OrigDC))
12699         OrigDC = OrigDC->getParent();
12700       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12701       while (OrigRec->isAnonymousStructOrUnion())
12702         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12703 
12704       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12705         if (OrigDC == CurContext) {
12706           Diag(Using->getLocation(),
12707                diag::err_using_decl_nested_name_specifier_is_current_class)
12708               << Using->getQualifierLoc().getSourceRange();
12709           Diag(Orig->getLocation(), diag::note_using_decl_target);
12710           Using->setInvalidDecl();
12711           return true;
12712         }
12713 
12714         Diag(Using->getQualifierLoc().getBeginLoc(),
12715              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12716             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12717             << Using->getQualifierLoc().getSourceRange();
12718         Diag(Orig->getLocation(), diag::note_using_decl_target);
12719         Using->setInvalidDecl();
12720         return true;
12721       }
12722     }
12723 
12724   if (Previous.empty()) return false;
12725 
12726   NamedDecl *Target = Orig;
12727   if (isa<UsingShadowDecl>(Target))
12728     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12729 
12730   // If the target happens to be one of the previous declarations, we
12731   // don't have a conflict.
12732   //
12733   // FIXME: but we might be increasing its access, in which case we
12734   // should redeclare it.
12735   NamedDecl *NonTag = nullptr, *Tag = nullptr;
12736   bool FoundEquivalentDecl = false;
12737   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12738          I != E; ++I) {
12739     NamedDecl *D = (*I)->getUnderlyingDecl();
12740     // We can have UsingDecls in our Previous results because we use the same
12741     // LookupResult for checking whether the UsingDecl itself is a valid
12742     // redeclaration.
12743     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12744       continue;
12745 
12746     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12747       // C++ [class.mem]p19:
12748       //   If T is the name of a class, then [every named member other than
12749       //   a non-static data member] shall have a name different from T
12750       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12751           !isa<IndirectFieldDecl>(Target) &&
12752           !isa<UnresolvedUsingValueDecl>(Target) &&
12753           DiagnoseClassNameShadow(
12754               CurContext,
12755               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12756         return true;
12757     }
12758 
12759     if (IsEquivalentForUsingDecl(Context, D, Target)) {
12760       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12761         PrevShadow = Shadow;
12762       FoundEquivalentDecl = true;
12763     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12764       // We don't conflict with an existing using shadow decl of an equivalent
12765       // declaration, but we're not a redeclaration of it.
12766       FoundEquivalentDecl = true;
12767     }
12768 
12769     if (isVisible(D))
12770       (isa<TagDecl>(D) ? Tag : NonTag) = D;
12771   }
12772 
12773   if (FoundEquivalentDecl)
12774     return false;
12775 
12776   // Always emit a diagnostic for a mismatch between an unresolved
12777   // using_if_exists and a resolved using declaration in either direction.
12778   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12779       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12780     if (!NonTag && !Tag)
12781       return false;
12782     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12783     Diag(Target->getLocation(), diag::note_using_decl_target);
12784     Diag((NonTag ? NonTag : Tag)->getLocation(),
12785          diag::note_using_decl_conflict);
12786     BUD->setInvalidDecl();
12787     return true;
12788   }
12789 
12790   if (FunctionDecl *FD = Target->getAsFunction()) {
12791     NamedDecl *OldDecl = nullptr;
12792     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12793                           /*IsForUsingDecl*/ true)) {
12794     case OverloadKind::Overload:
12795       return false;
12796 
12797     case OverloadKind::NonFunction:
12798       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12799       break;
12800 
12801     // We found a decl with the exact signature.
12802     case OverloadKind::Match:
12803       // If we're in a record, we want to hide the target, so we
12804       // return true (without a diagnostic) to tell the caller not to
12805       // build a shadow decl.
12806       if (CurContext->isRecord())
12807         return true;
12808 
12809       // If we're not in a record, this is an error.
12810       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12811       break;
12812     }
12813 
12814     Diag(Target->getLocation(), diag::note_using_decl_target);
12815     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12816     BUD->setInvalidDecl();
12817     return true;
12818   }
12819 
12820   // Target is not a function.
12821 
12822   if (isa<TagDecl>(Target)) {
12823     // No conflict between a tag and a non-tag.
12824     if (!Tag) return false;
12825 
12826     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12827     Diag(Target->getLocation(), diag::note_using_decl_target);
12828     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12829     BUD->setInvalidDecl();
12830     return true;
12831   }
12832 
12833   // No conflict between a tag and a non-tag.
12834   if (!NonTag) return false;
12835 
12836   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12837   Diag(Target->getLocation(), diag::note_using_decl_target);
12838   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12839   BUD->setInvalidDecl();
12840   return true;
12841 }
12842 
12843 /// Determine whether a direct base class is a virtual base class.
isVirtualDirectBase(CXXRecordDecl * Derived,CXXRecordDecl * Base)12844 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12845   if (!Derived->getNumVBases())
12846     return false;
12847   for (auto &B : Derived->bases())
12848     if (B.getType()->getAsCXXRecordDecl() == Base)
12849       return B.isVirtual();
12850   llvm_unreachable("not a direct base class");
12851 }
12852 
BuildUsingShadowDecl(Scope * S,BaseUsingDecl * BUD,NamedDecl * Orig,UsingShadowDecl * PrevDecl)12853 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12854                                             NamedDecl *Orig,
12855                                             UsingShadowDecl *PrevDecl) {
12856   // If we resolved to another shadow declaration, just coalesce them.
12857   NamedDecl *Target = Orig;
12858   if (isa<UsingShadowDecl>(Target)) {
12859     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12860     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12861   }
12862 
12863   NamedDecl *NonTemplateTarget = Target;
12864   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12865     NonTemplateTarget = TargetTD->getTemplatedDecl();
12866 
12867   UsingShadowDecl *Shadow;
12868   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12869     UsingDecl *Using = cast<UsingDecl>(BUD);
12870     bool IsVirtualBase =
12871         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12872                             Using->getQualifier()->getAsRecordDecl());
12873     Shadow = ConstructorUsingShadowDecl::Create(
12874         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12875   } else {
12876     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12877                                      Target->getDeclName(), BUD, Target);
12878   }
12879   BUD->addShadowDecl(Shadow);
12880 
12881   Shadow->setAccess(BUD->getAccess());
12882   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12883     Shadow->setInvalidDecl();
12884 
12885   Shadow->setPreviousDecl(PrevDecl);
12886 
12887   if (S)
12888     PushOnScopeChains(Shadow, S);
12889   else
12890     CurContext->addDecl(Shadow);
12891 
12892 
12893   return Shadow;
12894 }
12895 
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)12896 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12897   if (Shadow->getDeclName().getNameKind() ==
12898         DeclarationName::CXXConversionFunctionName)
12899     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12900 
12901   // Remove it from the DeclContext...
12902   Shadow->getDeclContext()->removeDecl(Shadow);
12903 
12904   // ...and the scope, if applicable...
12905   if (S) {
12906     S->RemoveDecl(Shadow);
12907     IdResolver.RemoveDecl(Shadow);
12908   }
12909 
12910   // ...and the using decl.
12911   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12912 
12913   // TODO: complain somehow if Shadow was used.  It shouldn't
12914   // be possible for this to happen, because...?
12915 }
12916 
12917 /// Find the base specifier for a base class with the given type.
findDirectBaseWithType(CXXRecordDecl * Derived,QualType DesiredBase,bool & AnyDependentBases)12918 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12919                                                 QualType DesiredBase,
12920                                                 bool &AnyDependentBases) {
12921   // Check whether the named type is a direct base class.
12922   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12923     .getUnqualifiedType();
12924   for (auto &Base : Derived->bases()) {
12925     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12926     if (CanonicalDesiredBase == BaseType)
12927       return &Base;
12928     if (BaseType->isDependentType())
12929       AnyDependentBases = true;
12930   }
12931   return nullptr;
12932 }
12933 
12934 namespace {
12935 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12936 public:
UsingValidatorCCC(bool HasTypenameKeyword,bool IsInstantiation,NestedNameSpecifier * NNS,CXXRecordDecl * RequireMemberOf)12937   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12938                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12939       : HasTypenameKeyword(HasTypenameKeyword),
12940         IsInstantiation(IsInstantiation), OldNNS(NNS),
12941         RequireMemberOf(RequireMemberOf) {}
12942 
ValidateCandidate(const TypoCorrection & Candidate)12943   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12944     NamedDecl *ND = Candidate.getCorrectionDecl();
12945 
12946     // Keywords are not valid here.
12947     if (!ND || isa<NamespaceDecl>(ND))
12948       return false;
12949 
12950     // Completely unqualified names are invalid for a 'using' declaration.
12951     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12952       return false;
12953 
12954     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12955     // reject.
12956 
12957     if (RequireMemberOf) {
12958       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12959       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12960         // No-one ever wants a using-declaration to name an injected-class-name
12961         // of a base class, unless they're declaring an inheriting constructor.
12962         ASTContext &Ctx = ND->getASTContext();
12963         if (!Ctx.getLangOpts().CPlusPlus11)
12964           return false;
12965         QualType FoundType = Ctx.getRecordType(FoundRecord);
12966 
12967         // Check that the injected-class-name is named as a member of its own
12968         // type; we don't want to suggest 'using Derived::Base;', since that
12969         // means something else.
12970         NestedNameSpecifier *Specifier =
12971             Candidate.WillReplaceSpecifier()
12972                 ? Candidate.getCorrectionSpecifier()
12973                 : OldNNS;
12974         if (!Specifier->getAsType() ||
12975             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12976           return false;
12977 
12978         // Check that this inheriting constructor declaration actually names a
12979         // direct base class of the current class.
12980         bool AnyDependentBases = false;
12981         if (!findDirectBaseWithType(RequireMemberOf,
12982                                     Ctx.getRecordType(FoundRecord),
12983                                     AnyDependentBases) &&
12984             !AnyDependentBases)
12985           return false;
12986       } else {
12987         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12988         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12989           return false;
12990 
12991         // FIXME: Check that the base class member is accessible?
12992       }
12993     } else {
12994       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12995       if (FoundRecord && FoundRecord->isInjectedClassName())
12996         return false;
12997     }
12998 
12999     if (isa<TypeDecl>(ND))
13000       return HasTypenameKeyword || !IsInstantiation;
13001 
13002     return !HasTypenameKeyword;
13003   }
13004 
clone()13005   std::unique_ptr<CorrectionCandidateCallback> clone() override {
13006     return std::make_unique<UsingValidatorCCC>(*this);
13007   }
13008 
13009 private:
13010   bool HasTypenameKeyword;
13011   bool IsInstantiation;
13012   NestedNameSpecifier *OldNNS;
13013   CXXRecordDecl *RequireMemberOf;
13014 };
13015 } // end anonymous namespace
13016 
FilterUsingLookup(Scope * S,LookupResult & Previous)13017 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13018   // It is really dumb that we have to do this.
13019   LookupResult::Filter F = Previous.makeFilter();
13020   while (F.hasNext()) {
13021     NamedDecl *D = F.next();
13022     if (!isDeclInScope(D, CurContext, S))
13023       F.erase();
13024     // If we found a local extern declaration that's not ordinarily visible,
13025     // and this declaration is being added to a non-block scope, ignore it.
13026     // We're only checking for scope conflicts here, not also for violations
13027     // of the linkage rules.
13028     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13029              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13030       F.erase();
13031   }
13032   F.done();
13033 }
13034 
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,bool HasTypenameKeyword,SourceLocation TypenameLoc,CXXScopeSpec & SS,DeclarationNameInfo NameInfo,SourceLocation EllipsisLoc,const ParsedAttributesView & AttrList,bool IsInstantiation,bool IsUsingIfExists)13035 NamedDecl *Sema::BuildUsingDeclaration(
13036     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13037     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13038     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13039     const ParsedAttributesView &AttrList, bool IsInstantiation,
13040     bool IsUsingIfExists) {
13041   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13042   SourceLocation IdentLoc = NameInfo.getLoc();
13043   assert(IdentLoc.isValid() && "Invalid TargetName location.");
13044 
13045   // FIXME: We ignore attributes for now.
13046 
13047   // For an inheriting constructor declaration, the name of the using
13048   // declaration is the name of a constructor in this class, not in the
13049   // base class.
13050   DeclarationNameInfo UsingName = NameInfo;
13051   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13052     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13053       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13054           Context.getCanonicalType(Context.getRecordType(RD))));
13055 
13056   // Do the redeclaration lookup in the current scope.
13057   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13058                         RedeclarationKind::ForVisibleRedeclaration);
13059   Previous.setHideTags(false);
13060   if (S) {
13061     LookupName(Previous, S);
13062 
13063     FilterUsingLookup(S, Previous);
13064   } else {
13065     assert(IsInstantiation && "no scope in non-instantiation");
13066     if (CurContext->isRecord())
13067       LookupQualifiedName(Previous, CurContext);
13068     else {
13069       // No redeclaration check is needed here; in non-member contexts we
13070       // diagnosed all possible conflicts with other using-declarations when
13071       // building the template:
13072       //
13073       // For a dependent non-type using declaration, the only valid case is
13074       // if we instantiate to a single enumerator. We check for conflicts
13075       // between shadow declarations we introduce, and we check in the template
13076       // definition for conflicts between a non-type using declaration and any
13077       // other declaration, which together covers all cases.
13078       //
13079       // A dependent typename using declaration will never successfully
13080       // instantiate, since it will always name a class member, so we reject
13081       // that in the template definition.
13082     }
13083   }
13084 
13085   // Check for invalid redeclarations.
13086   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13087                                   SS, IdentLoc, Previous))
13088     return nullptr;
13089 
13090   // 'using_if_exists' doesn't make sense on an inherited constructor.
13091   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13092                              DeclarationName::CXXConstructorName) {
13093     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13094     return nullptr;
13095   }
13096 
13097   DeclContext *LookupContext = computeDeclContext(SS);
13098   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13099   if (!LookupContext || EllipsisLoc.isValid()) {
13100     NamedDecl *D;
13101     // Dependent scope, or an unexpanded pack
13102     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13103                                                   SS, NameInfo, IdentLoc))
13104       return nullptr;
13105 
13106     if (Previous.isSingleResult() &&
13107         Previous.getFoundDecl()->isTemplateParameter())
13108       DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13109 
13110     if (HasTypenameKeyword) {
13111       // FIXME: not all declaration name kinds are legal here
13112       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
13113                                               UsingLoc, TypenameLoc,
13114                                               QualifierLoc,
13115                                               IdentLoc, NameInfo.getName(),
13116                                               EllipsisLoc);
13117     } else {
13118       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
13119                                            QualifierLoc, NameInfo, EllipsisLoc);
13120     }
13121     D->setAccess(AS);
13122     CurContext->addDecl(D);
13123     ProcessDeclAttributeList(S, D, AttrList);
13124     return D;
13125   }
13126 
13127   auto Build = [&](bool Invalid) {
13128     UsingDecl *UD =
13129         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13130                           UsingName, HasTypenameKeyword);
13131     UD->setAccess(AS);
13132     CurContext->addDecl(UD);
13133     ProcessDeclAttributeList(S, UD, AttrList);
13134     UD->setInvalidDecl(Invalid);
13135     return UD;
13136   };
13137   auto BuildInvalid = [&]{ return Build(true); };
13138   auto BuildValid = [&]{ return Build(false); };
13139 
13140   if (RequireCompleteDeclContext(SS, LookupContext))
13141     return BuildInvalid();
13142 
13143   // Look up the target name.
13144   LookupResult R(*this, NameInfo, LookupOrdinaryName);
13145 
13146   // Unlike most lookups, we don't always want to hide tag
13147   // declarations: tag names are visible through the using declaration
13148   // even if hidden by ordinary names, *except* in a dependent context
13149   // where they may be used by two-phase lookup.
13150   if (!IsInstantiation)
13151     R.setHideTags(false);
13152 
13153   // For the purposes of this lookup, we have a base object type
13154   // equal to that of the current context.
13155   if (CurContext->isRecord()) {
13156     R.setBaseObjectType(
13157                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
13158   }
13159 
13160   LookupQualifiedName(R, LookupContext);
13161 
13162   // Validate the context, now we have a lookup
13163   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13164                               IdentLoc, &R))
13165     return nullptr;
13166 
13167   if (R.empty() && IsUsingIfExists)
13168     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
13169                                                   UsingName.getName()),
13170               AS_public);
13171 
13172   // Try to correct typos if possible. If constructor name lookup finds no
13173   // results, that means the named class has no explicit constructors, and we
13174   // suppressed declaring implicit ones (probably because it's dependent or
13175   // invalid).
13176   if (R.empty() &&
13177       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13178     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13179     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13180     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13181     auto *II = NameInfo.getName().getAsIdentifierInfo();
13182     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13183         CurContext->isStdNamespace() &&
13184         isa<TranslationUnitDecl>(LookupContext) &&
13185         PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13186         getSourceManager().isInSystemHeader(UsingLoc))
13187       return nullptr;
13188     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13189                           dyn_cast<CXXRecordDecl>(CurContext));
13190     if (TypoCorrection Corrected =
13191             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13192                         CorrectTypoKind::ErrorRecovery)) {
13193       // We reject candidates where DroppedSpecifier == true, hence the
13194       // literal '0' below.
13195       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13196                                 << NameInfo.getName() << LookupContext << 0
13197                                 << SS.getRange());
13198 
13199       // If we picked a correction with no attached Decl we can't do anything
13200       // useful with it, bail out.
13201       NamedDecl *ND = Corrected.getCorrectionDecl();
13202       if (!ND)
13203         return BuildInvalid();
13204 
13205       // If we corrected to an inheriting constructor, handle it as one.
13206       auto *RD = dyn_cast<CXXRecordDecl>(ND);
13207       if (RD && RD->isInjectedClassName()) {
13208         // The parent of the injected class name is the class itself.
13209         RD = cast<CXXRecordDecl>(RD->getParent());
13210 
13211         // Fix up the information we'll use to build the using declaration.
13212         if (Corrected.WillReplaceSpecifier()) {
13213           NestedNameSpecifierLocBuilder Builder;
13214           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13215                               QualifierLoc.getSourceRange());
13216           QualifierLoc = Builder.getWithLocInContext(Context);
13217         }
13218 
13219         // In this case, the name we introduce is the name of a derived class
13220         // constructor.
13221         auto *CurClass = cast<CXXRecordDecl>(CurContext);
13222         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13223             Context.getCanonicalType(Context.getRecordType(CurClass))));
13224         UsingName.setNamedTypeInfo(nullptr);
13225         for (auto *Ctor : LookupConstructors(RD))
13226           R.addDecl(Ctor);
13227         R.resolveKind();
13228       } else {
13229         // FIXME: Pick up all the declarations if we found an overloaded
13230         // function.
13231         UsingName.setName(ND->getDeclName());
13232         R.addDecl(ND);
13233       }
13234     } else {
13235       Diag(IdentLoc, diag::err_no_member)
13236         << NameInfo.getName() << LookupContext << SS.getRange();
13237       return BuildInvalid();
13238     }
13239   }
13240 
13241   if (R.isAmbiguous())
13242     return BuildInvalid();
13243 
13244   if (HasTypenameKeyword) {
13245     // If we asked for a typename and got a non-type decl, error out.
13246     if (!R.getAsSingle<TypeDecl>() &&
13247         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13248       Diag(IdentLoc, diag::err_using_typename_non_type);
13249       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13250         Diag((*I)->getUnderlyingDecl()->getLocation(),
13251              diag::note_using_decl_target);
13252       return BuildInvalid();
13253     }
13254   } else {
13255     // If we asked for a non-typename and we got a type, error out,
13256     // but only if this is an instantiation of an unresolved using
13257     // decl.  Otherwise just silently find the type name.
13258     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13259       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13260       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13261       return BuildInvalid();
13262     }
13263   }
13264 
13265   // C++14 [namespace.udecl]p6:
13266   // A using-declaration shall not name a namespace.
13267   if (R.getAsSingle<NamespaceDecl>()) {
13268     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13269         << SS.getRange();
13270     // Suggest using 'using namespace ...' instead.
13271     Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13272         << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13273     return BuildInvalid();
13274   }
13275 
13276   UsingDecl *UD = BuildValid();
13277 
13278   // Some additional rules apply to inheriting constructors.
13279   if (UsingName.getName().getNameKind() ==
13280         DeclarationName::CXXConstructorName) {
13281     // Suppress access diagnostics; the access check is instead performed at the
13282     // point of use for an inheriting constructor.
13283     R.suppressDiagnostics();
13284     if (CheckInheritingConstructorUsingDecl(UD))
13285       return UD;
13286   }
13287 
13288   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13289     UsingShadowDecl *PrevDecl = nullptr;
13290     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13291       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13292   }
13293 
13294   return UD;
13295 }
13296 
BuildUsingEnumDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation EnumLoc,SourceLocation NameLoc,TypeSourceInfo * EnumType,EnumDecl * ED)13297 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13298                                            SourceLocation UsingLoc,
13299                                            SourceLocation EnumLoc,
13300                                            SourceLocation NameLoc,
13301                                            TypeSourceInfo *EnumType,
13302                                            EnumDecl *ED) {
13303   bool Invalid = false;
13304 
13305   if (CurContext->getRedeclContext()->isRecord()) {
13306     /// In class scope, check if this is a duplicate, for better a diagnostic.
13307     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13308     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13309                           RedeclarationKind::ForVisibleRedeclaration);
13310 
13311     LookupQualifiedName(Previous, CurContext);
13312 
13313     for (NamedDecl *D : Previous)
13314       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13315         if (UED->getEnumDecl() == ED) {
13316           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13317               << SourceRange(EnumLoc, NameLoc);
13318           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13319           Invalid = true;
13320           break;
13321         }
13322   }
13323 
13324   if (RequireCompleteEnumDecl(ED, NameLoc))
13325     Invalid = true;
13326 
13327   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
13328                                             EnumLoc, NameLoc, EnumType);
13329   UD->setAccess(AS);
13330   CurContext->addDecl(UD);
13331 
13332   if (Invalid) {
13333     UD->setInvalidDecl();
13334     return UD;
13335   }
13336 
13337   // Create the shadow decls for each enumerator
13338   for (EnumConstantDecl *EC : ED->enumerators()) {
13339     UsingShadowDecl *PrevDecl = nullptr;
13340     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13341     LookupResult Previous(*this, DNI, LookupOrdinaryName,
13342                           RedeclarationKind::ForVisibleRedeclaration);
13343     LookupName(Previous, S);
13344     FilterUsingLookup(S, Previous);
13345 
13346     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13347       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13348   }
13349 
13350   return UD;
13351 }
13352 
BuildUsingPackDecl(NamedDecl * InstantiatedFrom,ArrayRef<NamedDecl * > Expansions)13353 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13354                                     ArrayRef<NamedDecl *> Expansions) {
13355   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13356          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13357          isa<UsingPackDecl>(InstantiatedFrom));
13358 
13359   auto *UPD =
13360       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13361   UPD->setAccess(InstantiatedFrom->getAccess());
13362   CurContext->addDecl(UPD);
13363   return UPD;
13364 }
13365 
CheckInheritingConstructorUsingDecl(UsingDecl * UD)13366 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13367   assert(!UD->hasTypename() && "expecting a constructor name");
13368 
13369   const Type *SourceType = UD->getQualifier()->getAsType();
13370   assert(SourceType &&
13371          "Using decl naming constructor doesn't have type in scope spec.");
13372   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13373 
13374   // Check whether the named type is a direct base class.
13375   bool AnyDependentBases = false;
13376   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13377                                       AnyDependentBases);
13378   if (!Base && !AnyDependentBases) {
13379     Diag(UD->getUsingLoc(),
13380          diag::err_using_decl_constructor_not_in_direct_base)
13381       << UD->getNameInfo().getSourceRange()
13382       << QualType(SourceType, 0) << TargetClass;
13383     UD->setInvalidDecl();
13384     return true;
13385   }
13386 
13387   if (Base)
13388     Base->setInheritConstructors();
13389 
13390   return false;
13391 }
13392 
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool HasTypenameKeyword,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)13393 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13394                                        bool HasTypenameKeyword,
13395                                        const CXXScopeSpec &SS,
13396                                        SourceLocation NameLoc,
13397                                        const LookupResult &Prev) {
13398   NestedNameSpecifier *Qual = SS.getScopeRep();
13399 
13400   // C++03 [namespace.udecl]p8:
13401   // C++0x [namespace.udecl]p10:
13402   //   A using-declaration is a declaration and can therefore be used
13403   //   repeatedly where (and only where) multiple declarations are
13404   //   allowed.
13405   //
13406   // That's in non-member contexts.
13407   if (!CurContext->getRedeclContext()->isRecord()) {
13408     // A dependent qualifier outside a class can only ever resolve to an
13409     // enumeration type. Therefore it conflicts with any other non-type
13410     // declaration in the same scope.
13411     // FIXME: How should we check for dependent type-type conflicts at block
13412     // scope?
13413     if (Qual->isDependent() && !HasTypenameKeyword) {
13414       for (auto *D : Prev) {
13415         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13416           bool OldCouldBeEnumerator =
13417               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13418           Diag(NameLoc,
13419                OldCouldBeEnumerator ? diag::err_redefinition
13420                                     : diag::err_redefinition_different_kind)
13421               << Prev.getLookupName();
13422           Diag(D->getLocation(), diag::note_previous_definition);
13423           return true;
13424         }
13425       }
13426     }
13427     return false;
13428   }
13429 
13430   const NestedNameSpecifier *CNNS =
13431       Context.getCanonicalNestedNameSpecifier(Qual);
13432   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13433     NamedDecl *D = *I;
13434 
13435     bool DTypename;
13436     NestedNameSpecifier *DQual;
13437     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13438       DTypename = UD->hasTypename();
13439       DQual = UD->getQualifier();
13440     } else if (UnresolvedUsingValueDecl *UD
13441                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13442       DTypename = false;
13443       DQual = UD->getQualifier();
13444     } else if (UnresolvedUsingTypenameDecl *UD
13445                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13446       DTypename = true;
13447       DQual = UD->getQualifier();
13448     } else continue;
13449 
13450     // using decls differ if one says 'typename' and the other doesn't.
13451     // FIXME: non-dependent using decls?
13452     if (HasTypenameKeyword != DTypename) continue;
13453 
13454     // using decls differ if they name different scopes (but note that
13455     // template instantiation can cause this check to trigger when it
13456     // didn't before instantiation).
13457     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13458       continue;
13459 
13460     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13461     Diag(D->getLocation(), diag::note_using_decl) << 1;
13462     return true;
13463   }
13464 
13465   return false;
13466 }
13467 
CheckUsingDeclQualifier(SourceLocation UsingLoc,bool HasTypename,const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,SourceLocation NameLoc,const LookupResult * R,const UsingDecl * UD)13468 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13469                                    const CXXScopeSpec &SS,
13470                                    const DeclarationNameInfo &NameInfo,
13471                                    SourceLocation NameLoc,
13472                                    const LookupResult *R, const UsingDecl *UD) {
13473   DeclContext *NamedContext = computeDeclContext(SS);
13474   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13475          "resolvable context must have exactly one set of decls");
13476 
13477   // C++ 20 permits using an enumerator that does not have a class-hierarchy
13478   // relationship.
13479   bool Cxx20Enumerator = false;
13480   if (NamedContext) {
13481     EnumConstantDecl *EC = nullptr;
13482     if (R)
13483       EC = R->getAsSingle<EnumConstantDecl>();
13484     else if (UD && UD->shadow_size() == 1)
13485       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13486     if (EC)
13487       Cxx20Enumerator = getLangOpts().CPlusPlus20;
13488 
13489     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13490       // C++14 [namespace.udecl]p7:
13491       // A using-declaration shall not name a scoped enumerator.
13492       // C++20 p1099 permits enumerators.
13493       if (EC && R && ED->isScoped())
13494         Diag(SS.getBeginLoc(),
13495              getLangOpts().CPlusPlus20
13496                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13497                  : diag::ext_using_decl_scoped_enumerator)
13498             << SS.getRange();
13499 
13500       // We want to consider the scope of the enumerator
13501       NamedContext = ED->getDeclContext();
13502     }
13503   }
13504 
13505   if (!CurContext->isRecord()) {
13506     // C++03 [namespace.udecl]p3:
13507     // C++0x [namespace.udecl]p8:
13508     //   A using-declaration for a class member shall be a member-declaration.
13509     // C++20 [namespace.udecl]p7
13510     //   ... other than an enumerator ...
13511 
13512     // If we weren't able to compute a valid scope, it might validly be a
13513     // dependent class or enumeration scope. If we have a 'typename' keyword,
13514     // the scope must resolve to a class type.
13515     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13516                      : !HasTypename)
13517       return false; // OK
13518 
13519     Diag(NameLoc,
13520          Cxx20Enumerator
13521              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13522              : diag::err_using_decl_can_not_refer_to_class_member)
13523         << SS.getRange();
13524 
13525     if (Cxx20Enumerator)
13526       return false; // OK
13527 
13528     auto *RD = NamedContext
13529                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13530                    : nullptr;
13531     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13532       // See if there's a helpful fixit
13533 
13534       if (!R) {
13535         // We will have already diagnosed the problem on the template
13536         // definition,  Maybe we should do so again?
13537       } else if (R->getAsSingle<TypeDecl>()) {
13538         if (getLangOpts().CPlusPlus11) {
13539           // Convert 'using X::Y;' to 'using Y = X::Y;'.
13540           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13541               << diag::MemClassWorkaround::AliasDecl
13542               << FixItHint::CreateInsertion(SS.getBeginLoc(),
13543                                             NameInfo.getName().getAsString() +
13544                                                 " = ");
13545         } else {
13546           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13547           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13548           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13549               << diag::MemClassWorkaround::TypedefDecl
13550               << FixItHint::CreateReplacement(UsingLoc, "typedef")
13551               << FixItHint::CreateInsertion(
13552                      InsertLoc, " " + NameInfo.getName().getAsString());
13553         }
13554       } else if (R->getAsSingle<VarDecl>()) {
13555         // Don't provide a fixit outside C++11 mode; we don't want to suggest
13556         // repeating the type of the static data member here.
13557         FixItHint FixIt;
13558         if (getLangOpts().CPlusPlus11) {
13559           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13560           FixIt = FixItHint::CreateReplacement(
13561               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13562         }
13563 
13564         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13565             << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13566       } else if (R->getAsSingle<EnumConstantDecl>()) {
13567         // Don't provide a fixit outside C++11 mode; we don't want to suggest
13568         // repeating the type of the enumeration here, and we can't do so if
13569         // the type is anonymous.
13570         FixItHint FixIt;
13571         if (getLangOpts().CPlusPlus11) {
13572           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13573           FixIt = FixItHint::CreateReplacement(
13574               UsingLoc,
13575               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13576         }
13577 
13578         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13579             << (getLangOpts().CPlusPlus11
13580                     ? diag::MemClassWorkaround::ConstexprVar
13581                     : diag::MemClassWorkaround::ConstVar)
13582             << FixIt;
13583       }
13584     }
13585 
13586     return true; // Fail
13587   }
13588 
13589   // If the named context is dependent, we can't decide much.
13590   if (!NamedContext) {
13591     // FIXME: in C++0x, we can diagnose if we can prove that the
13592     // nested-name-specifier does not refer to a base class, which is
13593     // still possible in some cases.
13594 
13595     // Otherwise we have to conservatively report that things might be
13596     // okay.
13597     return false;
13598   }
13599 
13600   // The current scope is a record.
13601   if (!NamedContext->isRecord()) {
13602     // Ideally this would point at the last name in the specifier,
13603     // but we don't have that level of source info.
13604     Diag(SS.getBeginLoc(),
13605          Cxx20Enumerator
13606              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13607              : diag::err_using_decl_nested_name_specifier_is_not_class)
13608         << SS.getScopeRep() << SS.getRange();
13609 
13610     if (Cxx20Enumerator)
13611       return false; // OK
13612 
13613     return true;
13614   }
13615 
13616   if (!NamedContext->isDependentContext() &&
13617       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13618     return true;
13619 
13620   // C++26 [namespace.udecl]p3:
13621   //   In a using-declaration used as a member-declaration, each
13622   //   using-declarator shall either name an enumerator or have a
13623   //   nested-name-specifier naming a base class of the current class
13624   //   ([expr.prim.this]). ...
13625   // "have a nested-name-specifier naming a base class of the current class"
13626   // was introduced by CWG400.
13627 
13628   if (cast<CXXRecordDecl>(CurContext)
13629           ->isProvablyNotDerivedFrom(cast<CXXRecordDecl>(NamedContext))) {
13630 
13631     if (Cxx20Enumerator) {
13632       Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13633           << SS.getRange();
13634       return false;
13635     }
13636 
13637     if (CurContext == NamedContext) {
13638       Diag(SS.getBeginLoc(),
13639            diag::err_using_decl_nested_name_specifier_is_current_class)
13640           << SS.getRange();
13641       return true;
13642     }
13643 
13644     if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13645       Diag(SS.getBeginLoc(),
13646            diag::err_using_decl_nested_name_specifier_is_not_base_class)
13647           << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13648           << SS.getRange();
13649     }
13650     return true;
13651   }
13652 
13653   return false;
13654 }
13655 
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,const ParsedAttributesView & AttrList,TypeResult Type,Decl * DeclFromDeclSpec)13656 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13657                                   MultiTemplateParamsArg TemplateParamLists,
13658                                   SourceLocation UsingLoc, UnqualifiedId &Name,
13659                                   const ParsedAttributesView &AttrList,
13660                                   TypeResult Type, Decl *DeclFromDeclSpec) {
13661 
13662   if (Type.isInvalid())
13663     return nullptr;
13664 
13665   bool Invalid = false;
13666   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13667   TypeSourceInfo *TInfo = nullptr;
13668   GetTypeFromParser(Type.get(), &TInfo);
13669 
13670   if (DiagnoseClassNameShadow(CurContext, NameInfo))
13671     return nullptr;
13672 
13673   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13674                                       UPPC_DeclarationType)) {
13675     Invalid = true;
13676     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13677                                              TInfo->getTypeLoc().getBeginLoc());
13678   }
13679 
13680   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13681                         TemplateParamLists.size()
13682                             ? forRedeclarationInCurContext()
13683                             : RedeclarationKind::ForVisibleRedeclaration);
13684   LookupName(Previous, S);
13685 
13686   // Warn about shadowing the name of a template parameter.
13687   if (Previous.isSingleResult() &&
13688       Previous.getFoundDecl()->isTemplateParameter()) {
13689     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13690     Previous.clear();
13691   }
13692 
13693   assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13694          "name in alias declaration must be an identifier");
13695   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13696                                                Name.StartLocation,
13697                                                Name.Identifier, TInfo);
13698 
13699   NewTD->setAccess(AS);
13700 
13701   if (Invalid)
13702     NewTD->setInvalidDecl();
13703 
13704   ProcessDeclAttributeList(S, NewTD, AttrList);
13705   AddPragmaAttributes(S, NewTD);
13706   ProcessAPINotes(NewTD);
13707 
13708   CheckTypedefForVariablyModifiedType(S, NewTD);
13709   Invalid |= NewTD->isInvalidDecl();
13710 
13711   // Get the innermost enclosing declaration scope.
13712   S = S->getDeclParent();
13713 
13714   bool Redeclaration = false;
13715 
13716   NamedDecl *NewND;
13717   if (TemplateParamLists.size()) {
13718     TypeAliasTemplateDecl *OldDecl = nullptr;
13719     TemplateParameterList *OldTemplateParams = nullptr;
13720 
13721     if (TemplateParamLists.size() != 1) {
13722       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13723         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13724          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13725       Invalid = true;
13726     }
13727     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13728 
13729     // Check that we can declare a template here.
13730     if (CheckTemplateDeclScope(S, TemplateParams))
13731       return nullptr;
13732 
13733     // Only consider previous declarations in the same scope.
13734     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13735                          /*ExplicitInstantiationOrSpecialization*/false);
13736     if (!Previous.empty()) {
13737       Redeclaration = true;
13738 
13739       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13740       if (!OldDecl && !Invalid) {
13741         Diag(UsingLoc, diag::err_redefinition_different_kind)
13742           << Name.Identifier;
13743 
13744         NamedDecl *OldD = Previous.getRepresentativeDecl();
13745         if (OldD->getLocation().isValid())
13746           Diag(OldD->getLocation(), diag::note_previous_definition);
13747 
13748         Invalid = true;
13749       }
13750 
13751       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13752         if (TemplateParameterListsAreEqual(TemplateParams,
13753                                            OldDecl->getTemplateParameters(),
13754                                            /*Complain=*/true,
13755                                            TPL_TemplateMatch))
13756           OldTemplateParams =
13757               OldDecl->getMostRecentDecl()->getTemplateParameters();
13758         else
13759           Invalid = true;
13760 
13761         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13762         if (!Invalid &&
13763             !Context.hasSameType(OldTD->getUnderlyingType(),
13764                                  NewTD->getUnderlyingType())) {
13765           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13766           // but we can't reasonably accept it.
13767           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13768             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13769           if (OldTD->getLocation().isValid())
13770             Diag(OldTD->getLocation(), diag::note_previous_definition);
13771           Invalid = true;
13772         }
13773       }
13774     }
13775 
13776     // Merge any previous default template arguments into our parameters,
13777     // and check the parameter list.
13778     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13779                                    TPC_Other))
13780       return nullptr;
13781 
13782     TypeAliasTemplateDecl *NewDecl =
13783       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13784                                     Name.Identifier, TemplateParams,
13785                                     NewTD);
13786     NewTD->setDescribedAliasTemplate(NewDecl);
13787 
13788     NewDecl->setAccess(AS);
13789 
13790     if (Invalid)
13791       NewDecl->setInvalidDecl();
13792     else if (OldDecl) {
13793       NewDecl->setPreviousDecl(OldDecl);
13794       CheckRedeclarationInModule(NewDecl, OldDecl);
13795     }
13796 
13797     NewND = NewDecl;
13798   } else {
13799     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13800       setTagNameForLinkagePurposes(TD, NewTD);
13801       handleTagNumbering(TD, S);
13802     }
13803     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13804     NewND = NewTD;
13805   }
13806 
13807   PushOnScopeChains(NewND, S);
13808   ActOnDocumentableDecl(NewND);
13809   return NewND;
13810 }
13811 
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)13812 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13813                                    SourceLocation AliasLoc,
13814                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13815                                    SourceLocation IdentLoc,
13816                                    IdentifierInfo *Ident) {
13817 
13818   // Lookup the namespace name.
13819   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13820   LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13821 
13822   if (R.isAmbiguous())
13823     return nullptr;
13824 
13825   if (R.empty()) {
13826     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13827       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13828       return nullptr;
13829     }
13830   }
13831   assert(!R.isAmbiguous() && !R.empty());
13832   NamedDecl *ND = R.getRepresentativeDecl();
13833 
13834   // Check if we have a previous declaration with the same name.
13835   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13836                      RedeclarationKind::ForVisibleRedeclaration);
13837   LookupName(PrevR, S);
13838 
13839   // Check we're not shadowing a template parameter.
13840   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13841     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13842     PrevR.clear();
13843   }
13844 
13845   // Filter out any other lookup result from an enclosing scope.
13846   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13847                        /*AllowInlineNamespace*/false);
13848 
13849   // Find the previous declaration and check that we can redeclare it.
13850   NamespaceAliasDecl *Prev = nullptr;
13851   if (PrevR.isSingleResult()) {
13852     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13853     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13854       // We already have an alias with the same name that points to the same
13855       // namespace; check that it matches.
13856       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13857         Prev = AD;
13858       } else if (isVisible(PrevDecl)) {
13859         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13860           << Alias;
13861         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13862           << AD->getNamespace();
13863         return nullptr;
13864       }
13865     } else if (isVisible(PrevDecl)) {
13866       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13867                             ? diag::err_redefinition
13868                             : diag::err_redefinition_different_kind;
13869       Diag(AliasLoc, DiagID) << Alias;
13870       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13871       return nullptr;
13872     }
13873   }
13874 
13875   // The use of a nested name specifier may trigger deprecation warnings.
13876   DiagnoseUseOfDecl(ND, IdentLoc);
13877 
13878   NamespaceAliasDecl *AliasDecl =
13879     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13880                                Alias, SS.getWithLocInContext(Context),
13881                                IdentLoc, ND);
13882   if (Prev)
13883     AliasDecl->setPreviousDecl(Prev);
13884 
13885   PushOnScopeChains(AliasDecl, S);
13886   return AliasDecl;
13887 }
13888 
13889 namespace {
13890 struct SpecialMemberExceptionSpecInfo
13891     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13892   SourceLocation Loc;
13893   Sema::ImplicitExceptionSpecification ExceptSpec;
13894 
SpecialMemberExceptionSpecInfo__anon42c808803811::SpecialMemberExceptionSpecInfo13895   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13896                                  CXXSpecialMemberKind CSM,
13897                                  Sema::InheritedConstructorInfo *ICI,
13898                                  SourceLocation Loc)
13899       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13900 
13901   bool visitBase(CXXBaseSpecifier *Base);
13902   bool visitField(FieldDecl *FD);
13903 
13904   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13905                            unsigned Quals);
13906 
13907   void visitSubobjectCall(Subobject Subobj,
13908                           Sema::SpecialMemberOverloadResult SMOR);
13909 };
13910 }
13911 
visitBase(CXXBaseSpecifier * Base)13912 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13913   auto *RT = Base->getType()->getAs<RecordType>();
13914   if (!RT)
13915     return false;
13916 
13917   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13918   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13919   if (auto *BaseCtor = SMOR.getMethod()) {
13920     visitSubobjectCall(Base, BaseCtor);
13921     return false;
13922   }
13923 
13924   visitClassSubobject(BaseClass, Base, 0);
13925   return false;
13926 }
13927 
visitField(FieldDecl * FD)13928 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13929   if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
13930       FD->hasInClassInitializer()) {
13931     Expr *E = FD->getInClassInitializer();
13932     if (!E)
13933       // FIXME: It's a little wasteful to build and throw away a
13934       // CXXDefaultInitExpr here.
13935       // FIXME: We should have a single context note pointing at Loc, and
13936       // this location should be MD->getLocation() instead, since that's
13937       // the location where we actually use the default init expression.
13938       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13939     if (E)
13940       ExceptSpec.CalledExpr(E);
13941   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13942                             ->getAs<RecordType>()) {
13943     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13944                         FD->getType().getCVRQualifiers());
13945   }
13946   return false;
13947 }
13948 
visitClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)13949 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13950                                                          Subobject Subobj,
13951                                                          unsigned Quals) {
13952   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13953   bool IsMutable = Field && Field->isMutable();
13954   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13955 }
13956 
visitSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult SMOR)13957 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13958     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13959   // Note, if lookup fails, it doesn't matter what exception specification we
13960   // choose because the special member will be deleted.
13961   if (CXXMethodDecl *MD = SMOR.getMethod())
13962     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13963 }
13964 
tryResolveExplicitSpecifier(ExplicitSpecifier & ExplicitSpec)13965 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13966   llvm::APSInt Result;
13967   ExprResult Converted = CheckConvertedConstantExpression(
13968       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
13969   ExplicitSpec.setExpr(Converted.get());
13970   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13971     ExplicitSpec.setKind(Result.getBoolValue()
13972                              ? ExplicitSpecKind::ResolvedTrue
13973                              : ExplicitSpecKind::ResolvedFalse);
13974     return true;
13975   }
13976   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13977   return false;
13978 }
13979 
ActOnExplicitBoolSpecifier(Expr * ExplicitExpr)13980 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13981   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13982   if (!ExplicitExpr->isTypeDependent())
13983     tryResolveExplicitSpecifier(ES);
13984   return ES;
13985 }
13986 
13987 static Sema::ImplicitExceptionSpecification
ComputeDefaultedSpecialMemberExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD,CXXSpecialMemberKind CSM,Sema::InheritedConstructorInfo * ICI)13988 ComputeDefaultedSpecialMemberExceptionSpec(
13989     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
13990     Sema::InheritedConstructorInfo *ICI) {
13991   ComputingExceptionSpec CES(S, MD, Loc);
13992 
13993   CXXRecordDecl *ClassDecl = MD->getParent();
13994 
13995   // C++ [except.spec]p14:
13996   //   An implicitly declared special member function (Clause 12) shall have an
13997   //   exception-specification. [...]
13998   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13999   if (ClassDecl->isInvalidDecl())
14000     return Info.ExceptSpec;
14001 
14002   // FIXME: If this diagnostic fires, we're probably missing a check for
14003   // attempting to resolve an exception specification before it's known
14004   // at a higher level.
14005   if (S.RequireCompleteType(MD->getLocation(),
14006                             S.Context.getRecordType(ClassDecl),
14007                             diag::err_exception_spec_incomplete_type))
14008     return Info.ExceptSpec;
14009 
14010   // C++1z [except.spec]p7:
14011   //   [Look for exceptions thrown by] a constructor selected [...] to
14012   //   initialize a potentially constructed subobject,
14013   // C++1z [except.spec]p8:
14014   //   The exception specification for an implicitly-declared destructor, or a
14015   //   destructor without a noexcept-specifier, is potentially-throwing if and
14016   //   only if any of the destructors for any of its potentially constructed
14017   //   subojects is potentially throwing.
14018   // FIXME: We respect the first rule but ignore the "potentially constructed"
14019   // in the second rule to resolve a core issue (no number yet) that would have
14020   // us reject:
14021   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14022   //   struct B : A {};
14023   //   struct C : B { void f(); };
14024   // ... due to giving B::~B() a non-throwing exception specification.
14025   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14026                                 : Info.VisitAllBases);
14027 
14028   return Info.ExceptSpec;
14029 }
14030 
14031 namespace {
14032 /// RAII object to register a special member as being currently declared.
14033 struct DeclaringSpecialMember {
14034   Sema &S;
14035   Sema::SpecialMemberDecl D;
14036   Sema::ContextRAII SavedContext;
14037   bool WasAlreadyBeingDeclared;
14038 
DeclaringSpecialMember__anon42c808803911::DeclaringSpecialMember14039   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14040       : S(S), D(RD, CSM), SavedContext(S, RD) {
14041     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14042     if (WasAlreadyBeingDeclared)
14043       // This almost never happens, but if it does, ensure that our cache
14044       // doesn't contain a stale result.
14045       S.SpecialMemberCache.clear();
14046     else {
14047       // Register a note to be produced if we encounter an error while
14048       // declaring the special member.
14049       Sema::CodeSynthesisContext Ctx;
14050       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14051       // FIXME: We don't have a location to use here. Using the class's
14052       // location maintains the fiction that we declare all special members
14053       // with the class, but (1) it's not clear that lying about that helps our
14054       // users understand what's going on, and (2) there may be outer contexts
14055       // on the stack (some of which are relevant) and printing them exposes
14056       // our lies.
14057       Ctx.PointOfInstantiation = RD->getLocation();
14058       Ctx.Entity = RD;
14059       Ctx.SpecialMember = CSM;
14060       S.pushCodeSynthesisContext(Ctx);
14061     }
14062   }
~DeclaringSpecialMember__anon42c808803911::DeclaringSpecialMember14063   ~DeclaringSpecialMember() {
14064     if (!WasAlreadyBeingDeclared) {
14065       S.SpecialMembersBeingDeclared.erase(D);
14066       S.popCodeSynthesisContext();
14067     }
14068   }
14069 
14070   /// Are we already trying to declare this special member?
isAlreadyBeingDeclared__anon42c808803911::DeclaringSpecialMember14071   bool isAlreadyBeingDeclared() const {
14072     return WasAlreadyBeingDeclared;
14073   }
14074 };
14075 }
14076 
CheckImplicitSpecialMemberDeclaration(Scope * S,FunctionDecl * FD)14077 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14078   // Look up any existing declarations, but don't trigger declaration of all
14079   // implicit special members with this name.
14080   DeclarationName Name = FD->getDeclName();
14081   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14082                  RedeclarationKind::ForExternalRedeclaration);
14083   for (auto *D : FD->getParent()->lookup(Name))
14084     if (auto *Acceptable = R.getAcceptableDecl(D))
14085       R.addDecl(Acceptable);
14086   R.resolveKind();
14087   R.suppressDiagnostics();
14088 
14089   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14090                            FD->isThisDeclarationADefinition());
14091 }
14092 
setupImplicitSpecialMemberType(CXXMethodDecl * SpecialMem,QualType ResultTy,ArrayRef<QualType> Args)14093 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14094                                           QualType ResultTy,
14095                                           ArrayRef<QualType> Args) {
14096   // Build an exception specification pointing back at this constructor.
14097   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
14098 
14099   LangAS AS = getDefaultCXXMethodAddrSpace();
14100   if (AS != LangAS::Default) {
14101     EPI.TypeQuals.addAddressSpace(AS);
14102   }
14103 
14104   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14105   SpecialMem->setType(QT);
14106 
14107   // During template instantiation of implicit special member functions we need
14108   // a reliable TypeSourceInfo for the function prototype in order to allow
14109   // functions to be substituted.
14110   if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14111     TypeSourceInfo *TSI =
14112         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14113     SpecialMem->setTypeSourceInfo(TSI);
14114   }
14115 }
14116 
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)14117 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14118                                                      CXXRecordDecl *ClassDecl) {
14119   // C++ [class.ctor]p5:
14120   //   A default constructor for a class X is a constructor of class X
14121   //   that can be called without an argument. If there is no
14122   //   user-declared constructor for class X, a default constructor is
14123   //   implicitly declared. An implicitly-declared default constructor
14124   //   is an inline public member of its class.
14125   assert(ClassDecl->needsImplicitDefaultConstructor() &&
14126          "Should not build implicit default constructor!");
14127 
14128   DeclaringSpecialMember DSM(*this, ClassDecl,
14129                              CXXSpecialMemberKind::DefaultConstructor);
14130   if (DSM.isAlreadyBeingDeclared())
14131     return nullptr;
14132 
14133   bool Constexpr = defaultedSpecialMemberIsConstexpr(
14134       *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14135 
14136   // Create the actual constructor declaration.
14137   CanQualType ClassType
14138     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
14139   SourceLocation ClassLoc = ClassDecl->getLocation();
14140   DeclarationName Name
14141     = Context.DeclarationNames.getCXXConstructorName(ClassType);
14142   DeclarationNameInfo NameInfo(Name, ClassLoc);
14143   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14144       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14145       /*TInfo=*/nullptr, ExplicitSpecifier(),
14146       getCurFPFeatures().isFPConstrained(),
14147       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14148       Constexpr ? ConstexprSpecKind::Constexpr
14149                 : ConstexprSpecKind::Unspecified);
14150   DefaultCon->setAccess(AS_public);
14151   DefaultCon->setDefaulted();
14152 
14153   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14154 
14155   if (getLangOpts().CUDA)
14156     CUDA().inferTargetForImplicitSpecialMember(
14157         ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14158         /* ConstRHS */ false,
14159         /* Diagnose */ false);
14160 
14161   // We don't need to use SpecialMemberIsTrivial here; triviality for default
14162   // constructors is easy to compute.
14163   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14164 
14165   // Note that we have declared this constructor.
14166   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14167 
14168   Scope *S = getScopeForContext(ClassDecl);
14169   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
14170 
14171   if (ShouldDeleteSpecialMember(DefaultCon,
14172                                 CXXSpecialMemberKind::DefaultConstructor))
14173     SetDeclDeleted(DefaultCon, ClassLoc);
14174 
14175   if (S)
14176     PushOnScopeChains(DefaultCon, S, false);
14177   ClassDecl->addDecl(DefaultCon);
14178 
14179   return DefaultCon;
14180 }
14181 
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)14182 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14183                                             CXXConstructorDecl *Constructor) {
14184   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14185           !Constructor->doesThisDeclarationHaveABody() &&
14186           !Constructor->isDeleted()) &&
14187     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14188   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14189     return;
14190 
14191   CXXRecordDecl *ClassDecl = Constructor->getParent();
14192   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14193   if (ClassDecl->isInvalidDecl()) {
14194     return;
14195   }
14196 
14197   SynthesizedFunctionScope Scope(*this, Constructor);
14198 
14199   // The exception specification is needed because we are defining the
14200   // function.
14201   ResolveExceptionSpec(CurrentLocation,
14202                        Constructor->getType()->castAs<FunctionProtoType>());
14203   MarkVTableUsed(CurrentLocation, ClassDecl);
14204 
14205   // Add a context note for diagnostics produced after this point.
14206   Scope.addContextNote(CurrentLocation);
14207 
14208   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14209     Constructor->setInvalidDecl();
14210     return;
14211   }
14212 
14213   SourceLocation Loc = Constructor->getEndLoc().isValid()
14214                            ? Constructor->getEndLoc()
14215                            : Constructor->getLocation();
14216   Constructor->setBody(new (Context) CompoundStmt(Loc));
14217   Constructor->markUsed(Context);
14218 
14219   if (ASTMutationListener *L = getASTMutationListener()) {
14220     L->CompletedImplicitDefinition(Constructor);
14221   }
14222 
14223   DiagnoseUninitializedFields(*this, Constructor);
14224 }
14225 
ActOnFinishDelayedMemberInitializers(Decl * D)14226 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14227   // Perform any delayed checks on exception specifications.
14228   CheckDelayedMemberExceptionSpecs();
14229 }
14230 
14231 /// Find or create the fake constructor we synthesize to model constructing an
14232 /// object of a derived class via a constructor of a base class.
14233 CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc,CXXConstructorDecl * BaseCtor,ConstructorUsingShadowDecl * Shadow)14234 Sema::findInheritingConstructor(SourceLocation Loc,
14235                                 CXXConstructorDecl *BaseCtor,
14236                                 ConstructorUsingShadowDecl *Shadow) {
14237   CXXRecordDecl *Derived = Shadow->getParent();
14238   SourceLocation UsingLoc = Shadow->getLocation();
14239 
14240   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14241   // For now we use the name of the base class constructor as a member of the
14242   // derived class to indicate a (fake) inherited constructor name.
14243   DeclarationName Name = BaseCtor->getDeclName();
14244 
14245   // Check to see if we already have a fake constructor for this inherited
14246   // constructor call.
14247   for (NamedDecl *Ctor : Derived->lookup(Name))
14248     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14249                                ->getInheritedConstructor()
14250                                .getConstructor(),
14251                            BaseCtor))
14252       return cast<CXXConstructorDecl>(Ctor);
14253 
14254   DeclarationNameInfo NameInfo(Name, UsingLoc);
14255   TypeSourceInfo *TInfo =
14256       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14257   FunctionProtoTypeLoc ProtoLoc =
14258       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14259 
14260   // Check the inherited constructor is valid and find the list of base classes
14261   // from which it was inherited.
14262   InheritedConstructorInfo ICI(*this, Loc, Shadow);
14263 
14264   bool Constexpr = BaseCtor->isConstexpr() &&
14265                    defaultedSpecialMemberIsConstexpr(
14266                        *this, Derived, CXXSpecialMemberKind::DefaultConstructor,
14267                        false, BaseCtor, &ICI);
14268 
14269   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14270       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14271       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14272       /*isInline=*/true,
14273       /*isImplicitlyDeclared=*/true,
14274       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14275       InheritedConstructor(Shadow, BaseCtor),
14276       BaseCtor->getTrailingRequiresClause());
14277   if (Shadow->isInvalidDecl())
14278     DerivedCtor->setInvalidDecl();
14279 
14280   // Build an unevaluated exception specification for this fake constructor.
14281   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14282   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14283   EPI.ExceptionSpec.Type = EST_Unevaluated;
14284   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14285   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14286                                                FPT->getParamTypes(), EPI));
14287 
14288   // Build the parameter declarations.
14289   SmallVector<ParmVarDecl *, 16> ParamDecls;
14290   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14291     TypeSourceInfo *TInfo =
14292         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14293     ParmVarDecl *PD = ParmVarDecl::Create(
14294         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14295         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14296     PD->setScopeInfo(0, I);
14297     PD->setImplicit();
14298     // Ensure attributes are propagated onto parameters (this matters for
14299     // format, pass_object_size, ...).
14300     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14301     ParamDecls.push_back(PD);
14302     ProtoLoc.setParam(I, PD);
14303   }
14304 
14305   // Set up the new constructor.
14306   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14307   DerivedCtor->setAccess(BaseCtor->getAccess());
14308   DerivedCtor->setParams(ParamDecls);
14309   Derived->addDecl(DerivedCtor);
14310 
14311   if (ShouldDeleteSpecialMember(DerivedCtor,
14312                                 CXXSpecialMemberKind::DefaultConstructor, &ICI))
14313     SetDeclDeleted(DerivedCtor, UsingLoc);
14314 
14315   return DerivedCtor;
14316 }
14317 
NoteDeletedInheritingConstructor(CXXConstructorDecl * Ctor)14318 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14319   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14320                                Ctor->getInheritedConstructor().getShadowDecl());
14321   ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor,
14322                             &ICI,
14323                             /*Diagnose*/ true);
14324 }
14325 
DefineInheritingConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)14326 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14327                                        CXXConstructorDecl *Constructor) {
14328   CXXRecordDecl *ClassDecl = Constructor->getParent();
14329   assert(Constructor->getInheritedConstructor() &&
14330          !Constructor->doesThisDeclarationHaveABody() &&
14331          !Constructor->isDeleted());
14332   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14333     return;
14334 
14335   // Initializations are performed "as if by a defaulted default constructor",
14336   // so enter the appropriate scope.
14337   SynthesizedFunctionScope Scope(*this, Constructor);
14338 
14339   // The exception specification is needed because we are defining the
14340   // function.
14341   ResolveExceptionSpec(CurrentLocation,
14342                        Constructor->getType()->castAs<FunctionProtoType>());
14343   MarkVTableUsed(CurrentLocation, ClassDecl);
14344 
14345   // Add a context note for diagnostics produced after this point.
14346   Scope.addContextNote(CurrentLocation);
14347 
14348   ConstructorUsingShadowDecl *Shadow =
14349       Constructor->getInheritedConstructor().getShadowDecl();
14350   CXXConstructorDecl *InheritedCtor =
14351       Constructor->getInheritedConstructor().getConstructor();
14352 
14353   // [class.inhctor.init]p1:
14354   //   initialization proceeds as if a defaulted default constructor is used to
14355   //   initialize the D object and each base class subobject from which the
14356   //   constructor was inherited
14357 
14358   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14359   CXXRecordDecl *RD = Shadow->getParent();
14360   SourceLocation InitLoc = Shadow->getLocation();
14361 
14362   // Build explicit initializers for all base classes from which the
14363   // constructor was inherited.
14364   SmallVector<CXXCtorInitializer*, 8> Inits;
14365   for (bool VBase : {false, true}) {
14366     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14367       if (B.isVirtual() != VBase)
14368         continue;
14369 
14370       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14371       if (!BaseRD)
14372         continue;
14373 
14374       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14375       if (!BaseCtor.first)
14376         continue;
14377 
14378       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14379       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14380           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14381 
14382       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14383       Inits.push_back(new (Context) CXXCtorInitializer(
14384           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14385           SourceLocation()));
14386     }
14387   }
14388 
14389   // We now proceed as if for a defaulted default constructor, with the relevant
14390   // initializers replaced.
14391 
14392   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14393     Constructor->setInvalidDecl();
14394     return;
14395   }
14396 
14397   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14398   Constructor->markUsed(Context);
14399 
14400   if (ASTMutationListener *L = getASTMutationListener()) {
14401     L->CompletedImplicitDefinition(Constructor);
14402   }
14403 
14404   DiagnoseUninitializedFields(*this, Constructor);
14405 }
14406 
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)14407 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14408   // C++ [class.dtor]p2:
14409   //   If a class has no user-declared destructor, a destructor is
14410   //   declared implicitly. An implicitly-declared destructor is an
14411   //   inline public member of its class.
14412   assert(ClassDecl->needsImplicitDestructor());
14413 
14414   DeclaringSpecialMember DSM(*this, ClassDecl,
14415                              CXXSpecialMemberKind::Destructor);
14416   if (DSM.isAlreadyBeingDeclared())
14417     return nullptr;
14418 
14419   bool Constexpr = defaultedSpecialMemberIsConstexpr(
14420       *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14421 
14422   // Create the actual destructor declaration.
14423   CanQualType ClassType
14424     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
14425   SourceLocation ClassLoc = ClassDecl->getLocation();
14426   DeclarationName Name
14427     = Context.DeclarationNames.getCXXDestructorName(ClassType);
14428   DeclarationNameInfo NameInfo(Name, ClassLoc);
14429   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14430       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14431       getCurFPFeatures().isFPConstrained(),
14432       /*isInline=*/true,
14433       /*isImplicitlyDeclared=*/true,
14434       Constexpr ? ConstexprSpecKind::Constexpr
14435                 : ConstexprSpecKind::Unspecified);
14436   Destructor->setAccess(AS_public);
14437   Destructor->setDefaulted();
14438 
14439   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14440 
14441   if (getLangOpts().CUDA)
14442     CUDA().inferTargetForImplicitSpecialMember(
14443         ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,
14444         /* ConstRHS */ false,
14445         /* Diagnose */ false);
14446 
14447   // We don't need to use SpecialMemberIsTrivial here; triviality for
14448   // destructors is easy to compute.
14449   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14450   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14451                                 ClassDecl->hasTrivialDestructorForCall());
14452 
14453   // Note that we have declared this destructor.
14454   ++getASTContext().NumImplicitDestructorsDeclared;
14455 
14456   Scope *S = getScopeForContext(ClassDecl);
14457   CheckImplicitSpecialMemberDeclaration(S, Destructor);
14458 
14459   // We can't check whether an implicit destructor is deleted before we complete
14460   // the definition of the class, because its validity depends on the alignment
14461   // of the class. We'll check this from ActOnFields once the class is complete.
14462   if (ClassDecl->isCompleteDefinition() &&
14463       ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor))
14464     SetDeclDeleted(Destructor, ClassLoc);
14465 
14466   // Introduce this destructor into its scope.
14467   if (S)
14468     PushOnScopeChains(Destructor, S, false);
14469   ClassDecl->addDecl(Destructor);
14470 
14471   return Destructor;
14472 }
14473 
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)14474 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14475                                     CXXDestructorDecl *Destructor) {
14476   assert((Destructor->isDefaulted() &&
14477           !Destructor->doesThisDeclarationHaveABody() &&
14478           !Destructor->isDeleted()) &&
14479          "DefineImplicitDestructor - call it for implicit default dtor");
14480   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14481     return;
14482 
14483   CXXRecordDecl *ClassDecl = Destructor->getParent();
14484   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14485 
14486   SynthesizedFunctionScope Scope(*this, Destructor);
14487 
14488   // The exception specification is needed because we are defining the
14489   // function.
14490   ResolveExceptionSpec(CurrentLocation,
14491                        Destructor->getType()->castAs<FunctionProtoType>());
14492   MarkVTableUsed(CurrentLocation, ClassDecl);
14493 
14494   // Add a context note for diagnostics produced after this point.
14495   Scope.addContextNote(CurrentLocation);
14496 
14497   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14498                                          Destructor->getParent());
14499 
14500   if (CheckDestructor(Destructor)) {
14501     Destructor->setInvalidDecl();
14502     return;
14503   }
14504 
14505   SourceLocation Loc = Destructor->getEndLoc().isValid()
14506                            ? Destructor->getEndLoc()
14507                            : Destructor->getLocation();
14508   Destructor->setBody(new (Context) CompoundStmt(Loc));
14509   Destructor->markUsed(Context);
14510 
14511   if (ASTMutationListener *L = getASTMutationListener()) {
14512     L->CompletedImplicitDefinition(Destructor);
14513   }
14514 }
14515 
CheckCompleteDestructorVariant(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)14516 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14517                                           CXXDestructorDecl *Destructor) {
14518   if (Destructor->isInvalidDecl())
14519     return;
14520 
14521   CXXRecordDecl *ClassDecl = Destructor->getParent();
14522   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14523          "implicit complete dtors unneeded outside MS ABI");
14524   assert(ClassDecl->getNumVBases() > 0 &&
14525          "complete dtor only exists for classes with vbases");
14526 
14527   SynthesizedFunctionScope Scope(*this, Destructor);
14528 
14529   // Add a context note for diagnostics produced after this point.
14530   Scope.addContextNote(CurrentLocation);
14531 
14532   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14533 }
14534 
ActOnFinishCXXMemberDecls()14535 void Sema::ActOnFinishCXXMemberDecls() {
14536   // If the context is an invalid C++ class, just suppress these checks.
14537   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14538     if (Record->isInvalidDecl()) {
14539       DelayedOverridingExceptionSpecChecks.clear();
14540       DelayedEquivalentExceptionSpecChecks.clear();
14541       return;
14542     }
14543     checkForMultipleExportedDefaultConstructors(*this, Record);
14544   }
14545 }
14546 
ActOnFinishCXXNonNestedClass()14547 void Sema::ActOnFinishCXXNonNestedClass() {
14548   referenceDLLExportedClassMethods();
14549 
14550   if (!DelayedDllExportMemberFunctions.empty()) {
14551     SmallVector<CXXMethodDecl*, 4> WorkList;
14552     std::swap(DelayedDllExportMemberFunctions, WorkList);
14553     for (CXXMethodDecl *M : WorkList) {
14554       DefineDefaultedFunction(*this, M, M->getLocation());
14555 
14556       // Pass the method to the consumer to get emitted. This is not necessary
14557       // for explicit instantiation definitions, as they will get emitted
14558       // anyway.
14559       if (M->getParent()->getTemplateSpecializationKind() !=
14560           TSK_ExplicitInstantiationDefinition)
14561         ActOnFinishInlineFunctionDef(M);
14562     }
14563   }
14564 }
14565 
referenceDLLExportedClassMethods()14566 void Sema::referenceDLLExportedClassMethods() {
14567   if (!DelayedDllExportClasses.empty()) {
14568     // Calling ReferenceDllExportedMembers might cause the current function to
14569     // be called again, so use a local copy of DelayedDllExportClasses.
14570     SmallVector<CXXRecordDecl *, 4> WorkList;
14571     std::swap(DelayedDllExportClasses, WorkList);
14572     for (CXXRecordDecl *Class : WorkList)
14573       ReferenceDllExportedMembers(*this, Class);
14574   }
14575 }
14576 
AdjustDestructorExceptionSpec(CXXDestructorDecl * Destructor)14577 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14578   assert(getLangOpts().CPlusPlus11 &&
14579          "adjusting dtor exception specs was introduced in c++11");
14580 
14581   if (Destructor->isDependentContext())
14582     return;
14583 
14584   // C++11 [class.dtor]p3:
14585   //   A declaration of a destructor that does not have an exception-
14586   //   specification is implicitly considered to have the same exception-
14587   //   specification as an implicit declaration.
14588   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14589   if (DtorType->hasExceptionSpec())
14590     return;
14591 
14592   // Replace the destructor's type, building off the existing one. Fortunately,
14593   // the only thing of interest in the destructor type is its extended info.
14594   // The return and arguments are fixed.
14595   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14596   EPI.ExceptionSpec.Type = EST_Unevaluated;
14597   EPI.ExceptionSpec.SourceDecl = Destructor;
14598   Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14599 
14600   // FIXME: If the destructor has a body that could throw, and the newly created
14601   // spec doesn't allow exceptions, we should emit a warning, because this
14602   // change in behavior can break conforming C++03 programs at runtime.
14603   // However, we don't have a body or an exception specification yet, so it
14604   // needs to be done somewhere else.
14605 }
14606 
14607 namespace {
14608 /// An abstract base class for all helper classes used in building the
14609 //  copy/move operators. These classes serve as factory functions and help us
14610 //  avoid using the same Expr* in the AST twice.
14611 class ExprBuilder {
14612   ExprBuilder(const ExprBuilder&) = delete;
14613   ExprBuilder &operator=(const ExprBuilder&) = delete;
14614 
14615 protected:
assertNotNull(Expr * E)14616   static Expr *assertNotNull(Expr *E) {
14617     assert(E && "Expression construction must not fail.");
14618     return E;
14619   }
14620 
14621 public:
ExprBuilder()14622   ExprBuilder() {}
~ExprBuilder()14623   virtual ~ExprBuilder() {}
14624 
14625   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14626 };
14627 
14628 class RefBuilder: public ExprBuilder {
14629   VarDecl *Var;
14630   QualType VarType;
14631 
14632 public:
build(Sema & S,SourceLocation Loc) const14633   Expr *build(Sema &S, SourceLocation Loc) const override {
14634     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14635   }
14636 
RefBuilder(VarDecl * Var,QualType VarType)14637   RefBuilder(VarDecl *Var, QualType VarType)
14638       : Var(Var), VarType(VarType) {}
14639 };
14640 
14641 class ThisBuilder: public ExprBuilder {
14642 public:
build(Sema & S,SourceLocation Loc) const14643   Expr *build(Sema &S, SourceLocation Loc) const override {
14644     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14645   }
14646 };
14647 
14648 class CastBuilder: public ExprBuilder {
14649   const ExprBuilder &Builder;
14650   QualType Type;
14651   ExprValueKind Kind;
14652   const CXXCastPath &Path;
14653 
14654 public:
build(Sema & S,SourceLocation Loc) const14655   Expr *build(Sema &S, SourceLocation Loc) const override {
14656     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14657                                              CK_UncheckedDerivedToBase, Kind,
14658                                              &Path).get());
14659   }
14660 
CastBuilder(const ExprBuilder & Builder,QualType Type,ExprValueKind Kind,const CXXCastPath & Path)14661   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14662               const CXXCastPath &Path)
14663       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14664 };
14665 
14666 class DerefBuilder: public ExprBuilder {
14667   const ExprBuilder &Builder;
14668 
14669 public:
build(Sema & S,SourceLocation Loc) const14670   Expr *build(Sema &S, SourceLocation Loc) const override {
14671     return assertNotNull(
14672         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14673   }
14674 
DerefBuilder(const ExprBuilder & Builder)14675   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14676 };
14677 
14678 class MemberBuilder: public ExprBuilder {
14679   const ExprBuilder &Builder;
14680   QualType Type;
14681   CXXScopeSpec SS;
14682   bool IsArrow;
14683   LookupResult &MemberLookup;
14684 
14685 public:
build(Sema & S,SourceLocation Loc) const14686   Expr *build(Sema &S, SourceLocation Loc) const override {
14687     return assertNotNull(S.BuildMemberReferenceExpr(
14688         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14689         nullptr, MemberLookup, nullptr, nullptr).get());
14690   }
14691 
MemberBuilder(const ExprBuilder & Builder,QualType Type,bool IsArrow,LookupResult & MemberLookup)14692   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14693                 LookupResult &MemberLookup)
14694       : Builder(Builder), Type(Type), IsArrow(IsArrow),
14695         MemberLookup(MemberLookup) {}
14696 };
14697 
14698 class MoveCastBuilder: public ExprBuilder {
14699   const ExprBuilder &Builder;
14700 
14701 public:
build(Sema & S,SourceLocation Loc) const14702   Expr *build(Sema &S, SourceLocation Loc) const override {
14703     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14704   }
14705 
MoveCastBuilder(const ExprBuilder & Builder)14706   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14707 };
14708 
14709 class LvalueConvBuilder: public ExprBuilder {
14710   const ExprBuilder &Builder;
14711 
14712 public:
build(Sema & S,SourceLocation Loc) const14713   Expr *build(Sema &S, SourceLocation Loc) const override {
14714     return assertNotNull(
14715         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14716   }
14717 
LvalueConvBuilder(const ExprBuilder & Builder)14718   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14719 };
14720 
14721 class SubscriptBuilder: public ExprBuilder {
14722   const ExprBuilder &Base;
14723   const ExprBuilder &Index;
14724 
14725 public:
build(Sema & S,SourceLocation Loc) const14726   Expr *build(Sema &S, SourceLocation Loc) const override {
14727     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14728         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14729   }
14730 
SubscriptBuilder(const ExprBuilder & Base,const ExprBuilder & Index)14731   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14732       : Base(Base), Index(Index) {}
14733 };
14734 
14735 } // end anonymous namespace
14736 
14737 /// When generating a defaulted copy or move assignment operator, if a field
14738 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14739 /// do so. This optimization only applies for arrays of scalars, and for arrays
14740 /// of class type where the selected copy/move-assignment operator is trivial.
14741 static StmtResult
buildMemcpyForAssignmentOp(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & ToB,const ExprBuilder & FromB)14742 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14743                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14744   // Compute the size of the memory buffer to be copied.
14745   QualType SizeType = S.Context.getSizeType();
14746   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14747                    S.Context.getTypeSizeInChars(T).getQuantity());
14748 
14749   // Take the address of the field references for "from" and "to". We
14750   // directly construct UnaryOperators here because semantic analysis
14751   // does not permit us to take the address of an xvalue.
14752   Expr *From = FromB.build(S, Loc);
14753   From = UnaryOperator::Create(
14754       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14755       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14756   Expr *To = ToB.build(S, Loc);
14757   To = UnaryOperator::Create(
14758       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14759       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14760 
14761   const Type *E = T->getBaseElementTypeUnsafe();
14762   bool NeedsCollectableMemCpy =
14763       E->isRecordType() &&
14764       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14765 
14766   // Create a reference to the __builtin_objc_memmove_collectable function
14767   StringRef MemCpyName = NeedsCollectableMemCpy ?
14768     "__builtin_objc_memmove_collectable" :
14769     "__builtin_memcpy";
14770   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14771                  Sema::LookupOrdinaryName);
14772   S.LookupName(R, S.TUScope, true);
14773 
14774   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14775   if (!MemCpy)
14776     // Something went horribly wrong earlier, and we will have complained
14777     // about it.
14778     return StmtError();
14779 
14780   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14781                                             VK_PRValue, Loc, nullptr);
14782   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14783 
14784   Expr *CallArgs[] = {
14785     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14786   };
14787   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14788                                     Loc, CallArgs, Loc);
14789 
14790   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14791   return Call.getAs<Stmt>();
14792 }
14793 
14794 /// Builds a statement that copies/moves the given entity from \p From to
14795 /// \c To.
14796 ///
14797 /// This routine is used to copy/move the members of a class with an
14798 /// implicitly-declared copy/move assignment operator. When the entities being
14799 /// copied are arrays, this routine builds for loops to copy them.
14800 ///
14801 /// \param S The Sema object used for type-checking.
14802 ///
14803 /// \param Loc The location where the implicit copy/move is being generated.
14804 ///
14805 /// \param T The type of the expressions being copied/moved. Both expressions
14806 /// must have this type.
14807 ///
14808 /// \param To The expression we are copying/moving to.
14809 ///
14810 /// \param From The expression we are copying/moving from.
14811 ///
14812 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14813 /// Otherwise, it's a non-static member subobject.
14814 ///
14815 /// \param Copying Whether we're copying or moving.
14816 ///
14817 /// \param Depth Internal parameter recording the depth of the recursion.
14818 ///
14819 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14820 /// if a memcpy should be used instead.
14821 static StmtResult
buildSingleCopyAssignRecursively(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)14822 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14823                                  const ExprBuilder &To, const ExprBuilder &From,
14824                                  bool CopyingBaseSubobject, bool Copying,
14825                                  unsigned Depth = 0) {
14826   // C++11 [class.copy]p28:
14827   //   Each subobject is assigned in the manner appropriate to its type:
14828   //
14829   //     - if the subobject is of class type, as if by a call to operator= with
14830   //       the subobject as the object expression and the corresponding
14831   //       subobject of x as a single function argument (as if by explicit
14832   //       qualification; that is, ignoring any possible virtual overriding
14833   //       functions in more derived classes);
14834   //
14835   // C++03 [class.copy]p13:
14836   //     - if the subobject is of class type, the copy assignment operator for
14837   //       the class is used (as if by explicit qualification; that is,
14838   //       ignoring any possible virtual overriding functions in more derived
14839   //       classes);
14840   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14841     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14842 
14843     // Look for operator=.
14844     DeclarationName Name
14845       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14846     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14847     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14848 
14849     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14850     // operator.
14851     if (!S.getLangOpts().CPlusPlus11) {
14852       LookupResult::Filter F = OpLookup.makeFilter();
14853       while (F.hasNext()) {
14854         NamedDecl *D = F.next();
14855         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14856           if (Method->isCopyAssignmentOperator() ||
14857               (!Copying && Method->isMoveAssignmentOperator()))
14858             continue;
14859 
14860         F.erase();
14861       }
14862       F.done();
14863     }
14864 
14865     // Suppress the protected check (C++ [class.protected]) for each of the
14866     // assignment operators we found. This strange dance is required when
14867     // we're assigning via a base classes's copy-assignment operator. To
14868     // ensure that we're getting the right base class subobject (without
14869     // ambiguities), we need to cast "this" to that subobject type; to
14870     // ensure that we don't go through the virtual call mechanism, we need
14871     // to qualify the operator= name with the base class (see below). However,
14872     // this means that if the base class has a protected copy assignment
14873     // operator, the protected member access check will fail. So, we
14874     // rewrite "protected" access to "public" access in this case, since we
14875     // know by construction that we're calling from a derived class.
14876     if (CopyingBaseSubobject) {
14877       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14878            L != LEnd; ++L) {
14879         if (L.getAccess() == AS_protected)
14880           L.setAccess(AS_public);
14881       }
14882     }
14883 
14884     // Create the nested-name-specifier that will be used to qualify the
14885     // reference to operator=; this is required to suppress the virtual
14886     // call mechanism.
14887     CXXScopeSpec SS;
14888     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14889     SS.MakeTrivial(S.Context,
14890                    NestedNameSpecifier::Create(S.Context, nullptr, CanonicalT),
14891                    Loc);
14892 
14893     // Create the reference to operator=.
14894     ExprResult OpEqualRef
14895       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14896                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14897                                    /*FirstQualifierInScope=*/nullptr,
14898                                    OpLookup,
14899                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14900                                    /*SuppressQualifierCheck=*/true);
14901     if (OpEqualRef.isInvalid())
14902       return StmtError();
14903 
14904     // Build the call to the assignment operator.
14905 
14906     Expr *FromInst = From.build(S, Loc);
14907     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14908                                                   OpEqualRef.getAs<Expr>(),
14909                                                   Loc, FromInst, Loc);
14910     if (Call.isInvalid())
14911       return StmtError();
14912 
14913     // If we built a call to a trivial 'operator=' while copying an array,
14914     // bail out. We'll replace the whole shebang with a memcpy.
14915     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14916     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14917       return StmtResult((Stmt*)nullptr);
14918 
14919     // Convert to an expression-statement, and clean up any produced
14920     // temporaries.
14921     return S.ActOnExprStmt(Call);
14922   }
14923 
14924   //     - if the subobject is of scalar type, the built-in assignment
14925   //       operator is used.
14926   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14927   if (!ArrayTy) {
14928     ExprResult Assignment = S.CreateBuiltinBinOp(
14929         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14930     if (Assignment.isInvalid())
14931       return StmtError();
14932     return S.ActOnExprStmt(Assignment);
14933   }
14934 
14935   //     - if the subobject is an array, each element is assigned, in the
14936   //       manner appropriate to the element type;
14937 
14938   // Construct a loop over the array bounds, e.g.,
14939   //
14940   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14941   //
14942   // that will copy each of the array elements.
14943   QualType SizeType = S.Context.getSizeType();
14944 
14945   // Create the iteration variable.
14946   IdentifierInfo *IterationVarName = nullptr;
14947   {
14948     SmallString<8> Str;
14949     llvm::raw_svector_ostream OS(Str);
14950     OS << "__i" << Depth;
14951     IterationVarName = &S.Context.Idents.get(OS.str());
14952   }
14953   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14954                                           IterationVarName, SizeType,
14955                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14956                                           SC_None);
14957 
14958   // Initialize the iteration variable to zero.
14959   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14960   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14961 
14962   // Creates a reference to the iteration variable.
14963   RefBuilder IterationVarRef(IterationVar, SizeType);
14964   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14965 
14966   // Create the DeclStmt that holds the iteration variable.
14967   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14968 
14969   // Subscript the "from" and "to" expressions with the iteration variable.
14970   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14971   MoveCastBuilder FromIndexMove(FromIndexCopy);
14972   const ExprBuilder *FromIndex;
14973   if (Copying)
14974     FromIndex = &FromIndexCopy;
14975   else
14976     FromIndex = &FromIndexMove;
14977 
14978   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14979 
14980   // Build the copy/move for an individual element of the array.
14981   StmtResult Copy =
14982     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14983                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14984                                      Copying, Depth + 1);
14985   // Bail out if copying fails or if we determined that we should use memcpy.
14986   if (Copy.isInvalid() || !Copy.get())
14987     return Copy;
14988 
14989   // Create the comparison against the array bound.
14990   llvm::APInt Upper
14991     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14992   Expr *Comparison = BinaryOperator::Create(
14993       S.Context, IterationVarRefRVal.build(S, Loc),
14994       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14995       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14996       S.CurFPFeatureOverrides());
14997 
14998   // Create the pre-increment of the iteration variable. We can determine
14999   // whether the increment will overflow based on the value of the array
15000   // bound.
15001   Expr *Increment = UnaryOperator::Create(
15002       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15003       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15004 
15005   // Construct the loop that copies all elements of this array.
15006   return S.ActOnForStmt(
15007       Loc, Loc, InitStmt,
15008       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
15009       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15010 }
15011 
15012 static StmtResult
buildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying)15013 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15014                       const ExprBuilder &To, const ExprBuilder &From,
15015                       bool CopyingBaseSubobject, bool Copying) {
15016   // Maybe we should use a memcpy?
15017   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15018       T.isTriviallyCopyableType(S.Context))
15019     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15020 
15021   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15022                                                      CopyingBaseSubobject,
15023                                                      Copying, 0));
15024 
15025   // If we ended up picking a trivial assignment operator for an array of a
15026   // non-trivially-copyable class type, just emit a memcpy.
15027   if (!Result.isInvalid() && !Result.get())
15028     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15029 
15030   return Result;
15031 }
15032 
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)15033 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15034   // Note: The following rules are largely analoguous to the copy
15035   // constructor rules. Note that virtual bases are not taken into account
15036   // for determining the argument type of the operator. Note also that
15037   // operators taking an object instead of a reference are allowed.
15038   assert(ClassDecl->needsImplicitCopyAssignment());
15039 
15040   DeclaringSpecialMember DSM(*this, ClassDecl,
15041                              CXXSpecialMemberKind::CopyAssignment);
15042   if (DSM.isAlreadyBeingDeclared())
15043     return nullptr;
15044 
15045   QualType ArgType = Context.getTypeDeclType(ClassDecl);
15046   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15047                                       ArgType, nullptr);
15048   LangAS AS = getDefaultCXXMethodAddrSpace();
15049   if (AS != LangAS::Default)
15050     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15051   QualType RetType = Context.getLValueReferenceType(ArgType);
15052   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15053   if (Const)
15054     ArgType = ArgType.withConst();
15055 
15056   ArgType = Context.getLValueReferenceType(ArgType);
15057 
15058   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15059       *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15060 
15061   //   An implicitly-declared copy assignment operator is an inline public
15062   //   member of its class.
15063   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15064   SourceLocation ClassLoc = ClassDecl->getLocation();
15065   DeclarationNameInfo NameInfo(Name, ClassLoc);
15066   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15067       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15068       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15069       getCurFPFeatures().isFPConstrained(),
15070       /*isInline=*/true,
15071       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15072       SourceLocation());
15073   CopyAssignment->setAccess(AS_public);
15074   CopyAssignment->setDefaulted();
15075   CopyAssignment->setImplicit();
15076 
15077   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15078 
15079   if (getLangOpts().CUDA)
15080     CUDA().inferTargetForImplicitSpecialMember(
15081         ClassDecl, CXXSpecialMemberKind::CopyAssignment, CopyAssignment,
15082         /* ConstRHS */ Const,
15083         /* Diagnose */ false);
15084 
15085   // Add the parameter to the operator.
15086   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
15087                                                ClassLoc, ClassLoc,
15088                                                /*Id=*/nullptr, ArgType,
15089                                                /*TInfo=*/nullptr, SC_None,
15090                                                nullptr);
15091   CopyAssignment->setParams(FromParam);
15092 
15093   CopyAssignment->setTrivial(
15094       ClassDecl->needsOverloadResolutionForCopyAssignment()
15095           ? SpecialMemberIsTrivial(CopyAssignment,
15096                                    CXXSpecialMemberKind::CopyAssignment)
15097           : ClassDecl->hasTrivialCopyAssignment());
15098 
15099   // Note that we have added this copy-assignment operator.
15100   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15101 
15102   Scope *S = getScopeForContext(ClassDecl);
15103   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
15104 
15105   if (ShouldDeleteSpecialMember(CopyAssignment,
15106                                 CXXSpecialMemberKind::CopyAssignment)) {
15107     ClassDecl->setImplicitCopyAssignmentIsDeleted();
15108     SetDeclDeleted(CopyAssignment, ClassLoc);
15109   }
15110 
15111   if (S)
15112     PushOnScopeChains(CopyAssignment, S, false);
15113   ClassDecl->addDecl(CopyAssignment);
15114 
15115   return CopyAssignment;
15116 }
15117 
15118 /// Diagnose an implicit copy operation for a class which is odr-used, but
15119 /// which is deprecated because the class has a user-declared copy constructor,
15120 /// copy assignment operator, or destructor.
diagnoseDeprecatedCopyOperation(Sema & S,CXXMethodDecl * CopyOp)15121 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15122   assert(CopyOp->isImplicit());
15123 
15124   CXXRecordDecl *RD = CopyOp->getParent();
15125   CXXMethodDecl *UserDeclaredOperation = nullptr;
15126 
15127   if (RD->hasUserDeclaredDestructor()) {
15128     UserDeclaredOperation = RD->getDestructor();
15129   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15130              RD->hasUserDeclaredCopyConstructor()) {
15131     // Find any user-declared copy constructor.
15132     for (auto *I : RD->ctors()) {
15133       if (I->isCopyConstructor()) {
15134         UserDeclaredOperation = I;
15135         break;
15136       }
15137     }
15138     assert(UserDeclaredOperation);
15139   } else if (isa<CXXConstructorDecl>(CopyOp) &&
15140              RD->hasUserDeclaredCopyAssignment()) {
15141     // Find any user-declared move assignment operator.
15142     for (auto *I : RD->methods()) {
15143       if (I->isCopyAssignmentOperator()) {
15144         UserDeclaredOperation = I;
15145         break;
15146       }
15147     }
15148     assert(UserDeclaredOperation);
15149   }
15150 
15151   if (UserDeclaredOperation) {
15152     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15153     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15154     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15155     unsigned DiagID =
15156         (UDOIsUserProvided && UDOIsDestructor)
15157             ? diag::warn_deprecated_copy_with_user_provided_dtor
15158         : (UDOIsUserProvided && !UDOIsDestructor)
15159             ? diag::warn_deprecated_copy_with_user_provided_copy
15160         : (!UDOIsUserProvided && UDOIsDestructor)
15161             ? diag::warn_deprecated_copy_with_dtor
15162             : diag::warn_deprecated_copy;
15163     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15164         << RD << IsCopyAssignment;
15165   }
15166 }
15167 
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)15168 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15169                                         CXXMethodDecl *CopyAssignOperator) {
15170   assert((CopyAssignOperator->isDefaulted() &&
15171           CopyAssignOperator->isOverloadedOperator() &&
15172           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15173           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15174           !CopyAssignOperator->isDeleted()) &&
15175          "DefineImplicitCopyAssignment called for wrong function");
15176   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15177     return;
15178 
15179   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15180   if (ClassDecl->isInvalidDecl()) {
15181     CopyAssignOperator->setInvalidDecl();
15182     return;
15183   }
15184 
15185   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15186 
15187   // The exception specification is needed because we are defining the
15188   // function.
15189   ResolveExceptionSpec(CurrentLocation,
15190                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15191 
15192   // Add a context note for diagnostics produced after this point.
15193   Scope.addContextNote(CurrentLocation);
15194 
15195   // C++11 [class.copy]p18:
15196   //   The [definition of an implicitly declared copy assignment operator] is
15197   //   deprecated if the class has a user-declared copy constructor or a
15198   //   user-declared destructor.
15199   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15200     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15201 
15202   // C++0x [class.copy]p30:
15203   //   The implicitly-defined or explicitly-defaulted copy assignment operator
15204   //   for a non-union class X performs memberwise copy assignment of its
15205   //   subobjects. The direct base classes of X are assigned first, in the
15206   //   order of their declaration in the base-specifier-list, and then the
15207   //   immediate non-static data members of X are assigned, in the order in
15208   //   which they were declared in the class definition.
15209 
15210   // The statements that form the synthesized function body.
15211   SmallVector<Stmt*, 8> Statements;
15212 
15213   // The parameter for the "other" object, which we are copying from.
15214   ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15215   Qualifiers OtherQuals = Other->getType().getQualifiers();
15216   QualType OtherRefType = Other->getType();
15217   if (OtherRefType->isLValueReferenceType()) {
15218     OtherRefType = OtherRefType->getPointeeType();
15219     OtherQuals = OtherRefType.getQualifiers();
15220   }
15221 
15222   // Our location for everything implicitly-generated.
15223   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15224                            ? CopyAssignOperator->getEndLoc()
15225                            : CopyAssignOperator->getLocation();
15226 
15227   // Builds a DeclRefExpr for the "other" object.
15228   RefBuilder OtherRef(Other, OtherRefType);
15229 
15230   // Builds the function object parameter.
15231   std::optional<ThisBuilder> This;
15232   std::optional<DerefBuilder> DerefThis;
15233   std::optional<RefBuilder> ExplicitObject;
15234   bool IsArrow = false;
15235   QualType ObjectType;
15236   if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15237     ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15238     if (ObjectType->isReferenceType())
15239       ObjectType = ObjectType->getPointeeType();
15240     ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15241   } else {
15242     ObjectType = getCurrentThisType();
15243     This.emplace();
15244     DerefThis.emplace(*This);
15245     IsArrow = !LangOpts.HLSL;
15246   }
15247   ExprBuilder &ObjectParameter =
15248       ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15249                      : static_cast<ExprBuilder &>(*This);
15250 
15251   // Assign base classes.
15252   bool Invalid = false;
15253   for (auto &Base : ClassDecl->bases()) {
15254     // Form the assignment:
15255     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15256     QualType BaseType = Base.getType().getUnqualifiedType();
15257     if (!BaseType->isRecordType()) {
15258       Invalid = true;
15259       continue;
15260     }
15261 
15262     CXXCastPath BasePath;
15263     BasePath.push_back(&Base);
15264 
15265     // Construct the "from" expression, which is an implicit cast to the
15266     // appropriately-qualified base type.
15267     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15268                      VK_LValue, BasePath);
15269 
15270     // Dereference "this".
15271     CastBuilder To(
15272         ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15273                        : static_cast<ExprBuilder &>(*DerefThis),
15274         Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15275         VK_LValue, BasePath);
15276 
15277     // Build the copy.
15278     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15279                                             To, From,
15280                                             /*CopyingBaseSubobject=*/true,
15281                                             /*Copying=*/true);
15282     if (Copy.isInvalid()) {
15283       CopyAssignOperator->setInvalidDecl();
15284       return;
15285     }
15286 
15287     // Success! Record the copy.
15288     Statements.push_back(Copy.getAs<Expr>());
15289   }
15290 
15291   // Assign non-static members.
15292   for (auto *Field : ClassDecl->fields()) {
15293     // FIXME: We should form some kind of AST representation for the implied
15294     // memcpy in a union copy operation.
15295     if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15296       continue;
15297 
15298     if (Field->isInvalidDecl()) {
15299       Invalid = true;
15300       continue;
15301     }
15302 
15303     // Check for members of reference type; we can't copy those.
15304     if (Field->getType()->isReferenceType()) {
15305       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15306         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15307       Diag(Field->getLocation(), diag::note_declared_at);
15308       Invalid = true;
15309       continue;
15310     }
15311 
15312     // Check for members of const-qualified, non-class type.
15313     QualType BaseType = Context.getBaseElementType(Field->getType());
15314     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15315       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15316         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15317       Diag(Field->getLocation(), diag::note_declared_at);
15318       Invalid = true;
15319       continue;
15320     }
15321 
15322     // Suppress assigning zero-width bitfields.
15323     if (Field->isZeroLengthBitField())
15324       continue;
15325 
15326     QualType FieldType = Field->getType().getNonReferenceType();
15327     if (FieldType->isIncompleteArrayType()) {
15328       assert(ClassDecl->hasFlexibleArrayMember() &&
15329              "Incomplete array type is not valid");
15330       continue;
15331     }
15332 
15333     // Build references to the field in the object we're copying from and to.
15334     CXXScopeSpec SS; // Intentionally empty
15335     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15336                               LookupMemberName);
15337     MemberLookup.addDecl(Field);
15338     MemberLookup.resolveKind();
15339 
15340     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15341     MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15342     // Build the copy of this field.
15343     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15344                                             To, From,
15345                                             /*CopyingBaseSubobject=*/false,
15346                                             /*Copying=*/true);
15347     if (Copy.isInvalid()) {
15348       CopyAssignOperator->setInvalidDecl();
15349       return;
15350     }
15351 
15352     // Success! Record the copy.
15353     Statements.push_back(Copy.getAs<Stmt>());
15354   }
15355 
15356   if (!Invalid) {
15357     // Add a "return *this;"
15358     Expr *ThisExpr =
15359         (ExplicitObject  ? static_cast<ExprBuilder &>(*ExplicitObject)
15360          : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15361                          : static_cast<ExprBuilder &>(*DerefThis))
15362             .build(*this, Loc);
15363     StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15364     if (Return.isInvalid())
15365       Invalid = true;
15366     else
15367       Statements.push_back(Return.getAs<Stmt>());
15368   }
15369 
15370   if (Invalid) {
15371     CopyAssignOperator->setInvalidDecl();
15372     return;
15373   }
15374 
15375   StmtResult Body;
15376   {
15377     CompoundScopeRAII CompoundScope(*this);
15378     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15379                              /*isStmtExpr=*/false);
15380     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15381   }
15382   CopyAssignOperator->setBody(Body.getAs<Stmt>());
15383   CopyAssignOperator->markUsed(Context);
15384 
15385   if (ASTMutationListener *L = getASTMutationListener()) {
15386     L->CompletedImplicitDefinition(CopyAssignOperator);
15387   }
15388 }
15389 
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)15390 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15391   assert(ClassDecl->needsImplicitMoveAssignment());
15392 
15393   DeclaringSpecialMember DSM(*this, ClassDecl,
15394                              CXXSpecialMemberKind::MoveAssignment);
15395   if (DSM.isAlreadyBeingDeclared())
15396     return nullptr;
15397 
15398   // Note: The following rules are largely analoguous to the move
15399   // constructor rules.
15400 
15401   QualType ArgType = Context.getTypeDeclType(ClassDecl);
15402   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15403                                       ArgType, nullptr);
15404   LangAS AS = getDefaultCXXMethodAddrSpace();
15405   if (AS != LangAS::Default)
15406     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15407   QualType RetType = Context.getLValueReferenceType(ArgType);
15408   ArgType = Context.getRValueReferenceType(ArgType);
15409 
15410   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15411       *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15412 
15413   //   An implicitly-declared move assignment operator is an inline public
15414   //   member of its class.
15415   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15416   SourceLocation ClassLoc = ClassDecl->getLocation();
15417   DeclarationNameInfo NameInfo(Name, ClassLoc);
15418   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15419       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15420       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15421       getCurFPFeatures().isFPConstrained(),
15422       /*isInline=*/true,
15423       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15424       SourceLocation());
15425   MoveAssignment->setAccess(AS_public);
15426   MoveAssignment->setDefaulted();
15427   MoveAssignment->setImplicit();
15428 
15429   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15430 
15431   if (getLangOpts().CUDA)
15432     CUDA().inferTargetForImplicitSpecialMember(
15433         ClassDecl, CXXSpecialMemberKind::MoveAssignment, MoveAssignment,
15434         /* ConstRHS */ false,
15435         /* Diagnose */ false);
15436 
15437   // Add the parameter to the operator.
15438   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15439                                                ClassLoc, ClassLoc,
15440                                                /*Id=*/nullptr, ArgType,
15441                                                /*TInfo=*/nullptr, SC_None,
15442                                                nullptr);
15443   MoveAssignment->setParams(FromParam);
15444 
15445   MoveAssignment->setTrivial(
15446       ClassDecl->needsOverloadResolutionForMoveAssignment()
15447           ? SpecialMemberIsTrivial(MoveAssignment,
15448                                    CXXSpecialMemberKind::MoveAssignment)
15449           : ClassDecl->hasTrivialMoveAssignment());
15450 
15451   // Note that we have added this copy-assignment operator.
15452   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15453 
15454   Scope *S = getScopeForContext(ClassDecl);
15455   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15456 
15457   if (ShouldDeleteSpecialMember(MoveAssignment,
15458                                 CXXSpecialMemberKind::MoveAssignment)) {
15459     ClassDecl->setImplicitMoveAssignmentIsDeleted();
15460     SetDeclDeleted(MoveAssignment, ClassLoc);
15461   }
15462 
15463   if (S)
15464     PushOnScopeChains(MoveAssignment, S, false);
15465   ClassDecl->addDecl(MoveAssignment);
15466 
15467   return MoveAssignment;
15468 }
15469 
15470 /// Check if we're implicitly defining a move assignment operator for a class
15471 /// with virtual bases. Such a move assignment might move-assign the virtual
15472 /// base multiple times.
checkMoveAssignmentForRepeatedMove(Sema & S,CXXRecordDecl * Class,SourceLocation CurrentLocation)15473 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15474                                                SourceLocation CurrentLocation) {
15475   assert(!Class->isDependentContext() && "should not define dependent move");
15476 
15477   // Only a virtual base could get implicitly move-assigned multiple times.
15478   // Only a non-trivial move assignment can observe this. We only want to
15479   // diagnose if we implicitly define an assignment operator that assigns
15480   // two base classes, both of which move-assign the same virtual base.
15481   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15482       Class->getNumBases() < 2)
15483     return;
15484 
15485   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15486   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15487   VBaseMap VBases;
15488 
15489   for (auto &BI : Class->bases()) {
15490     Worklist.push_back(&BI);
15491     while (!Worklist.empty()) {
15492       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15493       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15494 
15495       // If the base has no non-trivial move assignment operators,
15496       // we don't care about moves from it.
15497       if (!Base->hasNonTrivialMoveAssignment())
15498         continue;
15499 
15500       // If there's nothing virtual here, skip it.
15501       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15502         continue;
15503 
15504       // If we're not actually going to call a move assignment for this base,
15505       // or the selected move assignment is trivial, skip it.
15506       Sema::SpecialMemberOverloadResult SMOR =
15507           S.LookupSpecialMember(Base, CXXSpecialMemberKind::MoveAssignment,
15508                                 /*ConstArg*/ false, /*VolatileArg*/ false,
15509                                 /*RValueThis*/ true, /*ConstThis*/ false,
15510                                 /*VolatileThis*/ false);
15511       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15512           !SMOR.getMethod()->isMoveAssignmentOperator())
15513         continue;
15514 
15515       if (BaseSpec->isVirtual()) {
15516         // We're going to move-assign this virtual base, and its move
15517         // assignment operator is not trivial. If this can happen for
15518         // multiple distinct direct bases of Class, diagnose it. (If it
15519         // only happens in one base, we'll diagnose it when synthesizing
15520         // that base class's move assignment operator.)
15521         CXXBaseSpecifier *&Existing =
15522             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15523                 .first->second;
15524         if (Existing && Existing != &BI) {
15525           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15526             << Class << Base;
15527           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15528               << (Base->getCanonicalDecl() ==
15529                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15530               << Base << Existing->getType() << Existing->getSourceRange();
15531           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15532               << (Base->getCanonicalDecl() ==
15533                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15534               << Base << BI.getType() << BaseSpec->getSourceRange();
15535 
15536           // Only diagnose each vbase once.
15537           Existing = nullptr;
15538         }
15539       } else {
15540         // Only walk over bases that have defaulted move assignment operators.
15541         // We assume that any user-provided move assignment operator handles
15542         // the multiple-moves-of-vbase case itself somehow.
15543         if (!SMOR.getMethod()->isDefaulted())
15544           continue;
15545 
15546         // We're going to move the base classes of Base. Add them to the list.
15547         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15548       }
15549     }
15550   }
15551 }
15552 
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)15553 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15554                                         CXXMethodDecl *MoveAssignOperator) {
15555   assert((MoveAssignOperator->isDefaulted() &&
15556           MoveAssignOperator->isOverloadedOperator() &&
15557           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15558           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15559           !MoveAssignOperator->isDeleted()) &&
15560          "DefineImplicitMoveAssignment called for wrong function");
15561   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15562     return;
15563 
15564   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15565   if (ClassDecl->isInvalidDecl()) {
15566     MoveAssignOperator->setInvalidDecl();
15567     return;
15568   }
15569 
15570   // C++0x [class.copy]p28:
15571   //   The implicitly-defined or move assignment operator for a non-union class
15572   //   X performs memberwise move assignment of its subobjects. The direct base
15573   //   classes of X are assigned first, in the order of their declaration in the
15574   //   base-specifier-list, and then the immediate non-static data members of X
15575   //   are assigned, in the order in which they were declared in the class
15576   //   definition.
15577 
15578   // Issue a warning if our implicit move assignment operator will move
15579   // from a virtual base more than once.
15580   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15581 
15582   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15583 
15584   // The exception specification is needed because we are defining the
15585   // function.
15586   ResolveExceptionSpec(CurrentLocation,
15587                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15588 
15589   // Add a context note for diagnostics produced after this point.
15590   Scope.addContextNote(CurrentLocation);
15591 
15592   // The statements that form the synthesized function body.
15593   SmallVector<Stmt*, 8> Statements;
15594 
15595   // The parameter for the "other" object, which we are move from.
15596   ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15597   QualType OtherRefType =
15598       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15599 
15600   // Our location for everything implicitly-generated.
15601   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15602                            ? MoveAssignOperator->getEndLoc()
15603                            : MoveAssignOperator->getLocation();
15604 
15605   // Builds a reference to the "other" object.
15606   RefBuilder OtherRef(Other, OtherRefType);
15607   // Cast to rvalue.
15608   MoveCastBuilder MoveOther(OtherRef);
15609 
15610   // Builds the function object parameter.
15611   std::optional<ThisBuilder> This;
15612   std::optional<DerefBuilder> DerefThis;
15613   std::optional<RefBuilder> ExplicitObject;
15614   QualType ObjectType;
15615   bool IsArrow = false;
15616   if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15617     ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15618     if (ObjectType->isReferenceType())
15619       ObjectType = ObjectType->getPointeeType();
15620     ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15621   } else {
15622     ObjectType = getCurrentThisType();
15623     This.emplace();
15624     DerefThis.emplace(*This);
15625     IsArrow = !getLangOpts().HLSL;
15626   }
15627   ExprBuilder &ObjectParameter =
15628       ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15629 
15630   // Assign base classes.
15631   bool Invalid = false;
15632   for (auto &Base : ClassDecl->bases()) {
15633     // C++11 [class.copy]p28:
15634     //   It is unspecified whether subobjects representing virtual base classes
15635     //   are assigned more than once by the implicitly-defined copy assignment
15636     //   operator.
15637     // FIXME: Do not assign to a vbase that will be assigned by some other base
15638     // class. For a move-assignment, this can result in the vbase being moved
15639     // multiple times.
15640 
15641     // Form the assignment:
15642     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15643     QualType BaseType = Base.getType().getUnqualifiedType();
15644     if (!BaseType->isRecordType()) {
15645       Invalid = true;
15646       continue;
15647     }
15648 
15649     CXXCastPath BasePath;
15650     BasePath.push_back(&Base);
15651 
15652     // Construct the "from" expression, which is an implicit cast to the
15653     // appropriately-qualified base type.
15654     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15655 
15656     // Implicitly cast "this" to the appropriately-qualified base type.
15657     // Dereference "this".
15658     CastBuilder To(
15659         ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15660                        : static_cast<ExprBuilder &>(*DerefThis),
15661         Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15662         VK_LValue, BasePath);
15663 
15664     // Build the move.
15665     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15666                                             To, From,
15667                                             /*CopyingBaseSubobject=*/true,
15668                                             /*Copying=*/false);
15669     if (Move.isInvalid()) {
15670       MoveAssignOperator->setInvalidDecl();
15671       return;
15672     }
15673 
15674     // Success! Record the move.
15675     Statements.push_back(Move.getAs<Expr>());
15676   }
15677 
15678   // Assign non-static members.
15679   for (auto *Field : ClassDecl->fields()) {
15680     // FIXME: We should form some kind of AST representation for the implied
15681     // memcpy in a union copy operation.
15682     if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15683       continue;
15684 
15685     if (Field->isInvalidDecl()) {
15686       Invalid = true;
15687       continue;
15688     }
15689 
15690     // Check for members of reference type; we can't move those.
15691     if (Field->getType()->isReferenceType()) {
15692       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15693         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15694       Diag(Field->getLocation(), diag::note_declared_at);
15695       Invalid = true;
15696       continue;
15697     }
15698 
15699     // Check for members of const-qualified, non-class type.
15700     QualType BaseType = Context.getBaseElementType(Field->getType());
15701     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15702       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15703         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15704       Diag(Field->getLocation(), diag::note_declared_at);
15705       Invalid = true;
15706       continue;
15707     }
15708 
15709     // Suppress assigning zero-width bitfields.
15710     if (Field->isZeroLengthBitField())
15711       continue;
15712 
15713     QualType FieldType = Field->getType().getNonReferenceType();
15714     if (FieldType->isIncompleteArrayType()) {
15715       assert(ClassDecl->hasFlexibleArrayMember() &&
15716              "Incomplete array type is not valid");
15717       continue;
15718     }
15719 
15720     // Build references to the field in the object we're copying from and to.
15721     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15722                               LookupMemberName);
15723     MemberLookup.addDecl(Field);
15724     MemberLookup.resolveKind();
15725     MemberBuilder From(MoveOther, OtherRefType,
15726                        /*IsArrow=*/false, MemberLookup);
15727     MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15728 
15729     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15730         "Member reference with rvalue base must be rvalue except for reference "
15731         "members, which aren't allowed for move assignment.");
15732 
15733     // Build the move of this field.
15734     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15735                                             To, From,
15736                                             /*CopyingBaseSubobject=*/false,
15737                                             /*Copying=*/false);
15738     if (Move.isInvalid()) {
15739       MoveAssignOperator->setInvalidDecl();
15740       return;
15741     }
15742 
15743     // Success! Record the copy.
15744     Statements.push_back(Move.getAs<Stmt>());
15745   }
15746 
15747   if (!Invalid) {
15748     // Add a "return *this;"
15749     Expr *ThisExpr =
15750         (ExplicitObject  ? static_cast<ExprBuilder &>(*ExplicitObject)
15751          : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15752                          : static_cast<ExprBuilder &>(*DerefThis))
15753             .build(*this, Loc);
15754 
15755     StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15756     if (Return.isInvalid())
15757       Invalid = true;
15758     else
15759       Statements.push_back(Return.getAs<Stmt>());
15760   }
15761 
15762   if (Invalid) {
15763     MoveAssignOperator->setInvalidDecl();
15764     return;
15765   }
15766 
15767   StmtResult Body;
15768   {
15769     CompoundScopeRAII CompoundScope(*this);
15770     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15771                              /*isStmtExpr=*/false);
15772     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15773   }
15774   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15775   MoveAssignOperator->markUsed(Context);
15776 
15777   if (ASTMutationListener *L = getASTMutationListener()) {
15778     L->CompletedImplicitDefinition(MoveAssignOperator);
15779   }
15780 }
15781 
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)15782 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15783                                                     CXXRecordDecl *ClassDecl) {
15784   // C++ [class.copy]p4:
15785   //   If the class definition does not explicitly declare a copy
15786   //   constructor, one is declared implicitly.
15787   assert(ClassDecl->needsImplicitCopyConstructor());
15788 
15789   DeclaringSpecialMember DSM(*this, ClassDecl,
15790                              CXXSpecialMemberKind::CopyConstructor);
15791   if (DSM.isAlreadyBeingDeclared())
15792     return nullptr;
15793 
15794   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15795   QualType ArgType = ClassType;
15796   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15797                                       ArgType, nullptr);
15798   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15799   if (Const)
15800     ArgType = ArgType.withConst();
15801 
15802   LangAS AS = getDefaultCXXMethodAddrSpace();
15803   if (AS != LangAS::Default)
15804     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15805 
15806   ArgType = Context.getLValueReferenceType(ArgType);
15807 
15808   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15809       *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15810 
15811   DeclarationName Name
15812     = Context.DeclarationNames.getCXXConstructorName(
15813                                            Context.getCanonicalType(ClassType));
15814   SourceLocation ClassLoc = ClassDecl->getLocation();
15815   DeclarationNameInfo NameInfo(Name, ClassLoc);
15816 
15817   //   An implicitly-declared copy constructor is an inline public
15818   //   member of its class.
15819   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15820       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15821       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15822       /*isInline=*/true,
15823       /*isImplicitlyDeclared=*/true,
15824       Constexpr ? ConstexprSpecKind::Constexpr
15825                 : ConstexprSpecKind::Unspecified);
15826   CopyConstructor->setAccess(AS_public);
15827   CopyConstructor->setDefaulted();
15828 
15829   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15830 
15831   if (getLangOpts().CUDA)
15832     CUDA().inferTargetForImplicitSpecialMember(
15833         ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor,
15834         /* ConstRHS */ Const,
15835         /* Diagnose */ false);
15836 
15837   // During template instantiation of special member functions we need a
15838   // reliable TypeSourceInfo for the parameter types in order to allow functions
15839   // to be substituted.
15840   TypeSourceInfo *TSI = nullptr;
15841   if (inTemplateInstantiation() && ClassDecl->isLambda())
15842     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15843 
15844   // Add the parameter to the constructor.
15845   ParmVarDecl *FromParam =
15846       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15847                           /*IdentifierInfo=*/nullptr, ArgType,
15848                           /*TInfo=*/TSI, SC_None, nullptr);
15849   CopyConstructor->setParams(FromParam);
15850 
15851   CopyConstructor->setTrivial(
15852       ClassDecl->needsOverloadResolutionForCopyConstructor()
15853           ? SpecialMemberIsTrivial(CopyConstructor,
15854                                    CXXSpecialMemberKind::CopyConstructor)
15855           : ClassDecl->hasTrivialCopyConstructor());
15856 
15857   CopyConstructor->setTrivialForCall(
15858       ClassDecl->hasAttr<TrivialABIAttr>() ||
15859       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15860            ? SpecialMemberIsTrivial(CopyConstructor,
15861                                     CXXSpecialMemberKind::CopyConstructor,
15862                                     TrivialABIHandling::ConsiderTrivialABI)
15863            : ClassDecl->hasTrivialCopyConstructorForCall()));
15864 
15865   // Note that we have declared this constructor.
15866   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15867 
15868   Scope *S = getScopeForContext(ClassDecl);
15869   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15870 
15871   if (ShouldDeleteSpecialMember(CopyConstructor,
15872                                 CXXSpecialMemberKind::CopyConstructor)) {
15873     ClassDecl->setImplicitCopyConstructorIsDeleted();
15874     SetDeclDeleted(CopyConstructor, ClassLoc);
15875   }
15876 
15877   if (S)
15878     PushOnScopeChains(CopyConstructor, S, false);
15879   ClassDecl->addDecl(CopyConstructor);
15880 
15881   return CopyConstructor;
15882 }
15883 
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)15884 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15885                                          CXXConstructorDecl *CopyConstructor) {
15886   assert((CopyConstructor->isDefaulted() &&
15887           CopyConstructor->isCopyConstructor() &&
15888           !CopyConstructor->doesThisDeclarationHaveABody() &&
15889           !CopyConstructor->isDeleted()) &&
15890          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15891   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15892     return;
15893 
15894   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15895   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15896 
15897   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15898 
15899   // The exception specification is needed because we are defining the
15900   // function.
15901   ResolveExceptionSpec(CurrentLocation,
15902                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15903   MarkVTableUsed(CurrentLocation, ClassDecl);
15904 
15905   // Add a context note for diagnostics produced after this point.
15906   Scope.addContextNote(CurrentLocation);
15907 
15908   // C++11 [class.copy]p7:
15909   //   The [definition of an implicitly declared copy constructor] is
15910   //   deprecated if the class has a user-declared copy assignment operator
15911   //   or a user-declared destructor.
15912   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15913     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15914 
15915   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15916     CopyConstructor->setInvalidDecl();
15917   }  else {
15918     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15919                              ? CopyConstructor->getEndLoc()
15920                              : CopyConstructor->getLocation();
15921     Sema::CompoundScopeRAII CompoundScope(*this);
15922     CopyConstructor->setBody(
15923         ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15924     CopyConstructor->markUsed(Context);
15925   }
15926 
15927   if (ASTMutationListener *L = getASTMutationListener()) {
15928     L->CompletedImplicitDefinition(CopyConstructor);
15929   }
15930 }
15931 
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)15932 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15933                                                     CXXRecordDecl *ClassDecl) {
15934   assert(ClassDecl->needsImplicitMoveConstructor());
15935 
15936   DeclaringSpecialMember DSM(*this, ClassDecl,
15937                              CXXSpecialMemberKind::MoveConstructor);
15938   if (DSM.isAlreadyBeingDeclared())
15939     return nullptr;
15940 
15941   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15942 
15943   QualType ArgType = ClassType;
15944   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15945                                       ArgType, nullptr);
15946   LangAS AS = getDefaultCXXMethodAddrSpace();
15947   if (AS != LangAS::Default)
15948     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15949   ArgType = Context.getRValueReferenceType(ArgType);
15950 
15951   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15952       *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15953 
15954   DeclarationName Name
15955     = Context.DeclarationNames.getCXXConstructorName(
15956                                            Context.getCanonicalType(ClassType));
15957   SourceLocation ClassLoc = ClassDecl->getLocation();
15958   DeclarationNameInfo NameInfo(Name, ClassLoc);
15959 
15960   // C++11 [class.copy]p11:
15961   //   An implicitly-declared copy/move constructor is an inline public
15962   //   member of its class.
15963   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15964       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15965       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15966       /*isInline=*/true,
15967       /*isImplicitlyDeclared=*/true,
15968       Constexpr ? ConstexprSpecKind::Constexpr
15969                 : ConstexprSpecKind::Unspecified);
15970   MoveConstructor->setAccess(AS_public);
15971   MoveConstructor->setDefaulted();
15972 
15973   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15974 
15975   if (getLangOpts().CUDA)
15976     CUDA().inferTargetForImplicitSpecialMember(
15977         ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor,
15978         /* ConstRHS */ false,
15979         /* Diagnose */ false);
15980 
15981   // Add the parameter to the constructor.
15982   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15983                                                ClassLoc, ClassLoc,
15984                                                /*IdentifierInfo=*/nullptr,
15985                                                ArgType, /*TInfo=*/nullptr,
15986                                                SC_None, nullptr);
15987   MoveConstructor->setParams(FromParam);
15988 
15989   MoveConstructor->setTrivial(
15990       ClassDecl->needsOverloadResolutionForMoveConstructor()
15991           ? SpecialMemberIsTrivial(MoveConstructor,
15992                                    CXXSpecialMemberKind::MoveConstructor)
15993           : ClassDecl->hasTrivialMoveConstructor());
15994 
15995   MoveConstructor->setTrivialForCall(
15996       ClassDecl->hasAttr<TrivialABIAttr>() ||
15997       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15998            ? SpecialMemberIsTrivial(MoveConstructor,
15999                                     CXXSpecialMemberKind::MoveConstructor,
16000                                     TrivialABIHandling::ConsiderTrivialABI)
16001            : ClassDecl->hasTrivialMoveConstructorForCall()));
16002 
16003   // Note that we have declared this constructor.
16004   ++getASTContext().NumImplicitMoveConstructorsDeclared;
16005 
16006   Scope *S = getScopeForContext(ClassDecl);
16007   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
16008 
16009   if (ShouldDeleteSpecialMember(MoveConstructor,
16010                                 CXXSpecialMemberKind::MoveConstructor)) {
16011     ClassDecl->setImplicitMoveConstructorIsDeleted();
16012     SetDeclDeleted(MoveConstructor, ClassLoc);
16013   }
16014 
16015   if (S)
16016     PushOnScopeChains(MoveConstructor, S, false);
16017   ClassDecl->addDecl(MoveConstructor);
16018 
16019   return MoveConstructor;
16020 }
16021 
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)16022 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16023                                          CXXConstructorDecl *MoveConstructor) {
16024   assert((MoveConstructor->isDefaulted() &&
16025           MoveConstructor->isMoveConstructor() &&
16026           !MoveConstructor->doesThisDeclarationHaveABody() &&
16027           !MoveConstructor->isDeleted()) &&
16028          "DefineImplicitMoveConstructor - call it for implicit move ctor");
16029   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16030     return;
16031 
16032   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16033   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16034 
16035   SynthesizedFunctionScope Scope(*this, MoveConstructor);
16036 
16037   // The exception specification is needed because we are defining the
16038   // function.
16039   ResolveExceptionSpec(CurrentLocation,
16040                        MoveConstructor->getType()->castAs<FunctionProtoType>());
16041   MarkVTableUsed(CurrentLocation, ClassDecl);
16042 
16043   // Add a context note for diagnostics produced after this point.
16044   Scope.addContextNote(CurrentLocation);
16045 
16046   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16047     MoveConstructor->setInvalidDecl();
16048   } else {
16049     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16050                              ? MoveConstructor->getEndLoc()
16051                              : MoveConstructor->getLocation();
16052     Sema::CompoundScopeRAII CompoundScope(*this);
16053     MoveConstructor->setBody(
16054         ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16055     MoveConstructor->markUsed(Context);
16056   }
16057 
16058   if (ASTMutationListener *L = getASTMutationListener()) {
16059     L->CompletedImplicitDefinition(MoveConstructor);
16060   }
16061 }
16062 
isImplicitlyDeleted(FunctionDecl * FD)16063 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16064   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16065 }
16066 
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)16067 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16068                             SourceLocation CurrentLocation,
16069                             CXXConversionDecl *Conv) {
16070   SynthesizedFunctionScope Scope(*this, Conv);
16071   assert(!Conv->getReturnType()->isUndeducedType());
16072 
16073   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16074   CallingConv CC =
16075       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16076 
16077   CXXRecordDecl *Lambda = Conv->getParent();
16078   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16079   FunctionDecl *Invoker =
16080       CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16081           ? CallOp
16082           : Lambda->getLambdaStaticInvoker(CC);
16083 
16084   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16085     CallOp = InstantiateFunctionDeclaration(
16086         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16087     if (!CallOp)
16088       return;
16089 
16090     if (CallOp != Invoker) {
16091       Invoker = InstantiateFunctionDeclaration(
16092           Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16093           CurrentLocation);
16094       if (!Invoker)
16095         return;
16096     }
16097   }
16098 
16099   if (CallOp->isInvalidDecl())
16100     return;
16101 
16102   // Mark the call operator referenced (and add to pending instantiations
16103   // if necessary).
16104   // For both the conversion and static-invoker template specializations
16105   // we construct their body's in this function, so no need to add them
16106   // to the PendingInstantiations.
16107   MarkFunctionReferenced(CurrentLocation, CallOp);
16108 
16109   if (Invoker != CallOp) {
16110     // Fill in the __invoke function with a dummy implementation. IR generation
16111     // will fill in the actual details. Update its type in case it contained
16112     // an 'auto'.
16113     Invoker->markUsed(Context);
16114     Invoker->setReferenced();
16115     Invoker->setType(Conv->getReturnType()->getPointeeType());
16116     Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16117   }
16118 
16119   // Construct the body of the conversion function { return __invoke; }.
16120   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16121                                        Conv->getLocation());
16122   assert(FunctionRef && "Can't refer to __invoke function?");
16123   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16124   Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
16125                                      Conv->getLocation(), Conv->getLocation()));
16126   Conv->markUsed(Context);
16127   Conv->setReferenced();
16128 
16129   if (ASTMutationListener *L = getASTMutationListener()) {
16130     L->CompletedImplicitDefinition(Conv);
16131     if (Invoker != CallOp)
16132       L->CompletedImplicitDefinition(Invoker);
16133   }
16134 }
16135 
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)16136 void Sema::DefineImplicitLambdaToBlockPointerConversion(
16137     SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16138   assert(!Conv->getParent()->isGenericLambda());
16139 
16140   SynthesizedFunctionScope Scope(*this, Conv);
16141 
16142   // Copy-initialize the lambda object as needed to capture it.
16143   Expr *This = ActOnCXXThis(CurrentLocation).get();
16144   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16145 
16146   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16147                                                         Conv->getLocation(),
16148                                                         Conv, DerefThis);
16149 
16150   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16151   // behavior.  Note that only the general conversion function does this
16152   // (since it's unusable otherwise); in the case where we inline the
16153   // block literal, it has block literal lifetime semantics.
16154   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16155     BuildBlock = ImplicitCastExpr::Create(
16156         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16157         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16158 
16159   if (BuildBlock.isInvalid()) {
16160     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16161     Conv->setInvalidDecl();
16162     return;
16163   }
16164 
16165   // Create the return statement that returns the block from the conversion
16166   // function.
16167   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16168   if (Return.isInvalid()) {
16169     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16170     Conv->setInvalidDecl();
16171     return;
16172   }
16173 
16174   // Set the body of the conversion function.
16175   Stmt *ReturnS = Return.get();
16176   Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
16177                                      Conv->getLocation(), Conv->getLocation()));
16178   Conv->markUsed(Context);
16179 
16180   // We're done; notify the mutation listener, if any.
16181   if (ASTMutationListener *L = getASTMutationListener()) {
16182     L->CompletedImplicitDefinition(Conv);
16183   }
16184 }
16185 
16186 /// Determine whether the given list arguments contains exactly one
16187 /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)16188 static bool hasOneRealArgument(MultiExprArg Args) {
16189   switch (Args.size()) {
16190   case 0:
16191     return false;
16192 
16193   default:
16194     if (!Args[1]->isDefaultArgument())
16195       return false;
16196 
16197     [[fallthrough]];
16198   case 1:
16199     return !Args[0]->isDefaultArgument();
16200   }
16201 
16202   return false;
16203 }
16204 
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,CXXConstructionKind ConstructKind,SourceRange ParenRange)16205 ExprResult Sema::BuildCXXConstructExpr(
16206     SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16207     CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16208     bool HadMultipleCandidates, bool IsListInitialization,
16209     bool IsStdInitListInitialization, bool RequiresZeroInit,
16210     CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16211   bool Elidable = false;
16212 
16213   // C++0x [class.copy]p34:
16214   //   When certain criteria are met, an implementation is allowed to
16215   //   omit the copy/move construction of a class object, even if the
16216   //   copy/move constructor and/or destructor for the object have
16217   //   side effects. [...]
16218   //     - when a temporary class object that has not been bound to a
16219   //       reference (12.2) would be copied/moved to a class object
16220   //       with the same cv-unqualified type, the copy/move operation
16221   //       can be omitted by constructing the temporary object
16222   //       directly into the target of the omitted copy/move
16223   if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16224       // FIXME: Converting constructors should also be accepted.
16225       // But to fix this, the logic that digs down into a CXXConstructExpr
16226       // to find the source object needs to handle it.
16227       // Right now it assumes the source object is passed directly as the
16228       // first argument.
16229       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16230     Expr *SubExpr = ExprArgs[0];
16231     // FIXME: Per above, this is also incorrect if we want to accept
16232     //        converting constructors, as isTemporaryObject will
16233     //        reject temporaries with different type from the
16234     //        CXXRecord itself.
16235     Elidable = SubExpr->isTemporaryObject(
16236         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16237   }
16238 
16239   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16240                                FoundDecl, Constructor,
16241                                Elidable, ExprArgs, HadMultipleCandidates,
16242                                IsListInitialization,
16243                                IsStdInitListInitialization, RequiresZeroInit,
16244                                ConstructKind, ParenRange);
16245 }
16246 
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,CXXConstructionKind ConstructKind,SourceRange ParenRange)16247 ExprResult Sema::BuildCXXConstructExpr(
16248     SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16249     CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16250     bool HadMultipleCandidates, bool IsListInitialization,
16251     bool IsStdInitListInitialization, bool RequiresZeroInit,
16252     CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16253   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16254     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16255     // The only way to get here is if we did overload resolution to find the
16256     // shadow decl, so we don't need to worry about re-checking the trailing
16257     // requires clause.
16258     if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16259       return ExprError();
16260   }
16261 
16262   return BuildCXXConstructExpr(
16263       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16264       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16265       RequiresZeroInit, ConstructKind, ParenRange);
16266 }
16267 
16268 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
16269 /// including handling of its default argument expressions.
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,CXXConstructionKind ConstructKind,SourceRange ParenRange)16270 ExprResult Sema::BuildCXXConstructExpr(
16271     SourceLocation ConstructLoc, QualType DeclInitType,
16272     CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16273     bool HadMultipleCandidates, bool IsListInitialization,
16274     bool IsStdInitListInitialization, bool RequiresZeroInit,
16275     CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16276   assert(declaresSameEntity(
16277              Constructor->getParent(),
16278              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16279          "given constructor for wrong type");
16280   MarkFunctionReferenced(ConstructLoc, Constructor);
16281   if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16282     return ExprError();
16283 
16284   return CheckForImmediateInvocation(
16285       CXXConstructExpr::Create(
16286           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16287           HadMultipleCandidates, IsListInitialization,
16288           IsStdInitListInitialization, RequiresZeroInit,
16289           static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16290       Constructor);
16291 }
16292 
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)16293 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16294   if (VD->isInvalidDecl()) return;
16295   // If initializing the variable failed, don't also diagnose problems with
16296   // the destructor, they're likely related.
16297   if (VD->getInit() && VD->getInit()->containsErrors())
16298     return;
16299 
16300   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16301   if (ClassDecl->isInvalidDecl()) return;
16302   if (ClassDecl->hasIrrelevantDestructor()) return;
16303   if (ClassDecl->isDependentContext()) return;
16304 
16305   if (VD->isNoDestroy(getASTContext()))
16306     return;
16307 
16308   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16309   // The result of `LookupDestructor` might be nullptr if the destructor is
16310   // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16311   // will not be selected by `CXXRecordDecl::getDestructor()`.
16312   if (!Destructor)
16313     return;
16314   // If this is an array, we'll require the destructor during initialization, so
16315   // we can skip over this. We still want to emit exit-time destructor warnings
16316   // though.
16317   if (!VD->getType()->isArrayType()) {
16318     MarkFunctionReferenced(VD->getLocation(), Destructor);
16319     CheckDestructorAccess(VD->getLocation(), Destructor,
16320                           PDiag(diag::err_access_dtor_var)
16321                               << VD->getDeclName() << VD->getType());
16322     DiagnoseUseOfDecl(Destructor, VD->getLocation());
16323   }
16324 
16325   if (Destructor->isTrivial()) return;
16326 
16327   // If the destructor is constexpr, check whether the variable has constant
16328   // destruction now.
16329   if (Destructor->isConstexpr()) {
16330     bool HasConstantInit = false;
16331     if (VD->getInit() && !VD->getInit()->isValueDependent())
16332       HasConstantInit = VD->evaluateValue();
16333     SmallVector<PartialDiagnosticAt, 8> Notes;
16334     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16335         HasConstantInit) {
16336       Diag(VD->getLocation(),
16337            diag::err_constexpr_var_requires_const_destruction) << VD;
16338       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16339         Diag(Notes[I].first, Notes[I].second);
16340     }
16341   }
16342 
16343   if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16344     return;
16345 
16346   // Emit warning for non-trivial dtor in global scope (a real global,
16347   // class-static, function-static).
16348   if (!VD->hasAttr<AlwaysDestroyAttr>())
16349     Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16350 
16351   // TODO: this should be re-enabled for static locals by !CXAAtExit
16352   if (!VD->isStaticLocal())
16353     Diag(VD->getLocation(), diag::warn_global_destructor);
16354 }
16355 
CompleteConstructorCall(CXXConstructorDecl * Constructor,QualType DeclInitType,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit,bool IsListInitialization)16356 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16357                                    QualType DeclInitType, MultiExprArg ArgsPtr,
16358                                    SourceLocation Loc,
16359                                    SmallVectorImpl<Expr *> &ConvertedArgs,
16360                                    bool AllowExplicit,
16361                                    bool IsListInitialization) {
16362   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16363   unsigned NumArgs = ArgsPtr.size();
16364   Expr **Args = ArgsPtr.data();
16365 
16366   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16367   unsigned NumParams = Proto->getNumParams();
16368 
16369   // If too few arguments are available, we'll fill in the rest with defaults.
16370   if (NumArgs < NumParams)
16371     ConvertedArgs.reserve(NumParams);
16372   else
16373     ConvertedArgs.reserve(NumArgs);
16374 
16375   VariadicCallType CallType = Proto->isVariadic()
16376                                   ? VariadicCallType::Constructor
16377                                   : VariadicCallType::DoesNotApply;
16378   SmallVector<Expr *, 8> AllArgs;
16379   bool Invalid = GatherArgumentsForCall(
16380       Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16381       CallType, AllowExplicit, IsListInitialization);
16382   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16383 
16384   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16385 
16386   CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16387                        Proto, Loc);
16388 
16389   return Invalid;
16390 }
16391 
ShouldUseTypeAwareOperatorNewOrDelete() const16392 TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16393   bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16394   return typeAwareAllocationModeFromBool(SeenTypedOperators);
16395 }
16396 
16397 FunctionDecl *
BuildTypeAwareUsualDelete(FunctionTemplateDecl * FnTemplateDecl,QualType DeallocType,SourceLocation Loc)16398 Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16399                                 QualType DeallocType, SourceLocation Loc) {
16400   if (DeallocType.isNull())
16401     return nullptr;
16402 
16403   FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16404   if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16405     return nullptr;
16406 
16407   if (FnDecl->isVariadic())
16408     return nullptr;
16409 
16410   unsigned NumParams = FnDecl->getNumParams();
16411   constexpr unsigned RequiredParameterCount =
16412       FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16413   // A usual deallocation function has no placement parameters
16414   if (NumParams != RequiredParameterCount)
16415     return nullptr;
16416 
16417   // A type aware allocation is only usual if the only dependent parameter is
16418   // the first parameter.
16419   if (llvm::any_of(FnDecl->parameters().drop_front(),
16420                    [](const ParmVarDecl *ParamDecl) {
16421                      return ParamDecl->getType()->isDependentType();
16422                    }))
16423     return nullptr;
16424 
16425   QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16426   if (SpecializedTypeIdentity.isNull())
16427     return nullptr;
16428 
16429   SmallVector<QualType, RequiredParameterCount> ArgTypes;
16430   ArgTypes.reserve(NumParams);
16431 
16432   // The first parameter to a type aware operator delete is by definition the
16433   // type-identity argument, so we explicitly set this to the target
16434   // type-identity type, the remaining usual parameters should then simply match
16435   // the type declared in the function template.
16436   ArgTypes.push_back(SpecializedTypeIdentity);
16437   for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16438     ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16439 
16440   FunctionProtoType::ExtProtoInfo EPI;
16441   QualType ExpectedFunctionType =
16442       Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16443   sema::TemplateDeductionInfo Info(Loc);
16444   FunctionDecl *Result;
16445   if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16446                               Result, Info) != TemplateDeductionResult::Success)
16447     return nullptr;
16448   return Result;
16449 }
16450 
16451 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)16452 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16453                                        const FunctionDecl *FnDecl) {
16454   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16455   if (isa<NamespaceDecl>(DC)) {
16456     return SemaRef.Diag(FnDecl->getLocation(),
16457                         diag::err_operator_new_delete_declared_in_namespace)
16458       << FnDecl->getDeclName();
16459   }
16460 
16461   if (isa<TranslationUnitDecl>(DC) &&
16462       FnDecl->getStorageClass() == SC_Static) {
16463     return SemaRef.Diag(FnDecl->getLocation(),
16464                         diag::err_operator_new_delete_declared_static)
16465       << FnDecl->getDeclName();
16466   }
16467 
16468   return false;
16469 }
16470 
RemoveAddressSpaceFromPtr(Sema & SemaRef,const PointerType * PtrTy)16471 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16472                                              const PointerType *PtrTy) {
16473   auto &Ctx = SemaRef.Context;
16474   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16475   PtrQuals.removeAddressSpace();
16476   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16477       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16478 }
16479 
16480 enum class AllocationOperatorKind { New, Delete };
16481 
IsPotentiallyTypeAwareOperatorNewOrDelete(Sema & SemaRef,const FunctionDecl * FD,bool * WasMalformed)16482 static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16483                                                       const FunctionDecl *FD,
16484                                                       bool *WasMalformed) {
16485   const Decl *MalformedDecl = nullptr;
16486   if (FD->getNumParams() > 0 &&
16487       SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16488                                 /*TypeArgument=*/nullptr, &MalformedDecl))
16489     return true;
16490 
16491   if (!MalformedDecl)
16492     return false;
16493 
16494   if (WasMalformed)
16495     *WasMalformed = true;
16496 
16497   return true;
16498 }
16499 
isDestroyingDeleteT(QualType Type)16500 static bool isDestroyingDeleteT(QualType Type) {
16501   auto *RD = Type->getAsCXXRecordDecl();
16502   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16503          RD->getIdentifier()->isStr("destroying_delete_t");
16504 }
16505 
IsPotentiallyDestroyingOperatorDelete(Sema & SemaRef,const FunctionDecl * FD)16506 static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16507                                                   const FunctionDecl *FD) {
16508   // C++ P0722:
16509   //   Within a class C, a single object deallocation function with signature
16510   //     (T, std::destroying_delete_t, <more params>)
16511   //   is a destroying operator delete.
16512   bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16513       SemaRef, FD, /*WasMalformed=*/nullptr);
16514   unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16515   return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16516          FD->getNumParams() > DestroyingDeleteIdx &&
16517          isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16518 }
16519 
CheckOperatorNewDeleteTypes(Sema & SemaRef,FunctionDecl * FnDecl,AllocationOperatorKind OperatorKind,CanQualType ExpectedResultType,CanQualType ExpectedSizeOrAddressParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)16520 static inline bool CheckOperatorNewDeleteTypes(
16521     Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16522     CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16523     unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16524   auto NormalizeType = [&SemaRef](QualType T) {
16525     if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16526       // The operator is valid on any address space for OpenCL.
16527       // Drop address space from actual and expected result types.
16528       if (const auto PtrTy = T->template getAs<PointerType>())
16529         T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16530     }
16531     return SemaRef.Context.getCanonicalType(T);
16532   };
16533 
16534   const unsigned NumParams = FnDecl->getNumParams();
16535   unsigned FirstNonTypeParam = 0;
16536   bool MalformedTypeIdentity = false;
16537   bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16538       SemaRef, FnDecl, &MalformedTypeIdentity);
16539   unsigned MinimumMandatoryArgumentCount = 1;
16540   unsigned SizeParameterIndex = 0;
16541   if (IsPotentiallyTypeAware) {
16542     // We don't emit this diagnosis for template instantiations as we will
16543     // have already emitted it for the original template declaration.
16544     if (!FnDecl->isTemplateInstantiation())
16545       SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16546 
16547     if (OperatorKind == AllocationOperatorKind::New) {
16548       SizeParameterIndex = 1;
16549       MinimumMandatoryArgumentCount =
16550           FunctionDecl::RequiredTypeAwareNewParameterCount;
16551     } else {
16552       SizeParameterIndex = 2;
16553       MinimumMandatoryArgumentCount =
16554           FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16555     }
16556     FirstNonTypeParam = 1;
16557   }
16558 
16559   bool IsPotentiallyDestroyingDelete =
16560       IsPotentiallyDestroyingOperatorDelete(SemaRef, FnDecl);
16561 
16562   if (IsPotentiallyDestroyingDelete) {
16563     ++MinimumMandatoryArgumentCount;
16564     ++SizeParameterIndex;
16565   }
16566 
16567   if (NumParams < MinimumMandatoryArgumentCount)
16568     return SemaRef.Diag(FnDecl->getLocation(),
16569                         diag::err_operator_new_delete_too_few_parameters)
16570            << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16571            << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16572 
16573   for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16574     const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16575     if (ParamDecl->hasDefaultArg())
16576       return SemaRef.Diag(FnDecl->getLocation(),
16577                           diag::err_operator_new_default_arg)
16578              << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16579   }
16580 
16581   auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16582   QualType CanResultType = NormalizeType(FnType->getReturnType());
16583   QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16584   QualType CanExpectedSizeOrAddressParamType =
16585       NormalizeType(ExpectedSizeOrAddressParamType);
16586 
16587   // Check that the result type is what we expect.
16588   if (CanResultType != CanExpectedResultType) {
16589     // Reject even if the type is dependent; an operator delete function is
16590     // required to have a non-dependent result type.
16591     return SemaRef.Diag(
16592                FnDecl->getLocation(),
16593                CanResultType->isDependentType()
16594                    ? diag::err_operator_new_delete_dependent_result_type
16595                    : diag::err_operator_new_delete_invalid_result_type)
16596            << FnDecl->getDeclName() << ExpectedResultType;
16597   }
16598 
16599   // A function template must have at least 2 parameters.
16600   if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16601     return SemaRef.Diag(FnDecl->getLocation(),
16602                       diag::err_operator_new_delete_template_too_few_parameters)
16603         << FnDecl->getDeclName();
16604 
16605   auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16606                        auto FallbackType) -> bool {
16607     const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16608     if (ExpectedType.isNull()) {
16609       return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16610              << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16611              << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16612              << ParamDecl->getSourceRange();
16613     }
16614     CanQualType CanExpectedTy =
16615         NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16616     auto ActualParamType =
16617         NormalizeType(ParamDecl->getType().getUnqualifiedType());
16618     if (ActualParamType == CanExpectedTy)
16619       return false;
16620     unsigned Diagnostic = ActualParamType->isDependentType()
16621                               ? DependentParamTypeDiag
16622                               : InvalidParamTypeDiag;
16623     return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16624            << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16625            << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16626            << FallbackType << ParamDecl->getSourceRange();
16627   };
16628 
16629   // Check that the first parameter type is what we expect.
16630   if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16631     return true;
16632 
16633   FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16634 
16635   // If the first parameter type is not a type-identity we're done, otherwise
16636   // we need to ensure the size and alignment parameters have the correct type
16637   if (!IsPotentiallyTypeAware)
16638     return false;
16639 
16640   if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16641     return true;
16642   TypeDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16643   QualType StdAlignValT =
16644       StdAlignValTDecl ? SemaRef.Context.getTypeDeclType(StdAlignValTDecl)
16645                        : QualType();
16646   if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16647     return true;
16648 
16649   FnDecl->setIsTypeAwareOperatorNewOrDelete();
16650   return MalformedTypeIdentity;
16651 }
16652 
CheckOperatorNewDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)16653 static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16654   // C++ [basic.stc.dynamic.allocation]p1:
16655   //   A program is ill-formed if an allocation function is declared in a
16656   //   namespace scope other than global scope or declared static in global
16657   //   scope.
16658   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16659     return true;
16660 
16661   CanQualType SizeTy =
16662     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16663 
16664   // C++ [basic.stc.dynamic.allocation]p1:
16665   //  The return type shall be void*. The first parameter shall have type
16666   //  std::size_t.
16667   return CheckOperatorNewDeleteTypes(
16668       SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16669       SizeTy, diag::err_operator_new_dependent_param_type,
16670       diag::err_operator_new_param_type);
16671 }
16672 
16673 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)16674 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16675   // C++ [basic.stc.dynamic.deallocation]p1:
16676   //   A program is ill-formed if deallocation functions are declared in a
16677   //   namespace scope other than global scope or declared static in global
16678   //   scope.
16679   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16680     return true;
16681 
16682   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16683   auto ConstructDestroyingDeleteAddressType = [&]() {
16684     assert(MD);
16685     return SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16686         SemaRef.Context.getRecordType(MD->getParent())));
16687   };
16688 
16689   // C++ P2719: A destroying operator delete cannot be type aware
16690   // so for QoL we actually check for this explicitly by considering
16691   // an destroying-delete appropriate address type and the presence of
16692   // any parameter of type destroying_delete_t as an erroneous attempt
16693   // to declare a type aware destroying delete, rather than emitting a
16694   // pile of incorrect parameter type errors.
16695   if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16696                 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16697     QualType AddressParamType =
16698         SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16699     if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16700         AddressParamType == ConstructDestroyingDeleteAddressType()) {
16701       // The address parameter type implies an author trying to construct a
16702       // type aware destroying delete, so we'll see if we can find a parameter
16703       // of type `std::destroying_delete_t`, and if we find it we'll report
16704       // this as being an attempt at a type aware destroying delete just stop
16705       // here. If we don't do this, the resulting incorrect parameter ordering
16706       // results in a pile mismatched argument type errors that don't explain
16707       // the core problem.
16708       for (auto Param : MD->parameters()) {
16709         if (isDestroyingDeleteT(Param->getType())) {
16710           SemaRef.Diag(MD->getLocation(),
16711                        diag::err_type_aware_destroying_operator_delete)
16712               << Param->getSourceRange();
16713           return true;
16714         }
16715       }
16716     }
16717   }
16718 
16719   // C++ P0722:
16720   //   Within a class C, the first parameter of a destroying operator delete
16721   //   shall be of type C *. The first parameter of any other deallocation
16722   //   function shall be of type void *.
16723   CanQualType ExpectedAddressParamType =
16724       MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16725           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16726                 SemaRef.Context.getRecordType(MD->getParent())))
16727           : SemaRef.Context.VoidPtrTy;
16728 
16729   // C++ [basic.stc.dynamic.deallocation]p2:
16730   //   Each deallocation function shall return void
16731   if (CheckOperatorNewDeleteTypes(
16732           SemaRef, FnDecl, AllocationOperatorKind::Delete,
16733           SemaRef.Context.VoidTy, ExpectedAddressParamType,
16734           diag::err_operator_delete_dependent_param_type,
16735           diag::err_operator_delete_param_type))
16736     return true;
16737 
16738   // C++ P0722:
16739   //   A destroying operator delete shall be a usual deallocation function.
16740   if (MD && !MD->getParent()->isDependentContext() &&
16741       MD->isDestroyingOperatorDelete()) {
16742     if (!SemaRef.isUsualDeallocationFunction(MD)) {
16743       SemaRef.Diag(MD->getLocation(),
16744                    diag::err_destroying_operator_delete_not_usual);
16745       return true;
16746     }
16747   }
16748 
16749   return false;
16750 }
16751 
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)16752 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16753   assert(FnDecl && FnDecl->isOverloadedOperator() &&
16754          "Expected an overloaded operator declaration");
16755 
16756   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16757 
16758   // C++ [over.oper]p5:
16759   //   The allocation and deallocation functions, operator new,
16760   //   operator new[], operator delete and operator delete[], are
16761   //   described completely in 3.7.3. The attributes and restrictions
16762   //   found in the rest of this subclause do not apply to them unless
16763   //   explicitly stated in 3.7.3.
16764   if (Op == OO_Delete || Op == OO_Array_Delete)
16765     return CheckOperatorDeleteDeclaration(*this, FnDecl);
16766 
16767   if (Op == OO_New || Op == OO_Array_New)
16768     return CheckOperatorNewDeclaration(*this, FnDecl);
16769 
16770   // C++ [over.oper]p7:
16771   //   An operator function shall either be a member function or
16772   //   be a non-member function and have at least one parameter
16773   //   whose type is a class, a reference to a class, an enumeration,
16774   //   or a reference to an enumeration.
16775   // Note: Before C++23, a member function could not be static. The only member
16776   //       function allowed to be static is the call operator function.
16777   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16778     if (MethodDecl->isStatic()) {
16779       if (Op == OO_Call || Op == OO_Subscript)
16780         Diag(FnDecl->getLocation(),
16781              (LangOpts.CPlusPlus23
16782                   ? diag::warn_cxx20_compat_operator_overload_static
16783                   : diag::ext_operator_overload_static))
16784             << FnDecl;
16785       else
16786         return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16787                << FnDecl;
16788     }
16789   } else {
16790     bool ClassOrEnumParam = false;
16791     for (auto *Param : FnDecl->parameters()) {
16792       QualType ParamType = Param->getType().getNonReferenceType();
16793       if (ParamType->isDependentType() || ParamType->isRecordType() ||
16794           ParamType->isEnumeralType()) {
16795         ClassOrEnumParam = true;
16796         break;
16797       }
16798     }
16799 
16800     if (!ClassOrEnumParam)
16801       return Diag(FnDecl->getLocation(),
16802                   diag::err_operator_overload_needs_class_or_enum)
16803         << FnDecl->getDeclName();
16804   }
16805 
16806   // C++ [over.oper]p8:
16807   //   An operator function cannot have default arguments (8.3.6),
16808   //   except where explicitly stated below.
16809   //
16810   // Only the function-call operator (C++ [over.call]p1) and the subscript
16811   // operator (CWG2507) allow default arguments.
16812   if (Op != OO_Call) {
16813     ParmVarDecl *FirstDefaultedParam = nullptr;
16814     for (auto *Param : FnDecl->parameters()) {
16815       if (Param->hasDefaultArg()) {
16816         FirstDefaultedParam = Param;
16817         break;
16818       }
16819     }
16820     if (FirstDefaultedParam) {
16821       if (Op == OO_Subscript) {
16822         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16823                                         ? diag::ext_subscript_overload
16824                                         : diag::error_subscript_overload)
16825             << FnDecl->getDeclName() << 1
16826             << FirstDefaultedParam->getDefaultArgRange();
16827       } else {
16828         return Diag(FirstDefaultedParam->getLocation(),
16829                     diag::err_operator_overload_default_arg)
16830                << FnDecl->getDeclName()
16831                << FirstDefaultedParam->getDefaultArgRange();
16832       }
16833     }
16834   }
16835 
16836   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16837     { false, false, false }
16838 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16839     , { Unary, Binary, MemberOnly }
16840 #include "clang/Basic/OperatorKinds.def"
16841   };
16842 
16843   bool CanBeUnaryOperator = OperatorUses[Op][0];
16844   bool CanBeBinaryOperator = OperatorUses[Op][1];
16845   bool MustBeMemberOperator = OperatorUses[Op][2];
16846 
16847   // C++ [over.oper]p8:
16848   //   [...] Operator functions cannot have more or fewer parameters
16849   //   than the number required for the corresponding operator, as
16850   //   described in the rest of this subclause.
16851   unsigned NumParams = FnDecl->getNumParams() +
16852                        (isa<CXXMethodDecl>(FnDecl) &&
16853                                 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16854                             ? 1
16855                             : 0);
16856   if (Op != OO_Call && Op != OO_Subscript &&
16857       ((NumParams == 1 && !CanBeUnaryOperator) ||
16858        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16859        (NumParams > 2))) {
16860     // We have the wrong number of parameters.
16861     unsigned ErrorKind;
16862     if (CanBeUnaryOperator && CanBeBinaryOperator) {
16863       ErrorKind = 2;  // 2 -> unary or binary.
16864     } else if (CanBeUnaryOperator) {
16865       ErrorKind = 0;  // 0 -> unary
16866     } else {
16867       assert(CanBeBinaryOperator &&
16868              "All non-call overloaded operators are unary or binary!");
16869       ErrorKind = 1;  // 1 -> binary
16870     }
16871     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16872       << FnDecl->getDeclName() << NumParams << ErrorKind;
16873   }
16874 
16875   if (Op == OO_Subscript && NumParams != 2) {
16876     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16877                                     ? diag::ext_subscript_overload
16878                                     : diag::error_subscript_overload)
16879         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16880   }
16881 
16882   // Overloaded operators other than operator() and operator[] cannot be
16883   // variadic.
16884   if (Op != OO_Call &&
16885       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16886     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16887            << FnDecl->getDeclName();
16888   }
16889 
16890   // Some operators must be member functions.
16891   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16892     return Diag(FnDecl->getLocation(),
16893                 diag::err_operator_overload_must_be_member)
16894       << FnDecl->getDeclName();
16895   }
16896 
16897   // C++ [over.inc]p1:
16898   //   The user-defined function called operator++ implements the
16899   //   prefix and postfix ++ operator. If this function is a member
16900   //   function with no parameters, or a non-member function with one
16901   //   parameter of class or enumeration type, it defines the prefix
16902   //   increment operator ++ for objects of that type. If the function
16903   //   is a member function with one parameter (which shall be of type
16904   //   int) or a non-member function with two parameters (the second
16905   //   of which shall be of type int), it defines the postfix
16906   //   increment operator ++ for objects of that type.
16907   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16908     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16909     QualType ParamType = LastParam->getType();
16910 
16911     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16912         !ParamType->isDependentType())
16913       return Diag(LastParam->getLocation(),
16914                   diag::err_operator_overload_post_incdec_must_be_int)
16915         << LastParam->getType() << (Op == OO_MinusMinus);
16916   }
16917 
16918   return false;
16919 }
16920 
16921 static bool
checkLiteralOperatorTemplateParameterList(Sema & SemaRef,FunctionTemplateDecl * TpDecl)16922 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16923                                           FunctionTemplateDecl *TpDecl) {
16924   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16925 
16926   // Must have one or two template parameters.
16927   if (TemplateParams->size() == 1) {
16928     NonTypeTemplateParmDecl *PmDecl =
16929         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16930 
16931     // The template parameter must be a char parameter pack.
16932     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16933         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16934       return false;
16935 
16936     // C++20 [over.literal]p5:
16937     //   A string literal operator template is a literal operator template
16938     //   whose template-parameter-list comprises a single non-type
16939     //   template-parameter of class type.
16940     //
16941     // As a DR resolution, we also allow placeholders for deduced class
16942     // template specializations.
16943     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16944         !PmDecl->isTemplateParameterPack() &&
16945         (PmDecl->getType()->isRecordType() ||
16946          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16947       return false;
16948   } else if (TemplateParams->size() == 2) {
16949     TemplateTypeParmDecl *PmType =
16950         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16951     NonTypeTemplateParmDecl *PmArgs =
16952         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16953 
16954     // The second template parameter must be a parameter pack with the
16955     // first template parameter as its type.
16956     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16957         PmArgs->isTemplateParameterPack()) {
16958       const TemplateTypeParmType *TArgs =
16959           PmArgs->getType()->getAs<TemplateTypeParmType>();
16960       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16961           TArgs->getIndex() == PmType->getIndex()) {
16962         if (!SemaRef.inTemplateInstantiation())
16963           SemaRef.Diag(TpDecl->getLocation(),
16964                        diag::ext_string_literal_operator_template);
16965         return false;
16966       }
16967     }
16968   }
16969 
16970   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16971                diag::err_literal_operator_template)
16972       << TpDecl->getTemplateParameters()->getSourceRange();
16973   return true;
16974 }
16975 
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)16976 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16977   if (isa<CXXMethodDecl>(FnDecl)) {
16978     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16979       << FnDecl->getDeclName();
16980     return true;
16981   }
16982 
16983   if (FnDecl->isExternC()) {
16984     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16985     if (const LinkageSpecDecl *LSD =
16986             FnDecl->getDeclContext()->getExternCContext())
16987       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16988     return true;
16989   }
16990 
16991   // This might be the definition of a literal operator template.
16992   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16993 
16994   // This might be a specialization of a literal operator template.
16995   if (!TpDecl)
16996     TpDecl = FnDecl->getPrimaryTemplate();
16997 
16998   // template <char...> type operator "" name() and
16999   // template <class T, T...> type operator "" name() are the only valid
17000   // template signatures, and the only valid signatures with no parameters.
17001   //
17002   // C++20 also allows template <SomeClass T> type operator "" name().
17003   if (TpDecl) {
17004     if (FnDecl->param_size() != 0) {
17005       Diag(FnDecl->getLocation(),
17006            diag::err_literal_operator_template_with_params);
17007       return true;
17008     }
17009 
17010     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
17011       return true;
17012 
17013   } else if (FnDecl->param_size() == 1) {
17014     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17015 
17016     QualType ParamType = Param->getType().getUnqualifiedType();
17017 
17018     // Only unsigned long long int, long double, any character type, and const
17019     // char * are allowed as the only parameters.
17020     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17021         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17022         Context.hasSameType(ParamType, Context.CharTy) ||
17023         Context.hasSameType(ParamType, Context.WideCharTy) ||
17024         Context.hasSameType(ParamType, Context.Char8Ty) ||
17025         Context.hasSameType(ParamType, Context.Char16Ty) ||
17026         Context.hasSameType(ParamType, Context.Char32Ty)) {
17027     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17028       QualType InnerType = Ptr->getPointeeType();
17029 
17030       // Pointer parameter must be a const char *.
17031       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17032                                 Context.CharTy) &&
17033             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17034         Diag(Param->getSourceRange().getBegin(),
17035              diag::err_literal_operator_param)
17036             << ParamType << "'const char *'" << Param->getSourceRange();
17037         return true;
17038       }
17039 
17040     } else if (ParamType->isRealFloatingType()) {
17041       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17042           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17043       return true;
17044 
17045     } else if (ParamType->isIntegerType()) {
17046       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17047           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17048       return true;
17049 
17050     } else {
17051       Diag(Param->getSourceRange().getBegin(),
17052            diag::err_literal_operator_invalid_param)
17053           << ParamType << Param->getSourceRange();
17054       return true;
17055     }
17056 
17057   } else if (FnDecl->param_size() == 2) {
17058     FunctionDecl::param_iterator Param = FnDecl->param_begin();
17059 
17060     // First, verify that the first parameter is correct.
17061 
17062     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17063 
17064     // Two parameter function must have a pointer to const as a
17065     // first parameter; let's strip those qualifiers.
17066     const PointerType *PT = FirstParamType->getAs<PointerType>();
17067 
17068     if (!PT) {
17069       Diag((*Param)->getSourceRange().getBegin(),
17070            diag::err_literal_operator_param)
17071           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17072       return true;
17073     }
17074 
17075     QualType PointeeType = PT->getPointeeType();
17076     // First parameter must be const
17077     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17078       Diag((*Param)->getSourceRange().getBegin(),
17079            diag::err_literal_operator_param)
17080           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17081       return true;
17082     }
17083 
17084     QualType InnerType = PointeeType.getUnqualifiedType();
17085     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17086     // const char32_t* are allowed as the first parameter to a two-parameter
17087     // function
17088     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17089           Context.hasSameType(InnerType, Context.WideCharTy) ||
17090           Context.hasSameType(InnerType, Context.Char8Ty) ||
17091           Context.hasSameType(InnerType, Context.Char16Ty) ||
17092           Context.hasSameType(InnerType, Context.Char32Ty))) {
17093       Diag((*Param)->getSourceRange().getBegin(),
17094            diag::err_literal_operator_param)
17095           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17096       return true;
17097     }
17098 
17099     // Move on to the second and final parameter.
17100     ++Param;
17101 
17102     // The second parameter must be a std::size_t.
17103     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17104     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17105       Diag((*Param)->getSourceRange().getBegin(),
17106            diag::err_literal_operator_param)
17107           << SecondParamType << Context.getSizeType()
17108           << (*Param)->getSourceRange();
17109       return true;
17110     }
17111   } else {
17112     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17113     return true;
17114   }
17115 
17116   // Parameters are good.
17117 
17118   // A parameter-declaration-clause containing a default argument is not
17119   // equivalent to any of the permitted forms.
17120   for (auto *Param : FnDecl->parameters()) {
17121     if (Param->hasDefaultArg()) {
17122       Diag(Param->getDefaultArgRange().getBegin(),
17123            diag::err_literal_operator_default_argument)
17124         << Param->getDefaultArgRange();
17125       break;
17126     }
17127   }
17128 
17129   const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17130   ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17131   if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17132       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17133     // C++23 [usrlit.suffix]p1:
17134     //   Literal suffix identifiers that do not start with an underscore are
17135     //   reserved for future standardization. Literal suffix identifiers that
17136     //   contain a double underscore __ are reserved for use by C++
17137     //   implementations.
17138     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17139         << static_cast<int>(Status)
17140         << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
17141   }
17142 
17143   return false;
17144 }
17145 
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,Expr * LangStr,SourceLocation LBraceLoc)17146 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17147                                            Expr *LangStr,
17148                                            SourceLocation LBraceLoc) {
17149   StringLiteral *Lit = cast<StringLiteral>(LangStr);
17150   assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17151 
17152   StringRef Lang = Lit->getString();
17153   LinkageSpecLanguageIDs Language;
17154   if (Lang == "C")
17155     Language = LinkageSpecLanguageIDs::C;
17156   else if (Lang == "C++")
17157     Language = LinkageSpecLanguageIDs::CXX;
17158   else {
17159     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17160       << LangStr->getSourceRange();
17161     return nullptr;
17162   }
17163 
17164   // FIXME: Add all the various semantics of linkage specifications
17165 
17166   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
17167                                                LangStr->getExprLoc(), Language,
17168                                                LBraceLoc.isValid());
17169 
17170   /// C++ [module.unit]p7.2.3
17171   /// - Otherwise, if the declaration
17172   ///   - ...
17173   ///   - ...
17174   ///   - appears within a linkage-specification,
17175   ///   it is attached to the global module.
17176   ///
17177   /// If the declaration is already in global module fragment, we don't
17178   /// need to attach it again.
17179   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17180     Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17181     D->setLocalOwningModule(GlobalModule);
17182   }
17183 
17184   CurContext->addDecl(D);
17185   PushDeclContext(S, D);
17186   return D;
17187 }
17188 
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)17189 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17190                                             Decl *LinkageSpec,
17191                                             SourceLocation RBraceLoc) {
17192   if (RBraceLoc.isValid()) {
17193     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17194     LSDecl->setRBraceLoc(RBraceLoc);
17195   }
17196 
17197   // If the current module doesn't has Parent, it implies that the
17198   // LinkageSpec isn't in the module created by itself. So we don't
17199   // need to pop it.
17200   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17201       getCurrentModule()->isImplicitGlobalModule() &&
17202       getCurrentModule()->Parent)
17203     PopImplicitGlobalModuleFragment();
17204 
17205   PopDeclContext();
17206   return LinkageSpec;
17207 }
17208 
ActOnEmptyDeclaration(Scope * S,const ParsedAttributesView & AttrList,SourceLocation SemiLoc)17209 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17210                                   const ParsedAttributesView &AttrList,
17211                                   SourceLocation SemiLoc) {
17212   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17213   // Attribute declarations appertain to empty declaration so we handle
17214   // them here.
17215   ProcessDeclAttributeList(S, ED, AttrList);
17216 
17217   CurContext->addDecl(ED);
17218   return ED;
17219 }
17220 
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,const IdentifierInfo * Name)17221 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17222                                          SourceLocation StartLoc,
17223                                          SourceLocation Loc,
17224                                          const IdentifierInfo *Name) {
17225   bool Invalid = false;
17226   QualType ExDeclType = TInfo->getType();
17227 
17228   // Arrays and functions decay.
17229   if (ExDeclType->isArrayType())
17230     ExDeclType = Context.getArrayDecayedType(ExDeclType);
17231   else if (ExDeclType->isFunctionType())
17232     ExDeclType = Context.getPointerType(ExDeclType);
17233 
17234   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17235   // The exception-declaration shall not denote a pointer or reference to an
17236   // incomplete type, other than [cv] void*.
17237   // N2844 forbids rvalue references.
17238   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17239     Diag(Loc, diag::err_catch_rvalue_ref);
17240     Invalid = true;
17241   }
17242 
17243   if (ExDeclType->isVariablyModifiedType()) {
17244     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17245     Invalid = true;
17246   }
17247 
17248   QualType BaseType = ExDeclType;
17249   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17250   unsigned DK = diag::err_catch_incomplete;
17251   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17252     BaseType = Ptr->getPointeeType();
17253     Mode = 1;
17254     DK = diag::err_catch_incomplete_ptr;
17255   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17256     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17257     BaseType = Ref->getPointeeType();
17258     Mode = 2;
17259     DK = diag::err_catch_incomplete_ref;
17260   }
17261   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17262       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17263     Invalid = true;
17264 
17265   if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17266     Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17267     Invalid = true;
17268   }
17269 
17270   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17271     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17272     Invalid = true;
17273   }
17274 
17275   if (!Invalid && !ExDeclType->isDependentType() &&
17276       RequireNonAbstractType(Loc, ExDeclType,
17277                              diag::err_abstract_type_in_decl,
17278                              AbstractVariableType))
17279     Invalid = true;
17280 
17281   // Only the non-fragile NeXT runtime currently supports C++ catches
17282   // of ObjC types, and no runtime supports catching ObjC types by value.
17283   if (!Invalid && getLangOpts().ObjC) {
17284     QualType T = ExDeclType;
17285     if (const ReferenceType *RT = T->getAs<ReferenceType>())
17286       T = RT->getPointeeType();
17287 
17288     if (T->isObjCObjectType()) {
17289       Diag(Loc, diag::err_objc_object_catch);
17290       Invalid = true;
17291     } else if (T->isObjCObjectPointerType()) {
17292       // FIXME: should this be a test for macosx-fragile specifically?
17293       if (getLangOpts().ObjCRuntime.isFragile())
17294         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17295     }
17296   }
17297 
17298   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17299                                     ExDeclType, TInfo, SC_None);
17300   ExDecl->setExceptionVariable(true);
17301 
17302   // In ARC, infer 'retaining' for variables of retainable type.
17303   if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17304     Invalid = true;
17305 
17306   if (!Invalid && !ExDeclType->isDependentType()) {
17307     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17308       // Insulate this from anything else we might currently be parsing.
17309       EnterExpressionEvaluationContext scope(
17310           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17311 
17312       // C++ [except.handle]p16:
17313       //   The object declared in an exception-declaration or, if the
17314       //   exception-declaration does not specify a name, a temporary (12.2) is
17315       //   copy-initialized (8.5) from the exception object. [...]
17316       //   The object is destroyed when the handler exits, after the destruction
17317       //   of any automatic objects initialized within the handler.
17318       //
17319       // We just pretend to initialize the object with itself, then make sure
17320       // it can be destroyed later.
17321       QualType initType = Context.getExceptionObjectType(ExDeclType);
17322 
17323       InitializedEntity entity =
17324         InitializedEntity::InitializeVariable(ExDecl);
17325       InitializationKind initKind =
17326         InitializationKind::CreateCopy(Loc, SourceLocation());
17327 
17328       Expr *opaqueValue =
17329         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17330       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17331       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17332       if (result.isInvalid())
17333         Invalid = true;
17334       else {
17335         // If the constructor used was non-trivial, set this as the
17336         // "initializer".
17337         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17338         if (!construct->getConstructor()->isTrivial()) {
17339           Expr *init = MaybeCreateExprWithCleanups(construct);
17340           ExDecl->setInit(init);
17341         }
17342 
17343         // And make sure it's destructable.
17344         FinalizeVarWithDestructor(ExDecl, recordType);
17345       }
17346     }
17347   }
17348 
17349   if (Invalid)
17350     ExDecl->setInvalidDecl();
17351 
17352   return ExDecl;
17353 }
17354 
ActOnExceptionDeclarator(Scope * S,Declarator & D)17355 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17356   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17357   bool Invalid = D.isInvalidType();
17358 
17359   // Check for unexpanded parameter packs.
17360   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17361                                       UPPC_ExceptionType)) {
17362     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17363                                              D.getIdentifierLoc());
17364     Invalid = true;
17365   }
17366 
17367   const IdentifierInfo *II = D.getIdentifier();
17368   if (NamedDecl *PrevDecl =
17369           LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
17370                            RedeclarationKind::ForVisibleRedeclaration)) {
17371     // The scope should be freshly made just for us. There is just no way
17372     // it contains any previous declaration, except for function parameters in
17373     // a function-try-block's catch statement.
17374     assert(!S->isDeclScope(PrevDecl));
17375     if (isDeclInScope(PrevDecl, CurContext, S)) {
17376       Diag(D.getIdentifierLoc(), diag::err_redefinition)
17377         << D.getIdentifier();
17378       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17379       Invalid = true;
17380     } else if (PrevDecl->isTemplateParameter())
17381       // Maybe we will complain about the shadowed template parameter.
17382       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17383   }
17384 
17385   if (D.getCXXScopeSpec().isSet() && !Invalid) {
17386     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17387       << D.getCXXScopeSpec().getRange();
17388     Invalid = true;
17389   }
17390 
17391   VarDecl *ExDecl = BuildExceptionDeclaration(
17392       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17393   if (Invalid)
17394     ExDecl->setInvalidDecl();
17395 
17396   // Add the exception declaration into this scope.
17397   if (II)
17398     PushOnScopeChains(ExDecl, S);
17399   else
17400     CurContext->addDecl(ExDecl);
17401 
17402   ProcessDeclAttributes(S, ExDecl, D);
17403   return ExDecl;
17404 }
17405 
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)17406 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17407                                          Expr *AssertExpr,
17408                                          Expr *AssertMessageExpr,
17409                                          SourceLocation RParenLoc) {
17410   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
17411     return nullptr;
17412 
17413   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17414                                       AssertMessageExpr, RParenLoc, false);
17415 }
17416 
WriteCharTypePrefix(BuiltinType::Kind BTK,llvm::raw_ostream & OS)17417 static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17418   switch (BTK) {
17419   case BuiltinType::Char_S:
17420   case BuiltinType::Char_U:
17421     break;
17422   case BuiltinType::Char8:
17423     OS << "u8";
17424     break;
17425   case BuiltinType::Char16:
17426     OS << 'u';
17427     break;
17428   case BuiltinType::Char32:
17429     OS << 'U';
17430     break;
17431   case BuiltinType::WChar_S:
17432   case BuiltinType::WChar_U:
17433     OS << 'L';
17434     break;
17435   default:
17436     llvm_unreachable("Non-character type");
17437   }
17438 }
17439 
17440 /// Convert character's value, interpreted as a code unit, to a string.
17441 /// The value needs to be zero-extended to 32-bits.
17442 /// FIXME: This assumes Unicode literal encodings
WriteCharValueForDiagnostic(uint32_t Value,const BuiltinType * BTy,unsigned TyWidth,SmallVectorImpl<char> & Str)17443 static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17444                                         unsigned TyWidth,
17445                                         SmallVectorImpl<char> &Str) {
17446   char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17447   char *Ptr = Arr;
17448   BuiltinType::Kind K = BTy->getKind();
17449   llvm::raw_svector_ostream OS(Str);
17450 
17451   // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17452   // other types.
17453   if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17454       K == BuiltinType::Char8 || Value <= 0x7F) {
17455     StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17456     if (!Escaped.empty())
17457       EscapeStringForDiagnostic(Escaped, Str);
17458     else
17459       OS << static_cast<char>(Value);
17460     return;
17461   }
17462 
17463   switch (K) {
17464   case BuiltinType::Char16:
17465   case BuiltinType::Char32:
17466   case BuiltinType::WChar_S:
17467   case BuiltinType::WChar_U: {
17468     if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17469       EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17470     else
17471       OS << "\\x"
17472          << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17473     break;
17474   }
17475   default:
17476     llvm_unreachable("Non-character type is passed");
17477   }
17478 }
17479 
17480 /// Convert \V to a string we can present to the user in a diagnostic
17481 /// \T is the type of the expression that has been evaluated into \V
ConvertAPValueToString(const APValue & V,QualType T,SmallVectorImpl<char> & Str,ASTContext & Context)17482 static bool ConvertAPValueToString(const APValue &V, QualType T,
17483                                    SmallVectorImpl<char> &Str,
17484                                    ASTContext &Context) {
17485   if (!V.hasValue())
17486     return false;
17487 
17488   switch (V.getKind()) {
17489   case APValue::ValueKind::Int:
17490     if (T->isBooleanType()) {
17491       // Bools are reduced to ints during evaluation, but for
17492       // diagnostic purposes we want to print them as
17493       // true or false.
17494       int64_t BoolValue = V.getInt().getExtValue();
17495       assert((BoolValue == 0 || BoolValue == 1) &&
17496              "Bool type, but value is not 0 or 1");
17497       llvm::raw_svector_ostream OS(Str);
17498       OS << (BoolValue ? "true" : "false");
17499     } else {
17500       llvm::raw_svector_ostream OS(Str);
17501       // Same is true for chars.
17502       // We want to print the character representation for textual types
17503       const auto *BTy = T->getAs<BuiltinType>();
17504       if (BTy) {
17505         switch (BTy->getKind()) {
17506         case BuiltinType::Char_S:
17507         case BuiltinType::Char_U:
17508         case BuiltinType::Char8:
17509         case BuiltinType::Char16:
17510         case BuiltinType::Char32:
17511         case BuiltinType::WChar_S:
17512         case BuiltinType::WChar_U: {
17513           unsigned TyWidth = Context.getIntWidth(T);
17514           assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17515           uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17516           WriteCharTypePrefix(BTy->getKind(), OS);
17517           OS << '\'';
17518           WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17519           OS << "' (0x"
17520              << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17521                                            /*Upper=*/true)
17522              << ", " << V.getInt() << ')';
17523           return true;
17524         }
17525         default:
17526           break;
17527         }
17528       }
17529       V.getInt().toString(Str);
17530     }
17531 
17532     break;
17533 
17534   case APValue::ValueKind::Float:
17535     V.getFloat().toString(Str);
17536     break;
17537 
17538   case APValue::ValueKind::LValue:
17539     if (V.isNullPointer()) {
17540       llvm::raw_svector_ostream OS(Str);
17541       OS << "nullptr";
17542     } else
17543       return false;
17544     break;
17545 
17546   case APValue::ValueKind::ComplexFloat: {
17547     llvm::raw_svector_ostream OS(Str);
17548     OS << '(';
17549     V.getComplexFloatReal().toString(Str);
17550     OS << " + ";
17551     V.getComplexFloatImag().toString(Str);
17552     OS << "i)";
17553   } break;
17554 
17555   case APValue::ValueKind::ComplexInt: {
17556     llvm::raw_svector_ostream OS(Str);
17557     OS << '(';
17558     V.getComplexIntReal().toString(Str);
17559     OS << " + ";
17560     V.getComplexIntImag().toString(Str);
17561     OS << "i)";
17562   } break;
17563 
17564   default:
17565     return false;
17566   }
17567 
17568   return true;
17569 }
17570 
17571 /// Some Expression types are not useful to print notes about,
17572 /// e.g. literals and values that have already been expanded
17573 /// before such as int-valued template parameters.
UsefulToPrintExpr(const Expr * E)17574 static bool UsefulToPrintExpr(const Expr *E) {
17575   E = E->IgnoreParenImpCasts();
17576   // Literals are pretty easy for humans to understand.
17577   if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17578           CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
17579     return false;
17580 
17581   // These have been substituted from template parameters
17582   // and appear as literals in the static assert error.
17583   if (isa<SubstNonTypeTemplateParmExpr>(E))
17584     return false;
17585 
17586   // -5 is also simple to understand.
17587   if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17588     return UsefulToPrintExpr(UnaryOp->getSubExpr());
17589 
17590   // Only print nested arithmetic operators.
17591   if (const auto *BO = dyn_cast<BinaryOperator>(E))
17592     return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17593             BO->isBitwiseOp());
17594 
17595   return true;
17596 }
17597 
DiagnoseStaticAssertDetails(const Expr * E)17598 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17599   if (const auto *Op = dyn_cast<BinaryOperator>(E);
17600       Op && Op->getOpcode() != BO_LOr) {
17601     const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17602     const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17603 
17604     // Ignore comparisons of boolean expressions with a boolean literal.
17605     if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17606         (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17607       return;
17608 
17609     // Don't print obvious expressions.
17610     if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17611       return;
17612 
17613     struct {
17614       const clang::Expr *Cond;
17615       Expr::EvalResult Result;
17616       SmallString<12> ValueString;
17617       bool Print;
17618     } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17619                      {RHS, Expr::EvalResult(), {}, false}};
17620     for (unsigned I = 0; I < 2; I++) {
17621       const Expr *Side = DiagSide[I].Cond;
17622 
17623       Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17624 
17625       DiagSide[I].Print =
17626           ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17627                                  DiagSide[I].ValueString, Context);
17628     }
17629     if (DiagSide[0].Print && DiagSide[1].Print) {
17630       Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17631           << DiagSide[0].ValueString << Op->getOpcodeStr()
17632           << DiagSide[1].ValueString << Op->getSourceRange();
17633     }
17634   } else {
17635     DiagnoseTypeTraitDetails(E);
17636   }
17637 }
17638 
17639 template <typename ResultType>
EvaluateAsStringImpl(Sema & SemaRef,Expr * Message,ResultType & Result,ASTContext & Ctx,Sema::StringEvaluationContext EvalContext,bool ErrorOnInvalidMessage)17640 static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17641                                  ResultType &Result, ASTContext &Ctx,
17642                                  Sema::StringEvaluationContext EvalContext,
17643                                  bool ErrorOnInvalidMessage) {
17644 
17645   assert(Message);
17646   assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17647          "can't evaluate a dependant static assert message");
17648 
17649   if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17650     assert(SL->isUnevaluated() && "expected an unevaluated string");
17651     if constexpr (std::is_same_v<APValue, ResultType>) {
17652       Result =
17653           APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17654       const ConstantArrayType *CAT =
17655           SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17656       assert(CAT && "string literal isn't an array");
17657       QualType CharType = CAT->getElementType();
17658       llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17659                          CharType->isUnsignedIntegerType());
17660       for (unsigned I = 0; I < SL->getLength(); I++) {
17661         Value = SL->getCodeUnit(I);
17662         Result.getArrayInitializedElt(I) = APValue(Value);
17663       }
17664     } else {
17665       Result.assign(SL->getString().begin(), SL->getString().end());
17666     }
17667     return true;
17668   }
17669 
17670   SourceLocation Loc = Message->getBeginLoc();
17671   QualType T = Message->getType().getNonReferenceType();
17672   auto *RD = T->getAsCXXRecordDecl();
17673   if (!RD) {
17674     SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17675     return false;
17676   }
17677 
17678   auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17679     DeclarationName DN = SemaRef.PP.getIdentifierInfo(Member);
17680     LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17681     SemaRef.LookupQualifiedName(MemberLookup, RD);
17682     OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17683                                     OverloadCandidateSet::CSK_Normal);
17684     if (MemberLookup.empty())
17685       return std::nullopt;
17686     return std::move(MemberLookup);
17687   };
17688 
17689   std::optional<LookupResult> SizeMember = FindMember("size");
17690   std::optional<LookupResult> DataMember = FindMember("data");
17691   if (!SizeMember || !DataMember) {
17692     SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17693         << EvalContext
17694         << ((!SizeMember && !DataMember) ? 2
17695             : !SizeMember                ? 0
17696                                          : 1);
17697     return false;
17698   }
17699 
17700   auto BuildExpr = [&](LookupResult &LR) {
17701     ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17702         Message, Message->getType(), Message->getBeginLoc(), false,
17703         CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17704     if (Res.isInvalid())
17705       return ExprError();
17706     Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17707                                 false, true);
17708     if (Res.isInvalid())
17709       return ExprError();
17710     if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17711       return ExprError();
17712     return SemaRef.TemporaryMaterializationConversion(Res.get());
17713   };
17714 
17715   ExprResult SizeE = BuildExpr(*SizeMember);
17716   ExprResult DataE = BuildExpr(*DataMember);
17717 
17718   QualType SizeT = SemaRef.Context.getSizeType();
17719   QualType ConstCharPtr = SemaRef.Context.getPointerType(
17720       SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17721 
17722   ExprResult EvaluatedSize =
17723       SizeE.isInvalid()
17724           ? ExprError()
17725           : SemaRef.BuildConvertedConstantExpression(
17726                 SizeE.get(), SizeT, CCEKind::StaticAssertMessageSize);
17727   if (EvaluatedSize.isInvalid()) {
17728     SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17729         << EvalContext << /*size*/ 0;
17730     return false;
17731   }
17732 
17733   ExprResult EvaluatedData =
17734       DataE.isInvalid()
17735           ? ExprError()
17736           : SemaRef.BuildConvertedConstantExpression(
17737                 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17738   if (EvaluatedData.isInvalid()) {
17739     SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17740         << EvalContext << /*data*/ 1;
17741     return false;
17742   }
17743 
17744   if (!ErrorOnInvalidMessage &&
17745       SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17746     return true;
17747 
17748   Expr::EvalResult Status;
17749   SmallVector<PartialDiagnosticAt, 8> Notes;
17750   Status.Diag = &Notes;
17751   if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17752                                           EvaluatedData.get(), Ctx, Status) ||
17753       !Notes.empty()) {
17754     SemaRef.Diag(Message->getBeginLoc(),
17755                  ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17756                                        : diag::warn_user_defined_msg_constexpr)
17757         << EvalContext;
17758     for (const auto &Note : Notes)
17759       SemaRef.Diag(Note.first, Note.second);
17760     return !ErrorOnInvalidMessage;
17761   }
17762   return true;
17763 }
17764 
EvaluateAsString(Expr * Message,APValue & Result,ASTContext & Ctx,StringEvaluationContext EvalContext,bool ErrorOnInvalidMessage)17765 bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17766                             StringEvaluationContext EvalContext,
17767                             bool ErrorOnInvalidMessage) {
17768   return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17769                               ErrorOnInvalidMessage);
17770 }
17771 
EvaluateAsString(Expr * Message,std::string & Result,ASTContext & Ctx,StringEvaluationContext EvalContext,bool ErrorOnInvalidMessage)17772 bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17773                             StringEvaluationContext EvalContext,
17774                             bool ErrorOnInvalidMessage) {
17775   return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17776                               ErrorOnInvalidMessage);
17777 }
17778 
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessage,SourceLocation RParenLoc,bool Failed)17779 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17780                                          Expr *AssertExpr, Expr *AssertMessage,
17781                                          SourceLocation RParenLoc,
17782                                          bool Failed) {
17783   assert(AssertExpr != nullptr && "Expected non-null condition");
17784   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17785       (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17786                           !AssertMessage->isValueDependent())) &&
17787       !Failed) {
17788     // In a static_assert-declaration, the constant-expression shall be a
17789     // constant expression that can be contextually converted to bool.
17790     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17791     if (Converted.isInvalid())
17792       Failed = true;
17793 
17794     ExprResult FullAssertExpr =
17795         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17796                             /*DiscardedValue*/ false,
17797                             /*IsConstexpr*/ true);
17798     if (FullAssertExpr.isInvalid())
17799       Failed = true;
17800     else
17801       AssertExpr = FullAssertExpr.get();
17802 
17803     llvm::APSInt Cond;
17804     Expr *BaseExpr = AssertExpr;
17805     AllowFoldKind FoldKind = AllowFoldKind::No;
17806 
17807     if (!getLangOpts().CPlusPlus) {
17808       // In C mode, allow folding as an extension for better compatibility with
17809       // C++ in terms of expressions like static_assert("test") or
17810       // static_assert(nullptr).
17811       FoldKind = AllowFoldKind::Allow;
17812     }
17813 
17814     if (!Failed && VerifyIntegerConstantExpression(
17815                        BaseExpr, &Cond,
17816                        diag::err_static_assert_expression_is_not_constant,
17817                        FoldKind).isInvalid())
17818       Failed = true;
17819 
17820     // If the static_assert passes, only verify that
17821     // the message is grammatically valid without evaluating it.
17822     if (!Failed && AssertMessage && Cond.getBoolValue()) {
17823       std::string Str;
17824       EvaluateAsString(AssertMessage, Str, Context,
17825                        StringEvaluationContext::StaticAssert,
17826                        /*ErrorOnInvalidMessage=*/false);
17827     }
17828 
17829     // CWG2518
17830     // [dcl.pre]/p10  If [...] the expression is evaluated in the context of a
17831     // template definition, the declaration has no effect.
17832     bool InTemplateDefinition =
17833         getLangOpts().CPlusPlus && CurContext->isDependentContext();
17834 
17835     if (!Failed && !Cond && !InTemplateDefinition) {
17836       SmallString<256> MsgBuffer;
17837       llvm::raw_svector_ostream Msg(MsgBuffer);
17838       bool HasMessage = AssertMessage;
17839       if (AssertMessage) {
17840         std::string Str;
17841         HasMessage = EvaluateAsString(AssertMessage, Str, Context,
17842                                       StringEvaluationContext::StaticAssert,
17843                                       /*ErrorOnInvalidMessage=*/true) ||
17844                      !Str.empty();
17845         Msg << Str;
17846       }
17847       Expr *InnerCond = nullptr;
17848       std::string InnerCondDescription;
17849       std::tie(InnerCond, InnerCondDescription) =
17850         findFailedBooleanCondition(Converted.get());
17851       if (const auto *ConceptIDExpr =
17852               dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
17853         // Drill down into concept specialization expressions to see why they
17854         // weren't satisfied.
17855         Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17856             << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17857         ConstraintSatisfaction Satisfaction;
17858         if (!CheckConstraintSatisfaction(ConceptIDExpr, Satisfaction))
17859           DiagnoseUnsatisfiedConstraint(Satisfaction);
17860       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
17861                  !isa<IntegerLiteral>(InnerCond)) {
17862         Diag(InnerCond->getBeginLoc(),
17863              diag::err_static_assert_requirement_failed)
17864             << InnerCondDescription << !HasMessage << Msg.str()
17865             << InnerCond->getSourceRange();
17866         DiagnoseStaticAssertDetails(InnerCond);
17867       } else {
17868         Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17869             << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17870         PrintContextStack();
17871       }
17872       Failed = true;
17873     }
17874   } else {
17875     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17876                                                     /*DiscardedValue*/false,
17877                                                     /*IsConstexpr*/true);
17878     if (FullAssertExpr.isInvalid())
17879       Failed = true;
17880     else
17881       AssertExpr = FullAssertExpr.get();
17882   }
17883 
17884   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17885                                         AssertExpr, AssertMessage, RParenLoc,
17886                                         Failed);
17887 
17888   CurContext->addDecl(Decl);
17889   return Decl;
17890 }
17891 
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,SourceLocation EllipsisLoc,const ParsedAttributesView & Attr,MultiTemplateParamsArg TempParamLists)17892 DeclResult Sema::ActOnTemplatedFriendTag(
17893     Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17894     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17895     SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17896     MultiTemplateParamsArg TempParamLists) {
17897   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17898 
17899   bool IsMemberSpecialization = false;
17900   bool Invalid = false;
17901 
17902   if (TemplateParameterList *TemplateParams =
17903           MatchTemplateParametersToScopeSpecifier(
17904               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17905               IsMemberSpecialization, Invalid)) {
17906     if (TemplateParams->size() > 0) {
17907       // This is a declaration of a class template.
17908       if (Invalid)
17909         return true;
17910 
17911       return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17912                                 Name, NameLoc, Attr, TemplateParams, AS_public,
17913                                 /*ModulePrivateLoc=*/SourceLocation(),
17914                                 FriendLoc, TempParamLists.size() - 1,
17915                                 TempParamLists.data())
17916           .get();
17917     } else {
17918       // The "template<>" header is extraneous.
17919       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17920         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17921       IsMemberSpecialization = true;
17922     }
17923   }
17924 
17925   if (Invalid) return true;
17926 
17927   bool isAllExplicitSpecializations = true;
17928   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17929     if (TempParamLists[I]->size()) {
17930       isAllExplicitSpecializations = false;
17931       break;
17932     }
17933   }
17934 
17935   // FIXME: don't ignore attributes.
17936 
17937   // If it's explicit specializations all the way down, just forget
17938   // about the template header and build an appropriate non-templated
17939   // friend.  TODO: for source fidelity, remember the headers.
17940   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17941   if (isAllExplicitSpecializations) {
17942     if (SS.isEmpty()) {
17943       bool Owned = false;
17944       bool IsDependent = false;
17945       return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17946                       Attr, AS_public,
17947                       /*ModulePrivateLoc=*/SourceLocation(),
17948                       MultiTemplateParamsArg(), Owned, IsDependent,
17949                       /*ScopedEnumKWLoc=*/SourceLocation(),
17950                       /*ScopedEnumUsesClassTag=*/false,
17951                       /*UnderlyingType=*/TypeResult(),
17952                       /*IsTypeSpecifier=*/false,
17953                       /*IsTemplateParamOrArg=*/false,
17954                       /*OOK=*/OffsetOfKind::Outside);
17955     }
17956 
17957     ElaboratedTypeKeyword Keyword
17958       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17959     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17960                                    *Name, NameLoc);
17961     if (T.isNull())
17962       return true;
17963 
17964     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17965     if (isa<DependentNameType>(T)) {
17966       DependentNameTypeLoc TL =
17967           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17968       TL.setElaboratedKeywordLoc(TagLoc);
17969       TL.setQualifierLoc(QualifierLoc);
17970       TL.setNameLoc(NameLoc);
17971     } else {
17972       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17973       TL.setElaboratedKeywordLoc(TagLoc);
17974       TL.setQualifierLoc(QualifierLoc);
17975       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17976     }
17977 
17978     FriendDecl *Friend =
17979         FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17980                            EllipsisLoc, TempParamLists);
17981     Friend->setAccess(AS_public);
17982     CurContext->addDecl(Friend);
17983     return Friend;
17984   }
17985 
17986   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17987 
17988   // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
17989   // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
17990   // shall not have been introduced by the template-declaration.
17991   SmallVector<UnexpandedParameterPack, 1> Unexpanded;
17992   collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
17993   unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
17994   for (UnexpandedParameterPack &U : Unexpanded) {
17995     if (getDepthAndIndex(U).first >= FriendDeclDepth) {
17996       auto *ND = dyn_cast<NamedDecl *>(U.first);
17997       if (!ND)
17998         ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
17999       Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18000           << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18001       return true;
18002     }
18003   }
18004 
18005   // Handle the case of a templated-scope friend class.  e.g.
18006   //   template <class T> class A<T>::B;
18007   // FIXME: we don't support these right now.
18008   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18009     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
18010   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
18011   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18012   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18013   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18014   TL.setElaboratedKeywordLoc(TagLoc);
18015   TL.setQualifierLoc(SS.getWithLocInContext(Context));
18016   TL.setNameLoc(NameLoc);
18017 
18018   FriendDecl *Friend =
18019       FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18020                          EllipsisLoc, TempParamLists);
18021   Friend->setAccess(AS_public);
18022   Friend->setUnsupportedFriend(true);
18023   CurContext->addDecl(Friend);
18024   return Friend;
18025 }
18026 
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams,SourceLocation EllipsisLoc)18027 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18028                                 MultiTemplateParamsArg TempParams,
18029                                 SourceLocation EllipsisLoc) {
18030   SourceLocation Loc = DS.getBeginLoc();
18031   SourceLocation FriendLoc = DS.getFriendSpecLoc();
18032 
18033   assert(DS.isFriendSpecified());
18034   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18035 
18036   // C++ [class.friend]p3:
18037   // A friend declaration that does not declare a function shall have one of
18038   // the following forms:
18039   //     friend elaborated-type-specifier ;
18040   //     friend simple-type-specifier ;
18041   //     friend typename-specifier ;
18042   //
18043   // If the friend keyword isn't first, or if the declarations has any type
18044   // qualifiers, then the declaration doesn't have that form.
18045   if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18046     Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18047   if (DS.getTypeQualifiers()) {
18048     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18049       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18050     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18051       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18052     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18053       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18054     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18055       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18056     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18057       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18058   }
18059 
18060   // Try to convert the decl specifier to a type.  This works for
18061   // friend templates because ActOnTag never produces a ClassTemplateDecl
18062   // for a TagUseKind::Friend.
18063   Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18064                            DeclaratorContext::Member);
18065   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18066   QualType T = TSI->getType();
18067   if (TheDeclarator.isInvalidType())
18068     return nullptr;
18069 
18070   // If '...' is present, the type must contain an unexpanded parameter
18071   // pack, and vice versa.
18072   bool Invalid = false;
18073   if (EllipsisLoc.isInvalid() &&
18074       DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
18075     return nullptr;
18076   if (EllipsisLoc.isValid() &&
18077       !TSI->getType()->containsUnexpandedParameterPack()) {
18078     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18079         << TSI->getTypeLoc().getSourceRange();
18080     Invalid = true;
18081   }
18082 
18083   if (!T->isElaboratedTypeSpecifier()) {
18084     if (TempParams.size()) {
18085       // C++23 [dcl.pre]p5:
18086       //   In a simple-declaration, the optional init-declarator-list can be
18087       //   omitted only when declaring a class or enumeration, that is, when
18088       //   the decl-specifier-seq contains either a class-specifier, an
18089       //   elaborated-type-specifier with a class-key, or an enum-specifier.
18090       //
18091       // The declaration of a template-declaration or explicit-specialization
18092       // is never a member-declaration, so this must be a simple-declaration
18093       // with no init-declarator-list. Therefore, this is ill-formed.
18094       Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18095       return nullptr;
18096     } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18097       SmallString<16> InsertionText(" ");
18098       InsertionText += RD->getKindName();
18099 
18100       Diag(Loc, getLangOpts().CPlusPlus11
18101                     ? diag::warn_cxx98_compat_unelaborated_friend_type
18102                     : diag::ext_unelaborated_friend_type)
18103           << (unsigned)RD->getTagKind() << T
18104           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
18105                                         InsertionText);
18106     } else {
18107       DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18108           << T << DS.getSourceRange();
18109     }
18110   }
18111 
18112   // C++98 [class.friend]p1: A friend of a class is a function
18113   //   or class that is not a member of the class . . .
18114   // This is fixed in DR77, which just barely didn't make the C++03
18115   // deadline.  It's also a very silly restriction that seriously
18116   // affects inner classes and which nobody else seems to implement;
18117   // thus we never diagnose it, not even in -pedantic.
18118   //
18119   // But note that we could warn about it: it's always useless to
18120   // friend one of your own members (it's not, however, worthless to
18121   // friend a member of an arbitrary specialization of your template).
18122 
18123   Decl *D;
18124   if (!TempParams.empty())
18125     // TODO: Support variadic friend template decls?
18126     D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
18127                                    FriendLoc);
18128   else
18129     D = FriendDecl::Create(Context, CurContext, TSI->getTypeLoc().getBeginLoc(),
18130                            TSI, FriendLoc, EllipsisLoc);
18131 
18132   if (!D)
18133     return nullptr;
18134 
18135   D->setAccess(AS_public);
18136   CurContext->addDecl(D);
18137 
18138   if (Invalid)
18139     D->setInvalidDecl();
18140 
18141   return D;
18142 }
18143 
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)18144 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18145                                         MultiTemplateParamsArg TemplateParams) {
18146   const DeclSpec &DS = D.getDeclSpec();
18147 
18148   assert(DS.isFriendSpecified());
18149   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18150 
18151   SourceLocation Loc = D.getIdentifierLoc();
18152   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18153 
18154   // C++ [class.friend]p1
18155   //   A friend of a class is a function or class....
18156   // Note that this sees through typedefs, which is intended.
18157   // It *doesn't* see through dependent types, which is correct
18158   // according to [temp.arg.type]p3:
18159   //   If a declaration acquires a function type through a
18160   //   type dependent on a template-parameter and this causes
18161   //   a declaration that does not use the syntactic form of a
18162   //   function declarator to have a function type, the program
18163   //   is ill-formed.
18164   if (!TInfo->getType()->isFunctionType()) {
18165     Diag(Loc, diag::err_unexpected_friend);
18166 
18167     // It might be worthwhile to try to recover by creating an
18168     // appropriate declaration.
18169     return nullptr;
18170   }
18171 
18172   // C++ [namespace.memdef]p3
18173   //  - If a friend declaration in a non-local class first declares a
18174   //    class or function, the friend class or function is a member
18175   //    of the innermost enclosing namespace.
18176   //  - The name of the friend is not found by simple name lookup
18177   //    until a matching declaration is provided in that namespace
18178   //    scope (either before or after the class declaration granting
18179   //    friendship).
18180   //  - If a friend function is called, its name may be found by the
18181   //    name lookup that considers functions from namespaces and
18182   //    classes associated with the types of the function arguments.
18183   //  - When looking for a prior declaration of a class or a function
18184   //    declared as a friend, scopes outside the innermost enclosing
18185   //    namespace scope are not considered.
18186 
18187   CXXScopeSpec &SS = D.getCXXScopeSpec();
18188   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18189   assert(NameInfo.getName());
18190 
18191   // Check for unexpanded parameter packs.
18192   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
18193       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
18194       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
18195     return nullptr;
18196 
18197   // The context we found the declaration in, or in which we should
18198   // create the declaration.
18199   DeclContext *DC;
18200   Scope *DCScope = S;
18201   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18202                         RedeclarationKind::ForExternalRedeclaration);
18203 
18204   bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18205 
18206   // There are five cases here.
18207   //   - There's no scope specifier and we're in a local class. Only look
18208   //     for functions declared in the immediately-enclosing block scope.
18209   // We recover from invalid scope qualifiers as if they just weren't there.
18210   FunctionDecl *FunctionContainingLocalClass = nullptr;
18211   if ((SS.isInvalid() || !SS.isSet()) &&
18212       (FunctionContainingLocalClass =
18213            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18214     // C++11 [class.friend]p11:
18215     //   If a friend declaration appears in a local class and the name
18216     //   specified is an unqualified name, a prior declaration is
18217     //   looked up without considering scopes that are outside the
18218     //   innermost enclosing non-class scope. For a friend function
18219     //   declaration, if there is no prior declaration, the program is
18220     //   ill-formed.
18221 
18222     // Find the innermost enclosing non-class scope. This is the block
18223     // scope containing the local class definition (or for a nested class,
18224     // the outer local class).
18225     DCScope = S->getFnParent();
18226 
18227     // Look up the function name in the scope.
18228     Previous.clear(LookupLocalFriendName);
18229     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18230 
18231     if (!Previous.empty()) {
18232       // All possible previous declarations must have the same context:
18233       // either they were declared at block scope or they are members of
18234       // one of the enclosing local classes.
18235       DC = Previous.getRepresentativeDecl()->getDeclContext();
18236     } else {
18237       // This is ill-formed, but provide the context that we would have
18238       // declared the function in, if we were permitted to, for error recovery.
18239       DC = FunctionContainingLocalClass;
18240     }
18241     adjustContextForLocalExternDecl(DC);
18242 
18243   //   - There's no scope specifier, in which case we just go to the
18244   //     appropriate scope and look for a function or function template
18245   //     there as appropriate.
18246   } else if (SS.isInvalid() || !SS.isSet()) {
18247     // C++11 [namespace.memdef]p3:
18248     //   If the name in a friend declaration is neither qualified nor
18249     //   a template-id and the declaration is a function or an
18250     //   elaborated-type-specifier, the lookup to determine whether
18251     //   the entity has been previously declared shall not consider
18252     //   any scopes outside the innermost enclosing namespace.
18253 
18254     // Find the appropriate context according to the above.
18255     DC = CurContext;
18256 
18257     // Skip class contexts.  If someone can cite chapter and verse
18258     // for this behavior, that would be nice --- it's what GCC and
18259     // EDG do, and it seems like a reasonable intent, but the spec
18260     // really only says that checks for unqualified existing
18261     // declarations should stop at the nearest enclosing namespace,
18262     // not that they should only consider the nearest enclosing
18263     // namespace.
18264     while (DC->isRecord())
18265       DC = DC->getParent();
18266 
18267     DeclContext *LookupDC = DC->getNonTransparentContext();
18268     while (true) {
18269       LookupQualifiedName(Previous, LookupDC);
18270 
18271       if (!Previous.empty()) {
18272         DC = LookupDC;
18273         break;
18274       }
18275 
18276       if (isTemplateId) {
18277         if (isa<TranslationUnitDecl>(LookupDC)) break;
18278       } else {
18279         if (LookupDC->isFileContext()) break;
18280       }
18281       LookupDC = LookupDC->getParent();
18282     }
18283 
18284     DCScope = getScopeForDeclContext(S, DC);
18285 
18286   //   - There's a non-dependent scope specifier, in which case we
18287   //     compute it and do a previous lookup there for a function
18288   //     or function template.
18289   } else if (!SS.getScopeRep()->isDependent()) {
18290     DC = computeDeclContext(SS);
18291     if (!DC) return nullptr;
18292 
18293     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18294 
18295     LookupQualifiedName(Previous, DC);
18296 
18297     // C++ [class.friend]p1: A friend of a class is a function or
18298     //   class that is not a member of the class . . .
18299     if (DC->Equals(CurContext))
18300       Diag(DS.getFriendSpecLoc(),
18301            getLangOpts().CPlusPlus11 ?
18302              diag::warn_cxx98_compat_friend_is_member :
18303              diag::err_friend_is_member);
18304 
18305   //   - There's a scope specifier that does not match any template
18306   //     parameter lists, in which case we use some arbitrary context,
18307   //     create a method or method template, and wait for instantiation.
18308   //   - There's a scope specifier that does match some template
18309   //     parameter lists, which we don't handle right now.
18310   } else {
18311     DC = CurContext;
18312     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18313   }
18314 
18315   if (!DC->isRecord()) {
18316     int DiagArg = -1;
18317     switch (D.getName().getKind()) {
18318     case UnqualifiedIdKind::IK_ConstructorTemplateId:
18319     case UnqualifiedIdKind::IK_ConstructorName:
18320       DiagArg = 0;
18321       break;
18322     case UnqualifiedIdKind::IK_DestructorName:
18323       DiagArg = 1;
18324       break;
18325     case UnqualifiedIdKind::IK_ConversionFunctionId:
18326       DiagArg = 2;
18327       break;
18328     case UnqualifiedIdKind::IK_DeductionGuideName:
18329       DiagArg = 3;
18330       break;
18331     case UnqualifiedIdKind::IK_Identifier:
18332     case UnqualifiedIdKind::IK_ImplicitSelfParam:
18333     case UnqualifiedIdKind::IK_LiteralOperatorId:
18334     case UnqualifiedIdKind::IK_OperatorFunctionId:
18335     case UnqualifiedIdKind::IK_TemplateId:
18336       break;
18337     }
18338     // This implies that it has to be an operator or function.
18339     if (DiagArg >= 0) {
18340       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18341       return nullptr;
18342     }
18343   }
18344 
18345   // FIXME: This is an egregious hack to cope with cases where the scope stack
18346   // does not contain the declaration context, i.e., in an out-of-line
18347   // definition of a class.
18348   Scope FakeDCScope(S, Scope::DeclScope, Diags);
18349   if (!DCScope) {
18350     FakeDCScope.setEntity(DC);
18351     DCScope = &FakeDCScope;
18352   }
18353 
18354   bool AddToScope = true;
18355   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18356                                           TemplateParams, AddToScope);
18357   if (!ND) return nullptr;
18358 
18359   assert(ND->getLexicalDeclContext() == CurContext);
18360 
18361   // If we performed typo correction, we might have added a scope specifier
18362   // and changed the decl context.
18363   DC = ND->getDeclContext();
18364 
18365   // Add the function declaration to the appropriate lookup tables,
18366   // adjusting the redeclarations list as necessary.  We don't
18367   // want to do this yet if the friending class is dependent.
18368   //
18369   // Also update the scope-based lookup if the target context's
18370   // lookup context is in lexical scope.
18371   if (!CurContext->isDependentContext()) {
18372     DC = DC->getRedeclContext();
18373     DC->makeDeclVisibleInContext(ND);
18374     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18375       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18376   }
18377 
18378   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
18379                                        D.getIdentifierLoc(), ND,
18380                                        DS.getFriendSpecLoc());
18381   FrD->setAccess(AS_public);
18382   CurContext->addDecl(FrD);
18383 
18384   if (ND->isInvalidDecl()) {
18385     FrD->setInvalidDecl();
18386   } else {
18387     if (DC->isRecord()) CheckFriendAccess(ND);
18388 
18389     FunctionDecl *FD;
18390     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18391       FD = FTD->getTemplatedDecl();
18392     else
18393       FD = cast<FunctionDecl>(ND);
18394 
18395     // C++ [class.friend]p6:
18396     //   A function may be defined in a friend declaration of a class if and
18397     //   only if the class is a non-local class, and the function name is
18398     //   unqualified.
18399     if (D.isFunctionDefinition()) {
18400       // Qualified friend function definition.
18401       if (SS.isNotEmpty()) {
18402         // FIXME: We should only do this if the scope specifier names the
18403         // innermost enclosing namespace; otherwise the fixit changes the
18404         // meaning of the code.
18405         SemaDiagnosticBuilder DB =
18406             Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18407 
18408         DB << SS.getScopeRep();
18409         if (DC->isFileContext())
18410           DB << FixItHint::CreateRemoval(SS.getRange());
18411 
18412         // Friend function defined in a local class.
18413       } else if (FunctionContainingLocalClass) {
18414         Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18415 
18416         // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18417         // a template-id, the function name is not unqualified because these is
18418         // no name. While the wording requires some reading in-between the
18419         // lines, GCC, MSVC, and EDG all consider a friend function
18420         // specialization definitions to be de facto explicit specialization
18421         // and diagnose them as such.
18422       } else if (isTemplateId) {
18423         Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18424       }
18425     }
18426 
18427     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18428     // default argument expression, that declaration shall be a definition
18429     // and shall be the only declaration of the function or function
18430     // template in the translation unit.
18431     if (functionDeclHasDefaultArgument(FD)) {
18432       // We can't look at FD->getPreviousDecl() because it may not have been set
18433       // if we're in a dependent context. If the function is known to be a
18434       // redeclaration, we will have narrowed Previous down to the right decl.
18435       if (D.isRedeclaration()) {
18436         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18437         Diag(Previous.getRepresentativeDecl()->getLocation(),
18438              diag::note_previous_declaration);
18439       } else if (!D.isFunctionDefinition())
18440         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18441     }
18442 
18443     // Mark templated-scope function declarations as unsupported.
18444     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18445       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18446         << SS.getScopeRep() << SS.getRange()
18447         << cast<CXXRecordDecl>(CurContext);
18448       FrD->setUnsupportedFriend(true);
18449     }
18450   }
18451 
18452   warnOnReservedIdentifier(ND);
18453 
18454   return ND;
18455 }
18456 
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc,StringLiteral * Message)18457 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18458                           StringLiteral *Message) {
18459   AdjustDeclIfTemplate(Dcl);
18460 
18461   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18462   if (!Fn) {
18463     Diag(DelLoc, diag::err_deleted_non_function);
18464     return;
18465   }
18466 
18467   // Deleted function does not have a body.
18468   Fn->setWillHaveBody(false);
18469 
18470   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18471     // Don't consider the implicit declaration we generate for explicit
18472     // specializations. FIXME: Do not generate these implicit declarations.
18473     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18474          Prev->getPreviousDecl()) &&
18475         !Prev->isDefined()) {
18476       Diag(DelLoc, diag::err_deleted_decl_not_first);
18477       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18478            Prev->isImplicit() ? diag::note_previous_implicit_declaration
18479                               : diag::note_previous_declaration);
18480       // We can't recover from this; the declaration might have already
18481       // been used.
18482       Fn->setInvalidDecl();
18483       return;
18484     }
18485 
18486     // To maintain the invariant that functions are only deleted on their first
18487     // declaration, mark the implicitly-instantiated declaration of the
18488     // explicitly-specialized function as deleted instead of marking the
18489     // instantiated redeclaration.
18490     Fn = Fn->getCanonicalDecl();
18491   }
18492 
18493   // dllimport/dllexport cannot be deleted.
18494   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18495     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18496     Fn->setInvalidDecl();
18497   }
18498 
18499   // C++11 [basic.start.main]p3:
18500   //   A program that defines main as deleted [...] is ill-formed.
18501   if (Fn->isMain())
18502     Diag(DelLoc, diag::err_deleted_main);
18503 
18504   // C++11 [dcl.fct.def.delete]p4:
18505   //  A deleted function is implicitly inline.
18506   Fn->setImplicitlyInline();
18507   Fn->setDeletedAsWritten(true, Message);
18508 }
18509 
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)18510 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18511   if (!Dcl || Dcl->isInvalidDecl())
18512     return;
18513 
18514   auto *FD = dyn_cast<FunctionDecl>(Dcl);
18515   if (!FD) {
18516     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18517       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18518         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18519         return;
18520       }
18521     }
18522 
18523     Diag(DefaultLoc, diag::err_default_special_members)
18524         << getLangOpts().CPlusPlus20;
18525     return;
18526   }
18527 
18528   // Reject if this can't possibly be a defaultable function.
18529   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18530   if (!DefKind &&
18531       // A dependent function that doesn't locally look defaultable can
18532       // still instantiate to a defaultable function if it's a constructor
18533       // or assignment operator.
18534       (!FD->isDependentContext() ||
18535        (!isa<CXXConstructorDecl>(FD) &&
18536         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18537     Diag(DefaultLoc, diag::err_default_special_members)
18538         << getLangOpts().CPlusPlus20;
18539     return;
18540   }
18541 
18542   // Issue compatibility warning. We already warned if the operator is
18543   // 'operator<=>' when parsing the '<=>' token.
18544   if (DefKind.isComparison() &&
18545       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18546     Diag(DefaultLoc, getLangOpts().CPlusPlus20
18547                          ? diag::warn_cxx17_compat_defaulted_comparison
18548                          : diag::ext_defaulted_comparison);
18549   }
18550 
18551   FD->setDefaulted();
18552   FD->setExplicitlyDefaulted();
18553   FD->setDefaultLoc(DefaultLoc);
18554 
18555   // Defer checking functions that are defaulted in a dependent context.
18556   if (FD->isDependentContext())
18557     return;
18558 
18559   // Unset that we will have a body for this function. We might not,
18560   // if it turns out to be trivial, and we don't need this marking now
18561   // that we've marked it as defaulted.
18562   FD->setWillHaveBody(false);
18563 
18564   if (DefKind.isComparison()) {
18565     // If this comparison's defaulting occurs within the definition of its
18566     // lexical class context, we have to do the checking when complete.
18567     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18568       if (!RD->isCompleteDefinition())
18569         return;
18570   }
18571 
18572   // If this member fn was defaulted on its first declaration, we will have
18573   // already performed the checking in CheckCompletedCXXClass. Such a
18574   // declaration doesn't trigger an implicit definition.
18575   if (isa<CXXMethodDecl>(FD)) {
18576     const FunctionDecl *Primary = FD;
18577     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18578       // Ask the template instantiation pattern that actually had the
18579       // '= default' on it.
18580       Primary = Pattern;
18581     if (Primary->getCanonicalDecl()->isDefaulted())
18582       return;
18583   }
18584 
18585   if (DefKind.isComparison()) {
18586     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18587       FD->setInvalidDecl();
18588     else
18589       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18590   } else {
18591     auto *MD = cast<CXXMethodDecl>(FD);
18592 
18593     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
18594                                               DefaultLoc))
18595       MD->setInvalidDecl();
18596     else
18597       DefineDefaultedFunction(*this, MD, DefaultLoc);
18598   }
18599 }
18600 
SearchForReturnInStmt(Sema & Self,Stmt * S)18601 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18602   for (Stmt *SubStmt : S->children()) {
18603     if (!SubStmt)
18604       continue;
18605     if (isa<ReturnStmt>(SubStmt))
18606       Self.Diag(SubStmt->getBeginLoc(),
18607                 diag::err_return_in_constructor_handler);
18608     if (!isa<Expr>(SubStmt))
18609       SearchForReturnInStmt(Self, SubStmt);
18610   }
18611 }
18612 
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)18613 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18614   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18615     CXXCatchStmt *Handler = TryBlock->getHandler(I);
18616     SearchForReturnInStmt(*this, Handler);
18617   }
18618 }
18619 
SetFunctionBodyKind(Decl * D,SourceLocation Loc,FnBodyKind BodyKind,StringLiteral * DeletedMessage)18620 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18621                                StringLiteral *DeletedMessage) {
18622   switch (BodyKind) {
18623   case FnBodyKind::Delete:
18624     SetDeclDeleted(D, Loc, DeletedMessage);
18625     break;
18626   case FnBodyKind::Default:
18627     SetDeclDefaulted(D, Loc);
18628     break;
18629   case FnBodyKind::Other:
18630     llvm_unreachable(
18631         "Parsed function body should be '= delete;' or '= default;'");
18632   }
18633 }
18634 
CheckOverridingFunctionAttributes(CXXMethodDecl * New,const CXXMethodDecl * Old)18635 bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18636                                              const CXXMethodDecl *Old) {
18637   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18638   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18639 
18640   if (OldFT->hasExtParameterInfos()) {
18641     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18642       // A parameter of the overriding method should be annotated with noescape
18643       // if the corresponding parameter of the overridden method is annotated.
18644       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18645           !NewFT->getExtParameterInfo(I).isNoEscape()) {
18646         Diag(New->getParamDecl(I)->getLocation(),
18647              diag::warn_overriding_method_missing_noescape);
18648         Diag(Old->getParamDecl(I)->getLocation(),
18649              diag::note_overridden_marked_noescape);
18650       }
18651   }
18652 
18653   // SME attributes must match when overriding a function declaration.
18654   if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18655     Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18656         << New << New->getType() << Old->getType();
18657     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18658     return true;
18659   }
18660 
18661   // Virtual overrides must have the same code_seg.
18662   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18663   const auto *NewCSA = New->getAttr<CodeSegAttr>();
18664   if ((NewCSA || OldCSA) &&
18665       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18666     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18667     Diag(Old->getLocation(), diag::note_previous_declaration);
18668     return true;
18669   }
18670 
18671   // Virtual overrides: check for matching effects.
18672   if (Context.hasAnyFunctionEffects()) {
18673     const auto OldFX = Old->getFunctionEffects();
18674     const auto NewFXOrig = New->getFunctionEffects();
18675 
18676     if (OldFX != NewFXOrig) {
18677       FunctionEffectSet NewFX(NewFXOrig);
18678       const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18679       FunctionEffectSet::Conflicts Errs;
18680       for (const auto &Diff : Diffs) {
18681         switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18682         case FunctionEffectDiff::OverrideResult::NoAction:
18683           break;
18684         case FunctionEffectDiff::OverrideResult::Warn:
18685           Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18686               << Diff.effectName();
18687           Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18688               << Old->getReturnTypeSourceRange();
18689           break;
18690         case FunctionEffectDiff::OverrideResult::Merge: {
18691           NewFX.insert(Diff.Old.value(), Errs);
18692           const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18693           FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18694           EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18695           QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18696                                                    NewFT->getParamTypes(), EPI);
18697           New->setType(ModQT);
18698           break;
18699         }
18700         }
18701       }
18702       if (!Errs.empty())
18703         diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18704                                              Old->getLocation());
18705     }
18706   }
18707 
18708   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18709 
18710   // If the calling conventions match, everything is fine
18711   if (NewCC == OldCC)
18712     return false;
18713 
18714   // If the calling conventions mismatch because the new function is static,
18715   // suppress the calling convention mismatch error; the error about static
18716   // function override (err_static_overrides_virtual from
18717   // Sema::CheckFunctionDeclaration) is more clear.
18718   if (New->getStorageClass() == SC_Static)
18719     return false;
18720 
18721   Diag(New->getLocation(),
18722        diag::err_conflicting_overriding_cc_attributes)
18723     << New->getDeclName() << New->getType() << Old->getType();
18724   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18725   return true;
18726 }
18727 
CheckExplicitObjectOverride(CXXMethodDecl * New,const CXXMethodDecl * Old)18728 bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18729                                        const CXXMethodDecl *Old) {
18730   // CWG2553
18731   // A virtual function shall not be an explicit object member function.
18732   if (!New->isExplicitObjectMemberFunction())
18733     return true;
18734   Diag(New->getParamDecl(0)->getBeginLoc(),
18735        diag::err_explicit_object_parameter_nonmember)
18736       << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18737   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18738   New->setInvalidDecl();
18739   return false;
18740 }
18741 
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)18742 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18743                                              const CXXMethodDecl *Old) {
18744   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18745   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18746 
18747   if (Context.hasSameType(NewTy, OldTy) ||
18748       NewTy->isDependentType() || OldTy->isDependentType())
18749     return false;
18750 
18751   // Check if the return types are covariant
18752   QualType NewClassTy, OldClassTy;
18753 
18754   /// Both types must be pointers or references to classes.
18755   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18756     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18757       NewClassTy = NewPT->getPointeeType();
18758       OldClassTy = OldPT->getPointeeType();
18759     }
18760   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18761     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18762       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18763         NewClassTy = NewRT->getPointeeType();
18764         OldClassTy = OldRT->getPointeeType();
18765       }
18766     }
18767   }
18768 
18769   // The return types aren't either both pointers or references to a class type.
18770   if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18771     Diag(New->getLocation(),
18772          diag::err_different_return_type_for_overriding_virtual_function)
18773         << New->getDeclName() << NewTy << OldTy
18774         << New->getReturnTypeSourceRange();
18775     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18776         << Old->getReturnTypeSourceRange();
18777 
18778     return true;
18779   }
18780 
18781   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18782     // C++14 [class.virtual]p8:
18783     //   If the class type in the covariant return type of D::f differs from
18784     //   that of B::f, the class type in the return type of D::f shall be
18785     //   complete at the point of declaration of D::f or shall be the class
18786     //   type D.
18787     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18788       if (!RT->isBeingDefined() &&
18789           RequireCompleteType(New->getLocation(), NewClassTy,
18790                               diag::err_covariant_return_incomplete,
18791                               New->getDeclName()))
18792         return true;
18793     }
18794 
18795     // Check if the new class derives from the old class.
18796     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18797       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18798           << New->getDeclName() << NewTy << OldTy
18799           << New->getReturnTypeSourceRange();
18800       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18801           << Old->getReturnTypeSourceRange();
18802       return true;
18803     }
18804 
18805     // Check if we the conversion from derived to base is valid.
18806     if (CheckDerivedToBaseConversion(
18807             NewClassTy, OldClassTy,
18808             diag::err_covariant_return_inaccessible_base,
18809             diag::err_covariant_return_ambiguous_derived_to_base_conv,
18810             New->getLocation(), New->getReturnTypeSourceRange(),
18811             New->getDeclName(), nullptr)) {
18812       // FIXME: this note won't trigger for delayed access control
18813       // diagnostics, and it's impossible to get an undelayed error
18814       // here from access control during the original parse because
18815       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18816       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18817           << Old->getReturnTypeSourceRange();
18818       return true;
18819     }
18820   }
18821 
18822   // The qualifiers of the return types must be the same.
18823   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18824     Diag(New->getLocation(),
18825          diag::err_covariant_return_type_different_qualifications)
18826         << New->getDeclName() << NewTy << OldTy
18827         << New->getReturnTypeSourceRange();
18828     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18829         << Old->getReturnTypeSourceRange();
18830     return true;
18831   }
18832 
18833 
18834   // The new class type must have the same or less qualifiers as the old type.
18835   if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
18836     Diag(New->getLocation(),
18837          diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18838         << New->getDeclName() << NewTy << OldTy
18839         << New->getReturnTypeSourceRange();
18840     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18841         << Old->getReturnTypeSourceRange();
18842     return true;
18843   }
18844 
18845   return false;
18846 }
18847 
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)18848 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18849   SourceLocation EndLoc = InitRange.getEnd();
18850   if (EndLoc.isValid())
18851     Method->setRangeEnd(EndLoc);
18852 
18853   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18854     Method->setIsPureVirtual();
18855     return false;
18856   }
18857 
18858   if (!Method->isInvalidDecl())
18859     Diag(Method->getLocation(), diag::err_non_virtual_pure)
18860       << Method->getDeclName() << InitRange;
18861   return true;
18862 }
18863 
ActOnPureSpecifier(Decl * D,SourceLocation ZeroLoc)18864 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18865   if (D->getFriendObjectKind())
18866     Diag(D->getLocation(), diag::err_pure_friend);
18867   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18868     CheckPureMethod(M, ZeroLoc);
18869   else
18870     Diag(D->getLocation(), diag::err_illegal_initializer);
18871 }
18872 
18873 /// Invoked when we are about to parse an initializer for the declaration
18874 /// 'Dcl'.
18875 ///
18876 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18877 /// static data member of class X, names should be looked up in the scope of
18878 /// class X. If the declaration had a scope specifier, a scope will have
18879 /// been created and passed in for this purpose. Otherwise, S will be null.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)18880 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18881   assert(D && !D->isInvalidDecl());
18882 
18883   // We will always have a nested name specifier here, but this declaration
18884   // might not be out of line if the specifier names the current namespace:
18885   //   extern int n;
18886   //   int ::n = 0;
18887   if (S && D->isOutOfLine())
18888     EnterDeclaratorContext(S, D->getDeclContext());
18889 
18890   PushExpressionEvaluationContext(
18891       ExpressionEvaluationContext::PotentiallyEvaluated, D,
18892       ExpressionEvaluationContextRecord::EK_VariableInit);
18893 }
18894 
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)18895 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18896   assert(D);
18897 
18898   if (S && D->isOutOfLine())
18899     ExitDeclaratorContext(S);
18900 
18901   PopExpressionEvaluationContext();
18902 }
18903 
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)18904 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18905   // C++ 6.4p2:
18906   // The declarator shall not specify a function or an array.
18907   // The type-specifier-seq shall not contain typedef and shall not declare a
18908   // new class or enumeration.
18909   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18910          "Parser allowed 'typedef' as storage class of condition decl.");
18911 
18912   Decl *Dcl = ActOnDeclarator(S, D);
18913   if (!Dcl)
18914     return true;
18915 
18916   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18917     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18918       << D.getSourceRange();
18919     return true;
18920   }
18921 
18922   if (auto *VD = dyn_cast<VarDecl>(Dcl))
18923     VD->setCXXCondDecl();
18924 
18925   return Dcl;
18926 }
18927 
LoadExternalVTableUses()18928 void Sema::LoadExternalVTableUses() {
18929   if (!ExternalSource)
18930     return;
18931 
18932   SmallVector<ExternalVTableUse, 4> VTables;
18933   ExternalSource->ReadUsedVTables(VTables);
18934   SmallVector<VTableUse, 4> NewUses;
18935   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18936     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18937       = VTablesUsed.find(VTables[I].Record);
18938     // Even if a definition wasn't required before, it may be required now.
18939     if (Pos != VTablesUsed.end()) {
18940       if (!Pos->second && VTables[I].DefinitionRequired)
18941         Pos->second = true;
18942       continue;
18943     }
18944 
18945     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18946     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18947   }
18948 
18949   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18950 }
18951 
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)18952 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18953                           bool DefinitionRequired) {
18954   // Ignore any vtable uses in unevaluated operands or for classes that do
18955   // not have a vtable.
18956   if (!Class->isDynamicClass() || Class->isDependentContext() ||
18957       CurContext->isDependentContext() || isUnevaluatedContext())
18958     return;
18959   // Do not mark as used if compiling for the device outside of the target
18960   // region.
18961   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18962       !OpenMP().isInOpenMPDeclareTargetContext() &&
18963       !OpenMP().isInOpenMPTargetExecutionDirective()) {
18964     if (!DefinitionRequired)
18965       MarkVirtualMembersReferenced(Loc, Class);
18966     return;
18967   }
18968 
18969   // Try to insert this class into the map.
18970   LoadExternalVTableUses();
18971   Class = Class->getCanonicalDecl();
18972   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18973     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18974   if (!Pos.second) {
18975     // If we already had an entry, check to see if we are promoting this vtable
18976     // to require a definition. If so, we need to reappend to the VTableUses
18977     // list, since we may have already processed the first entry.
18978     if (DefinitionRequired && !Pos.first->second) {
18979       Pos.first->second = true;
18980     } else {
18981       // Otherwise, we can early exit.
18982       return;
18983     }
18984   } else {
18985     // The Microsoft ABI requires that we perform the destructor body
18986     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18987     // the deleting destructor is emitted with the vtable, not with the
18988     // destructor definition as in the Itanium ABI.
18989     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18990       CXXDestructorDecl *DD = Class->getDestructor();
18991       if (DD && DD->isVirtual() && !DD->isDeleted()) {
18992         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18993           // If this is an out-of-line declaration, marking it referenced will
18994           // not do anything. Manually call CheckDestructor to look up operator
18995           // delete().
18996           ContextRAII SavedContext(*this, DD);
18997           CheckDestructor(DD);
18998         } else {
18999           MarkFunctionReferenced(Loc, Class->getDestructor());
19000         }
19001       }
19002     }
19003   }
19004 
19005   // Local classes need to have their virtual members marked
19006   // immediately. For all other classes, we mark their virtual members
19007   // at the end of the translation unit.
19008   if (Class->isLocalClass())
19009     MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19010   else
19011     VTableUses.push_back(std::make_pair(Class, Loc));
19012 }
19013 
DefineUsedVTables()19014 bool Sema::DefineUsedVTables() {
19015   LoadExternalVTableUses();
19016   if (VTableUses.empty())
19017     return false;
19018 
19019   // Note: The VTableUses vector could grow as a result of marking
19020   // the members of a class as "used", so we check the size each
19021   // time through the loop and prefer indices (which are stable) to
19022   // iterators (which are not).
19023   bool DefinedAnything = false;
19024   for (unsigned I = 0; I != VTableUses.size(); ++I) {
19025     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19026     if (!Class)
19027       continue;
19028     TemplateSpecializationKind ClassTSK =
19029         Class->getTemplateSpecializationKind();
19030 
19031     SourceLocation Loc = VTableUses[I].second;
19032 
19033     bool DefineVTable = true;
19034 
19035     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19036     // V-tables for non-template classes with an owning module are always
19037     // uniquely emitted in that module.
19038     if (Class->isInCurrentModuleUnit()) {
19039       DefineVTable = true;
19040     } else if (KeyFunction && !KeyFunction->hasBody()) {
19041       // If this class has a key function, but that key function is
19042       // defined in another translation unit, we don't need to emit the
19043       // vtable even though we're using it.
19044       // The key function is in another translation unit.
19045       DefineVTable = false;
19046       TemplateSpecializationKind TSK =
19047           KeyFunction->getTemplateSpecializationKind();
19048       assert(TSK != TSK_ExplicitInstantiationDefinition &&
19049              TSK != TSK_ImplicitInstantiation &&
19050              "Instantiations don't have key functions");
19051       (void)TSK;
19052     } else if (!KeyFunction) {
19053       // If we have a class with no key function that is the subject
19054       // of an explicit instantiation declaration, suppress the
19055       // vtable; it will live with the explicit instantiation
19056       // definition.
19057       bool IsExplicitInstantiationDeclaration =
19058           ClassTSK == TSK_ExplicitInstantiationDeclaration;
19059       for (auto *R : Class->redecls()) {
19060         TemplateSpecializationKind TSK
19061           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19062         if (TSK == TSK_ExplicitInstantiationDeclaration)
19063           IsExplicitInstantiationDeclaration = true;
19064         else if (TSK == TSK_ExplicitInstantiationDefinition) {
19065           IsExplicitInstantiationDeclaration = false;
19066           break;
19067         }
19068       }
19069 
19070       if (IsExplicitInstantiationDeclaration)
19071         DefineVTable = false;
19072     }
19073 
19074     // The exception specifications for all virtual members may be needed even
19075     // if we are not providing an authoritative form of the vtable in this TU.
19076     // We may choose to emit it available_externally anyway.
19077     if (!DefineVTable) {
19078       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
19079       continue;
19080     }
19081 
19082     // Mark all of the virtual members of this class as referenced, so
19083     // that we can build a vtable. Then, tell the AST consumer that a
19084     // vtable for this class is required.
19085     DefinedAnything = true;
19086     MarkVirtualMembersReferenced(Loc, Class);
19087     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19088     if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19089       Consumer.HandleVTable(Class);
19090 
19091     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19092     // no key function or the key function is inlined. Don't warn in C++ ABIs
19093     // that lack key functions, since the user won't be able to make one.
19094     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19095         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19096         ClassTSK != TSK_ExplicitInstantiationDefinition) {
19097       const FunctionDecl *KeyFunctionDef = nullptr;
19098       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19099                            KeyFunctionDef->isInlined()))
19100         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19101     }
19102   }
19103   VTableUses.clear();
19104 
19105   return DefinedAnything;
19106 }
19107 
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)19108 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19109                                                  const CXXRecordDecl *RD) {
19110   for (const auto *I : RD->methods())
19111     if (I->isVirtual() && !I->isPureVirtual())
19112       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19113 }
19114 
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD,bool ConstexprOnly)19115 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19116                                         const CXXRecordDecl *RD,
19117                                         bool ConstexprOnly) {
19118   // Mark all functions which will appear in RD's vtable as used.
19119   CXXFinalOverriderMap FinalOverriders;
19120   RD->getFinalOverriders(FinalOverriders);
19121   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
19122                                             E = FinalOverriders.end();
19123        I != E; ++I) {
19124     for (OverridingMethods::const_iterator OI = I->second.begin(),
19125                                            OE = I->second.end();
19126          OI != OE; ++OI) {
19127       assert(OI->second.size() > 0 && "no final overrider");
19128       CXXMethodDecl *Overrider = OI->second.front().Method;
19129 
19130       // C++ [basic.def.odr]p2:
19131       //   [...] A virtual member function is used if it is not pure. [...]
19132       if (!Overrider->isPureVirtual() &&
19133           (!ConstexprOnly || Overrider->isConstexpr()))
19134         MarkFunctionReferenced(Loc, Overrider);
19135     }
19136   }
19137 
19138   // Only classes that have virtual bases need a VTT.
19139   if (RD->getNumVBases() == 0)
19140     return;
19141 
19142   for (const auto &I : RD->bases()) {
19143     const auto *Base =
19144         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
19145     if (Base->getNumVBases() == 0)
19146       continue;
19147     MarkVirtualMembersReferenced(Loc, Base);
19148   }
19149 }
19150 
19151 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Valid,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Current,Sema & S)19152 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19153                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19154                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19155                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19156                            Sema &S) {
19157   if (Ctor->isInvalidDecl())
19158     return;
19159 
19160   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19161 
19162   // Target may not be determinable yet, for instance if this is a dependent
19163   // call in an uninstantiated template.
19164   if (Target) {
19165     const FunctionDecl *FNTarget = nullptr;
19166     (void)Target->hasBody(FNTarget);
19167     Target = const_cast<CXXConstructorDecl*>(
19168       cast_or_null<CXXConstructorDecl>(FNTarget));
19169   }
19170 
19171   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19172                      // Avoid dereferencing a null pointer here.
19173                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19174 
19175   if (!Current.insert(Canonical).second)
19176     return;
19177 
19178   // We know that beyond here, we aren't chaining into a cycle.
19179   if (!Target || !Target->isDelegatingConstructor() ||
19180       Target->isInvalidDecl() || Valid.count(TCanonical)) {
19181     Valid.insert_range(Current);
19182     Current.clear();
19183   // We've hit a cycle.
19184   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19185              Current.count(TCanonical)) {
19186     // If we haven't diagnosed this cycle yet, do so now.
19187     if (!Invalid.count(TCanonical)) {
19188       S.Diag((*Ctor->init_begin())->getSourceLocation(),
19189              diag::warn_delegating_ctor_cycle)
19190         << Ctor;
19191 
19192       // Don't add a note for a function delegating directly to itself.
19193       if (TCanonical != Canonical)
19194         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19195 
19196       CXXConstructorDecl *C = Target;
19197       while (C->getCanonicalDecl() != Canonical) {
19198         const FunctionDecl *FNTarget = nullptr;
19199         (void)C->getTargetConstructor()->hasBody(FNTarget);
19200         assert(FNTarget && "Ctor cycle through bodiless function");
19201 
19202         C = const_cast<CXXConstructorDecl*>(
19203           cast<CXXConstructorDecl>(FNTarget));
19204         S.Diag(C->getLocation(), diag::note_which_delegates_to);
19205       }
19206     }
19207 
19208     Invalid.insert_range(Current);
19209     Current.clear();
19210   } else {
19211     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
19212   }
19213 }
19214 
19215 
CheckDelegatingCtorCycles()19216 void Sema::CheckDelegatingCtorCycles() {
19217   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19218 
19219   for (DelegatingCtorDeclsType::iterator
19220            I = DelegatingCtorDecls.begin(ExternalSource.get()),
19221            E = DelegatingCtorDecls.end();
19222        I != E; ++I)
19223     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19224 
19225   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
19226     (*CI)->setInvalidDecl();
19227 }
19228 
19229 namespace {
19230   /// AST visitor that finds references to the 'this' expression.
19231 class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19232   Sema &S;
19233 
19234 public:
FindCXXThisExpr(Sema & S)19235   explicit FindCXXThisExpr(Sema &S) : S(S) {}
19236 
VisitCXXThisExpr(CXXThisExpr * E)19237   bool VisitCXXThisExpr(CXXThisExpr *E) override {
19238     S.Diag(E->getLocation(), diag::err_this_static_member_func)
19239         << E->isImplicit();
19240     return false;
19241   }
19242 };
19243 }
19244 
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)19245 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19246   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19247   if (!TSInfo)
19248     return false;
19249 
19250   TypeLoc TL = TSInfo->getTypeLoc();
19251   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19252   if (!ProtoTL)
19253     return false;
19254 
19255   // C++11 [expr.prim.general]p3:
19256   //   [The expression this] shall not appear before the optional
19257   //   cv-qualifier-seq and it shall not appear within the declaration of a
19258   //   static member function (although its type and value category are defined
19259   //   within a static member function as they are within a non-static member
19260   //   function). [ Note: this is because declaration matching does not occur
19261   //  until the complete declarator is known. - end note ]
19262   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19263   FindCXXThisExpr Finder(*this);
19264 
19265   // If the return type came after the cv-qualifier-seq, check it now.
19266   if (Proto->hasTrailingReturn() &&
19267       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19268     return true;
19269 
19270   // Check the exception specification.
19271   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19272     return true;
19273 
19274   // Check the trailing requires clause
19275   if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19276     if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19277       return true;
19278 
19279   return checkThisInStaticMemberFunctionAttributes(Method);
19280 }
19281 
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)19282 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19283   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19284   if (!TSInfo)
19285     return false;
19286 
19287   TypeLoc TL = TSInfo->getTypeLoc();
19288   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19289   if (!ProtoTL)
19290     return false;
19291 
19292   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19293   FindCXXThisExpr Finder(*this);
19294 
19295   switch (Proto->getExceptionSpecType()) {
19296   case EST_Unparsed:
19297   case EST_Uninstantiated:
19298   case EST_Unevaluated:
19299   case EST_BasicNoexcept:
19300   case EST_NoThrow:
19301   case EST_DynamicNone:
19302   case EST_MSAny:
19303   case EST_None:
19304     break;
19305 
19306   case EST_DependentNoexcept:
19307   case EST_NoexceptFalse:
19308   case EST_NoexceptTrue:
19309     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19310       return true;
19311     [[fallthrough]];
19312 
19313   case EST_Dynamic:
19314     for (const auto &E : Proto->exceptions()) {
19315       if (!Finder.TraverseType(E))
19316         return true;
19317     }
19318     break;
19319   }
19320 
19321   return false;
19322 }
19323 
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)19324 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19325   FindCXXThisExpr Finder(*this);
19326 
19327   // Check attributes.
19328   for (const auto *A : Method->attrs()) {
19329     // FIXME: This should be emitted by tblgen.
19330     Expr *Arg = nullptr;
19331     ArrayRef<Expr *> Args;
19332     if (const auto *G = dyn_cast<GuardedByAttr>(A))
19333       Arg = G->getArg();
19334     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19335       Arg = G->getArg();
19336     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19337       Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19338     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19339       Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19340     else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19341       Arg = LR->getArg();
19342     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19343       Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19344     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19345       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19346     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19347       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19348     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19349       Arg = AC->getSuccessValue();
19350       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19351     } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19352       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19353 
19354     if (Arg && !Finder.TraverseStmt(Arg))
19355       return true;
19356 
19357     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19358       if (!Finder.TraverseStmt(Args[I]))
19359         return true;
19360     }
19361   }
19362 
19363   return false;
19364 }
19365 
checkExceptionSpecification(bool IsTopLevel,ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExceptionSpecInfo & ESI)19366 void Sema::checkExceptionSpecification(
19367     bool IsTopLevel, ExceptionSpecificationType EST,
19368     ArrayRef<ParsedType> DynamicExceptions,
19369     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19370     SmallVectorImpl<QualType> &Exceptions,
19371     FunctionProtoType::ExceptionSpecInfo &ESI) {
19372   Exceptions.clear();
19373   ESI.Type = EST;
19374   if (EST == EST_Dynamic) {
19375     Exceptions.reserve(DynamicExceptions.size());
19376     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19377       // FIXME: Preserve type source info.
19378       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19379 
19380       if (IsTopLevel) {
19381         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19382         collectUnexpandedParameterPacks(ET, Unexpanded);
19383         if (!Unexpanded.empty()) {
19384           DiagnoseUnexpandedParameterPacks(
19385               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19386               Unexpanded);
19387           continue;
19388         }
19389       }
19390 
19391       // Check that the type is valid for an exception spec, and
19392       // drop it if not.
19393       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19394         Exceptions.push_back(ET);
19395     }
19396     ESI.Exceptions = Exceptions;
19397     return;
19398   }
19399 
19400   if (isComputedNoexcept(EST)) {
19401     assert((NoexceptExpr->isTypeDependent() ||
19402             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19403             Context.BoolTy) &&
19404            "Parser should have made sure that the expression is boolean");
19405     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19406       ESI.Type = EST_BasicNoexcept;
19407       return;
19408     }
19409 
19410     ESI.NoexceptExpr = NoexceptExpr;
19411     return;
19412   }
19413 }
19414 
actOnDelayedExceptionSpecification(Decl * D,ExceptionSpecificationType EST,SourceRange SpecificationRange,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr)19415 void Sema::actOnDelayedExceptionSpecification(
19416     Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19417     ArrayRef<ParsedType> DynamicExceptions,
19418     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19419   if (!D)
19420     return;
19421 
19422   // Dig out the function we're referring to.
19423   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19424     D = FTD->getTemplatedDecl();
19425 
19426   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19427   if (!FD)
19428     return;
19429 
19430   // Check the exception specification.
19431   llvm::SmallVector<QualType, 4> Exceptions;
19432   FunctionProtoType::ExceptionSpecInfo ESI;
19433   checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19434                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
19435                               ESI);
19436 
19437   // Update the exception specification on the function type.
19438   Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19439 
19440   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19441     if (MD->isStatic())
19442       checkThisInStaticMemberFunctionExceptionSpec(MD);
19443 
19444     if (MD->isVirtual()) {
19445       // Check overrides, which we previously had to delay.
19446       for (const CXXMethodDecl *O : MD->overridden_methods())
19447         CheckOverridingFunctionExceptionSpec(MD, O);
19448     }
19449   }
19450 }
19451 
19452 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19453 ///
HandleMSProperty(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS,const ParsedAttr & MSPropertyAttr)19454 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19455                                        SourceLocation DeclStart, Declarator &D,
19456                                        Expr *BitWidth,
19457                                        InClassInitStyle InitStyle,
19458                                        AccessSpecifier AS,
19459                                        const ParsedAttr &MSPropertyAttr) {
19460   const IdentifierInfo *II = D.getIdentifier();
19461   if (!II) {
19462     Diag(DeclStart, diag::err_anonymous_property);
19463     return nullptr;
19464   }
19465   SourceLocation Loc = D.getIdentifierLoc();
19466 
19467   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19468   QualType T = TInfo->getType();
19469   if (getLangOpts().CPlusPlus) {
19470     CheckExtraCXXDefaultArguments(D);
19471 
19472     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19473                                         UPPC_DataMemberType)) {
19474       D.setInvalidType();
19475       T = Context.IntTy;
19476       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19477     }
19478   }
19479 
19480   DiagnoseFunctionSpecifiers(D.getDeclSpec());
19481 
19482   if (D.getDeclSpec().isInlineSpecified())
19483     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19484         << getLangOpts().CPlusPlus17;
19485   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19486     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19487          diag::err_invalid_thread)
19488       << DeclSpec::getSpecifierName(TSCS);
19489 
19490   // Check to see if this name was declared as a member previously
19491   NamedDecl *PrevDecl = nullptr;
19492   LookupResult Previous(*this, II, Loc, LookupMemberName,
19493                         RedeclarationKind::ForVisibleRedeclaration);
19494   LookupName(Previous, S);
19495   switch (Previous.getResultKind()) {
19496   case LookupResultKind::Found:
19497   case LookupResultKind::FoundUnresolvedValue:
19498     PrevDecl = Previous.getAsSingle<NamedDecl>();
19499     break;
19500 
19501   case LookupResultKind::FoundOverloaded:
19502     PrevDecl = Previous.getRepresentativeDecl();
19503     break;
19504 
19505   case LookupResultKind::NotFound:
19506   case LookupResultKind::NotFoundInCurrentInstantiation:
19507   case LookupResultKind::Ambiguous:
19508     break;
19509   }
19510 
19511   if (PrevDecl && PrevDecl->isTemplateParameter()) {
19512     // Maybe we will complain about the shadowed template parameter.
19513     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19514     // Just pretend that we didn't see the previous declaration.
19515     PrevDecl = nullptr;
19516   }
19517 
19518   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19519     PrevDecl = nullptr;
19520 
19521   SourceLocation TSSL = D.getBeginLoc();
19522   MSPropertyDecl *NewPD =
19523       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19524                              MSPropertyAttr.getPropertyDataGetter(),
19525                              MSPropertyAttr.getPropertyDataSetter());
19526   ProcessDeclAttributes(TUScope, NewPD, D);
19527   NewPD->setAccess(AS);
19528 
19529   if (NewPD->isInvalidDecl())
19530     Record->setInvalidDecl();
19531 
19532   if (D.getDeclSpec().isModulePrivateSpecified())
19533     NewPD->setModulePrivate();
19534 
19535   if (NewPD->isInvalidDecl() && PrevDecl) {
19536     // Don't introduce NewFD into scope; there's already something
19537     // with the same name in the same scope.
19538   } else if (II) {
19539     PushOnScopeChains(NewPD, S);
19540   } else
19541     Record->addDecl(NewPD);
19542 
19543   return NewPD;
19544 }
19545 
ActOnStartFunctionDeclarationDeclarator(Declarator & Declarator,unsigned TemplateParameterDepth)19546 void Sema::ActOnStartFunctionDeclarationDeclarator(
19547     Declarator &Declarator, unsigned TemplateParameterDepth) {
19548   auto &Info = InventedParameterInfos.emplace_back();
19549   TemplateParameterList *ExplicitParams = nullptr;
19550   ArrayRef<TemplateParameterList *> ExplicitLists =
19551       Declarator.getTemplateParameterLists();
19552   if (!ExplicitLists.empty()) {
19553     bool IsMemberSpecialization, IsInvalid;
19554     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19555         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
19556         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19557         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19558         /*SuppressDiagnostic=*/true);
19559   }
19560   // C++23 [dcl.fct]p23:
19561   //   An abbreviated function template can have a template-head. The invented
19562   //   template-parameters are appended to the template-parameter-list after
19563   //   the explicitly declared template-parameters.
19564   //
19565   // A template-head must have one or more template-parameters (read:
19566   // 'template<>' is *not* a template-head). Only append the invented
19567   // template parameters if we matched the nested-name-specifier to a non-empty
19568   // TemplateParameterList.
19569   if (ExplicitParams && !ExplicitParams->empty()) {
19570     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19571     llvm::append_range(Info.TemplateParams, *ExplicitParams);
19572     Info.NumExplicitTemplateParams = ExplicitParams->size();
19573   } else {
19574     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19575     Info.NumExplicitTemplateParams = 0;
19576   }
19577 }
19578 
ActOnFinishFunctionDeclarationDeclarator(Declarator & Declarator)19579 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19580   auto &FSI = InventedParameterInfos.back();
19581   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19582     if (FSI.NumExplicitTemplateParams != 0) {
19583       TemplateParameterList *ExplicitParams =
19584           Declarator.getTemplateParameterLists().back();
19585       Declarator.setInventedTemplateParameterList(
19586           TemplateParameterList::Create(
19587               Context, ExplicitParams->getTemplateLoc(),
19588               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19589               ExplicitParams->getRAngleLoc(),
19590               ExplicitParams->getRequiresClause()));
19591     } else {
19592       Declarator.setInventedTemplateParameterList(
19593           TemplateParameterList::Create(
19594               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19595               SourceLocation(), /*RequiresClause=*/nullptr));
19596     }
19597   }
19598   InventedParameterInfos.pop_back();
19599 }
19600