1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.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/RecursiveASTVisitor.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Basic/AttributeCommonInfo.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/EnterExpressionEvaluationContext.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Ownership.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/ScopeExit.h"
50 #include "llvm/ADT/SmallString.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Support/ConvertUTF.h"
53 #include "llvm/Support/SaveAndRestore.h"
54 #include <map>
55 #include <optional>
56 #include <set>
57
58 using namespace clang;
59
60 //===----------------------------------------------------------------------===//
61 // CheckDefaultArgumentVisitor
62 //===----------------------------------------------------------------------===//
63
64 namespace {
65 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
66 /// the default argument of a parameter to determine whether it
67 /// contains any ill-formed subexpressions. For example, this will
68 /// diagnose the use of local variables or parameters within the
69 /// default argument expression.
70 class CheckDefaultArgumentVisitor
71 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
72 Sema &S;
73 const Expr *DefaultArg;
74
75 public:
CheckDefaultArgumentVisitor(Sema & S,const Expr * DefaultArg)76 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
77 : S(S), DefaultArg(DefaultArg) {}
78
79 bool VisitExpr(const Expr *Node);
80 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
81 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
82 bool VisitLambdaExpr(const LambdaExpr *Lambda);
83 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
84 };
85
86 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(const Expr * Node)87 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
88 bool IsInvalid = false;
89 for (const Stmt *SubStmt : Node->children())
90 if (SubStmt)
91 IsInvalid |= Visit(SubStmt);
92 return IsInvalid;
93 }
94
95 /// VisitDeclRefExpr - Visit a reference to a declaration, to
96 /// determine whether this declaration can be used in the default
97 /// argument expression.
VisitDeclRefExpr(const DeclRefExpr * DRE)98 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
99 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
100
101 if (!isa<VarDecl, BindingDecl>(Decl))
102 return false;
103
104 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
105 // C++ [dcl.fct.default]p9:
106 // [...] parameters of a function shall not be used in default
107 // argument expressions, even if they are not evaluated. [...]
108 //
109 // C++17 [dcl.fct.default]p9 (by CWG 2082):
110 // [...] A parameter shall not appear as a potentially-evaluated
111 // expression in a default argument. [...]
112 //
113 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
114 return S.Diag(DRE->getBeginLoc(),
115 diag::err_param_default_argument_references_param)
116 << Param->getDeclName() << DefaultArg->getSourceRange();
117 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
118 // C++ [dcl.fct.default]p7:
119 // Local variables shall not be used in default argument
120 // expressions.
121 //
122 // C++17 [dcl.fct.default]p7 (by CWG 2082):
123 // A local variable shall not appear as a potentially-evaluated
124 // expression in a default argument.
125 //
126 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
127 // Note: A local variable cannot be odr-used (6.3) in a default
128 // argument.
129 //
130 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
131 return S.Diag(DRE->getBeginLoc(),
132 diag::err_param_default_argument_references_local)
133 << Decl << DefaultArg->getSourceRange();
134 }
135 return false;
136 }
137
138 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(const CXXThisExpr * ThisE)139 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
140 // C++ [dcl.fct.default]p8:
141 // The keyword this shall not be used in a default argument of a
142 // member function.
143 return S.Diag(ThisE->getBeginLoc(),
144 diag::err_param_default_argument_references_this)
145 << ThisE->getSourceRange();
146 }
147
VisitPseudoObjectExpr(const PseudoObjectExpr * POE)148 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
149 const PseudoObjectExpr *POE) {
150 bool Invalid = false;
151 for (const Expr *E : POE->semantics()) {
152 // Look through bindings.
153 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
154 E = OVE->getSourceExpr();
155 assert(E && "pseudo-object binding without source expression?");
156 }
157
158 Invalid |= Visit(E);
159 }
160 return Invalid;
161 }
162
VisitLambdaExpr(const LambdaExpr * Lambda)163 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
164 // [expr.prim.lambda.capture]p9
165 // a lambda-expression appearing in a default argument cannot implicitly or
166 // explicitly capture any local entity. Such a lambda-expression can still
167 // have an init-capture if any full-expression in its initializer satisfies
168 // the constraints of an expression appearing in a default argument.
169 bool Invalid = false;
170 for (const LambdaCapture &LC : Lambda->captures()) {
171 if (!Lambda->isInitCapture(&LC))
172 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
173 // Init captures are always VarDecl.
174 auto *D = cast<VarDecl>(LC.getCapturedVar());
175 Invalid |= Visit(D->getInit());
176 }
177 return Invalid;
178 }
179 } // namespace
180
181 void
CalledDecl(SourceLocation CallLoc,const CXXMethodDecl * Method)182 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
183 const CXXMethodDecl *Method) {
184 // If we have an MSAny spec already, don't bother.
185 if (!Method || ComputedEST == EST_MSAny)
186 return;
187
188 const FunctionProtoType *Proto
189 = Method->getType()->getAs<FunctionProtoType>();
190 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
191 if (!Proto)
192 return;
193
194 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
195
196 // If we have a throw-all spec at this point, ignore the function.
197 if (ComputedEST == EST_None)
198 return;
199
200 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
201 EST = EST_BasicNoexcept;
202
203 switch (EST) {
204 case EST_Unparsed:
205 case EST_Uninstantiated:
206 case EST_Unevaluated:
207 llvm_unreachable("should not see unresolved exception specs here");
208
209 // If this function can throw any exceptions, make a note of that.
210 case EST_MSAny:
211 case EST_None:
212 // FIXME: Whichever we see last of MSAny and None determines our result.
213 // We should make a consistent, order-independent choice here.
214 ClearExceptions();
215 ComputedEST = EST;
216 return;
217 case EST_NoexceptFalse:
218 ClearExceptions();
219 ComputedEST = EST_None;
220 return;
221 // FIXME: If the call to this decl is using any of its default arguments, we
222 // need to search them for potentially-throwing calls.
223 // If this function has a basic noexcept, it doesn't affect the outcome.
224 case EST_BasicNoexcept:
225 case EST_NoexceptTrue:
226 case EST_NoThrow:
227 return;
228 // If we're still at noexcept(true) and there's a throw() callee,
229 // change to that specification.
230 case EST_DynamicNone:
231 if (ComputedEST == EST_BasicNoexcept)
232 ComputedEST = EST_DynamicNone;
233 return;
234 case EST_DependentNoexcept:
235 llvm_unreachable(
236 "should not generate implicit declarations for dependent cases");
237 case EST_Dynamic:
238 break;
239 }
240 assert(EST == EST_Dynamic && "EST case not considered earlier.");
241 assert(ComputedEST != EST_None &&
242 "Shouldn't collect exceptions when throw-all is guaranteed.");
243 ComputedEST = EST_Dynamic;
244 // Record the exceptions in this function's exception specification.
245 for (const auto &E : Proto->exceptions())
246 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
247 Exceptions.push_back(E);
248 }
249
CalledStmt(Stmt * S)250 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
251 if (!S || ComputedEST == EST_MSAny)
252 return;
253
254 // FIXME:
255 //
256 // C++0x [except.spec]p14:
257 // [An] implicit exception-specification specifies the type-id T if and
258 // only if T is allowed by the exception-specification of a function directly
259 // invoked by f's implicit definition; f shall allow all exceptions if any
260 // function it directly invokes allows all exceptions, and f shall allow no
261 // exceptions if every function it directly invokes allows no exceptions.
262 //
263 // Note in particular that if an implicit exception-specification is generated
264 // for a function containing a throw-expression, that specification can still
265 // be noexcept(true).
266 //
267 // Note also that 'directly invoked' is not defined in the standard, and there
268 // is no indication that we should only consider potentially-evaluated calls.
269 //
270 // Ultimately we should implement the intent of the standard: the exception
271 // specification should be the set of exceptions which can be thrown by the
272 // implicit definition. For now, we assume that any non-nothrow expression can
273 // throw any exception.
274
275 if (Self->canThrow(S))
276 ComputedEST = EST_None;
277 }
278
ConvertParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)279 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
280 SourceLocation EqualLoc) {
281 if (RequireCompleteType(Param->getLocation(), Param->getType(),
282 diag::err_typecheck_decl_incomplete_type))
283 return true;
284
285 // C++ [dcl.fct.default]p5
286 // A default argument expression is implicitly converted (clause
287 // 4) to the parameter type. The default argument expression has
288 // the same semantic constraints as the initializer expression in
289 // a declaration of a variable of the parameter type, using the
290 // copy-initialization semantics (8.5).
291 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
292 Param);
293 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
294 EqualLoc);
295 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
297 if (Result.isInvalid())
298 return true;
299 Arg = Result.getAs<Expr>();
300
301 CheckCompletedExpr(Arg, EqualLoc);
302 Arg = MaybeCreateExprWithCleanups(Arg);
303
304 return Arg;
305 }
306
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)307 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
308 SourceLocation EqualLoc) {
309 // Add the default argument to the parameter
310 Param->setDefaultArg(Arg);
311
312 // We have already instantiated this parameter; provide each of the
313 // instantiations with the uninstantiated default argument.
314 UnparsedDefaultArgInstantiationsMap::iterator InstPos
315 = UnparsedDefaultArgInstantiations.find(Param);
316 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
317 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
318 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
319
320 // We're done tracking this parameter's instantiations.
321 UnparsedDefaultArgInstantiations.erase(InstPos);
322 }
323 }
324
325 /// ActOnParamDefaultArgument - Check whether the default argument
326 /// provided for a function parameter is well-formed. If so, attach it
327 /// to the parameter declaration.
328 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)329 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
330 Expr *DefaultArg) {
331 if (!param || !DefaultArg)
332 return;
333
334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
335 UnparsedDefaultArgLocs.erase(Param);
336
337 // Default arguments are only permitted in C++
338 if (!getLangOpts().CPlusPlus) {
339 Diag(EqualLoc, diag::err_param_default_argument)
340 << DefaultArg->getSourceRange();
341 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
342 }
343
344 // Check for unexpanded parameter packs.
345 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))
346 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
347
348 // C++11 [dcl.fct.default]p3
349 // A default argument expression [...] shall not be specified for a
350 // parameter pack.
351 if (Param->isParameterPack()) {
352 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
353 << DefaultArg->getSourceRange();
354 // Recover by discarding the default argument.
355 Param->setDefaultArg(nullptr);
356 return;
357 }
358
359 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
360 if (Result.isInvalid())
361 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
362
363 DefaultArg = Result.getAs<Expr>();
364
365 // Check that the default argument is well-formed
366 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
367 if (DefaultArgChecker.Visit(DefaultArg))
368 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
369
370 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
371 }
372
373 /// ActOnParamUnparsedDefaultArgument - We've seen a default
374 /// argument for a function parameter, but we can't parse it yet
375 /// because we're inside a class definition. Note that this default
376 /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)377 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
378 SourceLocation EqualLoc,
379 SourceLocation ArgLoc) {
380 if (!param)
381 return;
382
383 ParmVarDecl *Param = cast<ParmVarDecl>(param);
384 Param->setUnparsedDefaultArg();
385 UnparsedDefaultArgLocs[Param] = ArgLoc;
386 }
387
388 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389 /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)390 void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
391 Expr *DefaultArg) {
392 if (!param)
393 return;
394
395 ParmVarDecl *Param = cast<ParmVarDecl>(param);
396 Param->setInvalidDecl();
397 UnparsedDefaultArgLocs.erase(Param);
398 ExprResult RE;
399 if (DefaultArg) {
400 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
401 Param->getType().getNonReferenceType());
402 } else {
403 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
404 Param->getType().getNonReferenceType());
405 }
406 Param->setDefaultArg(RE.get());
407 }
408
409 /// CheckExtraCXXDefaultArguments - Check for any extra default
410 /// arguments in the declarator, which is not a function declaration
411 /// or definition and therefore is not permitted to have default
412 /// arguments. This routine should be invoked for every declarator
413 /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)414 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
415 // C++ [dcl.fct.default]p3
416 // A default argument expression shall be specified only in the
417 // parameter-declaration-clause of a function declaration or in a
418 // template-parameter (14.1). It shall not be specified for a
419 // parameter pack. If it is specified in a
420 // parameter-declaration-clause, it shall not occur within a
421 // declarator or abstract-declarator of a parameter-declaration.
422 bool MightBeFunction = D.isFunctionDeclarationContext();
423 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
424 DeclaratorChunk &chunk = D.getTypeObject(i);
425 if (chunk.Kind == DeclaratorChunk::Function) {
426 if (MightBeFunction) {
427 // This is a function declaration. It can have default arguments, but
428 // keep looking in case its return type is a function type with default
429 // arguments.
430 MightBeFunction = false;
431 continue;
432 }
433 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
434 ++argIdx) {
435 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
436 if (Param->hasUnparsedDefaultArg()) {
437 std::unique_ptr<CachedTokens> Toks =
438 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
439 SourceRange SR;
440 if (Toks->size() > 1)
441 SR = SourceRange((*Toks)[1].getLocation(),
442 Toks->back().getLocation());
443 else
444 SR = UnparsedDefaultArgLocs[Param];
445 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
446 << SR;
447 } else if (Param->getDefaultArg()) {
448 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
449 << Param->getDefaultArg()->getSourceRange();
450 Param->setDefaultArg(nullptr);
451 }
452 }
453 } else if (chunk.Kind != DeclaratorChunk::Paren) {
454 MightBeFunction = false;
455 }
456 }
457 }
458
functionDeclHasDefaultArgument(const FunctionDecl * FD)459 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
460 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
461 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
462 });
463 }
464
465 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
466 /// function, once we already know that they have the same
467 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
468 /// error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)469 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
470 Scope *S) {
471 bool Invalid = false;
472
473 // The declaration context corresponding to the scope is the semantic
474 // parent, unless this is a local function declaration, in which case
475 // it is that surrounding function.
476 DeclContext *ScopeDC = New->isLocalExternDecl()
477 ? New->getLexicalDeclContext()
478 : New->getDeclContext();
479
480 // Find the previous declaration for the purpose of default arguments.
481 FunctionDecl *PrevForDefaultArgs = Old;
482 for (/**/; PrevForDefaultArgs;
483 // Don't bother looking back past the latest decl if this is a local
484 // extern declaration; nothing else could work.
485 PrevForDefaultArgs = New->isLocalExternDecl()
486 ? nullptr
487 : PrevForDefaultArgs->getPreviousDecl()) {
488 // Ignore hidden declarations.
489 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
490 continue;
491
492 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
493 !New->isCXXClassMember()) {
494 // Ignore default arguments of old decl if they are not in
495 // the same scope and this is not an out-of-line definition of
496 // a member function.
497 continue;
498 }
499
500 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
501 // If only one of these is a local function declaration, then they are
502 // declared in different scopes, even though isDeclInScope may think
503 // they're in the same scope. (If both are local, the scope check is
504 // sufficient, and if neither is local, then they are in the same scope.)
505 continue;
506 }
507
508 // We found the right previous declaration.
509 break;
510 }
511
512 // C++ [dcl.fct.default]p4:
513 // For non-template functions, default arguments can be added in
514 // later declarations of a function in the same
515 // scope. Declarations in different scopes have completely
516 // distinct sets of default arguments. That is, declarations in
517 // inner scopes do not acquire default arguments from
518 // declarations in outer scopes, and vice versa. In a given
519 // function declaration, all parameters subsequent to a
520 // parameter with a default argument shall have default
521 // arguments supplied in this or previous declarations. A
522 // default argument shall not be redefined by a later
523 // declaration (not even to the same value).
524 //
525 // C++ [dcl.fct.default]p6:
526 // Except for member functions of class templates, the default arguments
527 // in a member function definition that appears outside of the class
528 // definition are added to the set of default arguments provided by the
529 // member function declaration in the class definition.
530 for (unsigned p = 0, NumParams = PrevForDefaultArgs
531 ? PrevForDefaultArgs->getNumParams()
532 : 0;
533 p < NumParams; ++p) {
534 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
535 ParmVarDecl *NewParam = New->getParamDecl(p);
536
537 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
538 bool NewParamHasDfl = NewParam->hasDefaultArg();
539
540 if (OldParamHasDfl && NewParamHasDfl) {
541 unsigned DiagDefaultParamID =
542 diag::err_param_default_argument_redefinition;
543
544 // MSVC accepts that default parameters be redefined for member functions
545 // of template class. The new default parameter's value is ignored.
546 Invalid = true;
547 if (getLangOpts().MicrosoftExt) {
548 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
549 if (MD && MD->getParent()->getDescribedClassTemplate()) {
550 // Merge the old default argument into the new parameter.
551 NewParam->setHasInheritedDefaultArg();
552 if (OldParam->hasUninstantiatedDefaultArg())
553 NewParam->setUninstantiatedDefaultArg(
554 OldParam->getUninstantiatedDefaultArg());
555 else
556 NewParam->setDefaultArg(OldParam->getInit());
557 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
558 Invalid = false;
559 }
560 }
561
562 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
563 // hint here. Alternatively, we could walk the type-source information
564 // for NewParam to find the last source location in the type... but it
565 // isn't worth the effort right now. This is the kind of test case that
566 // is hard to get right:
567 // int f(int);
568 // void g(int (*fp)(int) = f);
569 // void g(int (*fp)(int) = &f);
570 Diag(NewParam->getLocation(), DiagDefaultParamID)
571 << NewParam->getDefaultArgRange();
572
573 // Look for the function declaration where the default argument was
574 // actually written, which may be a declaration prior to Old.
575 for (auto Older = PrevForDefaultArgs;
576 OldParam->hasInheritedDefaultArg(); /**/) {
577 Older = Older->getPreviousDecl();
578 OldParam = Older->getParamDecl(p);
579 }
580
581 Diag(OldParam->getLocation(), diag::note_previous_definition)
582 << OldParam->getDefaultArgRange();
583 } else if (OldParamHasDfl) {
584 // Merge the old default argument into the new parameter unless the new
585 // function is a friend declaration in a template class. In the latter
586 // case the default arguments will be inherited when the friend
587 // declaration will be instantiated.
588 if (New->getFriendObjectKind() == Decl::FOK_None ||
589 !New->getLexicalDeclContext()->isDependentContext()) {
590 // It's important to use getInit() here; getDefaultArg()
591 // strips off any top-level ExprWithCleanups.
592 NewParam->setHasInheritedDefaultArg();
593 if (OldParam->hasUnparsedDefaultArg())
594 NewParam->setUnparsedDefaultArg();
595 else if (OldParam->hasUninstantiatedDefaultArg())
596 NewParam->setUninstantiatedDefaultArg(
597 OldParam->getUninstantiatedDefaultArg());
598 else
599 NewParam->setDefaultArg(OldParam->getInit());
600 }
601 } else if (NewParamHasDfl) {
602 if (New->getDescribedFunctionTemplate()) {
603 // Paragraph 4, quoted above, only applies to non-template functions.
604 Diag(NewParam->getLocation(),
605 diag::err_param_default_argument_template_redecl)
606 << NewParam->getDefaultArgRange();
607 Diag(PrevForDefaultArgs->getLocation(),
608 diag::note_template_prev_declaration)
609 << false;
610 } else if (New->getTemplateSpecializationKind()
611 != TSK_ImplicitInstantiation &&
612 New->getTemplateSpecializationKind() != TSK_Undeclared) {
613 // C++ [temp.expr.spec]p21:
614 // Default function arguments shall not be specified in a declaration
615 // or a definition for one of the following explicit specializations:
616 // - the explicit specialization of a function template;
617 // - the explicit specialization of a member function template;
618 // - the explicit specialization of a member function of a class
619 // template where the class template specialization to which the
620 // member function specialization belongs is implicitly
621 // instantiated.
622 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
623 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
624 << New->getDeclName()
625 << NewParam->getDefaultArgRange();
626 } else if (New->getDeclContext()->isDependentContext()) {
627 // C++ [dcl.fct.default]p6 (DR217):
628 // Default arguments for a member function of a class template shall
629 // be specified on the initial declaration of the member function
630 // within the class template.
631 //
632 // Reading the tea leaves a bit in DR217 and its reference to DR205
633 // leads me to the conclusion that one cannot add default function
634 // arguments for an out-of-line definition of a member function of a
635 // dependent type.
636 int WhichKind = 2;
637 if (CXXRecordDecl *Record
638 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
639 if (Record->getDescribedClassTemplate())
640 WhichKind = 0;
641 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
642 WhichKind = 1;
643 else
644 WhichKind = 2;
645 }
646
647 Diag(NewParam->getLocation(),
648 diag::err_param_default_argument_member_template_redecl)
649 << WhichKind
650 << NewParam->getDefaultArgRange();
651 }
652 }
653 }
654
655 // DR1344: If a default argument is added outside a class definition and that
656 // default argument makes the function a special member function, the program
657 // is ill-formed. This can only happen for constructors.
658 if (isa<CXXConstructorDecl>(New) &&
659 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
660 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
661 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
662 if (NewSM != OldSM) {
663 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
664 assert(NewParam->hasDefaultArg());
665 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
666 << NewParam->getDefaultArgRange() << NewSM;
667 Diag(Old->getLocation(), diag::note_previous_declaration);
668 }
669 }
670
671 const FunctionDecl *Def;
672 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
673 // template has a constexpr specifier then all its declarations shall
674 // contain the constexpr specifier.
675 if (New->getConstexprKind() != Old->getConstexprKind()) {
676 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
677 << New << static_cast<int>(New->getConstexprKind())
678 << static_cast<int>(Old->getConstexprKind());
679 Diag(Old->getLocation(), diag::note_previous_declaration);
680 Invalid = true;
681 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
682 Old->isDefined(Def) &&
683 // If a friend function is inlined but does not have 'inline'
684 // specifier, it is a definition. Do not report attribute conflict
685 // in this case, redefinition will be diagnosed later.
686 (New->isInlineSpecified() ||
687 New->getFriendObjectKind() == Decl::FOK_None)) {
688 // C++11 [dcl.fcn.spec]p4:
689 // If the definition of a function appears in a translation unit before its
690 // first declaration as inline, the program is ill-formed.
691 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
692 Diag(Def->getLocation(), diag::note_previous_definition);
693 Invalid = true;
694 }
695
696 // C++17 [temp.deduct.guide]p3:
697 // Two deduction guide declarations in the same translation unit
698 // for the same class template shall not have equivalent
699 // parameter-declaration-clauses.
700 if (isa<CXXDeductionGuideDecl>(New) &&
701 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
702 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
703 Diag(Old->getLocation(), diag::note_previous_declaration);
704 }
705
706 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
707 // argument expression, that declaration shall be a definition and shall be
708 // the only declaration of the function or function template in the
709 // translation unit.
710 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
711 functionDeclHasDefaultArgument(Old)) {
712 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
713 Diag(Old->getLocation(), diag::note_previous_declaration);
714 Invalid = true;
715 }
716
717 // C++11 [temp.friend]p4 (DR329):
718 // When a function is defined in a friend function declaration in a class
719 // template, the function is instantiated when the function is odr-used.
720 // The same restrictions on multiple declarations and definitions that
721 // apply to non-template function declarations and definitions also apply
722 // to these implicit definitions.
723 const FunctionDecl *OldDefinition = nullptr;
724 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
725 Old->isDefined(OldDefinition, true))
726 CheckForFunctionRedefinition(New, OldDefinition);
727
728 return Invalid;
729 }
730
DiagPlaceholderVariableDefinition(SourceLocation Loc)731 void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
732 Diag(Loc, getLangOpts().CPlusPlus26
733 ? diag::warn_cxx23_placeholder_var_definition
734 : diag::ext_placeholder_var_definition);
735 }
736
737 NamedDecl *
ActOnDecompositionDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)738 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
739 MultiTemplateParamsArg TemplateParamLists) {
740 assert(D.isDecompositionDeclarator());
741 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
742
743 // The syntax only allows a decomposition declarator as a simple-declaration,
744 // a for-range-declaration, or a condition in Clang, but we parse it in more
745 // cases than that.
746 if (!D.mayHaveDecompositionDeclarator()) {
747 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
748 << Decomp.getSourceRange();
749 return nullptr;
750 }
751
752 if (!TemplateParamLists.empty()) {
753 // FIXME: There's no rule against this, but there are also no rules that
754 // would actually make it usable, so we reject it for now.
755 Diag(TemplateParamLists.front()->getTemplateLoc(),
756 diag::err_decomp_decl_template);
757 return nullptr;
758 }
759
760 Diag(Decomp.getLSquareLoc(),
761 !getLangOpts().CPlusPlus17
762 ? diag::ext_decomp_decl
763 : D.getContext() == DeclaratorContext::Condition
764 ? diag::ext_decomp_decl_cond
765 : diag::warn_cxx14_compat_decomp_decl)
766 << Decomp.getSourceRange();
767
768 // The semantic context is always just the current context.
769 DeclContext *const DC = CurContext;
770
771 // C++17 [dcl.dcl]/8:
772 // The decl-specifier-seq shall contain only the type-specifier auto
773 // and cv-qualifiers.
774 // C++20 [dcl.dcl]/8:
775 // If decl-specifier-seq contains any decl-specifier other than static,
776 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
777 // C++23 [dcl.pre]/6:
778 // Each decl-specifier in the decl-specifier-seq shall be static,
779 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
780 auto &DS = D.getDeclSpec();
781 {
782 // Note: While constrained-auto needs to be checked, we do so separately so
783 // we can emit a better diagnostic.
784 SmallVector<StringRef, 8> BadSpecifiers;
785 SmallVector<SourceLocation, 8> BadSpecifierLocs;
786 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
787 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
788 if (auto SCS = DS.getStorageClassSpec()) {
789 if (SCS == DeclSpec::SCS_static) {
790 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
791 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
792 } else {
793 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
794 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
795 }
796 }
797 if (auto TSCS = DS.getThreadStorageClassSpec()) {
798 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
799 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
800 }
801 if (DS.hasConstexprSpecifier()) {
802 BadSpecifiers.push_back(
803 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
804 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
805 }
806 if (DS.isInlineSpecified()) {
807 BadSpecifiers.push_back("inline");
808 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
809 }
810
811 if (!BadSpecifiers.empty()) {
812 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
813 Err << (int)BadSpecifiers.size()
814 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
815 // Don't add FixItHints to remove the specifiers; we do still respect
816 // them when building the underlying variable.
817 for (auto Loc : BadSpecifierLocs)
818 Err << SourceRange(Loc, Loc);
819 } else if (!CPlusPlus20Specifiers.empty()) {
820 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
821 getLangOpts().CPlusPlus20
822 ? diag::warn_cxx17_compat_decomp_decl_spec
823 : diag::ext_decomp_decl_spec);
824 Warn << (int)CPlusPlus20Specifiers.size()
825 << llvm::join(CPlusPlus20Specifiers.begin(),
826 CPlusPlus20Specifiers.end(), " ");
827 for (auto Loc : CPlusPlus20SpecifierLocs)
828 Warn << SourceRange(Loc, Loc);
829 }
830 // We can't recover from it being declared as a typedef.
831 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
832 return nullptr;
833 }
834
835 // C++2a [dcl.struct.bind]p1:
836 // A cv that includes volatile is deprecated
837 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
838 getLangOpts().CPlusPlus20)
839 Diag(DS.getVolatileSpecLoc(),
840 diag::warn_deprecated_volatile_structured_binding);
841
842 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
843 QualType R = TInfo->getType();
844
845 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
846 UPPC_DeclarationType))
847 D.setInvalidType();
848
849 // The syntax only allows a single ref-qualifier prior to the decomposition
850 // declarator. No other declarator chunks are permitted. Also check the type
851 // specifier here.
852 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
853 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
854 (D.getNumTypeObjects() == 1 &&
855 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
856 Diag(Decomp.getLSquareLoc(),
857 (D.hasGroupingParens() ||
858 (D.getNumTypeObjects() &&
859 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
860 ? diag::err_decomp_decl_parens
861 : diag::err_decomp_decl_type)
862 << R;
863
864 // In most cases, there's no actual problem with an explicitly-specified
865 // type, but a function type won't work here, and ActOnVariableDeclarator
866 // shouldn't be called for such a type.
867 if (R->isFunctionType())
868 D.setInvalidType();
869 }
870
871 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872 if (DS.isConstrainedAuto()) {
873 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
874 assert(TemplRep->Kind == TNK_Concept_template &&
875 "No other template kind should be possible for a constrained auto");
876
877 SourceRange TemplRange{TemplRep->TemplateNameLoc,
878 TemplRep->RAngleLoc.isValid()
879 ? TemplRep->RAngleLoc
880 : TemplRep->TemplateNameLoc};
881 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
882 << TemplRange << FixItHint::CreateRemoval(TemplRange);
883 }
884
885 // Build the BindingDecls.
886 SmallVector<BindingDecl*, 8> Bindings;
887
888 // Build the BindingDecls.
889 for (auto &B : D.getDecompositionDeclarator().bindings()) {
890 // Check for name conflicts.
891 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
892 IdentifierInfo *VarName = B.Name;
893 assert(VarName && "Cannot have an unnamed binding declaration");
894
895 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
896 ForVisibleRedeclaration);
897 LookupName(Previous, S,
898 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
899
900 // It's not permitted to shadow a template parameter name.
901 if (Previous.isSingleResult() &&
902 Previous.getFoundDecl()->isTemplateParameter()) {
903 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
904 Previous.getFoundDecl());
905 Previous.clear();
906 }
907
908 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
909
910 // Find the shadowed declaration before filtering for scope.
911 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
912 ? getShadowedDeclaration(BD, Previous)
913 : nullptr;
914
915 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
916 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
917 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
918 /*AllowInlineNamespace*/false);
919
920 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
921 DC->isFunctionOrMethod() && VarName->isPlaceholder();
922 if (!Previous.empty()) {
923 if (IsPlaceholder) {
924 bool sameDC = (Previous.end() - 1)
925 ->getDeclContext()
926 ->getRedeclContext()
927 ->Equals(DC->getRedeclContext());
928 if (sameDC &&
929 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
930 Previous.clear();
931 DiagPlaceholderVariableDefinition(B.NameLoc);
932 }
933 } else {
934 auto *Old = Previous.getRepresentativeDecl();
935 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
936 Diag(Old->getLocation(), diag::note_previous_definition);
937 }
938 } else if (ShadowedDecl && !D.isRedeclaration()) {
939 CheckShadow(BD, ShadowedDecl, Previous);
940 }
941 PushOnScopeChains(BD, S, true);
942 Bindings.push_back(BD);
943 ParsingInitForAutoVars.insert(BD);
944 }
945
946 // There are no prior lookup results for the variable itself, because it
947 // is unnamed.
948 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
949 Decomp.getLSquareLoc());
950 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
951 ForVisibleRedeclaration);
952
953 // Build the variable that holds the non-decomposed object.
954 bool AddToScope = true;
955 NamedDecl *New =
956 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
957 MultiTemplateParamsArg(), AddToScope, Bindings);
958 if (AddToScope) {
959 S->AddDecl(New);
960 CurContext->addHiddenDecl(New);
961 }
962
963 if (isInOpenMPDeclareTargetContext())
964 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
965
966 return New;
967 }
968
checkSimpleDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const llvm::APSInt & NumElems,QualType ElemType,llvm::function_ref<ExprResult (SourceLocation,Expr *,unsigned)> GetInit)969 static bool checkSimpleDecomposition(
970 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
971 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
972 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
973 if ((int64_t)Bindings.size() != NumElems) {
974 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
975 << DecompType << (unsigned)Bindings.size()
976 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
977 << toString(NumElems, 10) << (NumElems < Bindings.size());
978 return true;
979 }
980
981 unsigned I = 0;
982 for (auto *B : Bindings) {
983 SourceLocation Loc = B->getLocation();
984 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
985 if (E.isInvalid())
986 return true;
987 E = GetInit(Loc, E.get(), I++);
988 if (E.isInvalid())
989 return true;
990 B->setBinding(ElemType, E.get());
991 }
992
993 return false;
994 }
995
checkArrayLikeDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const llvm::APSInt & NumElems,QualType ElemType)996 static bool checkArrayLikeDecomposition(Sema &S,
997 ArrayRef<BindingDecl *> Bindings,
998 ValueDecl *Src, QualType DecompType,
999 const llvm::APSInt &NumElems,
1000 QualType ElemType) {
1001 return checkSimpleDecomposition(
1002 S, Bindings, Src, DecompType, NumElems, ElemType,
1003 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1004 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1005 if (E.isInvalid())
1006 return ExprError();
1007 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1008 });
1009 }
1010
checkArrayDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const ConstantArrayType * CAT)1011 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1012 ValueDecl *Src, QualType DecompType,
1013 const ConstantArrayType *CAT) {
1014 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1015 llvm::APSInt(CAT->getSize()),
1016 CAT->getElementType());
1017 }
1018
checkVectorDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const VectorType * VT)1019 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1020 ValueDecl *Src, QualType DecompType,
1021 const VectorType *VT) {
1022 return checkArrayLikeDecomposition(
1023 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1024 S.Context.getQualifiedType(VT->getElementType(),
1025 DecompType.getQualifiers()));
1026 }
1027
checkComplexDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const ComplexType * CT)1028 static bool checkComplexDecomposition(Sema &S,
1029 ArrayRef<BindingDecl *> Bindings,
1030 ValueDecl *Src, QualType DecompType,
1031 const ComplexType *CT) {
1032 return checkSimpleDecomposition(
1033 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1034 S.Context.getQualifiedType(CT->getElementType(),
1035 DecompType.getQualifiers()),
1036 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1037 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1038 });
1039 }
1040
printTemplateArgs(const PrintingPolicy & PrintingPolicy,TemplateArgumentListInfo & Args,const TemplateParameterList * Params)1041 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1042 TemplateArgumentListInfo &Args,
1043 const TemplateParameterList *Params) {
1044 SmallString<128> SS;
1045 llvm::raw_svector_ostream OS(SS);
1046 bool First = true;
1047 unsigned I = 0;
1048 for (auto &Arg : Args.arguments()) {
1049 if (!First)
1050 OS << ", ";
1051 Arg.getArgument().print(PrintingPolicy, OS,
1052 TemplateParameterList::shouldIncludeTypeForArgument(
1053 PrintingPolicy, Params, I));
1054 First = false;
1055 I++;
1056 }
1057 return std::string(OS.str());
1058 }
1059
lookupStdTypeTraitMember(Sema & S,LookupResult & TraitMemberLookup,SourceLocation Loc,StringRef Trait,TemplateArgumentListInfo & Args,unsigned DiagID)1060 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1061 SourceLocation Loc, StringRef Trait,
1062 TemplateArgumentListInfo &Args,
1063 unsigned DiagID) {
1064 auto DiagnoseMissing = [&] {
1065 if (DiagID)
1066 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1067 Args, /*Params*/ nullptr);
1068 return true;
1069 };
1070
1071 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1072 NamespaceDecl *Std = S.getStdNamespace();
1073 if (!Std)
1074 return DiagnoseMissing();
1075
1076 // Look up the trait itself, within namespace std. We can diagnose various
1077 // problems with this lookup even if we've been asked to not diagnose a
1078 // missing specialization, because this can only fail if the user has been
1079 // declaring their own names in namespace std or we don't support the
1080 // standard library implementation in use.
1081 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1082 Loc, Sema::LookupOrdinaryName);
1083 if (!S.LookupQualifiedName(Result, Std))
1084 return DiagnoseMissing();
1085 if (Result.isAmbiguous())
1086 return true;
1087
1088 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1089 if (!TraitTD) {
1090 Result.suppressDiagnostics();
1091 NamedDecl *Found = *Result.begin();
1092 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1093 S.Diag(Found->getLocation(), diag::note_declared_at);
1094 return true;
1095 }
1096
1097 // Build the template-id.
1098 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1099 if (TraitTy.isNull())
1100 return true;
1101 if (!S.isCompleteType(Loc, TraitTy)) {
1102 if (DiagID)
1103 S.RequireCompleteType(
1104 Loc, TraitTy, DiagID,
1105 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1106 TraitTD->getTemplateParameters()));
1107 return true;
1108 }
1109
1110 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1111 assert(RD && "specialization of class template is not a class?");
1112
1113 // Look up the member of the trait type.
1114 S.LookupQualifiedName(TraitMemberLookup, RD);
1115 return TraitMemberLookup.isAmbiguous();
1116 }
1117
1118 static TemplateArgumentLoc
getTrivialIntegralTemplateArgument(Sema & S,SourceLocation Loc,QualType T,uint64_t I)1119 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1120 uint64_t I) {
1121 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1122 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1123 }
1124
1125 static TemplateArgumentLoc
getTrivialTypeTemplateArgument(Sema & S,SourceLocation Loc,QualType T)1126 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1127 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1128 }
1129
1130 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1131
isTupleLike(Sema & S,SourceLocation Loc,QualType T,llvm::APSInt & Size)1132 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1133 llvm::APSInt &Size) {
1134 EnterExpressionEvaluationContext ContextRAII(
1135 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1136
1137 DeclarationName Value = S.PP.getIdentifierInfo("value");
1138 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1139
1140 // Form template argument list for tuple_size<T>.
1141 TemplateArgumentListInfo Args(Loc, Loc);
1142 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1143
1144 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1145 // it's not tuple-like.
1146 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1147 R.empty())
1148 return IsTupleLike::NotTupleLike;
1149
1150 // If we get this far, we've committed to the tuple interpretation, but
1151 // we can still fail if there actually isn't a usable ::value.
1152
1153 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1154 LookupResult &R;
1155 TemplateArgumentListInfo &Args;
1156 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1157 : R(R), Args(Args) {}
1158 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1159 SourceLocation Loc) override {
1160 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1161 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1162 /*Params*/ nullptr);
1163 }
1164 } Diagnoser(R, Args);
1165
1166 ExprResult E =
1167 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1168 if (E.isInvalid())
1169 return IsTupleLike::Error;
1170
1171 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1172 if (E.isInvalid())
1173 return IsTupleLike::Error;
1174
1175 return IsTupleLike::TupleLike;
1176 }
1177
1178 /// \return std::tuple_element<I, T>::type.
getTupleLikeElementType(Sema & S,SourceLocation Loc,unsigned I,QualType T)1179 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1180 unsigned I, QualType T) {
1181 // Form template argument list for tuple_element<I, T>.
1182 TemplateArgumentListInfo Args(Loc, Loc);
1183 Args.addArgument(
1184 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1185 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1186
1187 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1188 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1189 if (lookupStdTypeTraitMember(
1190 S, R, Loc, "tuple_element", Args,
1191 diag::err_decomp_decl_std_tuple_element_not_specialized))
1192 return QualType();
1193
1194 auto *TD = R.getAsSingle<TypeDecl>();
1195 if (!TD) {
1196 R.suppressDiagnostics();
1197 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1198 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1199 /*Params*/ nullptr);
1200 if (!R.empty())
1201 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1202 return QualType();
1203 }
1204
1205 return S.Context.getTypeDeclType(TD);
1206 }
1207
1208 namespace {
1209 struct InitializingBinding {
1210 Sema &S;
InitializingBinding__anon067e66480711::InitializingBinding1211 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1212 Sema::CodeSynthesisContext Ctx;
1213 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1214 Ctx.PointOfInstantiation = BD->getLocation();
1215 Ctx.Entity = BD;
1216 S.pushCodeSynthesisContext(Ctx);
1217 }
~InitializingBinding__anon067e66480711::InitializingBinding1218 ~InitializingBinding() {
1219 S.popCodeSynthesisContext();
1220 }
1221 };
1222 }
1223
checkTupleLikeDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,VarDecl * Src,QualType DecompType,const llvm::APSInt & TupleSize)1224 static bool checkTupleLikeDecomposition(Sema &S,
1225 ArrayRef<BindingDecl *> Bindings,
1226 VarDecl *Src, QualType DecompType,
1227 const llvm::APSInt &TupleSize) {
1228 if ((int64_t)Bindings.size() != TupleSize) {
1229 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1230 << DecompType << (unsigned)Bindings.size()
1231 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1232 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1233 return true;
1234 }
1235
1236 if (Bindings.empty())
1237 return false;
1238
1239 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1240
1241 // [dcl.decomp]p3:
1242 // The unqualified-id get is looked up in the scope of E by class member
1243 // access lookup ...
1244 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1245 bool UseMemberGet = false;
1246 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1247 if (auto *RD = DecompType->getAsCXXRecordDecl())
1248 S.LookupQualifiedName(MemberGet, RD);
1249 if (MemberGet.isAmbiguous())
1250 return true;
1251 // ... and if that finds at least one declaration that is a function
1252 // template whose first template parameter is a non-type parameter ...
1253 for (NamedDecl *D : MemberGet) {
1254 if (FunctionTemplateDecl *FTD =
1255 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1256 TemplateParameterList *TPL = FTD->getTemplateParameters();
1257 if (TPL->size() != 0 &&
1258 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1259 // ... the initializer is e.get<i>().
1260 UseMemberGet = true;
1261 break;
1262 }
1263 }
1264 }
1265 }
1266
1267 unsigned I = 0;
1268 for (auto *B : Bindings) {
1269 InitializingBinding InitContext(S, B);
1270 SourceLocation Loc = B->getLocation();
1271
1272 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1273 if (E.isInvalid())
1274 return true;
1275
1276 // e is an lvalue if the type of the entity is an lvalue reference and
1277 // an xvalue otherwise
1278 if (!Src->getType()->isLValueReferenceType())
1279 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1280 E.get(), nullptr, VK_XValue,
1281 FPOptionsOverride());
1282
1283 TemplateArgumentListInfo Args(Loc, Loc);
1284 Args.addArgument(
1285 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1286
1287 if (UseMemberGet) {
1288 // if [lookup of member get] finds at least one declaration, the
1289 // initializer is e.get<i-1>().
1290 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1291 CXXScopeSpec(), SourceLocation(), nullptr,
1292 MemberGet, &Args, nullptr);
1293 if (E.isInvalid())
1294 return true;
1295
1296 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1297 } else {
1298 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1299 // in the associated namespaces.
1300 Expr *Get = UnresolvedLookupExpr::Create(
1301 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1302 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, &Args,
1303 UnresolvedSetIterator(), UnresolvedSetIterator(),
1304 /*KnownDependent=*/false);
1305
1306 Expr *Arg = E.get();
1307 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1308 }
1309 if (E.isInvalid())
1310 return true;
1311 Expr *Init = E.get();
1312
1313 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1314 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1315 if (T.isNull())
1316 return true;
1317
1318 // each vi is a variable of type "reference to T" initialized with the
1319 // initializer, where the reference is an lvalue reference if the
1320 // initializer is an lvalue and an rvalue reference otherwise
1321 QualType RefType =
1322 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1323 if (RefType.isNull())
1324 return true;
1325 auto *RefVD = VarDecl::Create(
1326 S.Context, Src->getDeclContext(), Loc, Loc,
1327 B->getDeclName().getAsIdentifierInfo(), RefType,
1328 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1329 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1330 RefVD->setTSCSpec(Src->getTSCSpec());
1331 RefVD->setImplicit();
1332 if (Src->isInlineSpecified())
1333 RefVD->setInlineSpecified();
1334 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1335
1336 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1337 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1338 InitializationSequence Seq(S, Entity, Kind, Init);
1339 E = Seq.Perform(S, Entity, Kind, Init);
1340 if (E.isInvalid())
1341 return true;
1342 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1343 if (E.isInvalid())
1344 return true;
1345 RefVD->setInit(E.get());
1346 S.CheckCompleteVariableDeclaration(RefVD);
1347
1348 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1349 DeclarationNameInfo(B->getDeclName(), Loc),
1350 RefVD);
1351 if (E.isInvalid())
1352 return true;
1353
1354 B->setBinding(T, E.get());
1355 I++;
1356 }
1357
1358 return false;
1359 }
1360
1361 /// Find the base class to decompose in a built-in decomposition of a class type.
1362 /// This base class search is, unfortunately, not quite like any other that we
1363 /// perform anywhere else in C++.
findDecomposableBaseClass(Sema & S,SourceLocation Loc,const CXXRecordDecl * RD,CXXCastPath & BasePath)1364 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1365 const CXXRecordDecl *RD,
1366 CXXCastPath &BasePath) {
1367 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1368 CXXBasePath &Path) {
1369 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1370 };
1371
1372 const CXXRecordDecl *ClassWithFields = nullptr;
1373 AccessSpecifier AS = AS_public;
1374 if (RD->hasDirectFields())
1375 // [dcl.decomp]p4:
1376 // Otherwise, all of E's non-static data members shall be public direct
1377 // members of E ...
1378 ClassWithFields = RD;
1379 else {
1380 // ... or of ...
1381 CXXBasePaths Paths;
1382 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1383 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1384 // If no classes have fields, just decompose RD itself. (This will work
1385 // if and only if zero bindings were provided.)
1386 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1387 }
1388
1389 CXXBasePath *BestPath = nullptr;
1390 for (auto &P : Paths) {
1391 if (!BestPath)
1392 BestPath = &P;
1393 else if (!S.Context.hasSameType(P.back().Base->getType(),
1394 BestPath->back().Base->getType())) {
1395 // ... the same ...
1396 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1397 << false << RD << BestPath->back().Base->getType()
1398 << P.back().Base->getType();
1399 return DeclAccessPair();
1400 } else if (P.Access < BestPath->Access) {
1401 BestPath = &P;
1402 }
1403 }
1404
1405 // ... unambiguous ...
1406 QualType BaseType = BestPath->back().Base->getType();
1407 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1408 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1409 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1410 return DeclAccessPair();
1411 }
1412
1413 // ... [accessible, implied by other rules] base class of E.
1414 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1415 *BestPath, diag::err_decomp_decl_inaccessible_base);
1416 AS = BestPath->Access;
1417
1418 ClassWithFields = BaseType->getAsCXXRecordDecl();
1419 S.BuildBasePathArray(Paths, BasePath);
1420 }
1421
1422 // The above search did not check whether the selected class itself has base
1423 // classes with fields, so check that now.
1424 CXXBasePaths Paths;
1425 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1426 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1427 << (ClassWithFields == RD) << RD << ClassWithFields
1428 << Paths.front().back().Base->getType();
1429 return DeclAccessPair();
1430 }
1431
1432 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1433 }
1434
checkMemberDecomposition(Sema & S,ArrayRef<BindingDecl * > Bindings,ValueDecl * Src,QualType DecompType,const CXXRecordDecl * OrigRD)1435 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1436 ValueDecl *Src, QualType DecompType,
1437 const CXXRecordDecl *OrigRD) {
1438 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1439 diag::err_incomplete_type))
1440 return true;
1441
1442 CXXCastPath BasePath;
1443 DeclAccessPair BasePair =
1444 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1445 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1446 if (!RD)
1447 return true;
1448 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1449 DecompType.getQualifiers());
1450
1451 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1452 unsigned NumFields = llvm::count_if(
1453 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1454 assert(Bindings.size() != NumFields);
1455 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1456 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1457 << (NumFields < Bindings.size());
1458 return true;
1459 };
1460
1461 // all of E's non-static data members shall be [...] well-formed
1462 // when named as e.name in the context of the structured binding,
1463 // E shall not have an anonymous union member, ...
1464 unsigned I = 0;
1465 for (auto *FD : RD->fields()) {
1466 if (FD->isUnnamedBitfield())
1467 continue;
1468
1469 // All the non-static data members are required to be nameable, so they
1470 // must all have names.
1471 if (!FD->getDeclName()) {
1472 if (RD->isLambda()) {
1473 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1474 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1475 return true;
1476 }
1477
1478 if (FD->isAnonymousStructOrUnion()) {
1479 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1480 << DecompType << FD->getType()->isUnionType();
1481 S.Diag(FD->getLocation(), diag::note_declared_at);
1482 return true;
1483 }
1484
1485 // FIXME: Are there any other ways we could have an anonymous member?
1486 }
1487
1488 // We have a real field to bind.
1489 if (I >= Bindings.size())
1490 return DiagnoseBadNumberOfBindings();
1491 auto *B = Bindings[I++];
1492 SourceLocation Loc = B->getLocation();
1493
1494 // The field must be accessible in the context of the structured binding.
1495 // We already checked that the base class is accessible.
1496 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1497 // const_cast here.
1498 S.CheckStructuredBindingMemberAccess(
1499 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1500 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1501 BasePair.getAccess(), FD->getAccess())));
1502
1503 // Initialize the binding to Src.FD.
1504 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1505 if (E.isInvalid())
1506 return true;
1507 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1508 VK_LValue, &BasePath);
1509 if (E.isInvalid())
1510 return true;
1511 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1512 CXXScopeSpec(), FD,
1513 DeclAccessPair::make(FD, FD->getAccess()),
1514 DeclarationNameInfo(FD->getDeclName(), Loc));
1515 if (E.isInvalid())
1516 return true;
1517
1518 // If the type of the member is T, the referenced type is cv T, where cv is
1519 // the cv-qualification of the decomposition expression.
1520 //
1521 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1522 // 'const' to the type of the field.
1523 Qualifiers Q = DecompType.getQualifiers();
1524 if (FD->isMutable())
1525 Q.removeConst();
1526 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1527 }
1528
1529 if (I != Bindings.size())
1530 return DiagnoseBadNumberOfBindings();
1531
1532 return false;
1533 }
1534
CheckCompleteDecompositionDeclaration(DecompositionDecl * DD)1535 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1536 QualType DecompType = DD->getType();
1537
1538 // If the type of the decomposition is dependent, then so is the type of
1539 // each binding.
1540 if (DecompType->isDependentType()) {
1541 for (auto *B : DD->bindings())
1542 B->setType(Context.DependentTy);
1543 return;
1544 }
1545
1546 DecompType = DecompType.getNonReferenceType();
1547 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1548
1549 // C++1z [dcl.decomp]/2:
1550 // If E is an array type [...]
1551 // As an extension, we also support decomposition of built-in complex and
1552 // vector types.
1553 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1554 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1555 DD->setInvalidDecl();
1556 return;
1557 }
1558 if (auto *VT = DecompType->getAs<VectorType>()) {
1559 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1560 DD->setInvalidDecl();
1561 return;
1562 }
1563 if (auto *CT = DecompType->getAs<ComplexType>()) {
1564 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1565 DD->setInvalidDecl();
1566 return;
1567 }
1568
1569 // C++1z [dcl.decomp]/3:
1570 // if the expression std::tuple_size<E>::value is a well-formed integral
1571 // constant expression, [...]
1572 llvm::APSInt TupleSize(32);
1573 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1574 case IsTupleLike::Error:
1575 DD->setInvalidDecl();
1576 return;
1577
1578 case IsTupleLike::TupleLike:
1579 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1580 DD->setInvalidDecl();
1581 return;
1582
1583 case IsTupleLike::NotTupleLike:
1584 break;
1585 }
1586
1587 // C++1z [dcl.dcl]/8:
1588 // [E shall be of array or non-union class type]
1589 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1590 if (!RD || RD->isUnion()) {
1591 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1592 << DD << !RD << DecompType;
1593 DD->setInvalidDecl();
1594 return;
1595 }
1596
1597 // C++1z [dcl.decomp]/4:
1598 // all of E's non-static data members shall be [...] direct members of
1599 // E or of the same unambiguous public base class of E, ...
1600 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1601 DD->setInvalidDecl();
1602 }
1603
1604 /// Merge the exception specifications of two variable declarations.
1605 ///
1606 /// This is called when there's a redeclaration of a VarDecl. The function
1607 /// checks if the redeclaration might have an exception specification and
1608 /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)1609 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1610 // Shortcut if exceptions are disabled.
1611 if (!getLangOpts().CXXExceptions)
1612 return;
1613
1614 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1615 "Should only be called if types are otherwise the same.");
1616
1617 QualType NewType = New->getType();
1618 QualType OldType = Old->getType();
1619
1620 // We're only interested in pointers and references to functions, as well
1621 // as pointers to member functions.
1622 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1623 NewType = R->getPointeeType();
1624 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1625 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1626 NewType = P->getPointeeType();
1627 OldType = OldType->castAs<PointerType>()->getPointeeType();
1628 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1629 NewType = M->getPointeeType();
1630 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1631 }
1632
1633 if (!NewType->isFunctionProtoType())
1634 return;
1635
1636 // There's lots of special cases for functions. For function pointers, system
1637 // libraries are hopefully not as broken so that we don't need these
1638 // workarounds.
1639 if (CheckEquivalentExceptionSpec(
1640 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1641 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1642 New->setInvalidDecl();
1643 }
1644 }
1645
1646 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1647 /// function declaration are well-formed according to C++
1648 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)1649 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1650 unsigned NumParams = FD->getNumParams();
1651 unsigned ParamIdx = 0;
1652
1653 // This checking doesn't make sense for explicit specializations; their
1654 // default arguments are determined by the declaration we're specializing,
1655 // not by FD.
1656 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1657 return;
1658 if (auto *FTD = FD->getDescribedFunctionTemplate())
1659 if (FTD->isMemberSpecialization())
1660 return;
1661
1662 // Find first parameter with a default argument
1663 for (; ParamIdx < NumParams; ++ParamIdx) {
1664 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1665 if (Param->hasDefaultArg())
1666 break;
1667 }
1668
1669 // C++20 [dcl.fct.default]p4:
1670 // In a given function declaration, each parameter subsequent to a parameter
1671 // with a default argument shall have a default argument supplied in this or
1672 // a previous declaration, unless the parameter was expanded from a
1673 // parameter pack, or shall be a function parameter pack.
1674 for (; ParamIdx < NumParams; ++ParamIdx) {
1675 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1676 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1677 !(CurrentInstantiationScope &&
1678 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1679 if (Param->isInvalidDecl())
1680 /* We already complained about this parameter. */;
1681 else if (Param->getIdentifier())
1682 Diag(Param->getLocation(),
1683 diag::err_param_default_argument_missing_name)
1684 << Param->getIdentifier();
1685 else
1686 Diag(Param->getLocation(),
1687 diag::err_param_default_argument_missing);
1688 }
1689 }
1690 }
1691
1692 /// Check that the given type is a literal type. Issue a diagnostic if not,
1693 /// if Kind is Diagnose.
1694 /// \return \c true if a problem has been found (and optionally diagnosed).
1695 template <typename... Ts>
CheckLiteralType(Sema & SemaRef,Sema::CheckConstexprKind Kind,SourceLocation Loc,QualType T,unsigned DiagID,Ts &&...DiagArgs)1696 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1697 SourceLocation Loc, QualType T, unsigned DiagID,
1698 Ts &&...DiagArgs) {
1699 if (T->isDependentType())
1700 return false;
1701
1702 switch (Kind) {
1703 case Sema::CheckConstexprKind::Diagnose:
1704 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1705 std::forward<Ts>(DiagArgs)...);
1706
1707 case Sema::CheckConstexprKind::CheckValid:
1708 return !T->isLiteralType(SemaRef.Context);
1709 }
1710
1711 llvm_unreachable("unknown CheckConstexprKind");
1712 }
1713
1714 /// Determine whether a destructor cannot be constexpr due to
CheckConstexprDestructorSubobjects(Sema & SemaRef,const CXXDestructorDecl * DD,Sema::CheckConstexprKind Kind)1715 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1716 const CXXDestructorDecl *DD,
1717 Sema::CheckConstexprKind Kind) {
1718 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1719 const CXXRecordDecl *RD =
1720 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1721 if (!RD || RD->hasConstexprDestructor())
1722 return true;
1723
1724 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1725 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1726 << static_cast<int>(DD->getConstexprKind()) << !FD
1727 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1728 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1729 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1730 }
1731 return false;
1732 };
1733
1734 const CXXRecordDecl *RD = DD->getParent();
1735 for (const CXXBaseSpecifier &B : RD->bases())
1736 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1737 return false;
1738 for (const FieldDecl *FD : RD->fields())
1739 if (!Check(FD->getLocation(), FD->getType(), FD))
1740 return false;
1741 return true;
1742 }
1743
1744 /// Check whether a function's parameter types are all literal types. If so,
1745 /// return true. If not, produce a suitable diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD,Sema::CheckConstexprKind Kind)1746 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1747 const FunctionDecl *FD,
1748 Sema::CheckConstexprKind Kind) {
1749 unsigned ArgIndex = 0;
1750 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1751 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1752 e = FT->param_type_end();
1753 i != e; ++i, ++ArgIndex) {
1754 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1755 assert(PD && "null in a parameter list");
1756 SourceLocation ParamLoc = PD->getLocation();
1757 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1758 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1759 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1760 FD->isConsteval()))
1761 return false;
1762 }
1763 return true;
1764 }
1765
1766 /// Check whether a function's return type is a literal type. If so, return
1767 /// true. If not, produce a suitable diagnostic and return false.
CheckConstexprReturnType(Sema & SemaRef,const FunctionDecl * FD,Sema::CheckConstexprKind Kind)1768 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1769 Sema::CheckConstexprKind Kind) {
1770 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1771 diag::err_constexpr_non_literal_return,
1772 FD->isConsteval()))
1773 return false;
1774 return true;
1775 }
1776
1777 /// Get diagnostic %select index for tag kind for
1778 /// record diagnostic message.
1779 /// WARNING: Indexes apply to particular diagnostics only!
1780 ///
1781 /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)1782 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1783 switch (Tag) {
1784 case TagTypeKind::Struct:
1785 return 0;
1786 case TagTypeKind::Interface:
1787 return 1;
1788 case TagTypeKind::Class:
1789 return 2;
1790 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1791 }
1792 }
1793
1794 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1795 Stmt *Body,
1796 Sema::CheckConstexprKind Kind);
1797
1798 // Check whether a function declaration satisfies the requirements of a
1799 // constexpr function definition or a constexpr constructor definition. If so,
1800 // return true. If not, produce appropriate diagnostics (unless asked not to by
1801 // Kind) and return false.
1802 //
1803 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
CheckConstexprFunctionDefinition(const FunctionDecl * NewFD,CheckConstexprKind Kind)1804 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1805 CheckConstexprKind Kind) {
1806 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1807 if (MD && MD->isInstance()) {
1808 // C++11 [dcl.constexpr]p4:
1809 // The definition of a constexpr constructor shall satisfy the following
1810 // constraints:
1811 // - the class shall not have any virtual base classes;
1812 //
1813 // FIXME: This only applies to constructors and destructors, not arbitrary
1814 // member functions.
1815 const CXXRecordDecl *RD = MD->getParent();
1816 if (RD->getNumVBases()) {
1817 if (Kind == CheckConstexprKind::CheckValid)
1818 return false;
1819
1820 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1821 << isa<CXXConstructorDecl>(NewFD)
1822 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1823 for (const auto &I : RD->vbases())
1824 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1825 << I.getSourceRange();
1826 return false;
1827 }
1828 }
1829
1830 if (!isa<CXXConstructorDecl>(NewFD)) {
1831 // C++11 [dcl.constexpr]p3:
1832 // The definition of a constexpr function shall satisfy the following
1833 // constraints:
1834 // - it shall not be virtual; (removed in C++20)
1835 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1836 if (Method && Method->isVirtual()) {
1837 if (getLangOpts().CPlusPlus20) {
1838 if (Kind == CheckConstexprKind::Diagnose)
1839 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1840 } else {
1841 if (Kind == CheckConstexprKind::CheckValid)
1842 return false;
1843
1844 Method = Method->getCanonicalDecl();
1845 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1846
1847 // If it's not obvious why this function is virtual, find an overridden
1848 // function which uses the 'virtual' keyword.
1849 const CXXMethodDecl *WrittenVirtual = Method;
1850 while (!WrittenVirtual->isVirtualAsWritten())
1851 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1852 if (WrittenVirtual != Method)
1853 Diag(WrittenVirtual->getLocation(),
1854 diag::note_overridden_virtual_function);
1855 return false;
1856 }
1857 }
1858
1859 // - its return type shall be a literal type;
1860 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1861 return false;
1862 }
1863
1864 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1865 // A destructor can be constexpr only if the defaulted destructor could be;
1866 // we don't need to check the members and bases if we already know they all
1867 // have constexpr destructors.
1868 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1869 if (Kind == CheckConstexprKind::CheckValid)
1870 return false;
1871 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1872 return false;
1873 }
1874 }
1875
1876 // - each of its parameter types shall be a literal type;
1877 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1878 return false;
1879
1880 Stmt *Body = NewFD->getBody();
1881 assert(Body &&
1882 "CheckConstexprFunctionDefinition called on function with no body");
1883 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1884 }
1885
1886 /// Check the given declaration statement is legal within a constexpr function
1887 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1888 ///
1889 /// \return true if the body is OK (maybe only as an extension), false if we
1890 /// have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS,SourceLocation & Cxx1yLoc,Sema::CheckConstexprKind Kind)1891 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1892 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1893 Sema::CheckConstexprKind Kind) {
1894 // C++11 [dcl.constexpr]p3 and p4:
1895 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1896 // contain only
1897 for (const auto *DclIt : DS->decls()) {
1898 switch (DclIt->getKind()) {
1899 case Decl::StaticAssert:
1900 case Decl::Using:
1901 case Decl::UsingShadow:
1902 case Decl::UsingDirective:
1903 case Decl::UnresolvedUsingTypename:
1904 case Decl::UnresolvedUsingValue:
1905 case Decl::UsingEnum:
1906 // - static_assert-declarations
1907 // - using-declarations,
1908 // - using-directives,
1909 // - using-enum-declaration
1910 continue;
1911
1912 case Decl::Typedef:
1913 case Decl::TypeAlias: {
1914 // - typedef declarations and alias-declarations that do not define
1915 // classes or enumerations,
1916 const auto *TN = cast<TypedefNameDecl>(DclIt);
1917 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1918 // Don't allow variably-modified types in constexpr functions.
1919 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1920 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1921 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1922 << TL.getSourceRange() << TL.getType()
1923 << isa<CXXConstructorDecl>(Dcl);
1924 }
1925 return false;
1926 }
1927 continue;
1928 }
1929
1930 case Decl::Enum:
1931 case Decl::CXXRecord:
1932 // C++1y allows types to be defined, not just declared.
1933 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1934 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1935 SemaRef.Diag(DS->getBeginLoc(),
1936 SemaRef.getLangOpts().CPlusPlus14
1937 ? diag::warn_cxx11_compat_constexpr_type_definition
1938 : diag::ext_constexpr_type_definition)
1939 << isa<CXXConstructorDecl>(Dcl);
1940 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1941 return false;
1942 }
1943 }
1944 continue;
1945
1946 case Decl::EnumConstant:
1947 case Decl::IndirectField:
1948 case Decl::ParmVar:
1949 // These can only appear with other declarations which are banned in
1950 // C++11 and permitted in C++1y, so ignore them.
1951 continue;
1952
1953 case Decl::Var:
1954 case Decl::Decomposition: {
1955 // C++1y [dcl.constexpr]p3 allows anything except:
1956 // a definition of a variable of non-literal type or of static or
1957 // thread storage duration or [before C++2a] for which no
1958 // initialization is performed.
1959 const auto *VD = cast<VarDecl>(DclIt);
1960 if (VD->isThisDeclarationADefinition()) {
1961 if (VD->isStaticLocal()) {
1962 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1963 SemaRef.Diag(VD->getLocation(),
1964 SemaRef.getLangOpts().CPlusPlus23
1965 ? diag::warn_cxx20_compat_constexpr_var
1966 : diag::ext_constexpr_static_var)
1967 << isa<CXXConstructorDecl>(Dcl)
1968 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1969 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1970 return false;
1971 }
1972 }
1973 if (SemaRef.LangOpts.CPlusPlus23) {
1974 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1975 diag::warn_cxx20_compat_constexpr_var,
1976 isa<CXXConstructorDecl>(Dcl),
1977 /*variable of non-literal type*/ 2);
1978 } else if (CheckLiteralType(
1979 SemaRef, Kind, VD->getLocation(), VD->getType(),
1980 diag::err_constexpr_local_var_non_literal_type,
1981 isa<CXXConstructorDecl>(Dcl))) {
1982 return false;
1983 }
1984 if (!VD->getType()->isDependentType() &&
1985 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1986 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1987 SemaRef.Diag(
1988 VD->getLocation(),
1989 SemaRef.getLangOpts().CPlusPlus20
1990 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1991 : diag::ext_constexpr_local_var_no_init)
1992 << isa<CXXConstructorDecl>(Dcl);
1993 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1994 return false;
1995 }
1996 continue;
1997 }
1998 }
1999 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2000 SemaRef.Diag(VD->getLocation(),
2001 SemaRef.getLangOpts().CPlusPlus14
2002 ? diag::warn_cxx11_compat_constexpr_local_var
2003 : diag::ext_constexpr_local_var)
2004 << isa<CXXConstructorDecl>(Dcl);
2005 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2006 return false;
2007 }
2008 continue;
2009 }
2010
2011 case Decl::NamespaceAlias:
2012 case Decl::Function:
2013 // These are disallowed in C++11 and permitted in C++1y. Allow them
2014 // everywhere as an extension.
2015 if (!Cxx1yLoc.isValid())
2016 Cxx1yLoc = DS->getBeginLoc();
2017 continue;
2018
2019 default:
2020 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2021 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2022 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2023 }
2024 return false;
2025 }
2026 }
2027
2028 return true;
2029 }
2030
2031 /// Check that the given field is initialized within a constexpr constructor.
2032 ///
2033 /// \param Dcl The constexpr constructor being checked.
2034 /// \param Field The field being checked. This may be a member of an anonymous
2035 /// struct or union nested within the class being checked.
2036 /// \param Inits All declarations, including anonymous struct/union members and
2037 /// indirect members, for which any initialization was provided.
2038 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2039 /// multiple notes for different members to the same error.
2040 /// \param Kind Whether we're diagnosing a constructor as written or determining
2041 /// whether the formal requirements are satisfied.
2042 /// \return \c false if we're checking for validity and the constructor does
2043 /// 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)2044 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2045 const FunctionDecl *Dcl,
2046 FieldDecl *Field,
2047 llvm::SmallSet<Decl*, 16> &Inits,
2048 bool &Diagnosed,
2049 Sema::CheckConstexprKind Kind) {
2050 // In C++20 onwards, there's nothing to check for validity.
2051 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2052 SemaRef.getLangOpts().CPlusPlus20)
2053 return true;
2054
2055 if (Field->isInvalidDecl())
2056 return true;
2057
2058 if (Field->isUnnamedBitfield())
2059 return true;
2060
2061 // Anonymous unions with no variant members and empty anonymous structs do not
2062 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2063 // indirect fields don't need initializing.
2064 if (Field->isAnonymousStructOrUnion() &&
2065 (Field->getType()->isUnionType()
2066 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2067 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2068 return true;
2069
2070 if (!Inits.count(Field)) {
2071 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2072 if (!Diagnosed) {
2073 SemaRef.Diag(Dcl->getLocation(),
2074 SemaRef.getLangOpts().CPlusPlus20
2075 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2076 : diag::ext_constexpr_ctor_missing_init);
2077 Diagnosed = true;
2078 }
2079 SemaRef.Diag(Field->getLocation(),
2080 diag::note_constexpr_ctor_missing_init);
2081 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2082 return false;
2083 }
2084 } else if (Field->isAnonymousStructOrUnion()) {
2085 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2086 for (auto *I : RD->fields())
2087 // If an anonymous union contains an anonymous struct of which any member
2088 // is initialized, all members must be initialized.
2089 if (!RD->isUnion() || Inits.count(I))
2090 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2091 Kind))
2092 return false;
2093 }
2094 return true;
2095 }
2096
2097 /// Check the provided statement is allowed in a constexpr function
2098 /// definition.
2099 static bool
CheckConstexprFunctionStmt(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * S,SmallVectorImpl<SourceLocation> & ReturnStmts,SourceLocation & Cxx1yLoc,SourceLocation & Cxx2aLoc,SourceLocation & Cxx2bLoc,Sema::CheckConstexprKind Kind)2100 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2101 SmallVectorImpl<SourceLocation> &ReturnStmts,
2102 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2103 SourceLocation &Cxx2bLoc,
2104 Sema::CheckConstexprKind Kind) {
2105 // - its function-body shall be [...] a compound-statement that contains only
2106 switch (S->getStmtClass()) {
2107 case Stmt::NullStmtClass:
2108 // - null statements,
2109 return true;
2110
2111 case Stmt::DeclStmtClass:
2112 // - static_assert-declarations
2113 // - using-declarations,
2114 // - using-directives,
2115 // - typedef declarations and alias-declarations that do not define
2116 // classes or enumerations,
2117 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2118 return false;
2119 return true;
2120
2121 case Stmt::ReturnStmtClass:
2122 // - and exactly one return statement;
2123 if (isa<CXXConstructorDecl>(Dcl)) {
2124 // C++1y allows return statements in constexpr constructors.
2125 if (!Cxx1yLoc.isValid())
2126 Cxx1yLoc = S->getBeginLoc();
2127 return true;
2128 }
2129
2130 ReturnStmts.push_back(S->getBeginLoc());
2131 return true;
2132
2133 case Stmt::AttributedStmtClass:
2134 // Attributes on a statement don't affect its formal kind and hence don't
2135 // affect its validity in a constexpr function.
2136 return CheckConstexprFunctionStmt(
2137 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2138 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2139
2140 case Stmt::CompoundStmtClass: {
2141 // C++1y allows compound-statements.
2142 if (!Cxx1yLoc.isValid())
2143 Cxx1yLoc = S->getBeginLoc();
2144
2145 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2146 for (auto *BodyIt : CompStmt->body()) {
2147 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2148 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2149 return false;
2150 }
2151 return true;
2152 }
2153
2154 case Stmt::IfStmtClass: {
2155 // C++1y allows if-statements.
2156 if (!Cxx1yLoc.isValid())
2157 Cxx1yLoc = S->getBeginLoc();
2158
2159 IfStmt *If = cast<IfStmt>(S);
2160 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2161 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2162 return false;
2163 if (If->getElse() &&
2164 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2165 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2166 return false;
2167 return true;
2168 }
2169
2170 case Stmt::WhileStmtClass:
2171 case Stmt::DoStmtClass:
2172 case Stmt::ForStmtClass:
2173 case Stmt::CXXForRangeStmtClass:
2174 case Stmt::ContinueStmtClass:
2175 // C++1y allows all of these. We don't allow them as extensions in C++11,
2176 // because they don't make sense without variable mutation.
2177 if (!SemaRef.getLangOpts().CPlusPlus14)
2178 break;
2179 if (!Cxx1yLoc.isValid())
2180 Cxx1yLoc = S->getBeginLoc();
2181 for (Stmt *SubStmt : S->children()) {
2182 if (SubStmt &&
2183 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2184 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2185 return false;
2186 }
2187 return true;
2188
2189 case Stmt::SwitchStmtClass:
2190 case Stmt::CaseStmtClass:
2191 case Stmt::DefaultStmtClass:
2192 case Stmt::BreakStmtClass:
2193 // C++1y allows switch-statements, and since they don't need variable
2194 // mutation, we can reasonably allow them in C++11 as an extension.
2195 if (!Cxx1yLoc.isValid())
2196 Cxx1yLoc = S->getBeginLoc();
2197 for (Stmt *SubStmt : S->children()) {
2198 if (SubStmt &&
2199 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2200 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2201 return false;
2202 }
2203 return true;
2204
2205 case Stmt::LabelStmtClass:
2206 case Stmt::GotoStmtClass:
2207 if (Cxx2bLoc.isInvalid())
2208 Cxx2bLoc = S->getBeginLoc();
2209 for (Stmt *SubStmt : S->children()) {
2210 if (SubStmt &&
2211 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2212 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2213 return false;
2214 }
2215 return true;
2216
2217 case Stmt::GCCAsmStmtClass:
2218 case Stmt::MSAsmStmtClass:
2219 // C++2a allows inline assembly statements.
2220 case Stmt::CXXTryStmtClass:
2221 if (Cxx2aLoc.isInvalid())
2222 Cxx2aLoc = S->getBeginLoc();
2223 for (Stmt *SubStmt : S->children()) {
2224 if (SubStmt &&
2225 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2226 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2227 return false;
2228 }
2229 return true;
2230
2231 case Stmt::CXXCatchStmtClass:
2232 // Do not bother checking the language mode (already covered by the
2233 // try block check).
2234 if (!CheckConstexprFunctionStmt(
2235 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2236 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237 return false;
2238 return true;
2239
2240 default:
2241 if (!isa<Expr>(S))
2242 break;
2243
2244 // C++1y allows expression-statements.
2245 if (!Cxx1yLoc.isValid())
2246 Cxx1yLoc = S->getBeginLoc();
2247 return true;
2248 }
2249
2250 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2251 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2252 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2253 }
2254 return false;
2255 }
2256
2257 /// Check the body for the given constexpr function declaration only contains
2258 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2259 ///
2260 /// \return true if the body is OK, false if we have found or diagnosed a
2261 /// problem.
CheckConstexprFunctionBody(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * Body,Sema::CheckConstexprKind Kind)2262 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2263 Stmt *Body,
2264 Sema::CheckConstexprKind Kind) {
2265 SmallVector<SourceLocation, 4> ReturnStmts;
2266
2267 if (isa<CXXTryStmt>(Body)) {
2268 // C++11 [dcl.constexpr]p3:
2269 // The definition of a constexpr function shall satisfy the following
2270 // constraints: [...]
2271 // - its function-body shall be = delete, = default, or a
2272 // compound-statement
2273 //
2274 // C++11 [dcl.constexpr]p4:
2275 // In the definition of a constexpr constructor, [...]
2276 // - its function-body shall not be a function-try-block;
2277 //
2278 // This restriction is lifted in C++2a, as long as inner statements also
2279 // apply the general constexpr rules.
2280 switch (Kind) {
2281 case Sema::CheckConstexprKind::CheckValid:
2282 if (!SemaRef.getLangOpts().CPlusPlus20)
2283 return false;
2284 break;
2285
2286 case Sema::CheckConstexprKind::Diagnose:
2287 SemaRef.Diag(Body->getBeginLoc(),
2288 !SemaRef.getLangOpts().CPlusPlus20
2289 ? diag::ext_constexpr_function_try_block_cxx20
2290 : diag::warn_cxx17_compat_constexpr_function_try_block)
2291 << isa<CXXConstructorDecl>(Dcl);
2292 break;
2293 }
2294 }
2295
2296 // - its function-body shall be [...] a compound-statement that contains only
2297 // [... list of cases ...]
2298 //
2299 // Note that walking the children here is enough to properly check for
2300 // CompoundStmt and CXXTryStmt body.
2301 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2302 for (Stmt *SubStmt : Body->children()) {
2303 if (SubStmt &&
2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308
2309 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2310 // If this is only valid as an extension, report that we don't satisfy the
2311 // constraints of the current language.
2312 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2313 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2314 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2315 return false;
2316 } else if (Cxx2bLoc.isValid()) {
2317 SemaRef.Diag(Cxx2bLoc,
2318 SemaRef.getLangOpts().CPlusPlus23
2319 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2320 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2321 << isa<CXXConstructorDecl>(Dcl);
2322 } else if (Cxx2aLoc.isValid()) {
2323 SemaRef.Diag(Cxx2aLoc,
2324 SemaRef.getLangOpts().CPlusPlus20
2325 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2326 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2327 << isa<CXXConstructorDecl>(Dcl);
2328 } else if (Cxx1yLoc.isValid()) {
2329 SemaRef.Diag(Cxx1yLoc,
2330 SemaRef.getLangOpts().CPlusPlus14
2331 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2332 : diag::ext_constexpr_body_invalid_stmt)
2333 << isa<CXXConstructorDecl>(Dcl);
2334 }
2335
2336 if (const CXXConstructorDecl *Constructor
2337 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2338 const CXXRecordDecl *RD = Constructor->getParent();
2339 // DR1359:
2340 // - every non-variant non-static data member and base class sub-object
2341 // shall be initialized;
2342 // DR1460:
2343 // - if the class is a union having variant members, exactly one of them
2344 // shall be initialized;
2345 if (RD->isUnion()) {
2346 if (Constructor->getNumCtorInitializers() == 0 &&
2347 RD->hasVariantMembers()) {
2348 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2349 SemaRef.Diag(
2350 Dcl->getLocation(),
2351 SemaRef.getLangOpts().CPlusPlus20
2352 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2353 : diag::ext_constexpr_union_ctor_no_init);
2354 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2355 return false;
2356 }
2357 }
2358 } else if (!Constructor->isDependentContext() &&
2359 !Constructor->isDelegatingConstructor()) {
2360 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2361
2362 // Skip detailed checking if we have enough initializers, and we would
2363 // allow at most one initializer per member.
2364 bool AnyAnonStructUnionMembers = false;
2365 unsigned Fields = 0;
2366 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2367 E = RD->field_end(); I != E; ++I, ++Fields) {
2368 if (I->isAnonymousStructOrUnion()) {
2369 AnyAnonStructUnionMembers = true;
2370 break;
2371 }
2372 }
2373 // DR1460:
2374 // - if the class is a union-like class, but is not a union, for each of
2375 // its anonymous union members having variant members, exactly one of
2376 // them shall be initialized;
2377 if (AnyAnonStructUnionMembers ||
2378 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2379 // Check initialization of non-static data members. Base classes are
2380 // always initialized so do not need to be checked. Dependent bases
2381 // might not have initializers in the member initializer list.
2382 llvm::SmallSet<Decl*, 16> Inits;
2383 for (const auto *I: Constructor->inits()) {
2384 if (FieldDecl *FD = I->getMember())
2385 Inits.insert(FD);
2386 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2387 Inits.insert(ID->chain_begin(), ID->chain_end());
2388 }
2389
2390 bool Diagnosed = false;
2391 for (auto *I : RD->fields())
2392 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2393 Kind))
2394 return false;
2395 }
2396 }
2397 } else {
2398 if (ReturnStmts.empty()) {
2399 // C++1y doesn't require constexpr functions to contain a 'return'
2400 // statement. We still do, unless the return type might be void, because
2401 // otherwise if there's no return statement, the function cannot
2402 // be used in a core constant expression.
2403 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2404 (Dcl->getReturnType()->isVoidType() ||
2405 Dcl->getReturnType()->isDependentType());
2406 switch (Kind) {
2407 case Sema::CheckConstexprKind::Diagnose:
2408 SemaRef.Diag(Dcl->getLocation(),
2409 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2410 : diag::err_constexpr_body_no_return)
2411 << Dcl->isConsteval();
2412 if (!OK)
2413 return false;
2414 break;
2415
2416 case Sema::CheckConstexprKind::CheckValid:
2417 // The formal requirements don't include this rule in C++14, even
2418 // though the "must be able to produce a constant expression" rules
2419 // still imply it in some cases.
2420 if (!SemaRef.getLangOpts().CPlusPlus14)
2421 return false;
2422 break;
2423 }
2424 } else if (ReturnStmts.size() > 1) {
2425 switch (Kind) {
2426 case Sema::CheckConstexprKind::Diagnose:
2427 SemaRef.Diag(
2428 ReturnStmts.back(),
2429 SemaRef.getLangOpts().CPlusPlus14
2430 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2431 : diag::ext_constexpr_body_multiple_return);
2432 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2433 SemaRef.Diag(ReturnStmts[I],
2434 diag::note_constexpr_body_previous_return);
2435 break;
2436
2437 case Sema::CheckConstexprKind::CheckValid:
2438 if (!SemaRef.getLangOpts().CPlusPlus14)
2439 return false;
2440 break;
2441 }
2442 }
2443 }
2444
2445 // C++11 [dcl.constexpr]p5:
2446 // if no function argument values exist such that the function invocation
2447 // substitution would produce a constant expression, the program is
2448 // ill-formed; no diagnostic required.
2449 // C++11 [dcl.constexpr]p3:
2450 // - every constructor call and implicit conversion used in initializing the
2451 // return value shall be one of those allowed in a constant expression.
2452 // C++11 [dcl.constexpr]p4:
2453 // - every constructor involved in initializing non-static data members and
2454 // base class sub-objects shall be a constexpr constructor.
2455 //
2456 // Note that this rule is distinct from the "requirements for a constexpr
2457 // function", so is not checked in CheckValid mode.
2458 SmallVector<PartialDiagnosticAt, 8> Diags;
2459 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2460 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2461 SemaRef.Diag(Dcl->getLocation(),
2462 diag::ext_constexpr_function_never_constant_expr)
2463 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2464 << Dcl->getNameInfo().getSourceRange();
2465 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2466 SemaRef.Diag(Diags[I].first, Diags[I].second);
2467 // Don't return false here: we allow this for compatibility in
2468 // system headers.
2469 }
2470
2471 return true;
2472 }
2473
CheckImmediateEscalatingFunctionDefinition(FunctionDecl * FD,const sema::FunctionScopeInfo * FSI)2474 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2475 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2476 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2477 return true;
2478 FD->setBodyContainsImmediateEscalatingExpressions(
2479 FSI->FoundImmediateEscalatingExpression);
2480 if (FSI->FoundImmediateEscalatingExpression) {
2481 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2482 if (it != UndefinedButUsed.end()) {
2483 Diag(it->second, diag::err_immediate_function_used_before_definition)
2484 << it->first;
2485 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2486 if (FD->isImmediateFunction() && !FD->isConsteval())
2487 DiagnoseImmediateEscalatingReason(FD);
2488 return false;
2489 }
2490 }
2491 return true;
2492 }
2493
DiagnoseImmediateEscalatingReason(FunctionDecl * FD)2494 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2495 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2496 "expected an immediate function");
2497 assert(FD->hasBody() && "expected the function to have a body");
2498 struct ImmediateEscalatingExpressionsVisitor
2499 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2500
2501 using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;
2502 Sema &SemaRef;
2503
2504 const FunctionDecl *ImmediateFn;
2505 bool ImmediateFnIsConstructor;
2506 CXXConstructorDecl *CurrentConstructor = nullptr;
2507 CXXCtorInitializer *CurrentInit = nullptr;
2508
2509 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2510 : SemaRef(SemaRef), ImmediateFn(FD),
2511 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2512
2513 bool shouldVisitImplicitCode() const { return true; }
2514 bool shouldVisitLambdaBody() const { return false; }
2515
2516 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2517 SourceLocation Loc = E->getBeginLoc();
2518 SourceRange Range = E->getSourceRange();
2519 if (CurrentConstructor && CurrentInit) {
2520 Loc = CurrentConstructor->getLocation();
2521 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2522 : SourceRange();
2523 }
2524
2525 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2526
2527 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2528 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2529 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2530 << (InitializedField != nullptr)
2531 << (CurrentInit && !CurrentInit->isWritten())
2532 << InitializedField << Range;
2533 }
2534 bool TraverseCallExpr(CallExpr *E) {
2535 if (const auto *DR =
2536 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2537 DR && DR->isImmediateEscalating()) {
2538 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2539 return false;
2540 }
2541
2542 for (Expr *A : E->arguments())
2543 if (!getDerived().TraverseStmt(A))
2544 return false;
2545
2546 return true;
2547 }
2548
2549 bool VisitDeclRefExpr(DeclRefExpr *E) {
2550 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2551 ReferencedFn && E->isImmediateEscalating()) {
2552 Diag(E, ReferencedFn, /*IsCall=*/false);
2553 return false;
2554 }
2555
2556 return true;
2557 }
2558
2559 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2560 CXXConstructorDecl *D = E->getConstructor();
2561 if (E->isImmediateEscalating()) {
2562 Diag(E, D, /*IsCall=*/true);
2563 return false;
2564 }
2565 return true;
2566 }
2567
2568 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2569 llvm::SaveAndRestore RAII(CurrentInit, Init);
2570 return Base::TraverseConstructorInitializer(Init);
2571 }
2572
2573 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2574 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2575 return Base::TraverseCXXConstructorDecl(Ctr);
2576 }
2577
2578 bool TraverseType(QualType T) { return true; }
2579 bool VisitBlockExpr(BlockExpr *T) { return true; }
2580
2581 } Visitor(*this, FD);
2582 Visitor.TraverseDecl(FD);
2583 }
2584
2585 /// Get the class that is directly named by the current context. This is the
2586 /// class for which an unqualified-id in this scope could name a constructor
2587 /// or destructor.
2588 ///
2589 /// If the scope specifier denotes a class, this will be that class.
2590 /// If the scope specifier is empty, this will be the class whose
2591 /// member-specification we are currently within. Otherwise, there
2592 /// is no such class.
getCurrentClass(Scope *,const CXXScopeSpec * SS)2593 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2594 assert(getLangOpts().CPlusPlus && "No class names in C!");
2595
2596 if (SS && SS->isInvalid())
2597 return nullptr;
2598
2599 if (SS && SS->isNotEmpty()) {
2600 DeclContext *DC = computeDeclContext(*SS, true);
2601 return dyn_cast_or_null<CXXRecordDecl>(DC);
2602 }
2603
2604 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2605 }
2606
2607 /// isCurrentClassName - Determine whether the identifier II is the
2608 /// name of the class type currently being defined. In the case of
2609 /// nested classes, this will only return true if II is the name of
2610 /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope * S,const CXXScopeSpec * SS)2611 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2612 const CXXScopeSpec *SS) {
2613 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2614 return CurDecl && &II == CurDecl->getIdentifier();
2615 }
2616
2617 /// Determine whether the identifier II is a typo for the name of
2618 /// the class type currently being defined. If so, update it to the identifier
2619 /// that should have been used.
isCurrentClassNameTypo(IdentifierInfo * & II,const CXXScopeSpec * SS)2620 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2621 assert(getLangOpts().CPlusPlus && "No class names in C!");
2622
2623 if (!getLangOpts().SpellChecking)
2624 return false;
2625
2626 CXXRecordDecl *CurDecl;
2627 if (SS && SS->isSet() && !SS->isInvalid()) {
2628 DeclContext *DC = computeDeclContext(*SS, true);
2629 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2630 } else
2631 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2632
2633 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2634 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2635 < II->getLength()) {
2636 II = CurDecl->getIdentifier();
2637 return true;
2638 }
2639
2640 return false;
2641 }
2642
2643 /// Determine whether the given class is a base class of the given
2644 /// class, including looking at dependent bases.
findCircularInheritance(const CXXRecordDecl * Class,const CXXRecordDecl * Current)2645 static bool findCircularInheritance(const CXXRecordDecl *Class,
2646 const CXXRecordDecl *Current) {
2647 SmallVector<const CXXRecordDecl*, 8> Queue;
2648
2649 Class = Class->getCanonicalDecl();
2650 while (true) {
2651 for (const auto &I : Current->bases()) {
2652 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2653 if (!Base)
2654 continue;
2655
2656 Base = Base->getDefinition();
2657 if (!Base)
2658 continue;
2659
2660 if (Base->getCanonicalDecl() == Class)
2661 return true;
2662
2663 Queue.push_back(Base);
2664 }
2665
2666 if (Queue.empty())
2667 return false;
2668
2669 Current = Queue.pop_back_val();
2670 }
2671
2672 return false;
2673 }
2674
2675 /// Check the validity of a C++ base class specifier.
2676 ///
2677 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2678 /// and returns NULL otherwise.
2679 CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)2680 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2681 SourceRange SpecifierRange,
2682 bool Virtual, AccessSpecifier Access,
2683 TypeSourceInfo *TInfo,
2684 SourceLocation EllipsisLoc) {
2685 // In HLSL, unspecified class access is public rather than private.
2686 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2687 Access == AS_none)
2688 Access = AS_public;
2689
2690 QualType BaseType = TInfo->getType();
2691 if (BaseType->containsErrors()) {
2692 // Already emitted a diagnostic when parsing the error type.
2693 return nullptr;
2694 }
2695 // C++ [class.union]p1:
2696 // A union shall not have base classes.
2697 if (Class->isUnion()) {
2698 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2699 << SpecifierRange;
2700 return nullptr;
2701 }
2702
2703 if (EllipsisLoc.isValid() &&
2704 !TInfo->getType()->containsUnexpandedParameterPack()) {
2705 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2706 << TInfo->getTypeLoc().getSourceRange();
2707 EllipsisLoc = SourceLocation();
2708 }
2709
2710 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2711
2712 if (BaseType->isDependentType()) {
2713 // Make sure that we don't have circular inheritance among our dependent
2714 // bases. For non-dependent bases, the check for completeness below handles
2715 // this.
2716 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2717 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2718 ((BaseDecl = BaseDecl->getDefinition()) &&
2719 findCircularInheritance(Class, BaseDecl))) {
2720 Diag(BaseLoc, diag::err_circular_inheritance)
2721 << BaseType << Context.getTypeDeclType(Class);
2722
2723 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2724 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2725 << BaseType;
2726
2727 return nullptr;
2728 }
2729 }
2730
2731 // Make sure that we don't make an ill-formed AST where the type of the
2732 // Class is non-dependent and its attached base class specifier is an
2733 // dependent type, which violates invariants in many clang code paths (e.g.
2734 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2735 // explicitly mark the Class decl invalid. The diagnostic was already
2736 // emitted.
2737 if (!Class->getTypeForDecl()->isDependentType())
2738 Class->setInvalidDecl();
2739 return new (Context) CXXBaseSpecifier(
2740 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2741 Access, TInfo, EllipsisLoc);
2742 }
2743
2744 // Base specifiers must be record types.
2745 if (!BaseType->isRecordType()) {
2746 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2747 return nullptr;
2748 }
2749
2750 // C++ [class.union]p1:
2751 // A union shall not be used as a base class.
2752 if (BaseType->isUnionType()) {
2753 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2754 return nullptr;
2755 }
2756
2757 // For the MS ABI, propagate DLL attributes to base class templates.
2758 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2759 Context.getTargetInfo().getTriple().isPS()) {
2760 if (Attr *ClassAttr = getDLLAttr(Class)) {
2761 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2762 BaseType->getAsCXXRecordDecl())) {
2763 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2764 BaseLoc);
2765 }
2766 }
2767 }
2768
2769 // C++ [class.derived]p2:
2770 // The class-name in a base-specifier shall not be an incompletely
2771 // defined class.
2772 if (RequireCompleteType(BaseLoc, BaseType,
2773 diag::err_incomplete_base_class, SpecifierRange)) {
2774 Class->setInvalidDecl();
2775 return nullptr;
2776 }
2777
2778 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2779 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2780 assert(BaseDecl && "Record type has no declaration");
2781 BaseDecl = BaseDecl->getDefinition();
2782 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2783 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2784 assert(CXXBaseDecl && "Base type is not a C++ type");
2785
2786 // Microsoft docs say:
2787 // "If a base-class has a code_seg attribute, derived classes must have the
2788 // same attribute."
2789 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2790 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2791 if ((DerivedCSA || BaseCSA) &&
2792 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2793 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2794 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2795 << CXXBaseDecl;
2796 return nullptr;
2797 }
2798
2799 // A class which contains a flexible array member is not suitable for use as a
2800 // base class:
2801 // - If the layout determines that a base comes before another base,
2802 // the flexible array member would index into the subsequent base.
2803 // - If the layout determines that base comes before the derived class,
2804 // the flexible array member would index into the derived class.
2805 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2806 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2807 << CXXBaseDecl->getDeclName();
2808 return nullptr;
2809 }
2810
2811 // C++ [class]p3:
2812 // If a class is marked final and it appears as a base-type-specifier in
2813 // base-clause, the program is ill-formed.
2814 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2815 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2816 << CXXBaseDecl->getDeclName()
2817 << FA->isSpelledAsSealed();
2818 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2819 << CXXBaseDecl->getDeclName() << FA->getRange();
2820 return nullptr;
2821 }
2822
2823 if (BaseDecl->isInvalidDecl())
2824 Class->setInvalidDecl();
2825
2826 // Create the base specifier.
2827 return new (Context) CXXBaseSpecifier(
2828 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2829 Access, TInfo, EllipsisLoc);
2830 }
2831
2832 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2833 /// one entry in the base class list of a class specifier, for
2834 /// example:
2835 /// class foo : public bar, virtual private baz {
2836 /// 'public bar' and 'virtual private baz' are each base-specifiers.
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,const ParsedAttributesView & Attributes,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)2837 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2838 const ParsedAttributesView &Attributes,
2839 bool Virtual, AccessSpecifier Access,
2840 ParsedType basetype, SourceLocation BaseLoc,
2841 SourceLocation EllipsisLoc) {
2842 if (!classdecl)
2843 return true;
2844
2845 AdjustDeclIfTemplate(classdecl);
2846 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2847 if (!Class)
2848 return true;
2849
2850 // We haven't yet attached the base specifiers.
2851 Class->setIsParsingBaseSpecifiers();
2852
2853 // We do not support any C++11 attributes on base-specifiers yet.
2854 // Diagnose any attributes we see.
2855 for (const ParsedAttr &AL : Attributes) {
2856 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2857 continue;
2858 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2859 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2860 << AL << AL.getRange();
2861 else
2862 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2863 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2864 }
2865
2866 TypeSourceInfo *TInfo = nullptr;
2867 GetTypeFromParser(basetype, &TInfo);
2868
2869 if (EllipsisLoc.isInvalid() &&
2870 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2871 UPPC_BaseType))
2872 return true;
2873
2874 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2875 Virtual, Access, TInfo,
2876 EllipsisLoc))
2877 return BaseSpec;
2878 else
2879 Class->setInvalidDecl();
2880
2881 return true;
2882 }
2883
2884 /// Use small set to collect indirect bases. As this is only used
2885 /// locally, there's no need to abstract the small size parameter.
2886 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2887
2888 /// Recursively add the bases of Type. Don't add Type itself.
2889 static void
NoteIndirectBases(ASTContext & Context,IndirectBaseSet & Set,const QualType & Type)2890 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2891 const QualType &Type)
2892 {
2893 // Even though the incoming type is a base, it might not be
2894 // a class -- it could be a template parm, for instance.
2895 if (auto Rec = Type->getAs<RecordType>()) {
2896 auto Decl = Rec->getAsCXXRecordDecl();
2897
2898 // Iterate over its bases.
2899 for (const auto &BaseSpec : Decl->bases()) {
2900 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2901 .getUnqualifiedType();
2902 if (Set.insert(Base).second)
2903 // If we've not already seen it, recurse.
2904 NoteIndirectBases(Context, Set, Base);
2905 }
2906 }
2907 }
2908
2909 /// Performs the actual work of attaching the given base class
2910 /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,MutableArrayRef<CXXBaseSpecifier * > Bases)2911 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2912 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2913 if (Bases.empty())
2914 return false;
2915
2916 // Used to keep track of which base types we have already seen, so
2917 // that we can properly diagnose redundant direct base types. Note
2918 // that the key is always the unqualified canonical type of the base
2919 // class.
2920 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2921
2922 // Used to track indirect bases so we can see if a direct base is
2923 // ambiguous.
2924 IndirectBaseSet IndirectBaseTypes;
2925
2926 // Copy non-redundant base specifiers into permanent storage.
2927 unsigned NumGoodBases = 0;
2928 bool Invalid = false;
2929 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2930 QualType NewBaseType
2931 = Context.getCanonicalType(Bases[idx]->getType());
2932 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2933
2934 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2935 if (KnownBase) {
2936 // C++ [class.mi]p3:
2937 // A class shall not be specified as a direct base class of a
2938 // derived class more than once.
2939 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2940 << KnownBase->getType() << Bases[idx]->getSourceRange();
2941
2942 // Delete the duplicate base class specifier; we're going to
2943 // overwrite its pointer later.
2944 Context.Deallocate(Bases[idx]);
2945
2946 Invalid = true;
2947 } else {
2948 // Okay, add this new base class.
2949 KnownBase = Bases[idx];
2950 Bases[NumGoodBases++] = Bases[idx];
2951
2952 if (NewBaseType->isDependentType())
2953 continue;
2954 // Note this base's direct & indirect bases, if there could be ambiguity.
2955 if (Bases.size() > 1)
2956 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2957
2958 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2959 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2960 if (Class->isInterface() &&
2961 (!RD->isInterfaceLike() ||
2962 KnownBase->getAccessSpecifier() != AS_public)) {
2963 // The Microsoft extension __interface does not permit bases that
2964 // are not themselves public interfaces.
2965 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2966 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2967 << RD->getSourceRange();
2968 Invalid = true;
2969 }
2970 if (RD->hasAttr<WeakAttr>())
2971 Class->addAttr(WeakAttr::CreateImplicit(Context));
2972 }
2973 }
2974 }
2975
2976 // Attach the remaining base class specifiers to the derived class.
2977 Class->setBases(Bases.data(), NumGoodBases);
2978
2979 // Check that the only base classes that are duplicate are virtual.
2980 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2981 // Check whether this direct base is inaccessible due to ambiguity.
2982 QualType BaseType = Bases[idx]->getType();
2983
2984 // Skip all dependent types in templates being used as base specifiers.
2985 // Checks below assume that the base specifier is a CXXRecord.
2986 if (BaseType->isDependentType())
2987 continue;
2988
2989 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2990 .getUnqualifiedType();
2991
2992 if (IndirectBaseTypes.count(CanonicalBase)) {
2993 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2994 /*DetectVirtual=*/true);
2995 bool found
2996 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2997 assert(found);
2998 (void)found;
2999
3000 if (Paths.isAmbiguous(CanonicalBase))
3001 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3002 << BaseType << getAmbiguousPathsDisplayString(Paths)
3003 << Bases[idx]->getSourceRange();
3004 else
3005 assert(Bases[idx]->isVirtual());
3006 }
3007
3008 // Delete the base class specifier, since its data has been copied
3009 // into the CXXRecordDecl.
3010 Context.Deallocate(Bases[idx]);
3011 }
3012
3013 return Invalid;
3014 }
3015
3016 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
3017 /// class, after checking whether there are any duplicate base
3018 /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,MutableArrayRef<CXXBaseSpecifier * > Bases)3019 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3020 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3021 if (!ClassDecl || Bases.empty())
3022 return;
3023
3024 AdjustDeclIfTemplate(ClassDecl);
3025 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3026 }
3027
3028 /// Determine whether the type \p Derived is a C++ class that is
3029 /// derived from the type \p Base.
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base)3030 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3031 if (!getLangOpts().CPlusPlus)
3032 return false;
3033
3034 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3035 if (!DerivedRD)
3036 return false;
3037
3038 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3039 if (!BaseRD)
3040 return false;
3041
3042 // If either the base or the derived type is invalid, don't try to
3043 // check whether one is derived from the other.
3044 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3045 return false;
3046
3047 // FIXME: In a modules build, do we need the entire path to be visible for us
3048 // to be able to use the inheritance relationship?
3049 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3050 return false;
3051
3052 return DerivedRD->isDerivedFrom(BaseRD);
3053 }
3054
3055 /// Determine whether the type \p Derived is a C++ class that is
3056 /// derived from the type \p Base.
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base,CXXBasePaths & Paths)3057 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3058 CXXBasePaths &Paths) {
3059 if (!getLangOpts().CPlusPlus)
3060 return false;
3061
3062 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3063 if (!DerivedRD)
3064 return false;
3065
3066 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3067 if (!BaseRD)
3068 return false;
3069
3070 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3071 return false;
3072
3073 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3074 }
3075
BuildBasePathArray(const CXXBasePath & Path,CXXCastPath & BasePathArray)3076 static void BuildBasePathArray(const CXXBasePath &Path,
3077 CXXCastPath &BasePathArray) {
3078 // We first go backward and check if we have a virtual base.
3079 // FIXME: It would be better if CXXBasePath had the base specifier for
3080 // the nearest virtual base.
3081 unsigned Start = 0;
3082 for (unsigned I = Path.size(); I != 0; --I) {
3083 if (Path[I - 1].Base->isVirtual()) {
3084 Start = I - 1;
3085 break;
3086 }
3087 }
3088
3089 // Now add all bases.
3090 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3091 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3092 }
3093
3094
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)3095 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3096 CXXCastPath &BasePathArray) {
3097 assert(BasePathArray.empty() && "Base path array must be empty!");
3098 assert(Paths.isRecordingPaths() && "Must record paths!");
3099 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3100 }
3101 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3102 /// conversion (where Derived and Base are class types) is
3103 /// well-formed, meaning that the conversion is unambiguous (and
3104 /// that all of the base classes are accessible). Returns true
3105 /// and emits a diagnostic if the code is ill-formed, returns false
3106 /// otherwise. Loc is the location where this routine should point to
3107 /// if there is an error, and Range is the source range to highlight
3108 /// if there is an error.
3109 ///
3110 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3111 /// diagnostic for the respective type of error will be suppressed, but the
3112 /// check for ill-formed code will still be performed.
3113 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbiguousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath,bool IgnoreAccess)3114 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3115 unsigned InaccessibleBaseID,
3116 unsigned AmbiguousBaseConvID,
3117 SourceLocation Loc, SourceRange Range,
3118 DeclarationName Name,
3119 CXXCastPath *BasePath,
3120 bool IgnoreAccess) {
3121 // First, determine whether the path from Derived to Base is
3122 // ambiguous. This is slightly more expensive than checking whether
3123 // the Derived to Base conversion exists, because here we need to
3124 // explore multiple paths to determine if there is an ambiguity.
3125 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3126 /*DetectVirtual=*/false);
3127 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3128 if (!DerivationOkay)
3129 return true;
3130
3131 const CXXBasePath *Path = nullptr;
3132 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3133 Path = &Paths.front();
3134
3135 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3136 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3137 // user to access such bases.
3138 if (!Path && getLangOpts().MSVCCompat) {
3139 for (const CXXBasePath &PossiblePath : Paths) {
3140 if (PossiblePath.size() == 1) {
3141 Path = &PossiblePath;
3142 if (AmbiguousBaseConvID)
3143 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3144 << Base << Derived << Range;
3145 break;
3146 }
3147 }
3148 }
3149
3150 if (Path) {
3151 if (!IgnoreAccess) {
3152 // Check that the base class can be accessed.
3153 switch (
3154 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3155 case AR_inaccessible:
3156 return true;
3157 case AR_accessible:
3158 case AR_dependent:
3159 case AR_delayed:
3160 break;
3161 }
3162 }
3163
3164 // Build a base path if necessary.
3165 if (BasePath)
3166 ::BuildBasePathArray(*Path, *BasePath);
3167 return false;
3168 }
3169
3170 if (AmbiguousBaseConvID) {
3171 // We know that the derived-to-base conversion is ambiguous, and
3172 // we're going to produce a diagnostic. Perform the derived-to-base
3173 // search just one more time to compute all of the possible paths so
3174 // that we can print them out. This is more expensive than any of
3175 // the previous derived-to-base checks we've done, but at this point
3176 // performance isn't as much of an issue.
3177 Paths.clear();
3178 Paths.setRecordingPaths(true);
3179 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3180 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3181 (void)StillOkay;
3182
3183 // Build up a textual representation of the ambiguous paths, e.g.,
3184 // D -> B -> A, that will be used to illustrate the ambiguous
3185 // conversions in the diagnostic. We only print one of the paths
3186 // to each base class subobject.
3187 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3188
3189 Diag(Loc, AmbiguousBaseConvID)
3190 << Derived << Base << PathDisplayStr << Range << Name;
3191 }
3192 return true;
3193 }
3194
3195 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)3196 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3197 SourceLocation Loc, SourceRange Range,
3198 CXXCastPath *BasePath,
3199 bool IgnoreAccess) {
3200 return CheckDerivedToBaseConversion(
3201 Derived, Base, diag::err_upcast_to_inaccessible_base,
3202 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3203 BasePath, IgnoreAccess);
3204 }
3205
3206
3207 /// Builds a string representing ambiguous paths from a
3208 /// specific derived class to different subobjects of the same base
3209 /// class.
3210 ///
3211 /// This function builds a string that can be used in error messages
3212 /// to show the different paths that one can take through the
3213 /// inheritance hierarchy to go from the derived class to different
3214 /// subobjects of a base class. The result looks something like this:
3215 /// @code
3216 /// struct D -> struct B -> struct A
3217 /// struct D -> struct C -> struct A
3218 /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)3219 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3220 std::string PathDisplayStr;
3221 std::set<unsigned> DisplayedPaths;
3222 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3223 Path != Paths.end(); ++Path) {
3224 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3225 // We haven't displayed a path to this particular base
3226 // class subobject yet.
3227 PathDisplayStr += "\n ";
3228 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3229 for (CXXBasePath::const_iterator Element = Path->begin();
3230 Element != Path->end(); ++Element)
3231 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3232 }
3233 }
3234
3235 return PathDisplayStr;
3236 }
3237
3238 //===----------------------------------------------------------------------===//
3239 // C++ class member Handling
3240 //===----------------------------------------------------------------------===//
3241
3242 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,const ParsedAttributesView & Attrs)3243 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3244 SourceLocation ColonLoc,
3245 const ParsedAttributesView &Attrs) {
3246 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3247 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3248 ASLoc, ColonLoc);
3249 CurContext->addHiddenDecl(ASDecl);
3250 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3251 }
3252
3253 /// CheckOverrideControl - Check C++11 override control semantics.
CheckOverrideControl(NamedDecl * D)3254 void Sema::CheckOverrideControl(NamedDecl *D) {
3255 if (D->isInvalidDecl())
3256 return;
3257
3258 // We only care about "override" and "final" declarations.
3259 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3260 return;
3261
3262 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3263
3264 // We can't check dependent instance methods.
3265 if (MD && MD->isInstance() &&
3266 (MD->getParent()->hasAnyDependentBases() ||
3267 MD->getType()->isDependentType()))
3268 return;
3269
3270 if (MD && !MD->isVirtual()) {
3271 // If we have a non-virtual method, check if it hides a virtual method.
3272 // (In that case, it's most likely the method has the wrong type.)
3273 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3274 FindHiddenVirtualMethods(MD, OverloadedMethods);
3275
3276 if (!OverloadedMethods.empty()) {
3277 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3278 Diag(OA->getLocation(),
3279 diag::override_keyword_hides_virtual_member_function)
3280 << "override" << (OverloadedMethods.size() > 1);
3281 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3282 Diag(FA->getLocation(),
3283 diag::override_keyword_hides_virtual_member_function)
3284 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3285 << (OverloadedMethods.size() > 1);
3286 }
3287 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3288 MD->setInvalidDecl();
3289 return;
3290 }
3291 // Fall through into the general case diagnostic.
3292 // FIXME: We might want to attempt typo correction here.
3293 }
3294
3295 if (!MD || !MD->isVirtual()) {
3296 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3297 Diag(OA->getLocation(),
3298 diag::override_keyword_only_allowed_on_virtual_member_functions)
3299 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3300 D->dropAttr<OverrideAttr>();
3301 }
3302 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3303 Diag(FA->getLocation(),
3304 diag::override_keyword_only_allowed_on_virtual_member_functions)
3305 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3306 << FixItHint::CreateRemoval(FA->getLocation());
3307 D->dropAttr<FinalAttr>();
3308 }
3309 return;
3310 }
3311
3312 // C++11 [class.virtual]p5:
3313 // If a function is marked with the virt-specifier override and
3314 // does not override a member function of a base class, the program is
3315 // ill-formed.
3316 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3317 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3318 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3319 << MD->getDeclName();
3320 }
3321
DiagnoseAbsenceOfOverrideControl(NamedDecl * D,bool Inconsistent)3322 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3323 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3324 return;
3325 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3326 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3327 return;
3328
3329 SourceLocation Loc = MD->getLocation();
3330 SourceLocation SpellingLoc = Loc;
3331 if (getSourceManager().isMacroArgExpansion(Loc))
3332 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3333 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3334 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3335 return;
3336
3337 if (MD->size_overridden_methods() > 0) {
3338 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3339 unsigned DiagID =
3340 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3341 ? DiagInconsistent
3342 : DiagSuggest;
3343 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3344 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3345 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3346 };
3347 if (isa<CXXDestructorDecl>(MD))
3348 EmitDiag(
3349 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3350 diag::warn_suggest_destructor_marked_not_override_overriding);
3351 else
3352 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3353 diag::warn_suggest_function_marked_not_override_overriding);
3354 }
3355 }
3356
3357 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3358 /// function overrides a virtual member function marked 'final', according to
3359 /// C++11 [class.virtual]p4.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)3360 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3361 const CXXMethodDecl *Old) {
3362 FinalAttr *FA = Old->getAttr<FinalAttr>();
3363 if (!FA)
3364 return false;
3365
3366 Diag(New->getLocation(), diag::err_final_function_overridden)
3367 << New->getDeclName()
3368 << FA->isSpelledAsSealed();
3369 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3370 return true;
3371 }
3372
InitializationHasSideEffects(const FieldDecl & FD)3373 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3374 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3375 // FIXME: Destruction of ObjC lifetime types has side-effects.
3376 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3377 return !RD->isCompleteDefinition() ||
3378 !RD->hasTrivialDefaultConstructor() ||
3379 !RD->hasTrivialDestructor();
3380 return false;
3381 }
3382
3383 // Check if there is a field shadowing.
CheckShadowInheritedFields(const SourceLocation & Loc,DeclarationName FieldName,const CXXRecordDecl * RD,bool DeclIsField)3384 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3385 DeclarationName FieldName,
3386 const CXXRecordDecl *RD,
3387 bool DeclIsField) {
3388 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3389 return;
3390
3391 // To record a shadowed field in a base
3392 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3393 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3394 CXXBasePath &Path) {
3395 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3396 // Record an ambiguous path directly
3397 if (Bases.find(Base) != Bases.end())
3398 return true;
3399 for (const auto Field : Base->lookup(FieldName)) {
3400 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3401 Field->getAccess() != AS_private) {
3402 assert(Field->getAccess() != AS_none);
3403 assert(Bases.find(Base) == Bases.end());
3404 Bases[Base] = Field;
3405 return true;
3406 }
3407 }
3408 return false;
3409 };
3410
3411 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3412 /*DetectVirtual=*/true);
3413 if (!RD->lookupInBases(FieldShadowed, Paths))
3414 return;
3415
3416 for (const auto &P : Paths) {
3417 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3418 auto It = Bases.find(Base);
3419 // Skip duplicated bases
3420 if (It == Bases.end())
3421 continue;
3422 auto BaseField = It->second;
3423 assert(BaseField->getAccess() != AS_private);
3424 if (AS_none !=
3425 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3426 Diag(Loc, diag::warn_shadow_field)
3427 << FieldName << RD << Base << DeclIsField;
3428 Diag(BaseField->getLocation(), diag::note_shadow_field);
3429 Bases.erase(It);
3430 }
3431 }
3432 }
3433
3434 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3435 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3436 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3437 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3438 /// present (but parsing it has been deferred).
3439 NamedDecl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BW,const VirtSpecifiers & VS,InClassInitStyle InitStyle)3440 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3441 MultiTemplateParamsArg TemplateParameterLists,
3442 Expr *BW, const VirtSpecifiers &VS,
3443 InClassInitStyle InitStyle) {
3444 const DeclSpec &DS = D.getDeclSpec();
3445 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3446 DeclarationName Name = NameInfo.getName();
3447 SourceLocation Loc = NameInfo.getLoc();
3448
3449 // For anonymous bitfields, the location should point to the type.
3450 if (Loc.isInvalid())
3451 Loc = D.getBeginLoc();
3452
3453 Expr *BitWidth = static_cast<Expr*>(BW);
3454
3455 assert(isa<CXXRecordDecl>(CurContext));
3456 assert(!DS.isFriendSpecified());
3457
3458 bool isFunc = D.isDeclarationOfFunction();
3459 const ParsedAttr *MSPropertyAttr =
3460 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3461
3462 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3463 // The Microsoft extension __interface only permits public member functions
3464 // and prohibits constructors, destructors, operators, non-public member
3465 // functions, static methods and data members.
3466 unsigned InvalidDecl;
3467 bool ShowDeclName = true;
3468 if (!isFunc &&
3469 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3470 InvalidDecl = 0;
3471 else if (!isFunc)
3472 InvalidDecl = 1;
3473 else if (AS != AS_public)
3474 InvalidDecl = 2;
3475 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3476 InvalidDecl = 3;
3477 else switch (Name.getNameKind()) {
3478 case DeclarationName::CXXConstructorName:
3479 InvalidDecl = 4;
3480 ShowDeclName = false;
3481 break;
3482
3483 case DeclarationName::CXXDestructorName:
3484 InvalidDecl = 5;
3485 ShowDeclName = false;
3486 break;
3487
3488 case DeclarationName::CXXOperatorName:
3489 case DeclarationName::CXXConversionFunctionName:
3490 InvalidDecl = 6;
3491 break;
3492
3493 default:
3494 InvalidDecl = 0;
3495 break;
3496 }
3497
3498 if (InvalidDecl) {
3499 if (ShowDeclName)
3500 Diag(Loc, diag::err_invalid_member_in_interface)
3501 << (InvalidDecl-1) << Name;
3502 else
3503 Diag(Loc, diag::err_invalid_member_in_interface)
3504 << (InvalidDecl-1) << "";
3505 return nullptr;
3506 }
3507 }
3508
3509 // C++ 9.2p6: A member shall not be declared to have automatic storage
3510 // duration (auto, register) or with the extern storage-class-specifier.
3511 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3512 // data members and cannot be applied to names declared const or static,
3513 // and cannot be applied to reference members.
3514 switch (DS.getStorageClassSpec()) {
3515 case DeclSpec::SCS_unspecified:
3516 case DeclSpec::SCS_typedef:
3517 case DeclSpec::SCS_static:
3518 break;
3519 case DeclSpec::SCS_mutable:
3520 if (isFunc) {
3521 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3522
3523 // FIXME: It would be nicer if the keyword was ignored only for this
3524 // declarator. Otherwise we could get follow-up errors.
3525 D.getMutableDeclSpec().ClearStorageClassSpecs();
3526 }
3527 break;
3528 default:
3529 Diag(DS.getStorageClassSpecLoc(),
3530 diag::err_storageclass_invalid_for_member);
3531 D.getMutableDeclSpec().ClearStorageClassSpecs();
3532 break;
3533 }
3534
3535 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3536 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3537 !isFunc);
3538
3539 if (DS.hasConstexprSpecifier() && isInstField) {
3540 SemaDiagnosticBuilder B =
3541 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3542 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3543 if (InitStyle == ICIS_NoInit) {
3544 B << 0 << 0;
3545 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3546 B << FixItHint::CreateRemoval(ConstexprLoc);
3547 else {
3548 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3549 D.getMutableDeclSpec().ClearConstexprSpec();
3550 const char *PrevSpec;
3551 unsigned DiagID;
3552 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3553 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3554 (void)Failed;
3555 assert(!Failed && "Making a constexpr member const shouldn't fail");
3556 }
3557 } else {
3558 B << 1;
3559 const char *PrevSpec;
3560 unsigned DiagID;
3561 if (D.getMutableDeclSpec().SetStorageClassSpec(
3562 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3563 Context.getPrintingPolicy())) {
3564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3565 "This is the only DeclSpec that should fail to be applied");
3566 B << 1;
3567 } else {
3568 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3569 isInstField = false;
3570 }
3571 }
3572 }
3573
3574 NamedDecl *Member;
3575 if (isInstField) {
3576 CXXScopeSpec &SS = D.getCXXScopeSpec();
3577
3578 // Data members must have identifiers for names.
3579 if (!Name.isIdentifier()) {
3580 Diag(Loc, diag::err_bad_variable_name)
3581 << Name;
3582 return nullptr;
3583 }
3584
3585 IdentifierInfo *II = Name.getAsIdentifierInfo();
3586
3587 // Member field could not be with "template" keyword.
3588 // So TemplateParameterLists should be empty in this case.
3589 if (TemplateParameterLists.size()) {
3590 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3591 if (TemplateParams->size()) {
3592 // There is no such thing as a member field template.
3593 Diag(D.getIdentifierLoc(), diag::err_template_member)
3594 << II
3595 << SourceRange(TemplateParams->getTemplateLoc(),
3596 TemplateParams->getRAngleLoc());
3597 } else {
3598 // There is an extraneous 'template<>' for this member.
3599 Diag(TemplateParams->getTemplateLoc(),
3600 diag::err_template_member_noparams)
3601 << II
3602 << SourceRange(TemplateParams->getTemplateLoc(),
3603 TemplateParams->getRAngleLoc());
3604 }
3605 return nullptr;
3606 }
3607
3608 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3609 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3610 << II
3611 << SourceRange(D.getName().TemplateId->LAngleLoc,
3612 D.getName().TemplateId->RAngleLoc)
3613 << D.getName().TemplateId->LAngleLoc;
3614 D.SetIdentifier(II, Loc);
3615 }
3616
3617 if (SS.isSet() && !SS.isInvalid()) {
3618 // The user provided a superfluous scope specifier inside a class
3619 // definition:
3620 //
3621 // class X {
3622 // int X::member;
3623 // };
3624 if (DeclContext *DC = computeDeclContext(SS, false))
3625 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3626 D.getName().getKind() ==
3627 UnqualifiedIdKind::IK_TemplateId);
3628 else
3629 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3630 << Name << SS.getRange();
3631
3632 SS.clear();
3633 }
3634
3635 if (MSPropertyAttr) {
3636 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3637 BitWidth, InitStyle, AS, *MSPropertyAttr);
3638 if (!Member)
3639 return nullptr;
3640 isInstField = false;
3641 } else {
3642 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3643 BitWidth, InitStyle, AS);
3644 if (!Member)
3645 return nullptr;
3646 }
3647
3648 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3649 } else {
3650 Member = HandleDeclarator(S, D, TemplateParameterLists);
3651 if (!Member)
3652 return nullptr;
3653
3654 // Non-instance-fields can't have a bitfield.
3655 if (BitWidth) {
3656 if (Member->isInvalidDecl()) {
3657 // don't emit another diagnostic.
3658 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3659 // C++ 9.6p3: A bit-field shall not be a static member.
3660 // "static member 'A' cannot be a bit-field"
3661 Diag(Loc, diag::err_static_not_bitfield)
3662 << Name << BitWidth->getSourceRange();
3663 } else if (isa<TypedefDecl>(Member)) {
3664 // "typedef member 'x' cannot be a bit-field"
3665 Diag(Loc, diag::err_typedef_not_bitfield)
3666 << Name << BitWidth->getSourceRange();
3667 } else {
3668 // A function typedef ("typedef int f(); f a;").
3669 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3670 Diag(Loc, diag::err_not_integral_type_bitfield)
3671 << Name << cast<ValueDecl>(Member)->getType()
3672 << BitWidth->getSourceRange();
3673 }
3674
3675 BitWidth = nullptr;
3676 Member->setInvalidDecl();
3677 }
3678
3679 NamedDecl *NonTemplateMember = Member;
3680 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3681 NonTemplateMember = FunTmpl->getTemplatedDecl();
3682 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3683 NonTemplateMember = VarTmpl->getTemplatedDecl();
3684
3685 Member->setAccess(AS);
3686
3687 // If we have declared a member function template or static data member
3688 // template, set the access of the templated declaration as well.
3689 if (NonTemplateMember != Member)
3690 NonTemplateMember->setAccess(AS);
3691
3692 // C++ [temp.deduct.guide]p3:
3693 // A deduction guide [...] for a member class template [shall be
3694 // declared] with the same access [as the template].
3695 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3696 auto *TD = DG->getDeducedTemplate();
3697 // Access specifiers are only meaningful if both the template and the
3698 // deduction guide are from the same scope.
3699 if (AS != TD->getAccess() &&
3700 TD->getDeclContext()->getRedeclContext()->Equals(
3701 DG->getDeclContext()->getRedeclContext())) {
3702 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3703 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3704 << TD->getAccess();
3705 const AccessSpecDecl *LastAccessSpec = nullptr;
3706 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3707 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3708 LastAccessSpec = AccessSpec;
3709 }
3710 assert(LastAccessSpec && "differing access with no access specifier");
3711 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3712 << AS;
3713 }
3714 }
3715 }
3716
3717 if (VS.isOverrideSpecified())
3718 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3719 if (VS.isFinalSpecified())
3720 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3721 VS.isFinalSpelledSealed()
3722 ? FinalAttr::Keyword_sealed
3723 : FinalAttr::Keyword_final));
3724
3725 if (VS.getLastLocation().isValid()) {
3726 // Update the end location of a method that has a virt-specifiers.
3727 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3728 MD->setRangeEnd(VS.getLastLocation());
3729 }
3730
3731 CheckOverrideControl(Member);
3732
3733 assert((Name || isInstField) && "No identifier for non-field ?");
3734
3735 if (isInstField) {
3736 FieldDecl *FD = cast<FieldDecl>(Member);
3737 FieldCollector->Add(FD);
3738
3739 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3740 // Remember all explicit private FieldDecls that have a name, no side
3741 // effects and are not part of a dependent type declaration.
3742
3743 auto DeclHasUnusedAttr = [](const QualType &T) {
3744 if (const TagDecl *TD = T->getAsTagDecl())
3745 return TD->hasAttr<UnusedAttr>();
3746 if (const TypedefType *TDT = T->getAs<TypedefType>())
3747 return TDT->getDecl()->hasAttr<UnusedAttr>();
3748 return false;
3749 };
3750
3751 if (!FD->isImplicit() && FD->getDeclName() &&
3752 FD->getAccess() == AS_private &&
3753 !FD->hasAttr<UnusedAttr>() &&
3754 !FD->getParent()->isDependentContext() &&
3755 !DeclHasUnusedAttr(FD->getType()) &&
3756 !InitializationHasSideEffects(*FD))
3757 UnusedPrivateFields.insert(FD);
3758 }
3759 }
3760
3761 return Member;
3762 }
3763
3764 namespace {
3765 class UninitializedFieldVisitor
3766 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3767 Sema &S;
3768 // List of Decls to generate a warning on. Also remove Decls that become
3769 // initialized.
3770 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3771 // List of base classes of the record. Classes are removed after their
3772 // initializers.
3773 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3774 // Vector of decls to be removed from the Decl set prior to visiting the
3775 // nodes. These Decls may have been initialized in the prior initializer.
3776 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3777 // If non-null, add a note to the warning pointing back to the constructor.
3778 const CXXConstructorDecl *Constructor;
3779 // Variables to hold state when processing an initializer list. When
3780 // InitList is true, special case initialization of FieldDecls matching
3781 // InitListFieldDecl.
3782 bool InitList;
3783 FieldDecl *InitListFieldDecl;
3784 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3785
3786 public:
3787 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,llvm::SmallPtrSetImpl<ValueDecl * > & Decls,llvm::SmallPtrSetImpl<QualType> & BaseClasses)3788 UninitializedFieldVisitor(Sema &S,
3789 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3790 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3791 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3792 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3793
3794 // Returns true if the use of ME is not an uninitialized use.
IsInitListMemberExprInitialized(MemberExpr * ME,bool CheckReferenceOnly)3795 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3796 bool CheckReferenceOnly) {
3797 llvm::SmallVector<FieldDecl*, 4> Fields;
3798 bool ReferenceField = false;
3799 while (ME) {
3800 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3801 if (!FD)
3802 return false;
3803 Fields.push_back(FD);
3804 if (FD->getType()->isReferenceType())
3805 ReferenceField = true;
3806 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3807 }
3808
3809 // Binding a reference to an uninitialized field is not an
3810 // uninitialized use.
3811 if (CheckReferenceOnly && !ReferenceField)
3812 return true;
3813
3814 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3815 // Discard the first field since it is the field decl that is being
3816 // initialized.
3817 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3818 UsedFieldIndex.push_back(FD->getFieldIndex());
3819
3820 for (auto UsedIter = UsedFieldIndex.begin(),
3821 UsedEnd = UsedFieldIndex.end(),
3822 OrigIter = InitFieldIndex.begin(),
3823 OrigEnd = InitFieldIndex.end();
3824 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3825 if (*UsedIter < *OrigIter)
3826 return true;
3827 if (*UsedIter > *OrigIter)
3828 break;
3829 }
3830
3831 return false;
3832 }
3833
HandleMemberExpr(MemberExpr * ME,bool CheckReferenceOnly,bool AddressOf)3834 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3835 bool AddressOf) {
3836 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3837 return;
3838
3839 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3840 // or union.
3841 MemberExpr *FieldME = ME;
3842
3843 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3844
3845 Expr *Base = ME;
3846 while (MemberExpr *SubME =
3847 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3848
3849 if (isa<VarDecl>(SubME->getMemberDecl()))
3850 return;
3851
3852 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3853 if (!FD->isAnonymousStructOrUnion())
3854 FieldME = SubME;
3855
3856 if (!FieldME->getType().isPODType(S.Context))
3857 AllPODFields = false;
3858
3859 Base = SubME->getBase();
3860 }
3861
3862 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3863 Visit(Base);
3864 return;
3865 }
3866
3867 if (AddressOf && AllPODFields)
3868 return;
3869
3870 ValueDecl* FoundVD = FieldME->getMemberDecl();
3871
3872 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3873 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3874 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3875 }
3876
3877 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3878 QualType T = BaseCast->getType();
3879 if (T->isPointerType() &&
3880 BaseClasses.count(T->getPointeeType())) {
3881 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3882 << T->getPointeeType() << FoundVD;
3883 }
3884 }
3885 }
3886
3887 if (!Decls.count(FoundVD))
3888 return;
3889
3890 const bool IsReference = FoundVD->getType()->isReferenceType();
3891
3892 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3893 // Special checking for initializer lists.
3894 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3895 return;
3896 }
3897 } else {
3898 // Prevent double warnings on use of unbounded references.
3899 if (CheckReferenceOnly && !IsReference)
3900 return;
3901 }
3902
3903 unsigned diag = IsReference
3904 ? diag::warn_reference_field_is_uninit
3905 : diag::warn_field_is_uninit;
3906 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3907 if (Constructor)
3908 S.Diag(Constructor->getLocation(),
3909 diag::note_uninit_in_this_constructor)
3910 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3911
3912 }
3913
HandleValue(Expr * E,bool AddressOf)3914 void HandleValue(Expr *E, bool AddressOf) {
3915 E = E->IgnoreParens();
3916
3917 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3918 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3919 AddressOf /*AddressOf*/);
3920 return;
3921 }
3922
3923 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3924 Visit(CO->getCond());
3925 HandleValue(CO->getTrueExpr(), AddressOf);
3926 HandleValue(CO->getFalseExpr(), AddressOf);
3927 return;
3928 }
3929
3930 if (BinaryConditionalOperator *BCO =
3931 dyn_cast<BinaryConditionalOperator>(E)) {
3932 Visit(BCO->getCond());
3933 HandleValue(BCO->getFalseExpr(), AddressOf);
3934 return;
3935 }
3936
3937 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3938 HandleValue(OVE->getSourceExpr(), AddressOf);
3939 return;
3940 }
3941
3942 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3943 switch (BO->getOpcode()) {
3944 default:
3945 break;
3946 case(BO_PtrMemD):
3947 case(BO_PtrMemI):
3948 HandleValue(BO->getLHS(), AddressOf);
3949 Visit(BO->getRHS());
3950 return;
3951 case(BO_Comma):
3952 Visit(BO->getLHS());
3953 HandleValue(BO->getRHS(), AddressOf);
3954 return;
3955 }
3956 }
3957
3958 Visit(E);
3959 }
3960
CheckInitListExpr(InitListExpr * ILE)3961 void CheckInitListExpr(InitListExpr *ILE) {
3962 InitFieldIndex.push_back(0);
3963 for (auto *Child : ILE->children()) {
3964 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3965 CheckInitListExpr(SubList);
3966 } else {
3967 Visit(Child);
3968 }
3969 ++InitFieldIndex.back();
3970 }
3971 InitFieldIndex.pop_back();
3972 }
3973
CheckInitializer(Expr * E,const CXXConstructorDecl * FieldConstructor,FieldDecl * Field,const Type * BaseClass)3974 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3975 FieldDecl *Field, const Type *BaseClass) {
3976 // Remove Decls that may have been initialized in the previous
3977 // initializer.
3978 for (ValueDecl* VD : DeclsToRemove)
3979 Decls.erase(VD);
3980 DeclsToRemove.clear();
3981
3982 Constructor = FieldConstructor;
3983 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3984
3985 if (ILE && Field) {
3986 InitList = true;
3987 InitListFieldDecl = Field;
3988 InitFieldIndex.clear();
3989 CheckInitListExpr(ILE);
3990 } else {
3991 InitList = false;
3992 Visit(E);
3993 }
3994
3995 if (Field)
3996 Decls.erase(Field);
3997 if (BaseClass)
3998 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3999 }
4000
VisitMemberExpr(MemberExpr * ME)4001 void VisitMemberExpr(MemberExpr *ME) {
4002 // All uses of unbounded reference fields will warn.
4003 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4004 }
4005
VisitImplicitCastExpr(ImplicitCastExpr * E)4006 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4007 if (E->getCastKind() == CK_LValueToRValue) {
4008 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4009 return;
4010 }
4011
4012 Inherited::VisitImplicitCastExpr(E);
4013 }
4014
VisitCXXConstructExpr(CXXConstructExpr * E)4015 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4016 if (E->getConstructor()->isCopyConstructor()) {
4017 Expr *ArgExpr = E->getArg(0);
4018 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4019 if (ILE->getNumInits() == 1)
4020 ArgExpr = ILE->getInit(0);
4021 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4022 if (ICE->getCastKind() == CK_NoOp)
4023 ArgExpr = ICE->getSubExpr();
4024 HandleValue(ArgExpr, false /*AddressOf*/);
4025 return;
4026 }
4027 Inherited::VisitCXXConstructExpr(E);
4028 }
4029
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)4030 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4031 Expr *Callee = E->getCallee();
4032 if (isa<MemberExpr>(Callee)) {
4033 HandleValue(Callee, false /*AddressOf*/);
4034 for (auto *Arg : E->arguments())
4035 Visit(Arg);
4036 return;
4037 }
4038
4039 Inherited::VisitCXXMemberCallExpr(E);
4040 }
4041
VisitCallExpr(CallExpr * E)4042 void VisitCallExpr(CallExpr *E) {
4043 // Treat std::move as a use.
4044 if (E->isCallToStdMove()) {
4045 HandleValue(E->getArg(0), /*AddressOf=*/false);
4046 return;
4047 }
4048
4049 Inherited::VisitCallExpr(E);
4050 }
4051
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)4052 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4053 Expr *Callee = E->getCallee();
4054
4055 if (isa<UnresolvedLookupExpr>(Callee))
4056 return Inherited::VisitCXXOperatorCallExpr(E);
4057
4058 Visit(Callee);
4059 for (auto *Arg : E->arguments())
4060 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4061 }
4062
VisitBinaryOperator(BinaryOperator * E)4063 void VisitBinaryOperator(BinaryOperator *E) {
4064 // If a field assignment is detected, remove the field from the
4065 // uninitiailized field set.
4066 if (E->getOpcode() == BO_Assign)
4067 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4068 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4069 if (!FD->getType()->isReferenceType())
4070 DeclsToRemove.push_back(FD);
4071
4072 if (E->isCompoundAssignmentOp()) {
4073 HandleValue(E->getLHS(), false /*AddressOf*/);
4074 Visit(E->getRHS());
4075 return;
4076 }
4077
4078 Inherited::VisitBinaryOperator(E);
4079 }
4080
VisitUnaryOperator(UnaryOperator * E)4081 void VisitUnaryOperator(UnaryOperator *E) {
4082 if (E->isIncrementDecrementOp()) {
4083 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4084 return;
4085 }
4086 if (E->getOpcode() == UO_AddrOf) {
4087 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4088 HandleValue(ME->getBase(), true /*AddressOf*/);
4089 return;
4090 }
4091 }
4092
4093 Inherited::VisitUnaryOperator(E);
4094 }
4095 };
4096
4097 // Diagnose value-uses of fields to initialize themselves, e.g.
4098 // foo(foo)
4099 // where foo is not also a parameter to the constructor.
4100 // Also diagnose across field uninitialized use such as
4101 // x(y), y(x)
4102 // TODO: implement -Wuninitialized and fold this into that framework.
DiagnoseUninitializedFields(Sema & SemaRef,const CXXConstructorDecl * Constructor)4103 static void DiagnoseUninitializedFields(
4104 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4105
4106 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4107 Constructor->getLocation())) {
4108 return;
4109 }
4110
4111 if (Constructor->isInvalidDecl())
4112 return;
4113
4114 const CXXRecordDecl *RD = Constructor->getParent();
4115
4116 if (RD->isDependentContext())
4117 return;
4118
4119 // Holds fields that are uninitialized.
4120 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4121
4122 // At the beginning, all fields are uninitialized.
4123 for (auto *I : RD->decls()) {
4124 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4125 UninitializedFields.insert(FD);
4126 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4127 UninitializedFields.insert(IFD->getAnonField());
4128 }
4129 }
4130
4131 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4132 for (const auto &I : RD->bases())
4133 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4134
4135 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4136 return;
4137
4138 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4139 UninitializedFields,
4140 UninitializedBaseClasses);
4141
4142 for (const auto *FieldInit : Constructor->inits()) {
4143 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4144 break;
4145
4146 Expr *InitExpr = FieldInit->getInit();
4147 if (!InitExpr)
4148 continue;
4149
4150 if (CXXDefaultInitExpr *Default =
4151 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4152 InitExpr = Default->getExpr();
4153 if (!InitExpr)
4154 continue;
4155 // In class initializers will point to the constructor.
4156 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4157 FieldInit->getAnyMember(),
4158 FieldInit->getBaseClass());
4159 } else {
4160 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4161 FieldInit->getAnyMember(),
4162 FieldInit->getBaseClass());
4163 }
4164 }
4165 }
4166 } // namespace
4167
4168 /// Enter a new C++ default initializer scope. After calling this, the
4169 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4170 /// parsing or instantiating the initializer failed.
ActOnStartCXXInClassMemberInitializer()4171 void Sema::ActOnStartCXXInClassMemberInitializer() {
4172 // Create a synthetic function scope to represent the call to the constructor
4173 // that notionally surrounds a use of this initializer.
4174 PushFunctionScope();
4175 }
4176
ActOnStartTrailingRequiresClause(Scope * S,Declarator & D)4177 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4178 if (!D.isFunctionDeclarator())
4179 return;
4180 auto &FTI = D.getFunctionTypeInfo();
4181 if (!FTI.Params)
4182 return;
4183 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4184 FTI.NumParams)) {
4185 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4186 if (ParamDecl->getDeclName())
4187 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4188 }
4189 }
4190
ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)4191 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4192 return ActOnRequiresClause(ConstraintExpr);
4193 }
4194
ActOnRequiresClause(ExprResult ConstraintExpr)4195 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4196 if (ConstraintExpr.isInvalid())
4197 return ExprError();
4198
4199 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4200 if (ConstraintExpr.isInvalid())
4201 return ExprError();
4202
4203 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4204 UPPC_RequiresClause))
4205 return ExprError();
4206
4207 return ConstraintExpr;
4208 }
4209
ConvertMemberDefaultInitExpression(FieldDecl * FD,Expr * InitExpr,SourceLocation InitLoc)4210 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4211 Expr *InitExpr,
4212 SourceLocation InitLoc) {
4213 InitializedEntity Entity =
4214 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4215 InitializationKind Kind =
4216 FD->getInClassInitStyle() == ICIS_ListInit
4217 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4218 InitExpr->getBeginLoc(),
4219 InitExpr->getEndLoc())
4220 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4221 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4222 return Seq.Perform(*this, Entity, Kind, InitExpr);
4223 }
4224
4225 /// This is invoked after parsing an in-class initializer for a
4226 /// non-static C++ class member, and after instantiating an in-class initializer
4227 /// in a class template. Such actions are deferred until the class is complete.
ActOnFinishCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,Expr * InitExpr)4228 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4229 SourceLocation InitLoc,
4230 Expr *InitExpr) {
4231 // Pop the notional constructor scope we created earlier.
4232 PopFunctionScopeInfo(nullptr, D);
4233
4234 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4235 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4236 "must set init style when field is created");
4237
4238 if (!InitExpr) {
4239 D->setInvalidDecl();
4240 if (FD)
4241 FD->removeInClassInitializer();
4242 return;
4243 }
4244
4245 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4246 FD->setInvalidDecl();
4247 FD->removeInClassInitializer();
4248 return;
4249 }
4250
4251 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4252 /*RecoverUncorrectedTypos=*/true);
4253 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4254 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4255 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4256 // C++11 [class.base.init]p7:
4257 // The initialization of each base and member constitutes a
4258 // full-expression.
4259 if (!Init.isInvalid())
4260 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4261 if (Init.isInvalid()) {
4262 FD->setInvalidDecl();
4263 return;
4264 }
4265 }
4266
4267 FD->setInClassInitializer(Init.get());
4268 }
4269
4270 /// Find the direct and/or virtual base specifiers that
4271 /// correspond to the given base type, for use in base initialization
4272 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)4273 static bool FindBaseInitializer(Sema &SemaRef,
4274 CXXRecordDecl *ClassDecl,
4275 QualType BaseType,
4276 const CXXBaseSpecifier *&DirectBaseSpec,
4277 const CXXBaseSpecifier *&VirtualBaseSpec) {
4278 // First, check for a direct base class.
4279 DirectBaseSpec = nullptr;
4280 for (const auto &Base : ClassDecl->bases()) {
4281 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4282 // We found a direct base of this type. That's what we're
4283 // initializing.
4284 DirectBaseSpec = &Base;
4285 break;
4286 }
4287 }
4288
4289 // Check for a virtual base class.
4290 // FIXME: We might be able to short-circuit this if we know in advance that
4291 // there are no virtual bases.
4292 VirtualBaseSpec = nullptr;
4293 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4294 // We haven't found a base yet; search the class hierarchy for a
4295 // virtual base class.
4296 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4297 /*DetectVirtual=*/false);
4298 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4299 SemaRef.Context.getTypeDeclType(ClassDecl),
4300 BaseType, Paths)) {
4301 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4302 Path != Paths.end(); ++Path) {
4303 if (Path->back().Base->isVirtual()) {
4304 VirtualBaseSpec = Path->back().Base;
4305 break;
4306 }
4307 }
4308 }
4309 }
4310
4311 return DirectBaseSpec || VirtualBaseSpec;
4312 }
4313
4314 /// Handle a C++ member initializer using braced-init-list syntax.
4315 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)4316 Sema::ActOnMemInitializer(Decl *ConstructorD,
4317 Scope *S,
4318 CXXScopeSpec &SS,
4319 IdentifierInfo *MemberOrBase,
4320 ParsedType TemplateTypeTy,
4321 const DeclSpec &DS,
4322 SourceLocation IdLoc,
4323 Expr *InitList,
4324 SourceLocation EllipsisLoc) {
4325 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4326 DS, IdLoc, InitList,
4327 EllipsisLoc);
4328 }
4329
4330 /// Handle a C++ member initializer using parentheses syntax.
4331 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)4332 Sema::ActOnMemInitializer(Decl *ConstructorD,
4333 Scope *S,
4334 CXXScopeSpec &SS,
4335 IdentifierInfo *MemberOrBase,
4336 ParsedType TemplateTypeTy,
4337 const DeclSpec &DS,
4338 SourceLocation IdLoc,
4339 SourceLocation LParenLoc,
4340 ArrayRef<Expr *> Args,
4341 SourceLocation RParenLoc,
4342 SourceLocation EllipsisLoc) {
4343 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4344 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4345 DS, IdLoc, List, EllipsisLoc);
4346 }
4347
4348 namespace {
4349
4350 // Callback to only accept typo corrections that can be a valid C++ member
4351 // initializer: either a non-static field member or a base class.
4352 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4353 public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)4354 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4355 : ClassDecl(ClassDecl) {}
4356
ValidateCandidate(const TypoCorrection & candidate)4357 bool ValidateCandidate(const TypoCorrection &candidate) override {
4358 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4359 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4360 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4361 return isa<TypeDecl>(ND);
4362 }
4363 return false;
4364 }
4365
clone()4366 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4367 return std::make_unique<MemInitializerValidatorCCC>(*this);
4368 }
4369
4370 private:
4371 CXXRecordDecl *ClassDecl;
4372 };
4373
4374 }
4375
DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,RecordDecl * ClassDecl,const IdentifierInfo * Name)4376 bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4377 RecordDecl *ClassDecl,
4378 const IdentifierInfo *Name) {
4379 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4380 DeclContextLookupResult::iterator Found =
4381 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4382 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4383 Elem->isPlaceholderVar(getLangOpts());
4384 });
4385 // We did not find a placeholder variable
4386 if (Found == Result.end())
4387 return false;
4388 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4389 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4390 const NamedDecl *ND = *It;
4391 if (ND->getDeclContext() != ND->getDeclContext())
4392 break;
4393 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4394 ND->isPlaceholderVar(getLangOpts()))
4395 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4396 }
4397 return true;
4398 }
4399
4400 ValueDecl *
tryLookupUnambiguousFieldDecl(RecordDecl * ClassDecl,const IdentifierInfo * MemberOrBase)4401 Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4402 const IdentifierInfo *MemberOrBase) {
4403 ValueDecl *ND = nullptr;
4404 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4405 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4406 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4407 if (ND) {
4408 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4409 return nullptr;
4410 break;
4411 }
4412 if (!IsPlaceholder)
4413 return cast<ValueDecl>(D);
4414 ND = cast<ValueDecl>(D);
4415 }
4416 }
4417 return ND;
4418 }
4419
tryLookupCtorInitMemberDecl(CXXRecordDecl * ClassDecl,CXXScopeSpec & SS,ParsedType TemplateTypeTy,IdentifierInfo * MemberOrBase)4420 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4421 CXXScopeSpec &SS,
4422 ParsedType TemplateTypeTy,
4423 IdentifierInfo *MemberOrBase) {
4424 if (SS.getScopeRep() || TemplateTypeTy)
4425 return nullptr;
4426 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4427 }
4428
4429 /// Handle a C++ member initializer.
4430 MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)4431 Sema::BuildMemInitializer(Decl *ConstructorD,
4432 Scope *S,
4433 CXXScopeSpec &SS,
4434 IdentifierInfo *MemberOrBase,
4435 ParsedType TemplateTypeTy,
4436 const DeclSpec &DS,
4437 SourceLocation IdLoc,
4438 Expr *Init,
4439 SourceLocation EllipsisLoc) {
4440 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4441 /*RecoverUncorrectedTypos=*/true);
4442 if (!Res.isUsable())
4443 return true;
4444 Init = Res.get();
4445
4446 if (!ConstructorD)
4447 return true;
4448
4449 AdjustDeclIfTemplate(ConstructorD);
4450
4451 CXXConstructorDecl *Constructor
4452 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4453 if (!Constructor) {
4454 // The user wrote a constructor initializer on a function that is
4455 // not a C++ constructor. Ignore the error for now, because we may
4456 // have more member initializers coming; we'll diagnose it just
4457 // once in ActOnMemInitializers.
4458 return true;
4459 }
4460
4461 CXXRecordDecl *ClassDecl = Constructor->getParent();
4462
4463 // C++ [class.base.init]p2:
4464 // Names in a mem-initializer-id are looked up in the scope of the
4465 // constructor's class and, if not found in that scope, are looked
4466 // up in the scope containing the constructor's definition.
4467 // [Note: if the constructor's class contains a member with the
4468 // same name as a direct or virtual base class of the class, a
4469 // mem-initializer-id naming the member or base class and composed
4470 // of a single identifier refers to the class member. A
4471 // mem-initializer-id for the hidden base class may be specified
4472 // using a qualified name. ]
4473
4474 // Look for a member, first.
4475 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4476 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4477 if (EllipsisLoc.isValid())
4478 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4479 << MemberOrBase
4480 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4481
4482 return BuildMemberInitializer(Member, Init, IdLoc);
4483 }
4484 // It didn't name a member, so see if it names a class.
4485 QualType BaseType;
4486 TypeSourceInfo *TInfo = nullptr;
4487
4488 if (TemplateTypeTy) {
4489 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4490 if (BaseType.isNull())
4491 return true;
4492 } else if (DS.getTypeSpecType() == TST_decltype) {
4493 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4494 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4495 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4496 return true;
4497 } else {
4498 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4499 LookupParsedName(R, S, &SS);
4500
4501 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4502 if (!TyD) {
4503 if (R.isAmbiguous()) return true;
4504
4505 // We don't want access-control diagnostics here.
4506 R.suppressDiagnostics();
4507
4508 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4509 bool NotUnknownSpecialization = false;
4510 DeclContext *DC = computeDeclContext(SS, false);
4511 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4512 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4513
4514 if (!NotUnknownSpecialization) {
4515 // When the scope specifier can refer to a member of an unknown
4516 // specialization, we take it as a type name.
4517 BaseType = CheckTypenameType(
4518 ElaboratedTypeKeyword::None, SourceLocation(),
4519 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4520 if (BaseType.isNull())
4521 return true;
4522
4523 TInfo = Context.CreateTypeSourceInfo(BaseType);
4524 DependentNameTypeLoc TL =
4525 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4526 if (!TL.isNull()) {
4527 TL.setNameLoc(IdLoc);
4528 TL.setElaboratedKeywordLoc(SourceLocation());
4529 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4530 }
4531
4532 R.clear();
4533 R.setLookupName(MemberOrBase);
4534 }
4535 }
4536
4537 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4538 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4539 auto *TempSpec = cast<TemplateSpecializationType>(
4540 UnqualifiedBase->getInjectedClassNameSpecialization());
4541 TemplateName TN = TempSpec->getTemplateName();
4542 for (auto const &Base : ClassDecl->bases()) {
4543 auto BaseTemplate =
4544 Base.getType()->getAs<TemplateSpecializationType>();
4545 if (BaseTemplate && Context.hasSameTemplateName(
4546 BaseTemplate->getTemplateName(), TN)) {
4547 Diag(IdLoc, diag::ext_unqualified_base_class)
4548 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4549 BaseType = Base.getType();
4550 break;
4551 }
4552 }
4553 }
4554 }
4555
4556 // If no results were found, try to correct typos.
4557 TypoCorrection Corr;
4558 MemInitializerValidatorCCC CCC(ClassDecl);
4559 if (R.empty() && BaseType.isNull() &&
4560 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4561 CCC, CTK_ErrorRecovery, ClassDecl))) {
4562 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4563 // We have found a non-static data member with a similar
4564 // name to what was typed; complain and initialize that
4565 // member.
4566 diagnoseTypo(Corr,
4567 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4568 << MemberOrBase << true);
4569 return BuildMemberInitializer(Member, Init, IdLoc);
4570 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4571 const CXXBaseSpecifier *DirectBaseSpec;
4572 const CXXBaseSpecifier *VirtualBaseSpec;
4573 if (FindBaseInitializer(*this, ClassDecl,
4574 Context.getTypeDeclType(Type),
4575 DirectBaseSpec, VirtualBaseSpec)) {
4576 // We have found a direct or virtual base class with a
4577 // similar name to what was typed; complain and initialize
4578 // that base class.
4579 diagnoseTypo(Corr,
4580 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4581 << MemberOrBase << false,
4582 PDiag() /*Suppress note, we provide our own.*/);
4583
4584 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4585 : VirtualBaseSpec;
4586 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4587 << BaseSpec->getType() << BaseSpec->getSourceRange();
4588
4589 TyD = Type;
4590 }
4591 }
4592 }
4593
4594 if (!TyD && BaseType.isNull()) {
4595 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4596 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4597 return true;
4598 }
4599 }
4600
4601 if (BaseType.isNull()) {
4602 BaseType = getElaboratedType(ElaboratedTypeKeyword::None, SS,
4603 Context.getTypeDeclType(TyD));
4604 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4605 TInfo = Context.CreateTypeSourceInfo(BaseType);
4606 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4607 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4608 TL.setElaboratedKeywordLoc(SourceLocation());
4609 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4610 }
4611 }
4612
4613 if (!TInfo)
4614 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4615
4616 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4617 }
4618
4619 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)4620 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4621 SourceLocation IdLoc) {
4622 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4623 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4624 assert((DirectMember || IndirectMember) &&
4625 "Member must be a FieldDecl or IndirectFieldDecl");
4626
4627 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4628 return true;
4629
4630 if (Member->isInvalidDecl())
4631 return true;
4632
4633 MultiExprArg Args;
4634 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4635 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4636 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4637 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4638 } else {
4639 // Template instantiation doesn't reconstruct ParenListExprs for us.
4640 Args = Init;
4641 }
4642
4643 SourceRange InitRange = Init->getSourceRange();
4644
4645 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4646 // Can't check initialization for a member of dependent type or when
4647 // any of the arguments are type-dependent expressions.
4648 DiscardCleanupsInEvaluationContext();
4649 } else {
4650 bool InitList = false;
4651 if (isa<InitListExpr>(Init)) {
4652 InitList = true;
4653 Args = Init;
4654 }
4655
4656 // Initialize the member.
4657 InitializedEntity MemberEntity =
4658 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4659 : InitializedEntity::InitializeMember(IndirectMember,
4660 nullptr);
4661 InitializationKind Kind =
4662 InitList ? InitializationKind::CreateDirectList(
4663 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4664 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4665 InitRange.getEnd());
4666
4667 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4668 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4669 nullptr);
4670 if (!MemberInit.isInvalid()) {
4671 // C++11 [class.base.init]p7:
4672 // The initialization of each base and member constitutes a
4673 // full-expression.
4674 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4675 /*DiscardedValue*/ false);
4676 }
4677
4678 if (MemberInit.isInvalid()) {
4679 // Args were sensible expressions but we couldn't initialize the member
4680 // from them. Preserve them in a RecoveryExpr instead.
4681 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4682 Member->getType())
4683 .get();
4684 if (!Init)
4685 return true;
4686 } else {
4687 Init = MemberInit.get();
4688 }
4689 }
4690
4691 if (DirectMember) {
4692 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4693 InitRange.getBegin(), Init,
4694 InitRange.getEnd());
4695 } else {
4696 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4697 InitRange.getBegin(), Init,
4698 InitRange.getEnd());
4699 }
4700 }
4701
4702 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)4703 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4704 CXXRecordDecl *ClassDecl) {
4705 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4706 if (!LangOpts.CPlusPlus11)
4707 return Diag(NameLoc, diag::err_delegating_ctor)
4708 << TInfo->getTypeLoc().getSourceRange();
4709 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4710
4711 bool InitList = true;
4712 MultiExprArg Args = Init;
4713 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4714 InitList = false;
4715 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4716 }
4717
4718 SourceRange InitRange = Init->getSourceRange();
4719 // Initialize the object.
4720 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4721 QualType(ClassDecl->getTypeForDecl(), 0));
4722 InitializationKind Kind =
4723 InitList ? InitializationKind::CreateDirectList(
4724 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4725 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4726 InitRange.getEnd());
4727 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4728 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4729 Args, nullptr);
4730 if (!DelegationInit.isInvalid()) {
4731 assert((DelegationInit.get()->containsErrors() ||
4732 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4733 "Delegating constructor with no target?");
4734
4735 // C++11 [class.base.init]p7:
4736 // The initialization of each base and member constitutes a
4737 // full-expression.
4738 DelegationInit = ActOnFinishFullExpr(
4739 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4740 }
4741
4742 if (DelegationInit.isInvalid()) {
4743 DelegationInit =
4744 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4745 QualType(ClassDecl->getTypeForDecl(), 0));
4746 if (DelegationInit.isInvalid())
4747 return true;
4748 } else {
4749 // If we are in a dependent context, template instantiation will
4750 // perform this type-checking again. Just save the arguments that we
4751 // received in a ParenListExpr.
4752 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4753 // of the information that we have about the base
4754 // initializer. However, deconstructing the ASTs is a dicey process,
4755 // and this approach is far more likely to get the corner cases right.
4756 if (CurContext->isDependentContext())
4757 DelegationInit = Init;
4758 }
4759
4760 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4761 DelegationInit.getAs<Expr>(),
4762 InitRange.getEnd());
4763 }
4764
4765 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)4766 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4767 Expr *Init, CXXRecordDecl *ClassDecl,
4768 SourceLocation EllipsisLoc) {
4769 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4770
4771 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4772 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4773 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4774
4775 // C++ [class.base.init]p2:
4776 // [...] Unless the mem-initializer-id names a nonstatic data
4777 // member of the constructor's class or a direct or virtual base
4778 // of that class, the mem-initializer is ill-formed. A
4779 // mem-initializer-list can initialize a base class using any
4780 // name that denotes that base class type.
4781
4782 // We can store the initializers in "as-written" form and delay analysis until
4783 // instantiation if the constructor is dependent. But not for dependent
4784 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4785 bool Dependent = CurContext->isDependentContext() &&
4786 (BaseType->isDependentType() || Init->isTypeDependent());
4787
4788 SourceRange InitRange = Init->getSourceRange();
4789 if (EllipsisLoc.isValid()) {
4790 // This is a pack expansion.
4791 if (!BaseType->containsUnexpandedParameterPack()) {
4792 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4793 << SourceRange(BaseLoc, InitRange.getEnd());
4794
4795 EllipsisLoc = SourceLocation();
4796 }
4797 } else {
4798 // Check for any unexpanded parameter packs.
4799 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4800 return true;
4801
4802 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4803 return true;
4804 }
4805
4806 // Check for direct and virtual base classes.
4807 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4808 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4809 if (!Dependent) {
4810 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4811 BaseType))
4812 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4813
4814 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4815 VirtualBaseSpec);
4816
4817 // C++ [base.class.init]p2:
4818 // Unless the mem-initializer-id names a nonstatic data member of the
4819 // constructor's class or a direct or virtual base of that class, the
4820 // mem-initializer is ill-formed.
4821 if (!DirectBaseSpec && !VirtualBaseSpec) {
4822 // If the class has any dependent bases, then it's possible that
4823 // one of those types will resolve to the same type as
4824 // BaseType. Therefore, just treat this as a dependent base
4825 // class initialization. FIXME: Should we try to check the
4826 // initialization anyway? It seems odd.
4827 if (ClassDecl->hasAnyDependentBases())
4828 Dependent = true;
4829 else
4830 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4831 << BaseType << Context.getTypeDeclType(ClassDecl)
4832 << BaseTInfo->getTypeLoc().getSourceRange();
4833 }
4834 }
4835
4836 if (Dependent) {
4837 DiscardCleanupsInEvaluationContext();
4838
4839 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4840 /*IsVirtual=*/false,
4841 InitRange.getBegin(), Init,
4842 InitRange.getEnd(), EllipsisLoc);
4843 }
4844
4845 // C++ [base.class.init]p2:
4846 // If a mem-initializer-id is ambiguous because it designates both
4847 // a direct non-virtual base class and an inherited virtual base
4848 // class, the mem-initializer is ill-formed.
4849 if (DirectBaseSpec && VirtualBaseSpec)
4850 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4851 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4852
4853 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4854 if (!BaseSpec)
4855 BaseSpec = VirtualBaseSpec;
4856
4857 // Initialize the base.
4858 bool InitList = true;
4859 MultiExprArg Args = Init;
4860 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4861 InitList = false;
4862 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4863 }
4864
4865 InitializedEntity BaseEntity =
4866 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4867 InitializationKind Kind =
4868 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4869 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4870 InitRange.getEnd());
4871 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4872 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4873 if (!BaseInit.isInvalid()) {
4874 // C++11 [class.base.init]p7:
4875 // The initialization of each base and member constitutes a
4876 // full-expression.
4877 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4878 /*DiscardedValue*/ false);
4879 }
4880
4881 if (BaseInit.isInvalid()) {
4882 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4883 Args, BaseType);
4884 if (BaseInit.isInvalid())
4885 return true;
4886 } else {
4887 // If we are in a dependent context, template instantiation will
4888 // perform this type-checking again. Just save the arguments that we
4889 // received in a ParenListExpr.
4890 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4891 // of the information that we have about the base
4892 // initializer. However, deconstructing the ASTs is a dicey process,
4893 // and this approach is far more likely to get the corner cases right.
4894 if (CurContext->isDependentContext())
4895 BaseInit = Init;
4896 }
4897
4898 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4899 BaseSpec->isVirtual(),
4900 InitRange.getBegin(),
4901 BaseInit.getAs<Expr>(),
4902 InitRange.getEnd(), EllipsisLoc);
4903 }
4904
4905 // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E)4906 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4907 QualType TargetType =
4908 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4909 SourceLocation(), DeclarationName());
4910 SourceLocation ExprLoc = E->getBeginLoc();
4911 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4912 TargetType, ExprLoc);
4913
4914 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4915 SourceRange(ExprLoc, ExprLoc),
4916 E->getSourceRange()).get();
4917 }
4918
4919 /// ImplicitInitializerKind - How an implicit base or member initializer should
4920 /// initialize its base or member.
4921 enum ImplicitInitializerKind {
4922 IIK_Default,
4923 IIK_Copy,
4924 IIK_Move,
4925 IIK_Inherit
4926 };
4927
4928 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)4929 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4930 ImplicitInitializerKind ImplicitInitKind,
4931 CXXBaseSpecifier *BaseSpec,
4932 bool IsInheritedVirtualBase,
4933 CXXCtorInitializer *&CXXBaseInit) {
4934 InitializedEntity InitEntity
4935 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4936 IsInheritedVirtualBase);
4937
4938 ExprResult BaseInit;
4939
4940 switch (ImplicitInitKind) {
4941 case IIK_Inherit:
4942 case IIK_Default: {
4943 InitializationKind InitKind
4944 = InitializationKind::CreateDefault(Constructor->getLocation());
4945 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4946 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4947 break;
4948 }
4949
4950 case IIK_Move:
4951 case IIK_Copy: {
4952 bool Moving = ImplicitInitKind == IIK_Move;
4953 ParmVarDecl *Param = Constructor->getParamDecl(0);
4954 QualType ParamType = Param->getType().getNonReferenceType();
4955
4956 Expr *CopyCtorArg =
4957 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4958 SourceLocation(), Param, false,
4959 Constructor->getLocation(), ParamType,
4960 VK_LValue, nullptr);
4961
4962 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4963
4964 // Cast to the base class to avoid ambiguities.
4965 QualType ArgTy =
4966 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4967 ParamType.getQualifiers());
4968
4969 if (Moving) {
4970 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4971 }
4972
4973 CXXCastPath BasePath;
4974 BasePath.push_back(BaseSpec);
4975 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4976 CK_UncheckedDerivedToBase,
4977 Moving ? VK_XValue : VK_LValue,
4978 &BasePath).get();
4979
4980 InitializationKind InitKind
4981 = InitializationKind::CreateDirect(Constructor->getLocation(),
4982 SourceLocation(), SourceLocation());
4983 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4984 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4985 break;
4986 }
4987 }
4988
4989 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4990 if (BaseInit.isInvalid())
4991 return true;
4992
4993 CXXBaseInit =
4994 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4995 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4996 SourceLocation()),
4997 BaseSpec->isVirtual(),
4998 SourceLocation(),
4999 BaseInit.getAs<Expr>(),
5000 SourceLocation(),
5001 SourceLocation());
5002
5003 return false;
5004 }
5005
RefersToRValueRef(Expr * MemRef)5006 static bool RefersToRValueRef(Expr *MemRef) {
5007 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5008 return Referenced->getType()->isRValueReferenceType();
5009 }
5010
5011 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)5012 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5013 ImplicitInitializerKind ImplicitInitKind,
5014 FieldDecl *Field, IndirectFieldDecl *Indirect,
5015 CXXCtorInitializer *&CXXMemberInit) {
5016 if (Field->isInvalidDecl())
5017 return true;
5018
5019 SourceLocation Loc = Constructor->getLocation();
5020
5021 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5022 bool Moving = ImplicitInitKind == IIK_Move;
5023 ParmVarDecl *Param = Constructor->getParamDecl(0);
5024 QualType ParamType = Param->getType().getNonReferenceType();
5025
5026 // Suppress copying zero-width bitfields.
5027 if (Field->isZeroLengthBitField(SemaRef.Context))
5028 return false;
5029
5030 Expr *MemberExprBase =
5031 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
5032 SourceLocation(), Param, false,
5033 Loc, ParamType, VK_LValue, nullptr);
5034
5035 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5036
5037 if (Moving) {
5038 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5039 }
5040
5041 // Build a reference to this field within the parameter.
5042 CXXScopeSpec SS;
5043 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5044 Sema::LookupMemberName);
5045 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5046 : cast<ValueDecl>(Field), AS_public);
5047 MemberLookup.resolveKind();
5048 ExprResult CtorArg
5049 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5050 ParamType, Loc,
5051 /*IsArrow=*/false,
5052 SS,
5053 /*TemplateKWLoc=*/SourceLocation(),
5054 /*FirstQualifierInScope=*/nullptr,
5055 MemberLookup,
5056 /*TemplateArgs=*/nullptr,
5057 /*S*/nullptr);
5058 if (CtorArg.isInvalid())
5059 return true;
5060
5061 // C++11 [class.copy]p15:
5062 // - if a member m has rvalue reference type T&&, it is direct-initialized
5063 // with static_cast<T&&>(x.m);
5064 if (RefersToRValueRef(CtorArg.get())) {
5065 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5066 }
5067
5068 InitializedEntity Entity =
5069 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5070 /*Implicit*/ true)
5071 : InitializedEntity::InitializeMember(Field, nullptr,
5072 /*Implicit*/ true);
5073
5074 // Direct-initialize to use the copy constructor.
5075 InitializationKind InitKind =
5076 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
5077
5078 Expr *CtorArgE = CtorArg.getAs<Expr>();
5079 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5080 ExprResult MemberInit =
5081 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5082 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5083 if (MemberInit.isInvalid())
5084 return true;
5085
5086 if (Indirect)
5087 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5088 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5089 else
5090 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5091 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5092 return false;
5093 }
5094
5095 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5096 "Unhandled implicit init kind!");
5097
5098 QualType FieldBaseElementType =
5099 SemaRef.Context.getBaseElementType(Field->getType());
5100
5101 if (FieldBaseElementType->isRecordType()) {
5102 InitializedEntity InitEntity =
5103 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5104 /*Implicit*/ true)
5105 : InitializedEntity::InitializeMember(Field, nullptr,
5106 /*Implicit*/ true);
5107 InitializationKind InitKind =
5108 InitializationKind::CreateDefault(Loc);
5109
5110 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5111 ExprResult MemberInit =
5112 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5113
5114 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5115 if (MemberInit.isInvalid())
5116 return true;
5117
5118 if (Indirect)
5119 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5120 Indirect, Loc,
5121 Loc,
5122 MemberInit.get(),
5123 Loc);
5124 else
5125 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5126 Field, Loc, Loc,
5127 MemberInit.get(),
5128 Loc);
5129 return false;
5130 }
5131
5132 if (!Field->getParent()->isUnion()) {
5133 if (FieldBaseElementType->isReferenceType()) {
5134 SemaRef.Diag(Constructor->getLocation(),
5135 diag::err_uninitialized_member_in_ctor)
5136 << (int)Constructor->isImplicit()
5137 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5138 << 0 << Field->getDeclName();
5139 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5140 return true;
5141 }
5142
5143 if (FieldBaseElementType.isConstQualified()) {
5144 SemaRef.Diag(Constructor->getLocation(),
5145 diag::err_uninitialized_member_in_ctor)
5146 << (int)Constructor->isImplicit()
5147 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5148 << 1 << Field->getDeclName();
5149 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5150 return true;
5151 }
5152 }
5153
5154 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5155 // ARC and Weak:
5156 // Default-initialize Objective-C pointers to NULL.
5157 CXXMemberInit
5158 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5159 Loc, Loc,
5160 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5161 Loc);
5162 return false;
5163 }
5164
5165 // Nothing to initialize.
5166 CXXMemberInit = nullptr;
5167 return false;
5168 }
5169
5170 namespace {
5171 struct BaseAndFieldInfo {
5172 Sema &S;
5173 CXXConstructorDecl *Ctor;
5174 bool AnyErrorsInInits;
5175 ImplicitInitializerKind IIK;
5176 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5177 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5178 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5179
BaseAndFieldInfo__anon067e66481211::BaseAndFieldInfo5180 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5181 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5182 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5183 if (Ctor->getInheritedConstructor())
5184 IIK = IIK_Inherit;
5185 else if (Generated && Ctor->isCopyConstructor())
5186 IIK = IIK_Copy;
5187 else if (Generated && Ctor->isMoveConstructor())
5188 IIK = IIK_Move;
5189 else
5190 IIK = IIK_Default;
5191 }
5192
isImplicitCopyOrMove__anon067e66481211::BaseAndFieldInfo5193 bool isImplicitCopyOrMove() const {
5194 switch (IIK) {
5195 case IIK_Copy:
5196 case IIK_Move:
5197 return true;
5198
5199 case IIK_Default:
5200 case IIK_Inherit:
5201 return false;
5202 }
5203
5204 llvm_unreachable("Invalid ImplicitInitializerKind!");
5205 }
5206
addFieldInitializer__anon067e66481211::BaseAndFieldInfo5207 bool addFieldInitializer(CXXCtorInitializer *Init) {
5208 AllToInit.push_back(Init);
5209
5210 // Check whether this initializer makes the field "used".
5211 if (Init->getInit()->HasSideEffects(S.Context))
5212 S.UnusedPrivateFields.remove(Init->getAnyMember());
5213
5214 return false;
5215 }
5216
isInactiveUnionMember__anon067e66481211::BaseAndFieldInfo5217 bool isInactiveUnionMember(FieldDecl *Field) {
5218 RecordDecl *Record = Field->getParent();
5219 if (!Record->isUnion())
5220 return false;
5221
5222 if (FieldDecl *Active =
5223 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5224 return Active != Field->getCanonicalDecl();
5225
5226 // In an implicit copy or move constructor, ignore any in-class initializer.
5227 if (isImplicitCopyOrMove())
5228 return true;
5229
5230 // If there's no explicit initialization, the field is active only if it
5231 // has an in-class initializer...
5232 if (Field->hasInClassInitializer())
5233 return false;
5234 // ... or it's an anonymous struct or union whose class has an in-class
5235 // initializer.
5236 if (!Field->isAnonymousStructOrUnion())
5237 return true;
5238 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5239 return !FieldRD->hasInClassInitializer();
5240 }
5241
5242 /// Determine whether the given field is, or is within, a union member
5243 /// that is inactive (because there was an initializer given for a different
5244 /// member of the union, or because the union was not initialized at all).
isWithinInactiveUnionMember__anon067e66481211::BaseAndFieldInfo5245 bool isWithinInactiveUnionMember(FieldDecl *Field,
5246 IndirectFieldDecl *Indirect) {
5247 if (!Indirect)
5248 return isInactiveUnionMember(Field);
5249
5250 for (auto *C : Indirect->chain()) {
5251 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5252 if (Field && isInactiveUnionMember(Field))
5253 return true;
5254 }
5255 return false;
5256 }
5257 };
5258 }
5259
5260 /// Determine whether the given type is an incomplete or zero-lenfgth
5261 /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)5262 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5263 if (T->isIncompleteArrayType())
5264 return true;
5265
5266 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5267 if (!ArrayT->getSize())
5268 return true;
5269
5270 T = ArrayT->getElementType();
5271 }
5272
5273 return false;
5274 }
5275
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=nullptr)5276 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5277 FieldDecl *Field,
5278 IndirectFieldDecl *Indirect = nullptr) {
5279 if (Field->isInvalidDecl())
5280 return false;
5281
5282 // Overwhelmingly common case: we have a direct initializer for this field.
5283 if (CXXCtorInitializer *Init =
5284 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5285 return Info.addFieldInitializer(Init);
5286
5287 // C++11 [class.base.init]p8:
5288 // if the entity is a non-static data member that has a
5289 // brace-or-equal-initializer and either
5290 // -- the constructor's class is a union and no other variant member of that
5291 // union is designated by a mem-initializer-id or
5292 // -- the constructor's class is not a union, and, if the entity is a member
5293 // of an anonymous union, no other member of that union is designated by
5294 // a mem-initializer-id,
5295 // the entity is initialized as specified in [dcl.init].
5296 //
5297 // We also apply the same rules to handle anonymous structs within anonymous
5298 // unions.
5299 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5300 return false;
5301
5302 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5303 ExprResult DIE =
5304 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5305 if (DIE.isInvalid())
5306 return true;
5307
5308 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5309 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5310
5311 CXXCtorInitializer *Init;
5312 if (Indirect)
5313 Init = new (SemaRef.Context)
5314 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5315 SourceLocation(), DIE.get(), SourceLocation());
5316 else
5317 Init = new (SemaRef.Context)
5318 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5319 SourceLocation(), DIE.get(), SourceLocation());
5320 return Info.addFieldInitializer(Init);
5321 }
5322
5323 // Don't initialize incomplete or zero-length arrays.
5324 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5325 return false;
5326
5327 // Don't try to build an implicit initializer if there were semantic
5328 // errors in any of the initializers (and therefore we might be
5329 // missing some that the user actually wrote).
5330 if (Info.AnyErrorsInInits)
5331 return false;
5332
5333 CXXCtorInitializer *Init = nullptr;
5334 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5335 Indirect, Init))
5336 return true;
5337
5338 if (!Init)
5339 return false;
5340
5341 return Info.addFieldInitializer(Init);
5342 }
5343
5344 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)5345 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5346 CXXCtorInitializer *Initializer) {
5347 assert(Initializer->isDelegatingInitializer());
5348 Constructor->setNumCtorInitializers(1);
5349 CXXCtorInitializer **initializer =
5350 new (Context) CXXCtorInitializer*[1];
5351 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5352 Constructor->setCtorInitializers(initializer);
5353
5354 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5355 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5356 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5357 }
5358
5359 DelegatingCtorDecls.push_back(Constructor);
5360
5361 DiagnoseUninitializedFields(*this, Constructor);
5362
5363 return false;
5364 }
5365
SetCtorInitializers(CXXConstructorDecl * Constructor,bool AnyErrors,ArrayRef<CXXCtorInitializer * > Initializers)5366 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5367 ArrayRef<CXXCtorInitializer *> Initializers) {
5368 if (Constructor->isDependentContext()) {
5369 // Just store the initializers as written, they will be checked during
5370 // instantiation.
5371 if (!Initializers.empty()) {
5372 Constructor->setNumCtorInitializers(Initializers.size());
5373 CXXCtorInitializer **baseOrMemberInitializers =
5374 new (Context) CXXCtorInitializer*[Initializers.size()];
5375 memcpy(baseOrMemberInitializers, Initializers.data(),
5376 Initializers.size() * sizeof(CXXCtorInitializer*));
5377 Constructor->setCtorInitializers(baseOrMemberInitializers);
5378 }
5379
5380 // Let template instantiation know whether we had errors.
5381 if (AnyErrors)
5382 Constructor->setInvalidDecl();
5383
5384 return false;
5385 }
5386
5387 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5388
5389 // We need to build the initializer AST according to order of construction
5390 // and not what user specified in the Initializers list.
5391 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5392 if (!ClassDecl)
5393 return true;
5394
5395 bool HadError = false;
5396
5397 for (unsigned i = 0; i < Initializers.size(); i++) {
5398 CXXCtorInitializer *Member = Initializers[i];
5399
5400 if (Member->isBaseInitializer())
5401 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5402 else {
5403 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5404
5405 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5406 for (auto *C : F->chain()) {
5407 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5408 if (FD && FD->getParent()->isUnion())
5409 Info.ActiveUnionMember.insert(std::make_pair(
5410 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5411 }
5412 } else if (FieldDecl *FD = Member->getMember()) {
5413 if (FD->getParent()->isUnion())
5414 Info.ActiveUnionMember.insert(std::make_pair(
5415 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5416 }
5417 }
5418 }
5419
5420 // Keep track of the direct virtual bases.
5421 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5422 for (auto &I : ClassDecl->bases()) {
5423 if (I.isVirtual())
5424 DirectVBases.insert(&I);
5425 }
5426
5427 // Push virtual bases before others.
5428 for (auto &VBase : ClassDecl->vbases()) {
5429 if (CXXCtorInitializer *Value
5430 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5431 // [class.base.init]p7, per DR257:
5432 // A mem-initializer where the mem-initializer-id names a virtual base
5433 // class is ignored during execution of a constructor of any class that
5434 // is not the most derived class.
5435 if (ClassDecl->isAbstract()) {
5436 // FIXME: Provide a fixit to remove the base specifier. This requires
5437 // tracking the location of the associated comma for a base specifier.
5438 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5439 << VBase.getType() << ClassDecl;
5440 DiagnoseAbstractType(ClassDecl);
5441 }
5442
5443 Info.AllToInit.push_back(Value);
5444 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5445 // [class.base.init]p8, per DR257:
5446 // If a given [...] base class is not named by a mem-initializer-id
5447 // [...] and the entity is not a virtual base class of an abstract
5448 // class, then [...] the entity is default-initialized.
5449 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5450 CXXCtorInitializer *CXXBaseInit;
5451 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5452 &VBase, IsInheritedVirtualBase,
5453 CXXBaseInit)) {
5454 HadError = true;
5455 continue;
5456 }
5457
5458 Info.AllToInit.push_back(CXXBaseInit);
5459 }
5460 }
5461
5462 // Non-virtual bases.
5463 for (auto &Base : ClassDecl->bases()) {
5464 // Virtuals are in the virtual base list and already constructed.
5465 if (Base.isVirtual())
5466 continue;
5467
5468 if (CXXCtorInitializer *Value
5469 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5470 Info.AllToInit.push_back(Value);
5471 } else if (!AnyErrors) {
5472 CXXCtorInitializer *CXXBaseInit;
5473 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5474 &Base, /*IsInheritedVirtualBase=*/false,
5475 CXXBaseInit)) {
5476 HadError = true;
5477 continue;
5478 }
5479
5480 Info.AllToInit.push_back(CXXBaseInit);
5481 }
5482 }
5483
5484 // Fields.
5485 for (auto *Mem : ClassDecl->decls()) {
5486 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5487 // C++ [class.bit]p2:
5488 // A declaration for a bit-field that omits the identifier declares an
5489 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5490 // initialized.
5491 if (F->isUnnamedBitfield())
5492 continue;
5493
5494 // If we're not generating the implicit copy/move constructor, then we'll
5495 // handle anonymous struct/union fields based on their individual
5496 // indirect fields.
5497 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5498 continue;
5499
5500 if (CollectFieldInitializer(*this, Info, F))
5501 HadError = true;
5502 continue;
5503 }
5504
5505 // Beyond this point, we only consider default initialization.
5506 if (Info.isImplicitCopyOrMove())
5507 continue;
5508
5509 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5510 if (F->getType()->isIncompleteArrayType()) {
5511 assert(ClassDecl->hasFlexibleArrayMember() &&
5512 "Incomplete array type is not valid");
5513 continue;
5514 }
5515
5516 // Initialize each field of an anonymous struct individually.
5517 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5518 HadError = true;
5519
5520 continue;
5521 }
5522 }
5523
5524 unsigned NumInitializers = Info.AllToInit.size();
5525 if (NumInitializers > 0) {
5526 Constructor->setNumCtorInitializers(NumInitializers);
5527 CXXCtorInitializer **baseOrMemberInitializers =
5528 new (Context) CXXCtorInitializer*[NumInitializers];
5529 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5530 NumInitializers * sizeof(CXXCtorInitializer*));
5531 Constructor->setCtorInitializers(baseOrMemberInitializers);
5532
5533 // Constructors implicitly reference the base and member
5534 // destructors.
5535 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5536 Constructor->getParent());
5537 }
5538
5539 return HadError;
5540 }
5541
PopulateKeysForFields(FieldDecl * Field,SmallVectorImpl<const void * > & IdealInits)5542 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5543 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5544 const RecordDecl *RD = RT->getDecl();
5545 if (RD->isAnonymousStructOrUnion()) {
5546 for (auto *Field : RD->fields())
5547 PopulateKeysForFields(Field, IdealInits);
5548 return;
5549 }
5550 }
5551 IdealInits.push_back(Field->getCanonicalDecl());
5552 }
5553
GetKeyForBase(ASTContext & Context,QualType BaseType)5554 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5555 return Context.getCanonicalType(BaseType).getTypePtr();
5556 }
5557
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)5558 static const void *GetKeyForMember(ASTContext &Context,
5559 CXXCtorInitializer *Member) {
5560 if (!Member->isAnyMemberInitializer())
5561 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5562
5563 return Member->getAnyMember()->getCanonicalDecl();
5564 }
5565
AddInitializerToDiag(const Sema::SemaDiagnosticBuilder & Diag,const CXXCtorInitializer * Previous,const CXXCtorInitializer * Current)5566 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5567 const CXXCtorInitializer *Previous,
5568 const CXXCtorInitializer *Current) {
5569 if (Previous->isAnyMemberInitializer())
5570 Diag << 0 << Previous->getAnyMember();
5571 else
5572 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5573
5574 if (Current->isAnyMemberInitializer())
5575 Diag << 0 << Current->getAnyMember();
5576 else
5577 Diag << 1 << Current->getTypeSourceInfo()->getType();
5578 }
5579
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,ArrayRef<CXXCtorInitializer * > Inits)5580 static void DiagnoseBaseOrMemInitializerOrder(
5581 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5582 ArrayRef<CXXCtorInitializer *> Inits) {
5583 if (Constructor->getDeclContext()->isDependentContext())
5584 return;
5585
5586 // Don't check initializers order unless the warning is enabled at the
5587 // location of at least one initializer.
5588 bool ShouldCheckOrder = false;
5589 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5590 CXXCtorInitializer *Init = Inits[InitIndex];
5591 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5592 Init->getSourceLocation())) {
5593 ShouldCheckOrder = true;
5594 break;
5595 }
5596 }
5597 if (!ShouldCheckOrder)
5598 return;
5599
5600 // Build the list of bases and members in the order that they'll
5601 // actually be initialized. The explicit initializers should be in
5602 // this same order but may be missing things.
5603 SmallVector<const void*, 32> IdealInitKeys;
5604
5605 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5606
5607 // 1. Virtual bases.
5608 for (const auto &VBase : ClassDecl->vbases())
5609 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5610
5611 // 2. Non-virtual bases.
5612 for (const auto &Base : ClassDecl->bases()) {
5613 if (Base.isVirtual())
5614 continue;
5615 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5616 }
5617
5618 // 3. Direct fields.
5619 for (auto *Field : ClassDecl->fields()) {
5620 if (Field->isUnnamedBitfield())
5621 continue;
5622
5623 PopulateKeysForFields(Field, IdealInitKeys);
5624 }
5625
5626 unsigned NumIdealInits = IdealInitKeys.size();
5627 unsigned IdealIndex = 0;
5628
5629 // Track initializers that are in an incorrect order for either a warning or
5630 // note if multiple ones occur.
5631 SmallVector<unsigned> WarnIndexes;
5632 // Correlates the index of an initializer in the init-list to the index of
5633 // the field/base in the class.
5634 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5635
5636 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5637 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5638
5639 // Scan forward to try to find this initializer in the idealized
5640 // initializers list.
5641 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5642 if (InitKey == IdealInitKeys[IdealIndex])
5643 break;
5644
5645 // If we didn't find this initializer, it must be because we
5646 // scanned past it on a previous iteration. That can only
5647 // happen if we're out of order; emit a warning.
5648 if (IdealIndex == NumIdealInits && InitIndex) {
5649 WarnIndexes.push_back(InitIndex);
5650
5651 // Move back to the initializer's location in the ideal list.
5652 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5653 if (InitKey == IdealInitKeys[IdealIndex])
5654 break;
5655
5656 assert(IdealIndex < NumIdealInits &&
5657 "initializer not found in initializer list");
5658 }
5659 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5660 }
5661
5662 if (WarnIndexes.empty())
5663 return;
5664
5665 // Sort based on the ideal order, first in the pair.
5666 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5667
5668 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5669 // emit the diagnostic before we can try adding notes.
5670 {
5671 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5672 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5673 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5674 : diag::warn_some_initializers_out_of_order);
5675
5676 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5677 if (CorrelatedInitOrder[I].second == I)
5678 continue;
5679 // Ideally we would be using InsertFromRange here, but clang doesn't
5680 // appear to handle InsertFromRange correctly when the source range is
5681 // modified by another fix-it.
5682 D << FixItHint::CreateReplacement(
5683 Inits[I]->getSourceRange(),
5684 Lexer::getSourceText(
5685 CharSourceRange::getTokenRange(
5686 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5687 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5688 }
5689
5690 // If there is only 1 item out of order, the warning expects the name and
5691 // type of each being added to it.
5692 if (WarnIndexes.size() == 1) {
5693 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5694 Inits[WarnIndexes.front()]);
5695 return;
5696 }
5697 }
5698 // More than 1 item to warn, create notes letting the user know which ones
5699 // are bad.
5700 for (unsigned WarnIndex : WarnIndexes) {
5701 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5702 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5703 diag::note_initializer_out_of_order);
5704 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5705 D << PrevInit->getSourceRange();
5706 }
5707 }
5708
5709 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)5710 bool CheckRedundantInit(Sema &S,
5711 CXXCtorInitializer *Init,
5712 CXXCtorInitializer *&PrevInit) {
5713 if (!PrevInit) {
5714 PrevInit = Init;
5715 return false;
5716 }
5717
5718 if (FieldDecl *Field = Init->getAnyMember())
5719 S.Diag(Init->getSourceLocation(),
5720 diag::err_multiple_mem_initialization)
5721 << Field->getDeclName()
5722 << Init->getSourceRange();
5723 else {
5724 const Type *BaseClass = Init->getBaseClass();
5725 assert(BaseClass && "neither field nor base");
5726 S.Diag(Init->getSourceLocation(),
5727 diag::err_multiple_base_initialization)
5728 << QualType(BaseClass, 0)
5729 << Init->getSourceRange();
5730 }
5731 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5732 << 0 << PrevInit->getSourceRange();
5733
5734 return true;
5735 }
5736
5737 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5738 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5739
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)5740 bool CheckRedundantUnionInit(Sema &S,
5741 CXXCtorInitializer *Init,
5742 RedundantUnionMap &Unions) {
5743 FieldDecl *Field = Init->getAnyMember();
5744 RecordDecl *Parent = Field->getParent();
5745 NamedDecl *Child = Field;
5746
5747 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5748 if (Parent->isUnion()) {
5749 UnionEntry &En = Unions[Parent];
5750 if (En.first && En.first != Child) {
5751 S.Diag(Init->getSourceLocation(),
5752 diag::err_multiple_mem_union_initialization)
5753 << Field->getDeclName()
5754 << Init->getSourceRange();
5755 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5756 << 0 << En.second->getSourceRange();
5757 return true;
5758 }
5759 if (!En.first) {
5760 En.first = Child;
5761 En.second = Init;
5762 }
5763 if (!Parent->isAnonymousStructOrUnion())
5764 return false;
5765 }
5766
5767 Child = Parent;
5768 Parent = cast<RecordDecl>(Parent->getDeclContext());
5769 }
5770
5771 return false;
5772 }
5773 } // namespace
5774
5775 /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,ArrayRef<CXXCtorInitializer * > MemInits,bool AnyErrors)5776 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5777 SourceLocation ColonLoc,
5778 ArrayRef<CXXCtorInitializer*> MemInits,
5779 bool AnyErrors) {
5780 if (!ConstructorDecl)
5781 return;
5782
5783 AdjustDeclIfTemplate(ConstructorDecl);
5784
5785 CXXConstructorDecl *Constructor
5786 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5787
5788 if (!Constructor) {
5789 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5790 return;
5791 }
5792
5793 // Mapping for the duplicate initializers check.
5794 // For member initializers, this is keyed with a FieldDecl*.
5795 // For base initializers, this is keyed with a Type*.
5796 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5797
5798 // Mapping for the inconsistent anonymous-union initializers check.
5799 RedundantUnionMap MemberUnions;
5800
5801 bool HadError = false;
5802 for (unsigned i = 0; i < MemInits.size(); i++) {
5803 CXXCtorInitializer *Init = MemInits[i];
5804
5805 // Set the source order index.
5806 Init->setSourceOrder(i);
5807
5808 if (Init->isAnyMemberInitializer()) {
5809 const void *Key = GetKeyForMember(Context, Init);
5810 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5811 CheckRedundantUnionInit(*this, Init, MemberUnions))
5812 HadError = true;
5813 } else if (Init->isBaseInitializer()) {
5814 const void *Key = GetKeyForMember(Context, Init);
5815 if (CheckRedundantInit(*this, Init, Members[Key]))
5816 HadError = true;
5817 } else {
5818 assert(Init->isDelegatingInitializer());
5819 // This must be the only initializer
5820 if (MemInits.size() != 1) {
5821 Diag(Init->getSourceLocation(),
5822 diag::err_delegating_initializer_alone)
5823 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5824 // We will treat this as being the only initializer.
5825 }
5826 SetDelegatingInitializer(Constructor, MemInits[i]);
5827 // Return immediately as the initializer is set.
5828 return;
5829 }
5830 }
5831
5832 if (HadError)
5833 return;
5834
5835 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5836
5837 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5838
5839 DiagnoseUninitializedFields(*this, Constructor);
5840 }
5841
5842 void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)5843 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5844 CXXRecordDecl *ClassDecl) {
5845 // Ignore dependent contexts. Also ignore unions, since their members never
5846 // have destructors implicitly called.
5847 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5848 return;
5849
5850 // FIXME: all the access-control diagnostics are positioned on the
5851 // field/base declaration. That's probably good; that said, the
5852 // user might reasonably want to know why the destructor is being
5853 // emitted, and we currently don't say.
5854
5855 // Non-static data members.
5856 for (auto *Field : ClassDecl->fields()) {
5857 if (Field->isInvalidDecl())
5858 continue;
5859
5860 // Don't destroy incomplete or zero-length arrays.
5861 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5862 continue;
5863
5864 QualType FieldType = Context.getBaseElementType(Field->getType());
5865
5866 const RecordType* RT = FieldType->getAs<RecordType>();
5867 if (!RT)
5868 continue;
5869
5870 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5871 if (FieldClassDecl->isInvalidDecl())
5872 continue;
5873 if (FieldClassDecl->hasIrrelevantDestructor())
5874 continue;
5875 // The destructor for an implicit anonymous union member is never invoked.
5876 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5877 continue;
5878
5879 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5880 // Dtor might still be missing, e.g because it's invalid.
5881 if (!Dtor)
5882 continue;
5883 CheckDestructorAccess(Field->getLocation(), Dtor,
5884 PDiag(diag::err_access_dtor_field)
5885 << Field->getDeclName()
5886 << FieldType);
5887
5888 MarkFunctionReferenced(Location, Dtor);
5889 DiagnoseUseOfDecl(Dtor, Location);
5890 }
5891
5892 // We only potentially invoke the destructors of potentially constructed
5893 // subobjects.
5894 bool VisitVirtualBases = !ClassDecl->isAbstract();
5895
5896 // If the destructor exists and has already been marked used in the MS ABI,
5897 // then virtual base destructors have already been checked and marked used.
5898 // Skip checking them again to avoid duplicate diagnostics.
5899 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5900 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5901 if (Dtor && Dtor->isUsed())
5902 VisitVirtualBases = false;
5903 }
5904
5905 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5906
5907 // Bases.
5908 for (const auto &Base : ClassDecl->bases()) {
5909 const RecordType *RT = Base.getType()->getAs<RecordType>();
5910 if (!RT)
5911 continue;
5912
5913 // Remember direct virtual bases.
5914 if (Base.isVirtual()) {
5915 if (!VisitVirtualBases)
5916 continue;
5917 DirectVirtualBases.insert(RT);
5918 }
5919
5920 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5921 // If our base class is invalid, we probably can't get its dtor anyway.
5922 if (BaseClassDecl->isInvalidDecl())
5923 continue;
5924 if (BaseClassDecl->hasIrrelevantDestructor())
5925 continue;
5926
5927 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5928 // Dtor might still be missing, e.g because it's invalid.
5929 if (!Dtor)
5930 continue;
5931
5932 // FIXME: caret should be on the start of the class name
5933 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5934 PDiag(diag::err_access_dtor_base)
5935 << Base.getType() << Base.getSourceRange(),
5936 Context.getTypeDeclType(ClassDecl));
5937
5938 MarkFunctionReferenced(Location, Dtor);
5939 DiagnoseUseOfDecl(Dtor, Location);
5940 }
5941
5942 if (VisitVirtualBases)
5943 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5944 &DirectVirtualBases);
5945 }
5946
MarkVirtualBaseDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl,llvm::SmallPtrSetImpl<const RecordType * > * DirectVirtualBases)5947 void Sema::MarkVirtualBaseDestructorsReferenced(
5948 SourceLocation Location, CXXRecordDecl *ClassDecl,
5949 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5950 // Virtual bases.
5951 for (const auto &VBase : ClassDecl->vbases()) {
5952 // Bases are always records in a well-formed non-dependent class.
5953 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5954
5955 // Ignore already visited direct virtual bases.
5956 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5957 continue;
5958
5959 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5960 // If our base class is invalid, we probably can't get its dtor anyway.
5961 if (BaseClassDecl->isInvalidDecl())
5962 continue;
5963 if (BaseClassDecl->hasIrrelevantDestructor())
5964 continue;
5965
5966 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5967 // Dtor might still be missing, e.g because it's invalid.
5968 if (!Dtor)
5969 continue;
5970 if (CheckDestructorAccess(
5971 ClassDecl->getLocation(), Dtor,
5972 PDiag(diag::err_access_dtor_vbase)
5973 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5974 Context.getTypeDeclType(ClassDecl)) ==
5975 AR_accessible) {
5976 CheckDerivedToBaseConversion(
5977 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5978 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5979 SourceRange(), DeclarationName(), nullptr);
5980 }
5981
5982 MarkFunctionReferenced(Location, Dtor);
5983 DiagnoseUseOfDecl(Dtor, Location);
5984 }
5985 }
5986
ActOnDefaultCtorInitializers(Decl * CDtorDecl)5987 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5988 if (!CDtorDecl)
5989 return;
5990
5991 if (CXXConstructorDecl *Constructor
5992 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5993 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5994 DiagnoseUninitializedFields(*this, Constructor);
5995 }
5996 }
5997
isAbstractType(SourceLocation Loc,QualType T)5998 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5999 if (!getLangOpts().CPlusPlus)
6000 return false;
6001
6002 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6003 if (!RD)
6004 return false;
6005
6006 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6007 // class template specialization here, but doing so breaks a lot of code.
6008
6009 // We can't answer whether something is abstract until it has a
6010 // definition. If it's currently being defined, we'll walk back
6011 // over all the declarations when we have a full definition.
6012 const CXXRecordDecl *Def = RD->getDefinition();
6013 if (!Def || Def->isBeingDefined())
6014 return false;
6015
6016 return RD->isAbstract();
6017 }
6018
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)6019 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6020 TypeDiagnoser &Diagnoser) {
6021 if (!isAbstractType(Loc, T))
6022 return false;
6023
6024 T = Context.getBaseElementType(T);
6025 Diagnoser.diagnose(*this, Loc, T);
6026 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6027 return true;
6028 }
6029
DiagnoseAbstractType(const CXXRecordDecl * RD)6030 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6031 // Check if we've already emitted the list of pure virtual functions
6032 // for this class.
6033 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
6034 return;
6035
6036 // If the diagnostic is suppressed, don't emit the notes. We're only
6037 // going to emit them once, so try to attach them to a diagnostic we're
6038 // actually going to show.
6039 if (Diags.isLastDiagnosticIgnored())
6040 return;
6041
6042 CXXFinalOverriderMap FinalOverriders;
6043 RD->getFinalOverriders(FinalOverriders);
6044
6045 // Keep a set of seen pure methods so we won't diagnose the same method
6046 // more than once.
6047 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6048
6049 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6050 MEnd = FinalOverriders.end();
6051 M != MEnd;
6052 ++M) {
6053 for (OverridingMethods::iterator SO = M->second.begin(),
6054 SOEnd = M->second.end();
6055 SO != SOEnd; ++SO) {
6056 // C++ [class.abstract]p4:
6057 // A class is abstract if it contains or inherits at least one
6058 // pure virtual function for which the final overrider is pure
6059 // virtual.
6060
6061 //
6062 if (SO->second.size() != 1)
6063 continue;
6064
6065 if (!SO->second.front().Method->isPureVirtual())
6066 continue;
6067
6068 if (!SeenPureMethods.insert(SO->second.front().Method).second)
6069 continue;
6070
6071 Diag(SO->second.front().Method->getLocation(),
6072 diag::note_pure_virtual_function)
6073 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6074 }
6075 }
6076
6077 if (!PureVirtualClassDiagSet)
6078 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
6079 PureVirtualClassDiagSet->insert(RD);
6080 }
6081
6082 namespace {
6083 struct AbstractUsageInfo {
6084 Sema &S;
6085 CXXRecordDecl *Record;
6086 CanQualType AbstractType;
6087 bool Invalid;
6088
AbstractUsageInfo__anon067e66481411::AbstractUsageInfo6089 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6090 : S(S), Record(Record),
6091 AbstractType(S.Context.getCanonicalType(
6092 S.Context.getTypeDeclType(Record))),
6093 Invalid(false) {}
6094
DiagnoseAbstractType__anon067e66481411::AbstractUsageInfo6095 void DiagnoseAbstractType() {
6096 if (Invalid) return;
6097 S.DiagnoseAbstractType(Record);
6098 Invalid = true;
6099 }
6100
6101 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6102 };
6103
6104 struct CheckAbstractUsage {
6105 AbstractUsageInfo &Info;
6106 const NamedDecl *Ctx;
6107
CheckAbstractUsage__anon067e66481411::CheckAbstractUsage6108 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6109 : Info(Info), Ctx(Ctx) {}
6110
Visit__anon067e66481411::CheckAbstractUsage6111 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6112 switch (TL.getTypeLocClass()) {
6113 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6114 #define TYPELOC(CLASS, PARENT) \
6115 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6116 #include "clang/AST/TypeLocNodes.def"
6117 }
6118 }
6119
Check__anon067e66481411::CheckAbstractUsage6120 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6121 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
6122 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6123 if (!TL.getParam(I))
6124 continue;
6125
6126 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6127 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6128 }
6129 }
6130
Check__anon067e66481411::CheckAbstractUsage6131 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6132 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
6133 }
6134
Check__anon067e66481411::CheckAbstractUsage6135 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6136 // Visit the type parameters from a permissive context.
6137 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6138 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6139 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6140 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6141 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6142 // TODO: other template argument types?
6143 }
6144 }
6145
6146 // Visit pointee types from a permissive context.
6147 #define CheckPolymorphic(Type) \
6148 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6149 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6150 }
6151 CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon067e66481411::CheckAbstractUsage6152 CheckPolymorphic(ReferenceTypeLoc)
6153 CheckPolymorphic(MemberPointerTypeLoc)
6154 CheckPolymorphic(BlockPointerTypeLoc)
6155 CheckPolymorphic(AtomicTypeLoc)
6156
6157 /// Handle all the types we haven't given a more specific
6158 /// implementation for above.
6159 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6160 // Every other kind of type that we haven't called out already
6161 // that has an inner type is either (1) sugar or (2) contains that
6162 // inner type in some way as a subobject.
6163 if (TypeLoc Next = TL.getNextTypeLoc())
6164 return Visit(Next, Sel);
6165
6166 // If there's no inner type and we're in a permissive context,
6167 // don't diagnose.
6168 if (Sel == Sema::AbstractNone) return;
6169
6170 // Check whether the type matches the abstract type.
6171 QualType T = TL.getType();
6172 if (T->isArrayType()) {
6173 Sel = Sema::AbstractArrayType;
6174 T = Info.S.Context.getBaseElementType(T);
6175 }
6176 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6177 if (CT != Info.AbstractType) return;
6178
6179 // It matched; do some magic.
6180 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6181 if (Sel == Sema::AbstractArrayType) {
6182 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6183 << T << TL.getSourceRange();
6184 } else {
6185 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6186 << Sel << T << TL.getSourceRange();
6187 }
6188 Info.DiagnoseAbstractType();
6189 }
6190 };
6191
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)6192 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6193 Sema::AbstractDiagSelID Sel) {
6194 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6195 }
6196
6197 }
6198
6199 /// Check for invalid uses of an abstract type in a function declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,FunctionDecl * FD)6200 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6201 FunctionDecl *FD) {
6202 // Only definitions are required to refer to complete and
6203 // non-abstract types.
6204 if (!FD->doesThisDeclarationHaveABody())
6205 return;
6206
6207 // For safety's sake, just ignore it if we don't have type source
6208 // information. This should never happen for non-implicit methods,
6209 // but...
6210 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6211 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6212 }
6213
6214 /// Check for invalid uses of an abstract type in a variable0 declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,VarDecl * VD)6215 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6216 VarDecl *VD) {
6217 // No need to do the check on definitions, which require that
6218 // the type is complete.
6219 if (VD->isThisDeclarationADefinition())
6220 return;
6221
6222 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6223 Sema::AbstractVariableType);
6224 }
6225
6226 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)6227 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6228 CXXRecordDecl *RD) {
6229 for (auto *D : RD->decls()) {
6230 if (D->isImplicit()) continue;
6231
6232 // Step through friends to the befriended declaration.
6233 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6234 D = FD->getFriendDecl();
6235 if (!D) continue;
6236 }
6237
6238 // Functions and function templates.
6239 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6240 CheckAbstractClassUsage(Info, FD);
6241 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6242 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6243
6244 // Fields and static variables.
6245 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6246 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6247 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6248 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6249 CheckAbstractClassUsage(Info, VD);
6250 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6251 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6252
6253 // Nested classes and class templates.
6254 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6255 CheckAbstractClassUsage(Info, RD);
6256 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6257 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6258 }
6259 }
6260 }
6261
ReferenceDllExportedMembers(Sema & S,CXXRecordDecl * Class)6262 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6263 Attr *ClassAttr = getDLLAttr(Class);
6264 if (!ClassAttr)
6265 return;
6266
6267 assert(ClassAttr->getKind() == attr::DLLExport);
6268
6269 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6270
6271 if (TSK == TSK_ExplicitInstantiationDeclaration)
6272 // Don't go any further if this is just an explicit instantiation
6273 // declaration.
6274 return;
6275
6276 // Add a context note to explain how we got to any diagnostics produced below.
6277 struct MarkingClassDllexported {
6278 Sema &S;
6279 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6280 SourceLocation AttrLoc)
6281 : S(S) {
6282 Sema::CodeSynthesisContext Ctx;
6283 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6284 Ctx.PointOfInstantiation = AttrLoc;
6285 Ctx.Entity = Class;
6286 S.pushCodeSynthesisContext(Ctx);
6287 }
6288 ~MarkingClassDllexported() {
6289 S.popCodeSynthesisContext();
6290 }
6291 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6292
6293 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6294 S.MarkVTableUsed(Class->getLocation(), Class, true);
6295
6296 for (Decl *Member : Class->decls()) {
6297 // Skip members that were not marked exported.
6298 if (!Member->hasAttr<DLLExportAttr>())
6299 continue;
6300
6301 // Defined static variables that are members of an exported base
6302 // class must be marked export too.
6303 auto *VD = dyn_cast<VarDecl>(Member);
6304 if (VD && VD->getStorageClass() == SC_Static &&
6305 TSK == TSK_ImplicitInstantiation)
6306 S.MarkVariableReferenced(VD->getLocation(), VD);
6307
6308 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6309 if (!MD)
6310 continue;
6311
6312 if (MD->isUserProvided()) {
6313 // Instantiate non-default class member functions ...
6314
6315 // .. except for certain kinds of template specializations.
6316 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6317 continue;
6318
6319 // If this is an MS ABI dllexport default constructor, instantiate any
6320 // default arguments.
6321 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6322 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6323 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6324 S.InstantiateDefaultCtorDefaultArgs(CD);
6325 }
6326 }
6327
6328 S.MarkFunctionReferenced(Class->getLocation(), MD);
6329
6330 // The function will be passed to the consumer when its definition is
6331 // encountered.
6332 } else if (MD->isExplicitlyDefaulted()) {
6333 // Synthesize and instantiate explicitly defaulted methods.
6334 S.MarkFunctionReferenced(Class->getLocation(), MD);
6335
6336 if (TSK != TSK_ExplicitInstantiationDefinition) {
6337 // Except for explicit instantiation defs, we will not see the
6338 // definition again later, so pass it to the consumer now.
6339 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6340 }
6341 } else if (!MD->isTrivial() ||
6342 MD->isCopyAssignmentOperator() ||
6343 MD->isMoveAssignmentOperator()) {
6344 // Synthesize and instantiate non-trivial implicit methods, and the copy
6345 // and move assignment operators. The latter are exported even if they
6346 // are trivial, because the address of an operator can be taken and
6347 // should compare equal across libraries.
6348 S.MarkFunctionReferenced(Class->getLocation(), MD);
6349
6350 // There is no later point when we will see the definition of this
6351 // function, so pass it to the consumer now.
6352 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6353 }
6354 }
6355 }
6356
checkForMultipleExportedDefaultConstructors(Sema & S,CXXRecordDecl * Class)6357 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6358 CXXRecordDecl *Class) {
6359 // Only the MS ABI has default constructor closures, so we don't need to do
6360 // this semantic checking anywhere else.
6361 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6362 return;
6363
6364 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6365 for (Decl *Member : Class->decls()) {
6366 // Look for exported default constructors.
6367 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6368 if (!CD || !CD->isDefaultConstructor())
6369 continue;
6370 auto *Attr = CD->getAttr<DLLExportAttr>();
6371 if (!Attr)
6372 continue;
6373
6374 // If the class is non-dependent, mark the default arguments as ODR-used so
6375 // that we can properly codegen the constructor closure.
6376 if (!Class->isDependentContext()) {
6377 for (ParmVarDecl *PD : CD->parameters()) {
6378 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6379 S.DiscardCleanupsInEvaluationContext();
6380 }
6381 }
6382
6383 if (LastExportedDefaultCtor) {
6384 S.Diag(LastExportedDefaultCtor->getLocation(),
6385 diag::err_attribute_dll_ambiguous_default_ctor)
6386 << Class;
6387 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6388 << CD->getDeclName();
6389 return;
6390 }
6391 LastExportedDefaultCtor = CD;
6392 }
6393 }
6394
checkCUDADeviceBuiltinSurfaceClassTemplate(Sema & S,CXXRecordDecl * Class)6395 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6396 CXXRecordDecl *Class) {
6397 bool ErrorReported = false;
6398 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6399 ClassTemplateDecl *TD) {
6400 if (ErrorReported)
6401 return;
6402 S.Diag(TD->getLocation(),
6403 diag::err_cuda_device_builtin_surftex_cls_template)
6404 << /*surface*/ 0 << TD;
6405 ErrorReported = true;
6406 };
6407
6408 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6409 if (!TD) {
6410 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6411 if (!SD) {
6412 S.Diag(Class->getLocation(),
6413 diag::err_cuda_device_builtin_surftex_ref_decl)
6414 << /*surface*/ 0 << Class;
6415 S.Diag(Class->getLocation(),
6416 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6417 << Class;
6418 return;
6419 }
6420 TD = SD->getSpecializedTemplate();
6421 }
6422
6423 TemplateParameterList *Params = TD->getTemplateParameters();
6424 unsigned N = Params->size();
6425
6426 if (N != 2) {
6427 reportIllegalClassTemplate(S, TD);
6428 S.Diag(TD->getLocation(),
6429 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6430 << TD << 2;
6431 }
6432 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6433 reportIllegalClassTemplate(S, TD);
6434 S.Diag(TD->getLocation(),
6435 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6436 << TD << /*1st*/ 0 << /*type*/ 0;
6437 }
6438 if (N > 1) {
6439 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6440 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6441 reportIllegalClassTemplate(S, TD);
6442 S.Diag(TD->getLocation(),
6443 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6444 << TD << /*2nd*/ 1 << /*integer*/ 1;
6445 }
6446 }
6447 }
6448
checkCUDADeviceBuiltinTextureClassTemplate(Sema & S,CXXRecordDecl * Class)6449 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6450 CXXRecordDecl *Class) {
6451 bool ErrorReported = false;
6452 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6453 ClassTemplateDecl *TD) {
6454 if (ErrorReported)
6455 return;
6456 S.Diag(TD->getLocation(),
6457 diag::err_cuda_device_builtin_surftex_cls_template)
6458 << /*texture*/ 1 << TD;
6459 ErrorReported = true;
6460 };
6461
6462 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6463 if (!TD) {
6464 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6465 if (!SD) {
6466 S.Diag(Class->getLocation(),
6467 diag::err_cuda_device_builtin_surftex_ref_decl)
6468 << /*texture*/ 1 << Class;
6469 S.Diag(Class->getLocation(),
6470 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6471 << Class;
6472 return;
6473 }
6474 TD = SD->getSpecializedTemplate();
6475 }
6476
6477 TemplateParameterList *Params = TD->getTemplateParameters();
6478 unsigned N = Params->size();
6479
6480 if (N != 3) {
6481 reportIllegalClassTemplate(S, TD);
6482 S.Diag(TD->getLocation(),
6483 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6484 << TD << 3;
6485 }
6486 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6487 reportIllegalClassTemplate(S, TD);
6488 S.Diag(TD->getLocation(),
6489 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6490 << TD << /*1st*/ 0 << /*type*/ 0;
6491 }
6492 if (N > 1) {
6493 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6494 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6495 reportIllegalClassTemplate(S, TD);
6496 S.Diag(TD->getLocation(),
6497 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6498 << TD << /*2nd*/ 1 << /*integer*/ 1;
6499 }
6500 }
6501 if (N > 2) {
6502 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6503 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6504 reportIllegalClassTemplate(S, TD);
6505 S.Diag(TD->getLocation(),
6506 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6507 << TD << /*3rd*/ 2 << /*integer*/ 1;
6508 }
6509 }
6510 }
6511
checkClassLevelCodeSegAttribute(CXXRecordDecl * Class)6512 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6513 // Mark any compiler-generated routines with the implicit code_seg attribute.
6514 for (auto *Method : Class->methods()) {
6515 if (Method->isUserProvided())
6516 continue;
6517 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6518 Method->addAttr(A);
6519 }
6520 }
6521
6522 /// Check class-level dllimport/dllexport attribute.
checkClassLevelDLLAttribute(CXXRecordDecl * Class)6523 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6524 Attr *ClassAttr = getDLLAttr(Class);
6525
6526 // MSVC inherits DLL attributes to partial class template specializations.
6527 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6528 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6529 if (Attr *TemplateAttr =
6530 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6531 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6532 A->setInherited(true);
6533 ClassAttr = A;
6534 }
6535 }
6536 }
6537
6538 if (!ClassAttr)
6539 return;
6540
6541 // MSVC allows imported or exported template classes that have UniqueExternal
6542 // linkage. This occurs when the template class has been instantiated with
6543 // a template parameter which itself has internal linkage.
6544 // We drop the attribute to avoid exporting or importing any members.
6545 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6546 Context.getTargetInfo().getTriple().isPS()) &&
6547 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6548 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6549 return;
6550 }
6551
6552 if (!Class->isExternallyVisible()) {
6553 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6554 << Class << ClassAttr;
6555 return;
6556 }
6557
6558 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6559 !ClassAttr->isInherited()) {
6560 // Diagnose dll attributes on members of class with dll attribute.
6561 for (Decl *Member : Class->decls()) {
6562 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6563 continue;
6564 InheritableAttr *MemberAttr = getDLLAttr(Member);
6565 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6566 continue;
6567
6568 Diag(MemberAttr->getLocation(),
6569 diag::err_attribute_dll_member_of_dll_class)
6570 << MemberAttr << ClassAttr;
6571 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6572 Member->setInvalidDecl();
6573 }
6574 }
6575
6576 if (Class->getDescribedClassTemplate())
6577 // Don't inherit dll attribute until the template is instantiated.
6578 return;
6579
6580 // The class is either imported or exported.
6581 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6582
6583 // Check if this was a dllimport attribute propagated from a derived class to
6584 // a base class template specialization. We don't apply these attributes to
6585 // static data members.
6586 const bool PropagatedImport =
6587 !ClassExported &&
6588 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6589
6590 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6591
6592 // Ignore explicit dllexport on explicit class template instantiation
6593 // declarations, except in MinGW mode.
6594 if (ClassExported && !ClassAttr->isInherited() &&
6595 TSK == TSK_ExplicitInstantiationDeclaration &&
6596 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6597 Class->dropAttr<DLLExportAttr>();
6598 return;
6599 }
6600
6601 // Force declaration of implicit members so they can inherit the attribute.
6602 ForceDeclarationOfImplicitMembers(Class);
6603
6604 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6605 // seem to be true in practice?
6606
6607 for (Decl *Member : Class->decls()) {
6608 VarDecl *VD = dyn_cast<VarDecl>(Member);
6609 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6610
6611 // Only methods and static fields inherit the attributes.
6612 if (!VD && !MD)
6613 continue;
6614
6615 if (MD) {
6616 // Don't process deleted methods.
6617 if (MD->isDeleted())
6618 continue;
6619
6620 if (MD->isInlined()) {
6621 // MinGW does not import or export inline methods. But do it for
6622 // template instantiations.
6623 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6624 TSK != TSK_ExplicitInstantiationDeclaration &&
6625 TSK != TSK_ExplicitInstantiationDefinition)
6626 continue;
6627
6628 // MSVC versions before 2015 don't export the move assignment operators
6629 // and move constructor, so don't attempt to import/export them if
6630 // we have a definition.
6631 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6632 if ((MD->isMoveAssignmentOperator() ||
6633 (Ctor && Ctor->isMoveConstructor())) &&
6634 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6635 continue;
6636
6637 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6638 // operator is exported anyway.
6639 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6640 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6641 continue;
6642 }
6643 }
6644
6645 // Don't apply dllimport attributes to static data members of class template
6646 // instantiations when the attribute is propagated from a derived class.
6647 if (VD && PropagatedImport)
6648 continue;
6649
6650 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6651 continue;
6652
6653 if (!getDLLAttr(Member)) {
6654 InheritableAttr *NewAttr = nullptr;
6655
6656 // Do not export/import inline function when -fno-dllexport-inlines is
6657 // passed. But add attribute for later local static var check.
6658 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6659 TSK != TSK_ExplicitInstantiationDeclaration &&
6660 TSK != TSK_ExplicitInstantiationDefinition) {
6661 if (ClassExported) {
6662 NewAttr = ::new (getASTContext())
6663 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6664 } else {
6665 NewAttr = ::new (getASTContext())
6666 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6667 }
6668 } else {
6669 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6670 }
6671
6672 NewAttr->setInherited(true);
6673 Member->addAttr(NewAttr);
6674
6675 if (MD) {
6676 // Propagate DLLAttr to friend re-declarations of MD that have already
6677 // been constructed.
6678 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6679 FD = FD->getPreviousDecl()) {
6680 if (FD->getFriendObjectKind() == Decl::FOK_None)
6681 continue;
6682 assert(!getDLLAttr(FD) &&
6683 "friend re-decl should not already have a DLLAttr");
6684 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6685 NewAttr->setInherited(true);
6686 FD->addAttr(NewAttr);
6687 }
6688 }
6689 }
6690 }
6691
6692 if (ClassExported)
6693 DelayedDllExportClasses.push_back(Class);
6694 }
6695
6696 /// Perform propagation of DLL attributes from a derived class to a
6697 /// templated base class for MS compatibility.
propagateDLLAttrToBaseClassTemplate(CXXRecordDecl * Class,Attr * ClassAttr,ClassTemplateSpecializationDecl * BaseTemplateSpec,SourceLocation BaseLoc)6698 void Sema::propagateDLLAttrToBaseClassTemplate(
6699 CXXRecordDecl *Class, Attr *ClassAttr,
6700 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6701 if (getDLLAttr(
6702 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6703 // If the base class template has a DLL attribute, don't try to change it.
6704 return;
6705 }
6706
6707 auto TSK = BaseTemplateSpec->getSpecializationKind();
6708 if (!getDLLAttr(BaseTemplateSpec) &&
6709 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6710 TSK == TSK_ImplicitInstantiation)) {
6711 // The template hasn't been instantiated yet (or it has, but only as an
6712 // explicit instantiation declaration or implicit instantiation, which means
6713 // we haven't codegenned any members yet), so propagate the attribute.
6714 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6715 NewAttr->setInherited(true);
6716 BaseTemplateSpec->addAttr(NewAttr);
6717
6718 // If this was an import, mark that we propagated it from a derived class to
6719 // a base class template specialization.
6720 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6721 ImportAttr->setPropagatedToBaseTemplate();
6722
6723 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6724 // needs to be run again to work see the new attribute. Otherwise this will
6725 // get run whenever the template is instantiated.
6726 if (TSK != TSK_Undeclared)
6727 checkClassLevelDLLAttribute(BaseTemplateSpec);
6728
6729 return;
6730 }
6731
6732 if (getDLLAttr(BaseTemplateSpec)) {
6733 // The template has already been specialized or instantiated with an
6734 // attribute, explicitly or through propagation. We should not try to change
6735 // it.
6736 return;
6737 }
6738
6739 // The template was previously instantiated or explicitly specialized without
6740 // a dll attribute, It's too late for us to add an attribute, so warn that
6741 // this is unsupported.
6742 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6743 << BaseTemplateSpec->isExplicitSpecialization();
6744 Diag(ClassAttr->getLocation(), diag::note_attribute);
6745 if (BaseTemplateSpec->isExplicitSpecialization()) {
6746 Diag(BaseTemplateSpec->getLocation(),
6747 diag::note_template_class_explicit_specialization_was_here)
6748 << BaseTemplateSpec;
6749 } else {
6750 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6751 diag::note_template_class_instantiation_was_here)
6752 << BaseTemplateSpec;
6753 }
6754 }
6755
6756 /// Determine the kind of defaulting that would be done for a given function.
6757 ///
6758 /// If the function is both a default constructor and a copy / move constructor
6759 /// (due to having a default argument for the first parameter), this picks
6760 /// CXXDefaultConstructor.
6761 ///
6762 /// FIXME: Check that case is properly handled by all callers.
6763 Sema::DefaultedFunctionKind
getDefaultedFunctionKind(const FunctionDecl * FD)6764 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6765 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6766 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6767 if (Ctor->isDefaultConstructor())
6768 return Sema::CXXDefaultConstructor;
6769
6770 if (Ctor->isCopyConstructor())
6771 return Sema::CXXCopyConstructor;
6772
6773 if (Ctor->isMoveConstructor())
6774 return Sema::CXXMoveConstructor;
6775 }
6776
6777 if (MD->isCopyAssignmentOperator())
6778 return Sema::CXXCopyAssignment;
6779
6780 if (MD->isMoveAssignmentOperator())
6781 return Sema::CXXMoveAssignment;
6782
6783 if (isa<CXXDestructorDecl>(FD))
6784 return Sema::CXXDestructor;
6785 }
6786
6787 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6788 case OO_EqualEqual:
6789 return DefaultedComparisonKind::Equal;
6790
6791 case OO_ExclaimEqual:
6792 return DefaultedComparisonKind::NotEqual;
6793
6794 case OO_Spaceship:
6795 // No point allowing this if <=> doesn't exist in the current language mode.
6796 if (!getLangOpts().CPlusPlus20)
6797 break;
6798 return DefaultedComparisonKind::ThreeWay;
6799
6800 case OO_Less:
6801 case OO_LessEqual:
6802 case OO_Greater:
6803 case OO_GreaterEqual:
6804 // No point allowing this if <=> doesn't exist in the current language mode.
6805 if (!getLangOpts().CPlusPlus20)
6806 break;
6807 return DefaultedComparisonKind::Relational;
6808
6809 default:
6810 break;
6811 }
6812
6813 // Not defaultable.
6814 return DefaultedFunctionKind();
6815 }
6816
DefineDefaultedFunction(Sema & S,FunctionDecl * FD,SourceLocation DefaultLoc)6817 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6818 SourceLocation DefaultLoc) {
6819 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6820 if (DFK.isComparison())
6821 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6822
6823 switch (DFK.asSpecialMember()) {
6824 case Sema::CXXDefaultConstructor:
6825 S.DefineImplicitDefaultConstructor(DefaultLoc,
6826 cast<CXXConstructorDecl>(FD));
6827 break;
6828 case Sema::CXXCopyConstructor:
6829 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6830 break;
6831 case Sema::CXXCopyAssignment:
6832 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6833 break;
6834 case Sema::CXXDestructor:
6835 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6836 break;
6837 case Sema::CXXMoveConstructor:
6838 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6839 break;
6840 case Sema::CXXMoveAssignment:
6841 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6842 break;
6843 case Sema::CXXInvalid:
6844 llvm_unreachable("Invalid special member.");
6845 }
6846 }
6847
6848 /// Determine whether a type is permitted to be passed or returned in
6849 /// registers, per C++ [class.temporary]p3.
canPassInRegisters(Sema & S,CXXRecordDecl * D,TargetInfo::CallingConvKind CCK)6850 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6851 TargetInfo::CallingConvKind CCK) {
6852 if (D->isDependentType() || D->isInvalidDecl())
6853 return false;
6854
6855 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6856 // The PS4 platform ABI follows the behavior of Clang 3.2.
6857 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6858 return !D->hasNonTrivialDestructorForCall() &&
6859 !D->hasNonTrivialCopyConstructorForCall();
6860
6861 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6862 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6863 bool DtorIsTrivialForCall = false;
6864
6865 // If a class has at least one eligible, trivial copy constructor, it
6866 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6867 //
6868 // Note: This permits classes with non-trivial copy or move ctors to be
6869 // passed in registers, so long as they *also* have a trivial copy ctor,
6870 // which is non-conforming.
6871 if (D->needsImplicitCopyConstructor()) {
6872 if (!D->defaultedCopyConstructorIsDeleted()) {
6873 if (D->hasTrivialCopyConstructor())
6874 CopyCtorIsTrivial = true;
6875 if (D->hasTrivialCopyConstructorForCall())
6876 CopyCtorIsTrivialForCall = true;
6877 }
6878 } else {
6879 for (const CXXConstructorDecl *CD : D->ctors()) {
6880 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6881 !CD->isIneligibleOrNotSelected()) {
6882 if (CD->isTrivial())
6883 CopyCtorIsTrivial = true;
6884 if (CD->isTrivialForCall())
6885 CopyCtorIsTrivialForCall = true;
6886 }
6887 }
6888 }
6889
6890 if (D->needsImplicitDestructor()) {
6891 if (!D->defaultedDestructorIsDeleted() &&
6892 D->hasTrivialDestructorForCall())
6893 DtorIsTrivialForCall = true;
6894 } else if (const auto *DD = D->getDestructor()) {
6895 if (!DD->isDeleted() && DD->isTrivialForCall())
6896 DtorIsTrivialForCall = true;
6897 }
6898
6899 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6900 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6901 return true;
6902
6903 // If a class has a destructor, we'd really like to pass it indirectly
6904 // because it allows us to elide copies. Unfortunately, MSVC makes that
6905 // impossible for small types, which it will pass in a single register or
6906 // stack slot. Most objects with dtors are large-ish, so handle that early.
6907 // We can't call out all large objects as being indirect because there are
6908 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6909 // how we pass large POD types.
6910
6911 // Note: This permits small classes with nontrivial destructors to be
6912 // passed in registers, which is non-conforming.
6913 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6914 uint64_t TypeSize = isAArch64 ? 128 : 64;
6915
6916 if (CopyCtorIsTrivial &&
6917 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6918 return true;
6919 return false;
6920 }
6921
6922 // Per C++ [class.temporary]p3, the relevant condition is:
6923 // each copy constructor, move constructor, and destructor of X is
6924 // either trivial or deleted, and X has at least one non-deleted copy
6925 // or move constructor
6926 bool HasNonDeletedCopyOrMove = false;
6927
6928 if (D->needsImplicitCopyConstructor() &&
6929 !D->defaultedCopyConstructorIsDeleted()) {
6930 if (!D->hasTrivialCopyConstructorForCall())
6931 return false;
6932 HasNonDeletedCopyOrMove = true;
6933 }
6934
6935 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6936 !D->defaultedMoveConstructorIsDeleted()) {
6937 if (!D->hasTrivialMoveConstructorForCall())
6938 return false;
6939 HasNonDeletedCopyOrMove = true;
6940 }
6941
6942 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6943 !D->hasTrivialDestructorForCall())
6944 return false;
6945
6946 for (const CXXMethodDecl *MD : D->methods()) {
6947 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6948 continue;
6949
6950 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6951 if (CD && CD->isCopyOrMoveConstructor())
6952 HasNonDeletedCopyOrMove = true;
6953 else if (!isa<CXXDestructorDecl>(MD))
6954 continue;
6955
6956 if (!MD->isTrivialForCall())
6957 return false;
6958 }
6959
6960 return HasNonDeletedCopyOrMove;
6961 }
6962
6963 /// Report an error regarding overriding, along with any relevant
6964 /// overridden methods.
6965 ///
6966 /// \param DiagID the primary error to report.
6967 /// \param MD the overriding method.
6968 static bool
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,llvm::function_ref<bool (const CXXMethodDecl *)> Report)6969 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6970 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6971 bool IssuedDiagnostic = false;
6972 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6973 if (Report(O)) {
6974 if (!IssuedDiagnostic) {
6975 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6976 IssuedDiagnostic = true;
6977 }
6978 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6979 }
6980 }
6981 return IssuedDiagnostic;
6982 }
6983
6984 /// Perform semantic checks on a class definition that has been
6985 /// completing, introducing implicitly-declared members, checking for
6986 /// abstract types, etc.
6987 ///
6988 /// \param S The scope in which the class was parsed. Null if we didn't just
6989 /// parse a class definition.
6990 /// \param Record The completed class.
CheckCompletedCXXClass(Scope * S,CXXRecordDecl * Record)6991 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6992 if (!Record)
6993 return;
6994
6995 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6996 AbstractUsageInfo Info(*this, Record);
6997 CheckAbstractClassUsage(Info, Record);
6998 }
6999
7000 // If this is not an aggregate type and has no user-declared constructor,
7001 // complain about any non-static data members of reference or const scalar
7002 // type, since they will never get initializers.
7003 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7004 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7005 !Record->isLambda()) {
7006 bool Complained = false;
7007 for (const auto *F : Record->fields()) {
7008 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
7009 continue;
7010
7011 if (F->getType()->isReferenceType() ||
7012 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7013 if (!Complained) {
7014 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7015 << llvm::to_underlying(Record->getTagKind()) << Record;
7016 Complained = true;
7017 }
7018
7019 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7020 << F->getType()->isReferenceType()
7021 << F->getDeclName();
7022 }
7023 }
7024 }
7025
7026 if (Record->getIdentifier()) {
7027 // C++ [class.mem]p13:
7028 // If T is the name of a class, then each of the following shall have a
7029 // name different from T:
7030 // - every member of every anonymous union that is a member of class T.
7031 //
7032 // C++ [class.mem]p14:
7033 // In addition, if class T has a user-declared constructor (12.1), every
7034 // non-static data member of class T shall have a name different from T.
7035 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7036 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7037 ++I) {
7038 NamedDecl *D = (*I)->getUnderlyingDecl();
7039 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7040 Record->hasUserDeclaredConstructor()) ||
7041 isa<IndirectFieldDecl>(D)) {
7042 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7043 << D->getDeclName();
7044 break;
7045 }
7046 }
7047 }
7048
7049 // Warn if the class has virtual methods but non-virtual public destructor.
7050 if (Record->isPolymorphic() && !Record->isDependentType()) {
7051 CXXDestructorDecl *dtor = Record->getDestructor();
7052 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7053 !Record->hasAttr<FinalAttr>())
7054 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7055 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7056 }
7057
7058 if (Record->isAbstract()) {
7059 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7060 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7061 << FA->isSpelledAsSealed();
7062 DiagnoseAbstractType(Record);
7063 }
7064 }
7065
7066 // Warn if the class has a final destructor but is not itself marked final.
7067 if (!Record->hasAttr<FinalAttr>()) {
7068 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7069 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7070 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7071 << FA->isSpelledAsSealed()
7072 << FixItHint::CreateInsertion(
7073 getLocForEndOfToken(Record->getLocation()),
7074 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7075 Diag(Record->getLocation(),
7076 diag::note_final_dtor_non_final_class_silence)
7077 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7078 }
7079 }
7080 }
7081
7082 // See if trivial_abi has to be dropped.
7083 if (Record->hasAttr<TrivialABIAttr>())
7084 checkIllFormedTrivialABIStruct(*Record);
7085
7086 // Set HasTrivialSpecialMemberForCall if the record has attribute
7087 // "trivial_abi".
7088 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7089
7090 if (HasTrivialABI)
7091 Record->setHasTrivialSpecialMemberForCall();
7092
7093 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7094 // We check these last because they can depend on the properties of the
7095 // primary comparison functions (==, <=>).
7096 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7097
7098 // Perform checks that can't be done until we know all the properties of a
7099 // member function (whether it's defaulted, deleted, virtual, overriding,
7100 // ...).
7101 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7102 // A static function cannot override anything.
7103 if (MD->getStorageClass() == SC_Static) {
7104 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7105 [](const CXXMethodDecl *) { return true; }))
7106 return;
7107 }
7108
7109 // A deleted function cannot override a non-deleted function and vice
7110 // versa.
7111 if (ReportOverrides(*this,
7112 MD->isDeleted() ? diag::err_deleted_override
7113 : diag::err_non_deleted_override,
7114 MD, [&](const CXXMethodDecl *V) {
7115 return MD->isDeleted() != V->isDeleted();
7116 })) {
7117 if (MD->isDefaulted() && MD->isDeleted())
7118 // Explain why this defaulted function was deleted.
7119 DiagnoseDeletedDefaultedFunction(MD);
7120 return;
7121 }
7122
7123 // A consteval function cannot override a non-consteval function and vice
7124 // versa.
7125 if (ReportOverrides(*this,
7126 MD->isConsteval() ? diag::err_consteval_override
7127 : diag::err_non_consteval_override,
7128 MD, [&](const CXXMethodDecl *V) {
7129 return MD->isConsteval() != V->isConsteval();
7130 })) {
7131 if (MD->isDefaulted() && MD->isDeleted())
7132 // Explain why this defaulted function was deleted.
7133 DiagnoseDeletedDefaultedFunction(MD);
7134 return;
7135 }
7136 };
7137
7138 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7139 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7140 return false;
7141
7142 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7143 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7144 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7145 DefaultedSecondaryComparisons.push_back(FD);
7146 return true;
7147 }
7148
7149 CheckExplicitlyDefaultedFunction(S, FD);
7150 return false;
7151 };
7152
7153 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7154 // Check whether the explicitly-defaulted members are valid.
7155 bool Incomplete = CheckForDefaultedFunction(M);
7156
7157 // Skip the rest of the checks for a member of a dependent class.
7158 if (Record->isDependentType())
7159 return;
7160
7161 // For an explicitly defaulted or deleted special member, we defer
7162 // determining triviality until the class is complete. That time is now!
7163 CXXSpecialMember CSM = getSpecialMember(M);
7164 if (!M->isImplicit() && !M->isUserProvided()) {
7165 if (CSM != CXXInvalid) {
7166 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7167 // Inform the class that we've finished declaring this member.
7168 Record->finishedDefaultedOrDeletedMember(M);
7169 M->setTrivialForCall(
7170 HasTrivialABI ||
7171 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
7172 Record->setTrivialForCallFlags(M);
7173 }
7174 }
7175
7176 // Set triviality for the purpose of calls if this is a user-provided
7177 // copy/move constructor or destructor.
7178 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
7179 CSM == CXXDestructor) && M->isUserProvided()) {
7180 M->setTrivialForCall(HasTrivialABI);
7181 Record->setTrivialForCallFlags(M);
7182 }
7183
7184 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7185 M->hasAttr<DLLExportAttr>()) {
7186 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7187 M->isTrivial() &&
7188 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
7189 CSM == CXXDestructor))
7190 M->dropAttr<DLLExportAttr>();
7191
7192 if (M->hasAttr<DLLExportAttr>()) {
7193 // Define after any fields with in-class initializers have been parsed.
7194 DelayedDllExportMemberFunctions.push_back(M);
7195 }
7196 }
7197
7198 // Define defaulted constexpr virtual functions that override a base class
7199 // function right away.
7200 // FIXME: We can defer doing this until the vtable is marked as used.
7201 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
7202 M->isConstexpr() && M->size_overridden_methods())
7203 DefineDefaultedFunction(*this, M, M->getLocation());
7204
7205 if (!Incomplete)
7206 CheckCompletedMemberFunction(M);
7207 };
7208
7209 // Check the destructor before any other member function. We need to
7210 // determine whether it's trivial in order to determine whether the claas
7211 // type is a literal type, which is a prerequisite for determining whether
7212 // other special member functions are valid and whether they're implicitly
7213 // 'constexpr'.
7214 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7215 CompleteMemberFunction(Dtor);
7216
7217 bool HasMethodWithOverrideControl = false,
7218 HasOverridingMethodWithoutOverrideControl = false;
7219 for (auto *D : Record->decls()) {
7220 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7221 // FIXME: We could do this check for dependent types with non-dependent
7222 // bases.
7223 if (!Record->isDependentType()) {
7224 // See if a method overloads virtual methods in a base
7225 // class without overriding any.
7226 if (!M->isStatic())
7227 DiagnoseHiddenVirtualMethods(M);
7228 if (M->hasAttr<OverrideAttr>())
7229 HasMethodWithOverrideControl = true;
7230 else if (M->size_overridden_methods() > 0)
7231 HasOverridingMethodWithoutOverrideControl = true;
7232 }
7233
7234 if (!isa<CXXDestructorDecl>(M))
7235 CompleteMemberFunction(M);
7236 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7237 CheckForDefaultedFunction(
7238 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7239 }
7240 }
7241
7242 if (HasOverridingMethodWithoutOverrideControl) {
7243 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7244 for (auto *M : Record->methods())
7245 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7246 }
7247
7248 // Check the defaulted secondary comparisons after any other member functions.
7249 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7250 CheckExplicitlyDefaultedFunction(S, FD);
7251
7252 // If this is a member function, we deferred checking it until now.
7253 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7254 CheckCompletedMemberFunction(MD);
7255 }
7256
7257 // ms_struct is a request to use the same ABI rules as MSVC. Check
7258 // whether this class uses any C++ features that are implemented
7259 // completely differently in MSVC, and if so, emit a diagnostic.
7260 // That diagnostic defaults to an error, but we allow projects to
7261 // map it down to a warning (or ignore it). It's a fairly common
7262 // practice among users of the ms_struct pragma to mass-annotate
7263 // headers, sweeping up a bunch of types that the project doesn't
7264 // really rely on MSVC-compatible layout for. We must therefore
7265 // support "ms_struct except for C++ stuff" as a secondary ABI.
7266 // Don't emit this diagnostic if the feature was enabled as a
7267 // language option (as opposed to via a pragma or attribute), as
7268 // the option -mms-bitfields otherwise essentially makes it impossible
7269 // to build C++ code, unless this diagnostic is turned off.
7270 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7271 (Record->isPolymorphic() || Record->getNumBases())) {
7272 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7273 }
7274
7275 checkClassLevelDLLAttribute(Record);
7276 checkClassLevelCodeSegAttribute(Record);
7277
7278 bool ClangABICompat4 =
7279 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7280 TargetInfo::CallingConvKind CCK =
7281 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7282 bool CanPass = canPassInRegisters(*this, Record, CCK);
7283
7284 // Do not change ArgPassingRestrictions if it has already been set to
7285 // ArgPassingKind::CanNeverPassInRegs.
7286 if (Record->getArgPassingRestrictions() !=
7287 RecordArgPassingKind::CanNeverPassInRegs)
7288 Record->setArgPassingRestrictions(
7289 CanPass ? RecordArgPassingKind::CanPassInRegs
7290 : RecordArgPassingKind::CannotPassInRegs);
7291
7292 // If canPassInRegisters returns true despite the record having a non-trivial
7293 // destructor, the record is destructed in the callee. This happens only when
7294 // the record or one of its subobjects has a field annotated with trivial_abi
7295 // or a field qualified with ObjC __strong/__weak.
7296 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7297 Record->setParamDestroyedInCallee(true);
7298 else if (Record->hasNonTrivialDestructor())
7299 Record->setParamDestroyedInCallee(CanPass);
7300
7301 if (getLangOpts().ForceEmitVTables) {
7302 // If we want to emit all the vtables, we need to mark it as used. This
7303 // is especially required for cases like vtable assumption loads.
7304 MarkVTableUsed(Record->getInnerLocStart(), Record);
7305 }
7306
7307 if (getLangOpts().CUDA) {
7308 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7309 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7310 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7311 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7312 }
7313 }
7314
7315 /// Look up the special member function that would be called by a special
7316 /// member function for a subobject of class type.
7317 ///
7318 /// \param Class The class type of the subobject.
7319 /// \param CSM The kind of special member function.
7320 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7321 /// \param ConstRHS True if this is a copy operation with a const object
7322 /// on its RHS, that is, if the argument to the outer special member
7323 /// function is 'const' and this is not a field marked 'mutable'.
lookupCallFromSpecialMember(Sema & S,CXXRecordDecl * Class,Sema::CXXSpecialMember CSM,unsigned FieldQuals,bool ConstRHS)7324 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7325 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7326 unsigned FieldQuals, bool ConstRHS) {
7327 unsigned LHSQuals = 0;
7328 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7329 LHSQuals = FieldQuals;
7330
7331 unsigned RHSQuals = FieldQuals;
7332 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7333 RHSQuals = 0;
7334 else if (ConstRHS)
7335 RHSQuals |= Qualifiers::Const;
7336
7337 return S.LookupSpecialMember(Class, CSM,
7338 RHSQuals & Qualifiers::Const,
7339 RHSQuals & Qualifiers::Volatile,
7340 false,
7341 LHSQuals & Qualifiers::Const,
7342 LHSQuals & Qualifiers::Volatile);
7343 }
7344
7345 class Sema::InheritedConstructorInfo {
7346 Sema &S;
7347 SourceLocation UseLoc;
7348
7349 /// A mapping from the base classes through which the constructor was
7350 /// inherited to the using shadow declaration in that base class (or a null
7351 /// pointer if the constructor was declared in that base class).
7352 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7353 InheritedFromBases;
7354
7355 public:
InheritedConstructorInfo(Sema & S,SourceLocation UseLoc,ConstructorUsingShadowDecl * Shadow)7356 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7357 ConstructorUsingShadowDecl *Shadow)
7358 : S(S), UseLoc(UseLoc) {
7359 bool DiagnosedMultipleConstructedBases = false;
7360 CXXRecordDecl *ConstructedBase = nullptr;
7361 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7362
7363 // Find the set of such base class subobjects and check that there's a
7364 // unique constructed subobject.
7365 for (auto *D : Shadow->redecls()) {
7366 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7367 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7368 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7369
7370 InheritedFromBases.insert(
7371 std::make_pair(DNominatedBase->getCanonicalDecl(),
7372 DShadow->getNominatedBaseClassShadowDecl()));
7373 if (DShadow->constructsVirtualBase())
7374 InheritedFromBases.insert(
7375 std::make_pair(DConstructedBase->getCanonicalDecl(),
7376 DShadow->getConstructedBaseClassShadowDecl()));
7377 else
7378 assert(DNominatedBase == DConstructedBase);
7379
7380 // [class.inhctor.init]p2:
7381 // If the constructor was inherited from multiple base class subobjects
7382 // of type B, the program is ill-formed.
7383 if (!ConstructedBase) {
7384 ConstructedBase = DConstructedBase;
7385 ConstructedBaseIntroducer = D->getIntroducer();
7386 } else if (ConstructedBase != DConstructedBase &&
7387 !Shadow->isInvalidDecl()) {
7388 if (!DiagnosedMultipleConstructedBases) {
7389 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7390 << Shadow->getTargetDecl();
7391 S.Diag(ConstructedBaseIntroducer->getLocation(),
7392 diag::note_ambiguous_inherited_constructor_using)
7393 << ConstructedBase;
7394 DiagnosedMultipleConstructedBases = true;
7395 }
7396 S.Diag(D->getIntroducer()->getLocation(),
7397 diag::note_ambiguous_inherited_constructor_using)
7398 << DConstructedBase;
7399 }
7400 }
7401
7402 if (DiagnosedMultipleConstructedBases)
7403 Shadow->setInvalidDecl();
7404 }
7405
7406 /// Find the constructor to use for inherited construction of a base class,
7407 /// and whether that base class constructor inherits the constructor from a
7408 /// virtual base class (in which case it won't actually invoke it).
7409 std::pair<CXXConstructorDecl *, bool>
findConstructorForBase(CXXRecordDecl * Base,CXXConstructorDecl * Ctor) const7410 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7411 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7412 if (It == InheritedFromBases.end())
7413 return std::make_pair(nullptr, false);
7414
7415 // This is an intermediary class.
7416 if (It->second)
7417 return std::make_pair(
7418 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7419 It->second->constructsVirtualBase());
7420
7421 // This is the base class from which the constructor was inherited.
7422 return std::make_pair(Ctor, false);
7423 }
7424 };
7425
7426 /// Is the special member function which would be selected to perform the
7427 /// specified operation on the specified class type a constexpr constructor?
7428 static bool
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)7429 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7430 Sema::CXXSpecialMember CSM, unsigned Quals,
7431 bool ConstRHS,
7432 CXXConstructorDecl *InheritedCtor = nullptr,
7433 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7434 // Suppress duplicate constraint checking here, in case a constraint check
7435 // caused us to decide to do this. Any truely recursive checks will get
7436 // caught during these checks anyway.
7437 Sema::SatisfactionStackResetRAII SSRAII{S};
7438
7439 // If we're inheriting a constructor, see if we need to call it for this base
7440 // class.
7441 if (InheritedCtor) {
7442 assert(CSM == Sema::CXXDefaultConstructor);
7443 auto BaseCtor =
7444 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7445 if (BaseCtor)
7446 return BaseCtor->isConstexpr();
7447 }
7448
7449 if (CSM == Sema::CXXDefaultConstructor)
7450 return ClassDecl->hasConstexprDefaultConstructor();
7451 if (CSM == Sema::CXXDestructor)
7452 return ClassDecl->hasConstexprDestructor();
7453
7454 Sema::SpecialMemberOverloadResult SMOR =
7455 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7456 if (!SMOR.getMethod())
7457 // A constructor we wouldn't select can't be "involved in initializing"
7458 // anything.
7459 return true;
7460 return SMOR.getMethod()->isConstexpr();
7461 }
7462
7463 /// Determine whether the specified special member function would be constexpr
7464 /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)7465 static bool defaultedSpecialMemberIsConstexpr(
7466 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7467 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7468 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7469 if (!S.getLangOpts().CPlusPlus11)
7470 return false;
7471
7472 // C++11 [dcl.constexpr]p4:
7473 // In the definition of a constexpr constructor [...]
7474 bool Ctor = true;
7475 switch (CSM) {
7476 case Sema::CXXDefaultConstructor:
7477 if (Inherited)
7478 break;
7479 // Since default constructor lookup is essentially trivial (and cannot
7480 // involve, for instance, template instantiation), we compute whether a
7481 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7482 //
7483 // This is important for performance; we need to know whether the default
7484 // constructor is constexpr to determine whether the type is a literal type.
7485 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7486
7487 case Sema::CXXCopyConstructor:
7488 case Sema::CXXMoveConstructor:
7489 // For copy or move constructors, we need to perform overload resolution.
7490 break;
7491
7492 case Sema::CXXCopyAssignment:
7493 case Sema::CXXMoveAssignment:
7494 if (!S.getLangOpts().CPlusPlus14)
7495 return false;
7496 // In C++1y, we need to perform overload resolution.
7497 Ctor = false;
7498 break;
7499
7500 case Sema::CXXDestructor:
7501 return ClassDecl->defaultedDestructorIsConstexpr();
7502
7503 case Sema::CXXInvalid:
7504 return false;
7505 }
7506
7507 // -- if the class is a non-empty union, or for each non-empty anonymous
7508 // union member of a non-union class, exactly one non-static data member
7509 // shall be initialized; [DR1359]
7510 //
7511 // If we squint, this is guaranteed, since exactly one non-static data member
7512 // will be initialized (if the constructor isn't deleted), we just don't know
7513 // which one.
7514 if (Ctor && ClassDecl->isUnion())
7515 return CSM == Sema::CXXDefaultConstructor
7516 ? ClassDecl->hasInClassInitializer() ||
7517 !ClassDecl->hasVariantMembers()
7518 : true;
7519
7520 // -- the class shall not have any virtual base classes;
7521 if (Ctor && ClassDecl->getNumVBases())
7522 return false;
7523
7524 // C++1y [class.copy]p26:
7525 // -- [the class] is a literal type, and
7526 if (!Ctor && !ClassDecl->isLiteral())
7527 return false;
7528
7529 // -- every constructor involved in initializing [...] base class
7530 // sub-objects shall be a constexpr constructor;
7531 // -- the assignment operator selected to copy/move each direct base
7532 // class is a constexpr function, and
7533 for (const auto &B : ClassDecl->bases()) {
7534 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7535 if (!BaseType)
7536 continue;
7537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7538 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7539 InheritedCtor, Inherited))
7540 return false;
7541 }
7542
7543 // -- every constructor involved in initializing non-static data members
7544 // [...] shall be a constexpr constructor;
7545 // -- every non-static data member and base class sub-object shall be
7546 // initialized
7547 // -- for each non-static data member of X that is of class type (or array
7548 // thereof), the assignment operator selected to copy/move that member is
7549 // a constexpr function
7550 for (const auto *F : ClassDecl->fields()) {
7551 if (F->isInvalidDecl())
7552 continue;
7553 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7554 continue;
7555 QualType BaseType = S.Context.getBaseElementType(F->getType());
7556 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7557 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7558 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7559 BaseType.getCVRQualifiers(),
7560 ConstArg && !F->isMutable()))
7561 return false;
7562 } else if (CSM == Sema::CXXDefaultConstructor) {
7563 return false;
7564 }
7565 }
7566
7567 // All OK, it's constexpr!
7568 return true;
7569 }
7570
7571 namespace {
7572 /// RAII object to register a defaulted function as having its exception
7573 /// specification computed.
7574 struct ComputingExceptionSpec {
7575 Sema &S;
7576
ComputingExceptionSpec__anon067e66481d11::ComputingExceptionSpec7577 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7578 : S(S) {
7579 Sema::CodeSynthesisContext Ctx;
7580 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7581 Ctx.PointOfInstantiation = Loc;
7582 Ctx.Entity = FD;
7583 S.pushCodeSynthesisContext(Ctx);
7584 }
~ComputingExceptionSpec__anon067e66481d11::ComputingExceptionSpec7585 ~ComputingExceptionSpec() {
7586 S.popCodeSynthesisContext();
7587 }
7588 };
7589 }
7590
7591 static Sema::ImplicitExceptionSpecification
7592 ComputeDefaultedSpecialMemberExceptionSpec(
7593 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7594 Sema::InheritedConstructorInfo *ICI);
7595
7596 static Sema::ImplicitExceptionSpecification
7597 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7598 FunctionDecl *FD,
7599 Sema::DefaultedComparisonKind DCK);
7600
7601 static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,FunctionDecl * FD)7602 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7603 auto DFK = S.getDefaultedFunctionKind(FD);
7604 if (DFK.isSpecialMember())
7605 return ComputeDefaultedSpecialMemberExceptionSpec(
7606 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7607 if (DFK.isComparison())
7608 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7609 DFK.asComparison());
7610
7611 auto *CD = cast<CXXConstructorDecl>(FD);
7612 assert(CD->getInheritedConstructor() &&
7613 "only defaulted functions and inherited constructors have implicit "
7614 "exception specs");
7615 Sema::InheritedConstructorInfo ICI(
7616 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7617 return ComputeDefaultedSpecialMemberExceptionSpec(
7618 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7619 }
7620
getImplicitMethodEPI(Sema & S,CXXMethodDecl * MD)7621 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7622 CXXMethodDecl *MD) {
7623 FunctionProtoType::ExtProtoInfo EPI;
7624
7625 // Build an exception specification pointing back at this member.
7626 EPI.ExceptionSpec.Type = EST_Unevaluated;
7627 EPI.ExceptionSpec.SourceDecl = MD;
7628
7629 // Set the calling convention to the default for C++ instance methods.
7630 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7631 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7632 /*IsCXXMethod=*/true));
7633 return EPI;
7634 }
7635
EvaluateImplicitExceptionSpec(SourceLocation Loc,FunctionDecl * FD)7636 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7637 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7638 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7639 return;
7640
7641 // Evaluate the exception specification.
7642 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7643 auto ESI = IES.getExceptionSpec();
7644
7645 // Update the type of the special member to use it.
7646 UpdateExceptionSpec(FD, ESI);
7647 }
7648
CheckExplicitlyDefaultedFunction(Scope * S,FunctionDecl * FD)7649 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7650 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7651
7652 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7653 if (!DefKind) {
7654 assert(FD->getDeclContext()->isDependentContext());
7655 return;
7656 }
7657
7658 if (DefKind.isComparison())
7659 UnusedPrivateFields.clear();
7660
7661 if (DefKind.isSpecialMember()
7662 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7663 DefKind.asSpecialMember(),
7664 FD->getDefaultLoc())
7665 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7666 FD->setInvalidDecl();
7667 }
7668
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,SourceLocation DefaultLoc)7669 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7670 CXXSpecialMember CSM,
7671 SourceLocation DefaultLoc) {
7672 CXXRecordDecl *RD = MD->getParent();
7673
7674 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7675 "not an explicitly-defaulted special member");
7676
7677 // Defer all checking for special members of a dependent type.
7678 if (RD->isDependentType())
7679 return false;
7680
7681 // Whether this was the first-declared instance of the constructor.
7682 // This affects whether we implicitly add an exception spec and constexpr.
7683 bool First = MD == MD->getCanonicalDecl();
7684
7685 bool HadError = false;
7686
7687 // C++11 [dcl.fct.def.default]p1:
7688 // A function that is explicitly defaulted shall
7689 // -- be a special member function [...] (checked elsewhere),
7690 // -- have the same type (except for ref-qualifiers, and except that a
7691 // copy operation can take a non-const reference) as an implicit
7692 // declaration, and
7693 // -- not have default arguments.
7694 // C++2a changes the second bullet to instead delete the function if it's
7695 // defaulted on its first declaration, unless it's "an assignment operator,
7696 // and its return type differs or its parameter type is not a reference".
7697 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7698 bool ShouldDeleteForTypeMismatch = false;
7699 unsigned ExpectedParams = 1;
7700 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7701 ExpectedParams = 0;
7702 if (MD->getNumExplicitParams() != ExpectedParams) {
7703 // This checks for default arguments: a copy or move constructor with a
7704 // default argument is classified as a default constructor, and assignment
7705 // operations and destructors can't have default arguments.
7706 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7707 << CSM << MD->getSourceRange();
7708 HadError = true;
7709 } else if (MD->isVariadic()) {
7710 if (DeleteOnTypeMismatch)
7711 ShouldDeleteForTypeMismatch = true;
7712 else {
7713 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7714 << CSM << MD->getSourceRange();
7715 HadError = true;
7716 }
7717 }
7718
7719 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7720
7721 bool CanHaveConstParam = false;
7722 if (CSM == CXXCopyConstructor)
7723 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7724 else if (CSM == CXXCopyAssignment)
7725 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7726
7727 QualType ReturnType = Context.VoidTy;
7728 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7729 // Check for return type matching.
7730 ReturnType = Type->getReturnType();
7731 QualType ThisType = MD->getFunctionObjectParameterType();
7732
7733 QualType DeclType = Context.getTypeDeclType(RD);
7734 DeclType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
7735 DeclType, nullptr);
7736 DeclType = Context.getAddrSpaceQualType(
7737 DeclType, ThisType.getQualifiers().getAddressSpace());
7738 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7739
7740 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7741 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7742 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7743 HadError = true;
7744 }
7745
7746 // A defaulted special member cannot have cv-qualifiers.
7747 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7748 if (DeleteOnTypeMismatch)
7749 ShouldDeleteForTypeMismatch = true;
7750 else {
7751 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7752 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7753 HadError = true;
7754 }
7755 }
7756 // [C++23][dcl.fct.def.default]/p2.2
7757 // if F2 has an implicit object parameter of type “reference to C”,
7758 // F1 may be an explicit object member function whose explicit object
7759 // parameter is of (possibly different) type “reference to C”,
7760 // in which case the type of F1 would differ from the type of F2
7761 // in that the type of F1 has an additional parameter;
7762 if (!Context.hasSameType(
7763 ThisType.getNonReferenceType().getUnqualifiedType(),
7764 Context.getRecordType(RD))) {
7765 if (DeleteOnTypeMismatch)
7766 ShouldDeleteForTypeMismatch = true;
7767 else {
7768 Diag(MD->getLocation(),
7769 diag::err_defaulted_special_member_explicit_object_mismatch)
7770 << (CSM == CXXMoveAssignment) << RD << MD->getSourceRange();
7771 HadError = true;
7772 }
7773 }
7774 }
7775
7776 // Check for parameter type matching.
7777 QualType ArgType =
7778 ExpectedParams
7779 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7780 : QualType();
7781 bool HasConstParam = false;
7782 if (ExpectedParams && ArgType->isReferenceType()) {
7783 // Argument must be reference to possibly-const T.
7784 QualType ReferentType = ArgType->getPointeeType();
7785 HasConstParam = ReferentType.isConstQualified();
7786
7787 if (ReferentType.isVolatileQualified()) {
7788 if (DeleteOnTypeMismatch)
7789 ShouldDeleteForTypeMismatch = true;
7790 else {
7791 Diag(MD->getLocation(),
7792 diag::err_defaulted_special_member_volatile_param) << CSM;
7793 HadError = true;
7794 }
7795 }
7796
7797 if (HasConstParam && !CanHaveConstParam) {
7798 if (DeleteOnTypeMismatch)
7799 ShouldDeleteForTypeMismatch = true;
7800 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7801 Diag(MD->getLocation(),
7802 diag::err_defaulted_special_member_copy_const_param)
7803 << (CSM == CXXCopyAssignment);
7804 // FIXME: Explain why this special member can't be const.
7805 HadError = true;
7806 } else {
7807 Diag(MD->getLocation(),
7808 diag::err_defaulted_special_member_move_const_param)
7809 << (CSM == CXXMoveAssignment);
7810 HadError = true;
7811 }
7812 }
7813 } else if (ExpectedParams) {
7814 // A copy assignment operator can take its argument by value, but a
7815 // defaulted one cannot.
7816 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7817 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7818 HadError = true;
7819 }
7820
7821 // C++11 [dcl.fct.def.default]p2:
7822 // An explicitly-defaulted function may be declared constexpr only if it
7823 // would have been implicitly declared as constexpr,
7824 // Do not apply this rule to members of class templates, since core issue 1358
7825 // makes such functions always instantiate to constexpr functions. For
7826 // functions which cannot be constexpr (for non-constructors in C++11 and for
7827 // destructors in C++14 and C++17), this is checked elsewhere.
7828 //
7829 // FIXME: This should not apply if the member is deleted.
7830 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7831 HasConstParam);
7832
7833 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7834 // If the instantiated template specialization of a constexpr function
7835 // template or member function of a class template would fail to satisfy
7836 // the requirements for a constexpr function or constexpr constructor, that
7837 // specialization is still a constexpr function or constexpr constructor,
7838 // even though a call to such a function cannot appear in a constant
7839 // expression.
7840 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7841 Constexpr = true;
7842
7843 if ((getLangOpts().CPlusPlus20 ||
7844 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7845 : isa<CXXConstructorDecl>(MD))) &&
7846 MD->isConstexpr() && !Constexpr &&
7847 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7848 if (!MD->isConsteval() && RD->getNumVBases()) {
7849 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr_with_vb)
7850 << CSM;
7851 for (const auto &I : RD->vbases())
7852 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7853 } else {
7854 Diag(MD->getBeginLoc(), MD->isConsteval()
7855 ? diag::err_incorrect_defaulted_consteval
7856 : diag::err_incorrect_defaulted_constexpr)
7857 << CSM;
7858 }
7859 // FIXME: Explain why the special member can't be constexpr.
7860 HadError = true;
7861 }
7862
7863 if (First) {
7864 // C++2a [dcl.fct.def.default]p3:
7865 // If a function is explicitly defaulted on its first declaration, it is
7866 // implicitly considered to be constexpr if the implicit declaration
7867 // would be.
7868 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7869 ? ConstexprSpecKind::Consteval
7870 : ConstexprSpecKind::Constexpr)
7871 : ConstexprSpecKind::Unspecified);
7872
7873 if (!Type->hasExceptionSpec()) {
7874 // C++2a [except.spec]p3:
7875 // If a declaration of a function does not have a noexcept-specifier
7876 // [and] is defaulted on its first declaration, [...] the exception
7877 // specification is as specified below
7878 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7879 EPI.ExceptionSpec.Type = EST_Unevaluated;
7880 EPI.ExceptionSpec.SourceDecl = MD;
7881 MD->setType(
7882 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7883 }
7884 }
7885
7886 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7887 if (First) {
7888 SetDeclDeleted(MD, MD->getLocation());
7889 if (!inTemplateInstantiation() && !HadError) {
7890 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7891 if (ShouldDeleteForTypeMismatch) {
7892 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7893 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7894 /*Diagnose*/ true) &&
7895 DefaultLoc.isValid()) {
7896 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7897 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7898 }
7899 }
7900 if (ShouldDeleteForTypeMismatch && !HadError) {
7901 Diag(MD->getLocation(),
7902 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7903 }
7904 } else {
7905 // C++11 [dcl.fct.def.default]p4:
7906 // [For a] user-provided explicitly-defaulted function [...] if such a
7907 // function is implicitly defined as deleted, the program is ill-formed.
7908 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7909 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7910 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7911 HadError = true;
7912 }
7913 }
7914
7915 return HadError;
7916 }
7917
7918 namespace {
7919 /// Helper class for building and checking a defaulted comparison.
7920 ///
7921 /// Defaulted functions are built in two phases:
7922 ///
7923 /// * First, the set of operations that the function will perform are
7924 /// identified, and some of them are checked. If any of the checked
7925 /// operations is invalid in certain ways, the comparison function is
7926 /// defined as deleted and no body is built.
7927 /// * Then, if the function is not defined as deleted, the body is built.
7928 ///
7929 /// This is accomplished by performing two visitation steps over the eventual
7930 /// body of the function.
7931 template<typename Derived, typename ResultList, typename Result,
7932 typename Subobject>
7933 class DefaultedComparisonVisitor {
7934 public:
7935 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7936
DefaultedComparisonVisitor(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK)7937 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7938 DefaultedComparisonKind DCK)
7939 : S(S), RD(RD), FD(FD), DCK(DCK) {
7940 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7941 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7942 // UnresolvedSet to avoid this copy.
7943 Fns.assign(Info->getUnqualifiedLookups().begin(),
7944 Info->getUnqualifiedLookups().end());
7945 }
7946 }
7947
visit()7948 ResultList visit() {
7949 // The type of an lvalue naming a parameter of this function.
7950 QualType ParamLvalType =
7951 FD->getParamDecl(0)->getType().getNonReferenceType();
7952
7953 ResultList Results;
7954
7955 switch (DCK) {
7956 case DefaultedComparisonKind::None:
7957 llvm_unreachable("not a defaulted comparison");
7958
7959 case DefaultedComparisonKind::Equal:
7960 case DefaultedComparisonKind::ThreeWay:
7961 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7962 return Results;
7963
7964 case DefaultedComparisonKind::NotEqual:
7965 case DefaultedComparisonKind::Relational:
7966 Results.add(getDerived().visitExpandedSubobject(
7967 ParamLvalType, getDerived().getCompleteObject()));
7968 return Results;
7969 }
7970 llvm_unreachable("");
7971 }
7972
7973 protected:
getDerived()7974 Derived &getDerived() { return static_cast<Derived&>(*this); }
7975
7976 /// Visit the expanded list of subobjects of the given type, as specified in
7977 /// C++2a [class.compare.default].
7978 ///
7979 /// \return \c true if the ResultList object said we're done, \c false if not.
visitSubobjects(ResultList & Results,CXXRecordDecl * Record,Qualifiers Quals)7980 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7981 Qualifiers Quals) {
7982 // C++2a [class.compare.default]p4:
7983 // The direct base class subobjects of C
7984 for (CXXBaseSpecifier &Base : Record->bases())
7985 if (Results.add(getDerived().visitSubobject(
7986 S.Context.getQualifiedType(Base.getType(), Quals),
7987 getDerived().getBase(&Base))))
7988 return true;
7989
7990 // followed by the non-static data members of C
7991 for (FieldDecl *Field : Record->fields()) {
7992 // C++23 [class.bit]p2:
7993 // Unnamed bit-fields are not members ...
7994 if (Field->isUnnamedBitfield())
7995 continue;
7996 // Recursively expand anonymous structs.
7997 if (Field->isAnonymousStructOrUnion()) {
7998 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7999 Quals))
8000 return true;
8001 continue;
8002 }
8003
8004 // Figure out the type of an lvalue denoting this field.
8005 Qualifiers FieldQuals = Quals;
8006 if (Field->isMutable())
8007 FieldQuals.removeConst();
8008 QualType FieldType =
8009 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8010
8011 if (Results.add(getDerived().visitSubobject(
8012 FieldType, getDerived().getField(Field))))
8013 return true;
8014 }
8015
8016 // form a list of subobjects.
8017 return false;
8018 }
8019
visitSubobject(QualType Type,Subobject Subobj)8020 Result visitSubobject(QualType Type, Subobject Subobj) {
8021 // In that list, any subobject of array type is recursively expanded
8022 const ArrayType *AT = S.Context.getAsArrayType(Type);
8023 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8024 return getDerived().visitSubobjectArray(CAT->getElementType(),
8025 CAT->getSize(), Subobj);
8026 return getDerived().visitExpandedSubobject(Type, Subobj);
8027 }
8028
visitSubobjectArray(QualType Type,const llvm::APInt & Size,Subobject Subobj)8029 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8030 Subobject Subobj) {
8031 return getDerived().visitSubobject(Type, Subobj);
8032 }
8033
8034 protected:
8035 Sema &S;
8036 CXXRecordDecl *RD;
8037 FunctionDecl *FD;
8038 DefaultedComparisonKind DCK;
8039 UnresolvedSet<16> Fns;
8040 };
8041
8042 /// Information about a defaulted comparison, as determined by
8043 /// DefaultedComparisonAnalyzer.
8044 struct DefaultedComparisonInfo {
8045 bool Deleted = false;
8046 bool Constexpr = true;
8047 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8048
deleted__anon067e66481e11::DefaultedComparisonInfo8049 static DefaultedComparisonInfo deleted() {
8050 DefaultedComparisonInfo Deleted;
8051 Deleted.Deleted = true;
8052 return Deleted;
8053 }
8054
add__anon067e66481e11::DefaultedComparisonInfo8055 bool add(const DefaultedComparisonInfo &R) {
8056 Deleted |= R.Deleted;
8057 Constexpr &= R.Constexpr;
8058 Category = commonComparisonType(Category, R.Category);
8059 return Deleted;
8060 }
8061 };
8062
8063 /// An element in the expanded list of subobjects of a defaulted comparison, as
8064 /// specified in C++2a [class.compare.default]p4.
8065 struct DefaultedComparisonSubobject {
8066 enum { CompleteObject, Member, Base } Kind;
8067 NamedDecl *Decl;
8068 SourceLocation Loc;
8069 };
8070
8071 /// A visitor over the notional body of a defaulted comparison that determines
8072 /// whether that body would be deleted or constexpr.
8073 class DefaultedComparisonAnalyzer
8074 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8075 DefaultedComparisonInfo,
8076 DefaultedComparisonInfo,
8077 DefaultedComparisonSubobject> {
8078 public:
8079 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8080
8081 private:
8082 DiagnosticKind Diagnose;
8083
8084 public:
8085 using Base = DefaultedComparisonVisitor;
8086 using Result = DefaultedComparisonInfo;
8087 using Subobject = DefaultedComparisonSubobject;
8088
8089 friend Base;
8090
DefaultedComparisonAnalyzer(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK,DiagnosticKind Diagnose=NoDiagnostics)8091 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8092 DefaultedComparisonKind DCK,
8093 DiagnosticKind Diagnose = NoDiagnostics)
8094 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8095
visit()8096 Result visit() {
8097 if ((DCK == DefaultedComparisonKind::Equal ||
8098 DCK == DefaultedComparisonKind::ThreeWay) &&
8099 RD->hasVariantMembers()) {
8100 // C++2a [class.compare.default]p2 [P2002R0]:
8101 // A defaulted comparison operator function for class C is defined as
8102 // deleted if [...] C has variant members.
8103 if (Diagnose == ExplainDeleted) {
8104 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8105 << FD << RD->isUnion() << RD;
8106 }
8107 return Result::deleted();
8108 }
8109
8110 return Base::visit();
8111 }
8112
8113 private:
getCompleteObject()8114 Subobject getCompleteObject() {
8115 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8116 }
8117
getBase(CXXBaseSpecifier * Base)8118 Subobject getBase(CXXBaseSpecifier *Base) {
8119 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8120 Base->getBaseTypeLoc()};
8121 }
8122
getField(FieldDecl * Field)8123 Subobject getField(FieldDecl *Field) {
8124 return Subobject{Subobject::Member, Field, Field->getLocation()};
8125 }
8126
visitExpandedSubobject(QualType Type,Subobject Subobj)8127 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8128 // C++2a [class.compare.default]p2 [P2002R0]:
8129 // A defaulted <=> or == operator function for class C is defined as
8130 // deleted if any non-static data member of C is of reference type
8131 if (Type->isReferenceType()) {
8132 if (Diagnose == ExplainDeleted) {
8133 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8134 << FD << RD;
8135 }
8136 return Result::deleted();
8137 }
8138
8139 // [...] Let xi be an lvalue denoting the ith element [...]
8140 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8141 Expr *Args[] = {&Xi, &Xi};
8142
8143 // All operators start by trying to apply that same operator recursively.
8144 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8145 assert(OO != OO_None && "not an overloaded operator!");
8146 return visitBinaryOperator(OO, Args, Subobj);
8147 }
8148
8149 Result
visitBinaryOperator(OverloadedOperatorKind OO,ArrayRef<Expr * > Args,Subobject Subobj,OverloadCandidateSet * SpaceshipCandidates=nullptr)8150 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8151 Subobject Subobj,
8152 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8153 // Note that there is no need to consider rewritten candidates here if
8154 // we've already found there is no viable 'operator<=>' candidate (and are
8155 // considering synthesizing a '<=>' from '==' and '<').
8156 OverloadCandidateSet CandidateSet(
8157 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8158 OverloadCandidateSet::OperatorRewriteInfo(
8159 OO, FD->getLocation(),
8160 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8161
8162 /// C++2a [class.compare.default]p1 [P2002R0]:
8163 /// [...] the defaulted function itself is never a candidate for overload
8164 /// resolution [...]
8165 CandidateSet.exclude(FD);
8166
8167 if (Args[0]->getType()->isOverloadableType())
8168 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8169 else
8170 // FIXME: We determine whether this is a valid expression by checking to
8171 // see if there's a viable builtin operator candidate for it. That isn't
8172 // really what the rules ask us to do, but should give the right results.
8173 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8174
8175 Result R;
8176
8177 OverloadCandidateSet::iterator Best;
8178 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8179 case OR_Success: {
8180 // C++2a [class.compare.secondary]p2 [P2002R0]:
8181 // The operator function [...] is defined as deleted if [...] the
8182 // candidate selected by overload resolution is not a rewritten
8183 // candidate.
8184 if ((DCK == DefaultedComparisonKind::NotEqual ||
8185 DCK == DefaultedComparisonKind::Relational) &&
8186 !Best->RewriteKind) {
8187 if (Diagnose == ExplainDeleted) {
8188 if (Best->Function) {
8189 S.Diag(Best->Function->getLocation(),
8190 diag::note_defaulted_comparison_not_rewritten_callee)
8191 << FD;
8192 } else {
8193 assert(Best->Conversions.size() == 2 &&
8194 Best->Conversions[0].isUserDefined() &&
8195 "non-user-defined conversion from class to built-in "
8196 "comparison");
8197 S.Diag(Best->Conversions[0]
8198 .UserDefined.FoundConversionFunction.getDecl()
8199 ->getLocation(),
8200 diag::note_defaulted_comparison_not_rewritten_conversion)
8201 << FD;
8202 }
8203 }
8204 return Result::deleted();
8205 }
8206
8207 // Throughout C++2a [class.compare]: if overload resolution does not
8208 // result in a usable function, the candidate function is defined as
8209 // deleted. This requires that we selected an accessible function.
8210 //
8211 // Note that this only considers the access of the function when named
8212 // within the type of the subobject, and not the access path for any
8213 // derived-to-base conversion.
8214 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8215 if (ArgClass && Best->FoundDecl.getDecl() &&
8216 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8217 QualType ObjectType = Subobj.Kind == Subobject::Member
8218 ? Args[0]->getType()
8219 : S.Context.getRecordType(RD);
8220 if (!S.isMemberAccessibleForDeletion(
8221 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8222 Diagnose == ExplainDeleted
8223 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8224 << FD << Subobj.Kind << Subobj.Decl
8225 : S.PDiag()))
8226 return Result::deleted();
8227 }
8228
8229 bool NeedsDeducing =
8230 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8231
8232 if (FunctionDecl *BestFD = Best->Function) {
8233 // C++2a [class.compare.default]p3 [P2002R0]:
8234 // A defaulted comparison function is constexpr-compatible if
8235 // [...] no overlod resolution performed [...] results in a
8236 // non-constexpr function.
8237 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8238 // If it's not constexpr, explain why not.
8239 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8240 if (Subobj.Kind != Subobject::CompleteObject)
8241 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8242 << Subobj.Kind << Subobj.Decl;
8243 S.Diag(BestFD->getLocation(),
8244 diag::note_defaulted_comparison_not_constexpr_here);
8245 // Bail out after explaining; we don't want any more notes.
8246 return Result::deleted();
8247 }
8248 R.Constexpr &= BestFD->isConstexpr();
8249
8250 if (NeedsDeducing) {
8251 // If any callee has an undeduced return type, deduce it now.
8252 // FIXME: It's not clear how a failure here should be handled. For
8253 // now, we produce an eager diagnostic, because that is forward
8254 // compatible with most (all?) other reasonable options.
8255 if (BestFD->getReturnType()->isUndeducedType() &&
8256 S.DeduceReturnType(BestFD, FD->getLocation(),
8257 /*Diagnose=*/false)) {
8258 // Don't produce a duplicate error when asked to explain why the
8259 // comparison is deleted: we diagnosed that when initially checking
8260 // the defaulted operator.
8261 if (Diagnose == NoDiagnostics) {
8262 S.Diag(
8263 FD->getLocation(),
8264 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8265 << Subobj.Kind << Subobj.Decl;
8266 S.Diag(
8267 Subobj.Loc,
8268 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8269 << Subobj.Kind << Subobj.Decl;
8270 S.Diag(BestFD->getLocation(),
8271 diag::note_defaulted_comparison_cannot_deduce_callee)
8272 << Subobj.Kind << Subobj.Decl;
8273 }
8274 return Result::deleted();
8275 }
8276 auto *Info = S.Context.CompCategories.lookupInfoForType(
8277 BestFD->getCallResultType());
8278 if (!Info) {
8279 if (Diagnose == ExplainDeleted) {
8280 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8281 << Subobj.Kind << Subobj.Decl
8282 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8283 S.Diag(BestFD->getLocation(),
8284 diag::note_defaulted_comparison_cannot_deduce_callee)
8285 << Subobj.Kind << Subobj.Decl;
8286 }
8287 return Result::deleted();
8288 }
8289 R.Category = Info->Kind;
8290 }
8291 } else {
8292 QualType T = Best->BuiltinParamTypes[0];
8293 assert(T == Best->BuiltinParamTypes[1] &&
8294 "builtin comparison for different types?");
8295 assert(Best->BuiltinParamTypes[2].isNull() &&
8296 "invalid builtin comparison");
8297
8298 if (NeedsDeducing) {
8299 std::optional<ComparisonCategoryType> Cat =
8300 getComparisonCategoryForBuiltinCmp(T);
8301 assert(Cat && "no category for builtin comparison?");
8302 R.Category = *Cat;
8303 }
8304 }
8305
8306 // Note that we might be rewriting to a different operator. That call is
8307 // not considered until we come to actually build the comparison function.
8308 break;
8309 }
8310
8311 case OR_Ambiguous:
8312 if (Diagnose == ExplainDeleted) {
8313 unsigned Kind = 0;
8314 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8315 Kind = OO == OO_EqualEqual ? 1 : 2;
8316 CandidateSet.NoteCandidates(
8317 PartialDiagnosticAt(
8318 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8319 << FD << Kind << Subobj.Kind << Subobj.Decl),
8320 S, OCD_AmbiguousCandidates, Args);
8321 }
8322 R = Result::deleted();
8323 break;
8324
8325 case OR_Deleted:
8326 if (Diagnose == ExplainDeleted) {
8327 if ((DCK == DefaultedComparisonKind::NotEqual ||
8328 DCK == DefaultedComparisonKind::Relational) &&
8329 !Best->RewriteKind) {
8330 S.Diag(Best->Function->getLocation(),
8331 diag::note_defaulted_comparison_not_rewritten_callee)
8332 << FD;
8333 } else {
8334 S.Diag(Subobj.Loc,
8335 diag::note_defaulted_comparison_calls_deleted)
8336 << FD << Subobj.Kind << Subobj.Decl;
8337 S.NoteDeletedFunction(Best->Function);
8338 }
8339 }
8340 R = Result::deleted();
8341 break;
8342
8343 case OR_No_Viable_Function:
8344 // If there's no usable candidate, we're done unless we can rewrite a
8345 // '<=>' in terms of '==' and '<'.
8346 if (OO == OO_Spaceship &&
8347 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8348 // For any kind of comparison category return type, we need a usable
8349 // '==' and a usable '<'.
8350 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8351 &CandidateSet)))
8352 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8353 break;
8354 }
8355
8356 if (Diagnose == ExplainDeleted) {
8357 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8358 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8359 << Subobj.Kind << Subobj.Decl;
8360
8361 // For a three-way comparison, list both the candidates for the
8362 // original operator and the candidates for the synthesized operator.
8363 if (SpaceshipCandidates) {
8364 SpaceshipCandidates->NoteCandidates(
8365 S, Args,
8366 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8367 Args, FD->getLocation()));
8368 S.Diag(Subobj.Loc,
8369 diag::note_defaulted_comparison_no_viable_function_synthesized)
8370 << (OO == OO_EqualEqual ? 0 : 1);
8371 }
8372
8373 CandidateSet.NoteCandidates(
8374 S, Args,
8375 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8376 FD->getLocation()));
8377 }
8378 R = Result::deleted();
8379 break;
8380 }
8381
8382 return R;
8383 }
8384 };
8385
8386 /// A list of statements.
8387 struct StmtListResult {
8388 bool IsInvalid = false;
8389 llvm::SmallVector<Stmt*, 16> Stmts;
8390
add__anon067e66481e11::StmtListResult8391 bool add(const StmtResult &S) {
8392 IsInvalid |= S.isInvalid();
8393 if (IsInvalid)
8394 return true;
8395 Stmts.push_back(S.get());
8396 return false;
8397 }
8398 };
8399
8400 /// A visitor over the notional body of a defaulted comparison that synthesizes
8401 /// the actual body.
8402 class DefaultedComparisonSynthesizer
8403 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8404 StmtListResult, StmtResult,
8405 std::pair<ExprResult, ExprResult>> {
8406 SourceLocation Loc;
8407 unsigned ArrayDepth = 0;
8408
8409 public:
8410 using Base = DefaultedComparisonVisitor;
8411 using ExprPair = std::pair<ExprResult, ExprResult>;
8412
8413 friend Base;
8414
DefaultedComparisonSynthesizer(Sema & S,CXXRecordDecl * RD,FunctionDecl * FD,DefaultedComparisonKind DCK,SourceLocation BodyLoc)8415 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8416 DefaultedComparisonKind DCK,
8417 SourceLocation BodyLoc)
8418 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8419
8420 /// Build a suitable function body for this defaulted comparison operator.
build()8421 StmtResult build() {
8422 Sema::CompoundScopeRAII CompoundScope(S);
8423
8424 StmtListResult Stmts = visit();
8425 if (Stmts.IsInvalid)
8426 return StmtError();
8427
8428 ExprResult RetVal;
8429 switch (DCK) {
8430 case DefaultedComparisonKind::None:
8431 llvm_unreachable("not a defaulted comparison");
8432
8433 case DefaultedComparisonKind::Equal: {
8434 // C++2a [class.eq]p3:
8435 // [...] compar[e] the corresponding elements [...] until the first
8436 // index i where xi == yi yields [...] false. If no such index exists,
8437 // V is true. Otherwise, V is false.
8438 //
8439 // Join the comparisons with '&&'s and return the result. Use a right
8440 // fold (traversing the conditions right-to-left), because that
8441 // short-circuits more naturally.
8442 auto OldStmts = std::move(Stmts.Stmts);
8443 Stmts.Stmts.clear();
8444 ExprResult CmpSoFar;
8445 // Finish a particular comparison chain.
8446 auto FinishCmp = [&] {
8447 if (Expr *Prior = CmpSoFar.get()) {
8448 // Convert the last expression to 'return ...;'
8449 if (RetVal.isUnset() && Stmts.Stmts.empty())
8450 RetVal = CmpSoFar;
8451 // Convert any prior comparison to 'if (!(...)) return false;'
8452 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8453 return true;
8454 CmpSoFar = ExprResult();
8455 }
8456 return false;
8457 };
8458 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8459 Expr *E = dyn_cast<Expr>(EAsStmt);
8460 if (!E) {
8461 // Found an array comparison.
8462 if (FinishCmp() || Stmts.add(EAsStmt))
8463 return StmtError();
8464 continue;
8465 }
8466
8467 if (CmpSoFar.isUnset()) {
8468 CmpSoFar = E;
8469 continue;
8470 }
8471 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8472 if (CmpSoFar.isInvalid())
8473 return StmtError();
8474 }
8475 if (FinishCmp())
8476 return StmtError();
8477 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8478 // If no such index exists, V is true.
8479 if (RetVal.isUnset())
8480 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8481 break;
8482 }
8483
8484 case DefaultedComparisonKind::ThreeWay: {
8485 // Per C++2a [class.spaceship]p3, as a fallback add:
8486 // return static_cast<R>(std::strong_ordering::equal);
8487 QualType StrongOrdering = S.CheckComparisonCategoryType(
8488 ComparisonCategoryType::StrongOrdering, Loc,
8489 Sema::ComparisonCategoryUsage::DefaultedOperator);
8490 if (StrongOrdering.isNull())
8491 return StmtError();
8492 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8493 .getValueInfo(ComparisonCategoryResult::Equal)
8494 ->VD;
8495 RetVal = getDecl(EqualVD);
8496 if (RetVal.isInvalid())
8497 return StmtError();
8498 RetVal = buildStaticCastToR(RetVal.get());
8499 break;
8500 }
8501
8502 case DefaultedComparisonKind::NotEqual:
8503 case DefaultedComparisonKind::Relational:
8504 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8505 break;
8506 }
8507
8508 // Build the final return statement.
8509 if (RetVal.isInvalid())
8510 return StmtError();
8511 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8512 if (ReturnStmt.isInvalid())
8513 return StmtError();
8514 Stmts.Stmts.push_back(ReturnStmt.get());
8515
8516 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8517 }
8518
8519 private:
getDecl(ValueDecl * VD)8520 ExprResult getDecl(ValueDecl *VD) {
8521 return S.BuildDeclarationNameExpr(
8522 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8523 }
8524
getParam(unsigned I)8525 ExprResult getParam(unsigned I) {
8526 ParmVarDecl *PD = FD->getParamDecl(I);
8527 return getDecl(PD);
8528 }
8529
getCompleteObject()8530 ExprPair getCompleteObject() {
8531 unsigned Param = 0;
8532 ExprResult LHS;
8533 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8534 MD && MD->isImplicitObjectMemberFunction()) {
8535 // LHS is '*this'.
8536 LHS = S.ActOnCXXThis(Loc);
8537 if (!LHS.isInvalid())
8538 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8539 } else {
8540 LHS = getParam(Param++);
8541 }
8542 ExprResult RHS = getParam(Param++);
8543 assert(Param == FD->getNumParams());
8544 return {LHS, RHS};
8545 }
8546
getBase(CXXBaseSpecifier * Base)8547 ExprPair getBase(CXXBaseSpecifier *Base) {
8548 ExprPair Obj = getCompleteObject();
8549 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8550 return {ExprError(), ExprError()};
8551 CXXCastPath Path = {Base};
8552 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8553 CK_DerivedToBase, VK_LValue, &Path),
8554 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8555 CK_DerivedToBase, VK_LValue, &Path)};
8556 }
8557
getField(FieldDecl * Field)8558 ExprPair getField(FieldDecl *Field) {
8559 ExprPair Obj = getCompleteObject();
8560 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8561 return {ExprError(), ExprError()};
8562
8563 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8564 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8565 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8566 CXXScopeSpec(), Field, Found, NameInfo),
8567 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8568 CXXScopeSpec(), Field, Found, NameInfo)};
8569 }
8570
8571 // FIXME: When expanding a subobject, register a note in the code synthesis
8572 // stack to say which subobject we're comparing.
8573
buildIfNotCondReturnFalse(ExprResult Cond)8574 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8575 if (Cond.isInvalid())
8576 return StmtError();
8577
8578 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8579 if (NotCond.isInvalid())
8580 return StmtError();
8581
8582 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8583 assert(!False.isInvalid() && "should never fail");
8584 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8585 if (ReturnFalse.isInvalid())
8586 return StmtError();
8587
8588 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8589 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8590 Sema::ConditionKind::Boolean),
8591 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8592 }
8593
visitSubobjectArray(QualType Type,llvm::APInt Size,ExprPair Subobj)8594 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8595 ExprPair Subobj) {
8596 QualType SizeType = S.Context.getSizeType();
8597 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8598
8599 // Build 'size_t i$n = 0'.
8600 IdentifierInfo *IterationVarName = nullptr;
8601 {
8602 SmallString<8> Str;
8603 llvm::raw_svector_ostream OS(Str);
8604 OS << "i" << ArrayDepth;
8605 IterationVarName = &S.Context.Idents.get(OS.str());
8606 }
8607 VarDecl *IterationVar = VarDecl::Create(
8608 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8609 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8610 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8611 IterationVar->setInit(
8612 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8613 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8614
8615 auto IterRef = [&] {
8616 ExprResult Ref = S.BuildDeclarationNameExpr(
8617 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8618 IterationVar);
8619 assert(!Ref.isInvalid() && "can't reference our own variable?");
8620 return Ref.get();
8621 };
8622
8623 // Build 'i$n != Size'.
8624 ExprResult Cond = S.CreateBuiltinBinOp(
8625 Loc, BO_NE, IterRef(),
8626 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8627 assert(!Cond.isInvalid() && "should never fail");
8628
8629 // Build '++i$n'.
8630 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8631 assert(!Inc.isInvalid() && "should never fail");
8632
8633 // Build 'a[i$n]' and 'b[i$n]'.
8634 auto Index = [&](ExprResult E) {
8635 if (E.isInvalid())
8636 return ExprError();
8637 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8638 };
8639 Subobj.first = Index(Subobj.first);
8640 Subobj.second = Index(Subobj.second);
8641
8642 // Compare the array elements.
8643 ++ArrayDepth;
8644 StmtResult Substmt = visitSubobject(Type, Subobj);
8645 --ArrayDepth;
8646
8647 if (Substmt.isInvalid())
8648 return StmtError();
8649
8650 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8651 // For outer levels or for an 'operator<=>' we already have a suitable
8652 // statement that returns as necessary.
8653 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8654 assert(DCK == DefaultedComparisonKind::Equal &&
8655 "should have non-expression statement");
8656 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8657 if (Substmt.isInvalid())
8658 return StmtError();
8659 }
8660
8661 // Build 'for (...) ...'
8662 return S.ActOnForStmt(Loc, Loc, Init,
8663 S.ActOnCondition(nullptr, Loc, Cond.get(),
8664 Sema::ConditionKind::Boolean),
8665 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8666 Substmt.get());
8667 }
8668
visitExpandedSubobject(QualType Type,ExprPair Obj)8669 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8670 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8671 return StmtError();
8672
8673 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8674 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8675 ExprResult Op;
8676 if (Type->isOverloadableType())
8677 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8678 Obj.second.get(), /*PerformADL=*/true,
8679 /*AllowRewrittenCandidates=*/true, FD);
8680 else
8681 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8682 if (Op.isInvalid())
8683 return StmtError();
8684
8685 switch (DCK) {
8686 case DefaultedComparisonKind::None:
8687 llvm_unreachable("not a defaulted comparison");
8688
8689 case DefaultedComparisonKind::Equal:
8690 // Per C++2a [class.eq]p2, each comparison is individually contextually
8691 // converted to bool.
8692 Op = S.PerformContextuallyConvertToBool(Op.get());
8693 if (Op.isInvalid())
8694 return StmtError();
8695 return Op.get();
8696
8697 case DefaultedComparisonKind::ThreeWay: {
8698 // Per C++2a [class.spaceship]p3, form:
8699 // if (R cmp = static_cast<R>(op); cmp != 0)
8700 // return cmp;
8701 QualType R = FD->getReturnType();
8702 Op = buildStaticCastToR(Op.get());
8703 if (Op.isInvalid())
8704 return StmtError();
8705
8706 // R cmp = ...;
8707 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8708 VarDecl *VD =
8709 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8710 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8711 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8712 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8713
8714 // cmp != 0
8715 ExprResult VDRef = getDecl(VD);
8716 if (VDRef.isInvalid())
8717 return StmtError();
8718 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8719 Expr *Zero =
8720 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8721 ExprResult Comp;
8722 if (VDRef.get()->getType()->isOverloadableType())
8723 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8724 true, FD);
8725 else
8726 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8727 if (Comp.isInvalid())
8728 return StmtError();
8729 Sema::ConditionResult Cond = S.ActOnCondition(
8730 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8731 if (Cond.isInvalid())
8732 return StmtError();
8733
8734 // return cmp;
8735 VDRef = getDecl(VD);
8736 if (VDRef.isInvalid())
8737 return StmtError();
8738 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8739 if (ReturnStmt.isInvalid())
8740 return StmtError();
8741
8742 // if (...)
8743 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8744 Loc, ReturnStmt.get(),
8745 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8746 }
8747
8748 case DefaultedComparisonKind::NotEqual:
8749 case DefaultedComparisonKind::Relational:
8750 // C++2a [class.compare.secondary]p2:
8751 // Otherwise, the operator function yields x @ y.
8752 return Op.get();
8753 }
8754 llvm_unreachable("");
8755 }
8756
8757 /// Build "static_cast<R>(E)".
buildStaticCastToR(Expr * E)8758 ExprResult buildStaticCastToR(Expr *E) {
8759 QualType R = FD->getReturnType();
8760 assert(!R->isUndeducedType() && "type should have been deduced already");
8761
8762 // Don't bother forming a no-op cast in the common case.
8763 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8764 return E;
8765 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8766 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8767 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8768 }
8769 };
8770 }
8771
8772 /// Perform the unqualified lookups that might be needed to form a defaulted
8773 /// comparison function for the given operator.
lookupOperatorsForDefaultedComparison(Sema & Self,Scope * S,UnresolvedSetImpl & Operators,OverloadedOperatorKind Op)8774 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8775 UnresolvedSetImpl &Operators,
8776 OverloadedOperatorKind Op) {
8777 auto Lookup = [&](OverloadedOperatorKind OO) {
8778 Self.LookupOverloadedOperatorName(OO, S, Operators);
8779 };
8780
8781 // Every defaulted operator looks up itself.
8782 Lookup(Op);
8783 // ... and the rewritten form of itself, if any.
8784 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8785 Lookup(ExtraOp);
8786
8787 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8788 // synthesize a three-way comparison from '<' and '=='. In a dependent
8789 // context, we also need to look up '==' in case we implicitly declare a
8790 // defaulted 'operator=='.
8791 if (Op == OO_Spaceship) {
8792 Lookup(OO_ExclaimEqual);
8793 Lookup(OO_Less);
8794 Lookup(OO_EqualEqual);
8795 }
8796 }
8797
CheckExplicitlyDefaultedComparison(Scope * S,FunctionDecl * FD,DefaultedComparisonKind DCK)8798 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8799 DefaultedComparisonKind DCK) {
8800 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8801
8802 // Perform any unqualified lookups we're going to need to default this
8803 // function.
8804 if (S) {
8805 UnresolvedSet<32> Operators;
8806 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8807 FD->getOverloadedOperator());
8808 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8809 Context, Operators.pairs()));
8810 }
8811
8812 // C++2a [class.compare.default]p1:
8813 // A defaulted comparison operator function for some class C shall be a
8814 // non-template function declared in the member-specification of C that is
8815 // -- a non-static const non-volatile member of C having one parameter of
8816 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8817 // -- a friend of C having two parameters of type const C& or two
8818 // parameters of type C.
8819
8820 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8821 bool IsMethod = isa<CXXMethodDecl>(FD);
8822 if (IsMethod) {
8823 auto *MD = cast<CXXMethodDecl>(FD);
8824 assert(!MD->isStatic() && "comparison function cannot be a static member");
8825
8826 if (MD->getRefQualifier() == RQ_RValue) {
8827 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8828
8829 // Remove the ref qualifier to recover.
8830 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8831 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8832 EPI.RefQualifier = RQ_None;
8833 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8834 FPT->getParamTypes(), EPI));
8835 }
8836
8837 // If we're out-of-class, this is the class we're comparing.
8838 if (!RD)
8839 RD = MD->getParent();
8840 QualType T = MD->getFunctionObjectParameterType();
8841 if (!T.isConstQualified()) {
8842 SourceLocation Loc, InsertLoc;
8843 if (MD->isExplicitObjectMemberFunction()) {
8844 Loc = MD->getParamDecl(0)->getBeginLoc();
8845 InsertLoc = getLocForEndOfToken(
8846 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8847 } else {
8848 Loc = MD->getLocation();
8849 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8850 InsertLoc = Loc.getRParenLoc();
8851 }
8852 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8853 // corresponding defaulted 'operator<=>' already.
8854 if (!MD->isImplicit()) {
8855 Diag(Loc, diag::err_defaulted_comparison_non_const)
8856 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8857 }
8858
8859 // Add the 'const' to the type to recover.
8860 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8861 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8862 EPI.TypeQuals.addConst();
8863 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8864 FPT->getParamTypes(), EPI));
8865 }
8866
8867 if (MD->isVolatile()) {
8868 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8869
8870 // Remove the 'volatile' from the type to recover.
8871 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8872 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8873 EPI.TypeQuals.removeVolatile();
8874 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8875 FPT->getParamTypes(), EPI));
8876 }
8877 }
8878
8879 if ((FD->getNumParams() -
8880 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8881 (IsMethod ? 1 : 2)) {
8882 // Let's not worry about using a variadic template pack here -- who would do
8883 // such a thing?
8884 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8885 << int(IsMethod) << int(DCK);
8886 return true;
8887 }
8888
8889 const ParmVarDecl *KnownParm = nullptr;
8890 for (const ParmVarDecl *Param : FD->parameters()) {
8891 if (Param->isExplicitObjectParameter())
8892 continue;
8893 QualType ParmTy = Param->getType();
8894
8895 if (!KnownParm) {
8896 auto CTy = ParmTy;
8897 // Is it `T const &`?
8898 bool Ok = !IsMethod;
8899 QualType ExpectedTy;
8900 if (RD)
8901 ExpectedTy = Context.getRecordType(RD);
8902 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8903 CTy = Ref->getPointeeType();
8904 if (RD)
8905 ExpectedTy.addConst();
8906 Ok = true;
8907 }
8908
8909 // Is T a class?
8910 if (!Ok) {
8911 } else if (RD) {
8912 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8913 Ok = false;
8914 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8915 RD = cast<CXXRecordDecl>(CRD);
8916 } else {
8917 Ok = false;
8918 }
8919
8920 if (Ok) {
8921 KnownParm = Param;
8922 } else {
8923 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8924 // corresponding defaulted 'operator<=>' already.
8925 if (!FD->isImplicit()) {
8926 if (RD) {
8927 QualType PlainTy = Context.getRecordType(RD);
8928 QualType RefTy =
8929 Context.getLValueReferenceType(PlainTy.withConst());
8930 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8931 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8932 << Param->getSourceRange();
8933 } else {
8934 assert(!IsMethod && "should know expected type for method");
8935 Diag(FD->getLocation(),
8936 diag::err_defaulted_comparison_param_unknown)
8937 << int(DCK) << ParmTy << Param->getSourceRange();
8938 }
8939 }
8940 return true;
8941 }
8942 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8943 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8944 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8945 << ParmTy << Param->getSourceRange();
8946 return true;
8947 }
8948 }
8949
8950 assert(RD && "must have determined class");
8951 if (IsMethod) {
8952 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8953 // In-class, must be a friend decl.
8954 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8955 } else {
8956 // Out of class, require the defaulted comparison to be a friend (of a
8957 // complete type).
8958 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8959 diag::err_defaulted_comparison_not_friend, int(DCK),
8960 int(1)))
8961 return true;
8962
8963 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8964 return FD->getCanonicalDecl() ==
8965 F->getFriendDecl()->getCanonicalDecl();
8966 })) {
8967 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8968 << int(DCK) << int(0) << RD;
8969 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8970 return true;
8971 }
8972 }
8973
8974 // C++2a [class.eq]p1, [class.rel]p1:
8975 // A [defaulted comparison other than <=>] shall have a declared return
8976 // type bool.
8977 if (DCK != DefaultedComparisonKind::ThreeWay &&
8978 !FD->getDeclaredReturnType()->isDependentType() &&
8979 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8980 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8981 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8982 << FD->getReturnTypeSourceRange();
8983 return true;
8984 }
8985 // C++2a [class.spaceship]p2 [P2002R0]:
8986 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8987 // R shall not contain a placeholder type.
8988 if (QualType RT = FD->getDeclaredReturnType();
8989 DCK == DefaultedComparisonKind::ThreeWay &&
8990 RT->getContainedDeducedType() &&
8991 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8992 RT->getContainedAutoType()->isConstrained())) {
8993 Diag(FD->getLocation(),
8994 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8995 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8996 << FD->getReturnTypeSourceRange();
8997 return true;
8998 }
8999
9000 // For a defaulted function in a dependent class, defer all remaining checks
9001 // until instantiation.
9002 if (RD->isDependentType())
9003 return false;
9004
9005 // Determine whether the function should be defined as deleted.
9006 DefaultedComparisonInfo Info =
9007 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9008
9009 bool First = FD == FD->getCanonicalDecl();
9010
9011 if (!First) {
9012 if (Info.Deleted) {
9013 // C++11 [dcl.fct.def.default]p4:
9014 // [For a] user-provided explicitly-defaulted function [...] if such a
9015 // function is implicitly defined as deleted, the program is ill-formed.
9016 //
9017 // This is really just a consequence of the general rule that you can
9018 // only delete a function on its first declaration.
9019 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9020 << FD->isImplicit() << (int)DCK;
9021 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9022 DefaultedComparisonAnalyzer::ExplainDeleted)
9023 .visit();
9024 return true;
9025 }
9026 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9027 // C++20 [class.compare.default]p1:
9028 // [...] A definition of a comparison operator as defaulted that appears
9029 // in a class shall be the first declaration of that function.
9030 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9031 << (int)DCK;
9032 Diag(FD->getCanonicalDecl()->getLocation(),
9033 diag::note_previous_declaration);
9034 return true;
9035 }
9036 }
9037
9038 // If we want to delete the function, then do so; there's nothing else to
9039 // check in that case.
9040 if (Info.Deleted) {
9041 SetDeclDeleted(FD, FD->getLocation());
9042 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9043 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9044 << (int)DCK;
9045 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9046 DefaultedComparisonAnalyzer::ExplainDeleted)
9047 .visit();
9048 if (FD->getDefaultLoc().isValid())
9049 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9050 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9051 }
9052 return false;
9053 }
9054
9055 // C++2a [class.spaceship]p2:
9056 // The return type is deduced as the common comparison type of R0, R1, ...
9057 if (DCK == DefaultedComparisonKind::ThreeWay &&
9058 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9059 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9060 if (RetLoc.isInvalid())
9061 RetLoc = FD->getBeginLoc();
9062 // FIXME: Should we really care whether we have the complete type and the
9063 // 'enumerator' constants here? A forward declaration seems sufficient.
9064 QualType Cat = CheckComparisonCategoryType(
9065 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9066 if (Cat.isNull())
9067 return true;
9068 Context.adjustDeducedFunctionResultType(
9069 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9070 }
9071
9072 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9073 // An explicitly-defaulted function that is not defined as deleted may be
9074 // declared constexpr or consteval only if it is constexpr-compatible.
9075 // C++2a [class.compare.default]p3 [P2002R0]:
9076 // A defaulted comparison function is constexpr-compatible if it satisfies
9077 // the requirements for a constexpr function [...]
9078 // The only relevant requirements are that the parameter and return types are
9079 // literal types. The remaining conditions are checked by the analyzer.
9080 //
9081 // We support P2448R2 in language modes earlier than C++23 as an extension.
9082 // The concept of constexpr-compatible was removed.
9083 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9084 // A function explicitly defaulted on its first declaration is implicitly
9085 // inline, and is implicitly constexpr if it is constexpr-suitable.
9086 // C++23 [dcl.constexpr]p3
9087 // A function is constexpr-suitable if
9088 // - it is not a coroutine, and
9089 // - if the function is a constructor or destructor, its class does not
9090 // have any virtual base classes.
9091 if (FD->isConstexpr()) {
9092 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
9093 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
9094 !Info.Constexpr) {
9095 Diag(FD->getBeginLoc(),
9096 getLangOpts().CPlusPlus23
9097 ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
9098 : diag::ext_defaulted_comparison_constexpr_mismatch)
9099 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9100 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9101 DefaultedComparisonAnalyzer::ExplainConstexpr)
9102 .visit();
9103 }
9104 }
9105
9106 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9107 // If a constexpr-compatible function is explicitly defaulted on its first
9108 // declaration, it is implicitly considered to be constexpr.
9109 // FIXME: Only applying this to the first declaration seems problematic, as
9110 // simple reorderings can affect the meaning of the program.
9111 if (First && !FD->isConstexpr() && Info.Constexpr)
9112 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9113
9114 // C++2a [except.spec]p3:
9115 // If a declaration of a function does not have a noexcept-specifier
9116 // [and] is defaulted on its first declaration, [...] the exception
9117 // specification is as specified below
9118 if (FD->getExceptionSpecType() == EST_None) {
9119 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9120 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9121 EPI.ExceptionSpec.Type = EST_Unevaluated;
9122 EPI.ExceptionSpec.SourceDecl = FD;
9123 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9124 FPT->getParamTypes(), EPI));
9125 }
9126
9127 return false;
9128 }
9129
DeclareImplicitEqualityComparison(CXXRecordDecl * RD,FunctionDecl * Spaceship)9130 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9131 FunctionDecl *Spaceship) {
9132 Sema::CodeSynthesisContext Ctx;
9133 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9134 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9135 Ctx.Entity = Spaceship;
9136 pushCodeSynthesisContext(Ctx);
9137
9138 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9139 EqualEqual->setImplicit();
9140
9141 popCodeSynthesisContext();
9142 }
9143
DefineDefaultedComparison(SourceLocation UseLoc,FunctionDecl * FD,DefaultedComparisonKind DCK)9144 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9145 DefaultedComparisonKind DCK) {
9146 assert(FD->isDefaulted() && !FD->isDeleted() &&
9147 !FD->doesThisDeclarationHaveABody());
9148 if (FD->willHaveBody() || FD->isInvalidDecl())
9149 return;
9150
9151 SynthesizedFunctionScope Scope(*this, FD);
9152
9153 // Add a context note for diagnostics produced after this point.
9154 Scope.addContextNote(UseLoc);
9155
9156 {
9157 // Build and set up the function body.
9158 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9159 // the type of the class being compared.
9160 auto PT = FD->getParamDecl(0)->getType();
9161 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9162 SourceLocation BodyLoc =
9163 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9164 StmtResult Body =
9165 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9166 if (Body.isInvalid()) {
9167 FD->setInvalidDecl();
9168 return;
9169 }
9170 FD->setBody(Body.get());
9171 FD->markUsed(Context);
9172 }
9173
9174 // The exception specification is needed because we are defining the
9175 // function. Note that this will reuse the body we just built.
9176 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9177
9178 if (ASTMutationListener *L = getASTMutationListener())
9179 L->CompletedImplicitDefinition(FD);
9180 }
9181
9182 static Sema::ImplicitExceptionSpecification
ComputeDefaultedComparisonExceptionSpec(Sema & S,SourceLocation Loc,FunctionDecl * FD,Sema::DefaultedComparisonKind DCK)9183 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9184 FunctionDecl *FD,
9185 Sema::DefaultedComparisonKind DCK) {
9186 ComputingExceptionSpec CES(S, FD, Loc);
9187 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9188
9189 if (FD->isInvalidDecl())
9190 return ExceptSpec;
9191
9192 // The common case is that we just defined the comparison function. In that
9193 // case, just look at whether the body can throw.
9194 if (FD->hasBody()) {
9195 ExceptSpec.CalledStmt(FD->getBody());
9196 } else {
9197 // Otherwise, build a body so we can check it. This should ideally only
9198 // happen when we're not actually marking the function referenced. (This is
9199 // only really important for efficiency: we don't want to build and throw
9200 // away bodies for comparison functions more than we strictly need to.)
9201
9202 // Pretend to synthesize the function body in an unevaluated context.
9203 // Note that we can't actually just go ahead and define the function here:
9204 // we are not permitted to mark its callees as referenced.
9205 Sema::SynthesizedFunctionScope Scope(S, FD);
9206 EnterExpressionEvaluationContext Context(
9207 S, Sema::ExpressionEvaluationContext::Unevaluated);
9208
9209 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9210 SourceLocation BodyLoc =
9211 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9212 StmtResult Body =
9213 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9214 if (!Body.isInvalid())
9215 ExceptSpec.CalledStmt(Body.get());
9216
9217 // FIXME: Can we hold onto this body and just transform it to potentially
9218 // evaluated when we're asked to define the function rather than rebuilding
9219 // it? Either that, or we should only build the bits of the body that we
9220 // need (the expressions, not the statements).
9221 }
9222
9223 return ExceptSpec;
9224 }
9225
CheckDelayedMemberExceptionSpecs()9226 void Sema::CheckDelayedMemberExceptionSpecs() {
9227 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9228 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9229
9230 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9231 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9232
9233 // Perform any deferred checking of exception specifications for virtual
9234 // destructors.
9235 for (auto &Check : Overriding)
9236 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9237
9238 // Perform any deferred checking of exception specifications for befriended
9239 // special members.
9240 for (auto &Check : Equivalent)
9241 CheckEquivalentExceptionSpec(Check.second, Check.first);
9242 }
9243
9244 namespace {
9245 /// CRTP base class for visiting operations performed by a special member
9246 /// function (or inherited constructor).
9247 template<typename Derived>
9248 struct SpecialMemberVisitor {
9249 Sema &S;
9250 CXXMethodDecl *MD;
9251 Sema::CXXSpecialMember CSM;
9252 Sema::InheritedConstructorInfo *ICI;
9253
9254 // Properties of the special member, computed for convenience.
9255 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9256
SpecialMemberVisitor__anon067e66482511::SpecialMemberVisitor9257 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
9258 Sema::InheritedConstructorInfo *ICI)
9259 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9260 switch (CSM) {
9261 case Sema::CXXDefaultConstructor:
9262 case Sema::CXXCopyConstructor:
9263 case Sema::CXXMoveConstructor:
9264 IsConstructor = true;
9265 break;
9266 case Sema::CXXCopyAssignment:
9267 case Sema::CXXMoveAssignment:
9268 IsAssignment = true;
9269 break;
9270 case Sema::CXXDestructor:
9271 break;
9272 case Sema::CXXInvalid:
9273 llvm_unreachable("invalid special member kind");
9274 }
9275
9276 if (MD->getNumExplicitParams()) {
9277 if (const ReferenceType *RT =
9278 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9279 ConstArg = RT->getPointeeType().isConstQualified();
9280 }
9281 }
9282
getDerived__anon067e66482511::SpecialMemberVisitor9283 Derived &getDerived() { return static_cast<Derived&>(*this); }
9284
9285 /// Is this a "move" special member?
isMove__anon067e66482511::SpecialMemberVisitor9286 bool isMove() const {
9287 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9288 }
9289
9290 /// Look up the corresponding special member in the given class.
lookupIn__anon067e66482511::SpecialMemberVisitor9291 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9292 unsigned Quals, bool IsMutable) {
9293 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9294 ConstArg && !IsMutable);
9295 }
9296
9297 /// Look up the constructor for the specified base class to see if it's
9298 /// overridden due to this being an inherited constructor.
lookupInheritedCtor__anon067e66482511::SpecialMemberVisitor9299 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9300 if (!ICI)
9301 return {};
9302 assert(CSM == Sema::CXXDefaultConstructor);
9303 auto *BaseCtor =
9304 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9305 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9306 return MD;
9307 return {};
9308 }
9309
9310 /// A base or member subobject.
9311 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9312
9313 /// Get the location to use for a subobject in diagnostics.
getSubobjectLoc__anon067e66482511::SpecialMemberVisitor9314 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9315 // FIXME: For an indirect virtual base, the direct base leading to
9316 // the indirect virtual base would be a more useful choice.
9317 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9318 return B->getBaseTypeLoc();
9319 else
9320 return Subobj.get<FieldDecl*>()->getLocation();
9321 }
9322
9323 enum BasesToVisit {
9324 /// Visit all non-virtual (direct) bases.
9325 VisitNonVirtualBases,
9326 /// Visit all direct bases, virtual or not.
9327 VisitDirectBases,
9328 /// Visit all non-virtual bases, and all virtual bases if the class
9329 /// is not abstract.
9330 VisitPotentiallyConstructedBases,
9331 /// Visit all direct or virtual bases.
9332 VisitAllBases
9333 };
9334
9335 // Visit the bases and members of the class.
visit__anon067e66482511::SpecialMemberVisitor9336 bool visit(BasesToVisit Bases) {
9337 CXXRecordDecl *RD = MD->getParent();
9338
9339 if (Bases == VisitPotentiallyConstructedBases)
9340 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9341
9342 for (auto &B : RD->bases())
9343 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9344 getDerived().visitBase(&B))
9345 return true;
9346
9347 if (Bases == VisitAllBases)
9348 for (auto &B : RD->vbases())
9349 if (getDerived().visitBase(&B))
9350 return true;
9351
9352 for (auto *F : RD->fields())
9353 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9354 getDerived().visitField(F))
9355 return true;
9356
9357 return false;
9358 }
9359 };
9360 }
9361
9362 namespace {
9363 struct SpecialMemberDeletionInfo
9364 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9365 bool Diagnose;
9366
9367 SourceLocation Loc;
9368
9369 bool AllFieldsAreConst;
9370
SpecialMemberDeletionInfo__anon067e66482611::SpecialMemberDeletionInfo9371 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9372 Sema::CXXSpecialMember CSM,
9373 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9374 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9375 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9376
inUnion__anon067e66482611::SpecialMemberDeletionInfo9377 bool inUnion() const { return MD->getParent()->isUnion(); }
9378
getEffectiveCSM__anon067e66482611::SpecialMemberDeletionInfo9379 Sema::CXXSpecialMember getEffectiveCSM() {
9380 return ICI ? Sema::CXXInvalid : CSM;
9381 }
9382
9383 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9384
visitBase__anon067e66482611::SpecialMemberDeletionInfo9385 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
visitField__anon067e66482611::SpecialMemberDeletionInfo9386 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9387
9388 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9389 bool shouldDeleteForField(FieldDecl *FD);
9390 bool shouldDeleteForAllConstMembers();
9391
9392 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9393 unsigned Quals);
9394 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9395 Sema::SpecialMemberOverloadResult SMOR,
9396 bool IsDtorCallInCtor);
9397
9398 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9399 };
9400 }
9401
9402 /// Is the given special member inaccessible when used on the given
9403 /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)9404 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9405 CXXMethodDecl *target) {
9406 /// If we're operating on a base class, the object type is the
9407 /// type of this special member.
9408 QualType objectTy;
9409 AccessSpecifier access = target->getAccess();
9410 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9411 objectTy = S.Context.getTypeDeclType(MD->getParent());
9412 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9413
9414 // If we're operating on a field, the object type is the type of the field.
9415 } else {
9416 objectTy = S.Context.getTypeDeclType(target->getParent());
9417 }
9418
9419 return S.isMemberAccessibleForDeletion(
9420 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9421 }
9422
9423 /// Check whether we should delete a special member due to the implicit
9424 /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult SMOR,bool IsDtorCallInCtor)9425 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9426 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9427 bool IsDtorCallInCtor) {
9428 CXXMethodDecl *Decl = SMOR.getMethod();
9429 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9430
9431 int DiagKind = -1;
9432
9433 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9434 DiagKind = !Decl ? 0 : 1;
9435 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9436 DiagKind = 2;
9437 else if (!isAccessible(Subobj, Decl))
9438 DiagKind = 3;
9439 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9440 !Decl->isTrivial()) {
9441 // A member of a union must have a trivial corresponding special member.
9442 // As a weird special case, a destructor call from a union's constructor
9443 // must be accessible and non-deleted, but need not be trivial. Such a
9444 // destructor is never actually called, but is semantically checked as
9445 // if it were.
9446 if (CSM == Sema::CXXDefaultConstructor) {
9447 // [class.default.ctor]p2:
9448 // A defaulted default constructor for class X is defined as deleted if
9449 // - X is a union that has a variant member with a non-trivial default
9450 // constructor and no variant member of X has a default member
9451 // initializer
9452 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9453 if (!RD->hasInClassInitializer())
9454 DiagKind = 4;
9455 } else {
9456 DiagKind = 4;
9457 }
9458 }
9459
9460 if (DiagKind == -1)
9461 return false;
9462
9463 if (Diagnose) {
9464 if (Field) {
9465 S.Diag(Field->getLocation(),
9466 diag::note_deleted_special_member_class_subobject)
9467 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9468 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9469 } else {
9470 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9471 S.Diag(Base->getBeginLoc(),
9472 diag::note_deleted_special_member_class_subobject)
9473 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9474 << Base->getType() << DiagKind << IsDtorCallInCtor
9475 << /*IsObjCPtr*/false;
9476 }
9477
9478 if (DiagKind == 1)
9479 S.NoteDeletedFunction(Decl);
9480 // FIXME: Explain inaccessibility if DiagKind == 3.
9481 }
9482
9483 return true;
9484 }
9485
9486 /// Check whether we should delete a special member function due to having a
9487 /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)9488 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9489 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9490 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9491 bool IsMutable = Field && Field->isMutable();
9492
9493 // C++11 [class.ctor]p5:
9494 // -- any direct or virtual base class, or non-static data member with no
9495 // brace-or-equal-initializer, has class type M (or array thereof) and
9496 // either M has no default constructor or overload resolution as applied
9497 // to M's default constructor results in an ambiguity or in a function
9498 // that is deleted or inaccessible
9499 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9500 // -- a direct or virtual base class B that cannot be copied/moved because
9501 // overload resolution, as applied to B's corresponding special member,
9502 // results in an ambiguity or a function that is deleted or inaccessible
9503 // from the defaulted special member
9504 // C++11 [class.dtor]p5:
9505 // -- any direct or virtual base class [...] has a type with a destructor
9506 // that is deleted or inaccessible
9507 if (!(CSM == Sema::CXXDefaultConstructor &&
9508 Field && Field->hasInClassInitializer()) &&
9509 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9510 false))
9511 return true;
9512
9513 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9514 // -- any direct or virtual base class or non-static data member has a
9515 // type with a destructor that is deleted or inaccessible
9516 if (IsConstructor) {
9517 Sema::SpecialMemberOverloadResult SMOR =
9518 S.LookupSpecialMember(Class, Sema::CXXDestructor,
9519 false, false, false, false, false);
9520 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9521 return true;
9522 }
9523
9524 return false;
9525 }
9526
shouldDeleteForVariantObjCPtrMember(FieldDecl * FD,QualType FieldType)9527 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9528 FieldDecl *FD, QualType FieldType) {
9529 // The defaulted special functions are defined as deleted if this is a variant
9530 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9531 // type under ARC.
9532 if (!FieldType.hasNonTrivialObjCLifetime())
9533 return false;
9534
9535 // Don't make the defaulted default constructor defined as deleted if the
9536 // member has an in-class initializer.
9537 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9538 return false;
9539
9540 if (Diagnose) {
9541 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9542 S.Diag(FD->getLocation(),
9543 diag::note_deleted_special_member_class_subobject)
9544 << getEffectiveCSM() << ParentClass << /*IsField*/true
9545 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9546 }
9547
9548 return true;
9549 }
9550
9551 /// Check whether we should delete a special member function due to the class
9552 /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)9553 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9554 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9555 // If program is correct, BaseClass cannot be null, but if it is, the error
9556 // must be reported elsewhere.
9557 if (!BaseClass)
9558 return false;
9559 // If we have an inheriting constructor, check whether we're calling an
9560 // inherited constructor instead of a default constructor.
9561 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9562 if (auto *BaseCtor = SMOR.getMethod()) {
9563 // Note that we do not check access along this path; other than that,
9564 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9565 // FIXME: Check that the base has a usable destructor! Sink this into
9566 // shouldDeleteForClassSubobject.
9567 if (BaseCtor->isDeleted() && Diagnose) {
9568 S.Diag(Base->getBeginLoc(),
9569 diag::note_deleted_special_member_class_subobject)
9570 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9571 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9572 << /*IsObjCPtr*/false;
9573 S.NoteDeletedFunction(BaseCtor);
9574 }
9575 return BaseCtor->isDeleted();
9576 }
9577 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9578 }
9579
9580 /// Check whether we should delete a special member function due to the class
9581 /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)9582 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9583 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9584 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9585
9586 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9587 return true;
9588
9589 if (CSM == Sema::CXXDefaultConstructor) {
9590 // For a default constructor, all references must be initialized in-class
9591 // and, if a union, it must have a non-const member.
9592 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9593 if (Diagnose)
9594 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9595 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9596 return true;
9597 }
9598 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9599 // data member of const-qualified type (or array thereof) with no
9600 // brace-or-equal-initializer is not const-default-constructible.
9601 if (!inUnion() && FieldType.isConstQualified() &&
9602 !FD->hasInClassInitializer() &&
9603 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9604 if (Diagnose)
9605 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9606 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9607 return true;
9608 }
9609
9610 if (inUnion() && !FieldType.isConstQualified())
9611 AllFieldsAreConst = false;
9612 } else if (CSM == Sema::CXXCopyConstructor) {
9613 // For a copy constructor, data members must not be of rvalue reference
9614 // type.
9615 if (FieldType->isRValueReferenceType()) {
9616 if (Diagnose)
9617 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9618 << MD->getParent() << FD << FieldType;
9619 return true;
9620 }
9621 } else if (IsAssignment) {
9622 // For an assignment operator, data members must not be of reference type.
9623 if (FieldType->isReferenceType()) {
9624 if (Diagnose)
9625 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9626 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9627 return true;
9628 }
9629 if (!FieldRecord && FieldType.isConstQualified()) {
9630 // C++11 [class.copy]p23:
9631 // -- a non-static data member of const non-class type (or array thereof)
9632 if (Diagnose)
9633 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9634 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9635 return true;
9636 }
9637 }
9638
9639 if (FieldRecord) {
9640 // Some additional restrictions exist on the variant members.
9641 if (!inUnion() && FieldRecord->isUnion() &&
9642 FieldRecord->isAnonymousStructOrUnion()) {
9643 bool AllVariantFieldsAreConst = true;
9644
9645 // FIXME: Handle anonymous unions declared within anonymous unions.
9646 for (auto *UI : FieldRecord->fields()) {
9647 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9648
9649 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9650 return true;
9651
9652 if (!UnionFieldType.isConstQualified())
9653 AllVariantFieldsAreConst = false;
9654
9655 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9656 if (UnionFieldRecord &&
9657 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9658 UnionFieldType.getCVRQualifiers()))
9659 return true;
9660 }
9661
9662 // At least one member in each anonymous union must be non-const
9663 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9664 !FieldRecord->field_empty()) {
9665 if (Diagnose)
9666 S.Diag(FieldRecord->getLocation(),
9667 diag::note_deleted_default_ctor_all_const)
9668 << !!ICI << MD->getParent() << /*anonymous union*/1;
9669 return true;
9670 }
9671
9672 // Don't check the implicit member of the anonymous union type.
9673 // This is technically non-conformant but supported, and we have a
9674 // diagnostic for this elsewhere.
9675 return false;
9676 }
9677
9678 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9679 FieldType.getCVRQualifiers()))
9680 return true;
9681 }
9682
9683 return false;
9684 }
9685
9686 /// C++11 [class.ctor] p5:
9687 /// A defaulted default constructor for a class X is defined as deleted if
9688 /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()9689 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9690 // This is a silly definition, because it gives an empty union a deleted
9691 // default constructor. Don't do that.
9692 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9693 bool AnyFields = false;
9694 for (auto *F : MD->getParent()->fields())
9695 if ((AnyFields = !F->isUnnamedBitfield()))
9696 break;
9697 if (!AnyFields)
9698 return false;
9699 if (Diagnose)
9700 S.Diag(MD->getParent()->getLocation(),
9701 diag::note_deleted_default_ctor_all_const)
9702 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9703 return true;
9704 }
9705 return false;
9706 }
9707
9708 /// Determine whether a defaulted special member function should be defined as
9709 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9710 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,InheritedConstructorInfo * ICI,bool Diagnose)9711 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9712 InheritedConstructorInfo *ICI,
9713 bool Diagnose) {
9714 if (MD->isInvalidDecl())
9715 return false;
9716 CXXRecordDecl *RD = MD->getParent();
9717 assert(!RD->isDependentType() && "do deletion after instantiation");
9718 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9719 return false;
9720
9721 // C++11 [expr.lambda.prim]p19:
9722 // The closure type associated with a lambda-expression has a
9723 // deleted (8.4.3) default constructor and a deleted copy
9724 // assignment operator.
9725 // C++2a adds back these operators if the lambda has no lambda-capture.
9726 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9727 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9728 if (Diagnose)
9729 Diag(RD->getLocation(), diag::note_lambda_decl);
9730 return true;
9731 }
9732
9733 // For an anonymous struct or union, the copy and assignment special members
9734 // will never be used, so skip the check. For an anonymous union declared at
9735 // namespace scope, the constructor and destructor are used.
9736 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9737 RD->isAnonymousStructOrUnion())
9738 return false;
9739
9740 // C++11 [class.copy]p7, p18:
9741 // If the class definition declares a move constructor or move assignment
9742 // operator, an implicitly declared copy constructor or copy assignment
9743 // operator is defined as deleted.
9744 if (MD->isImplicit() &&
9745 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9746 CXXMethodDecl *UserDeclaredMove = nullptr;
9747
9748 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9749 // deletion of the corresponding copy operation, not both copy operations.
9750 // MSVC 2015 has adopted the standards conforming behavior.
9751 bool DeletesOnlyMatchingCopy =
9752 getLangOpts().MSVCCompat &&
9753 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9754
9755 if (RD->hasUserDeclaredMoveConstructor() &&
9756 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9757 if (!Diagnose) return true;
9758
9759 // Find any user-declared move constructor.
9760 for (auto *I : RD->ctors()) {
9761 if (I->isMoveConstructor()) {
9762 UserDeclaredMove = I;
9763 break;
9764 }
9765 }
9766 assert(UserDeclaredMove);
9767 } else if (RD->hasUserDeclaredMoveAssignment() &&
9768 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9769 if (!Diagnose) return true;
9770
9771 // Find any user-declared move assignment operator.
9772 for (auto *I : RD->methods()) {
9773 if (I->isMoveAssignmentOperator()) {
9774 UserDeclaredMove = I;
9775 break;
9776 }
9777 }
9778 assert(UserDeclaredMove);
9779 }
9780
9781 if (UserDeclaredMove) {
9782 Diag(UserDeclaredMove->getLocation(),
9783 diag::note_deleted_copy_user_declared_move)
9784 << (CSM == CXXCopyAssignment) << RD
9785 << UserDeclaredMove->isMoveAssignmentOperator();
9786 return true;
9787 }
9788 }
9789
9790 // Do access control from the special member function
9791 ContextRAII MethodContext(*this, MD);
9792
9793 // C++11 [class.dtor]p5:
9794 // -- for a virtual destructor, lookup of the non-array deallocation function
9795 // results in an ambiguity or in a function that is deleted or inaccessible
9796 if (CSM == CXXDestructor && MD->isVirtual()) {
9797 FunctionDecl *OperatorDelete = nullptr;
9798 DeclarationName Name =
9799 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9800 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9801 OperatorDelete, /*Diagnose*/false)) {
9802 if (Diagnose)
9803 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9804 return true;
9805 }
9806 }
9807
9808 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9809
9810 // Per DR1611, do not consider virtual bases of constructors of abstract
9811 // classes, since we are not going to construct them.
9812 // Per DR1658, do not consider virtual bases of destructors of abstract
9813 // classes either.
9814 // Per DR2180, for assignment operators we only assign (and thus only
9815 // consider) direct bases.
9816 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9817 : SMI.VisitPotentiallyConstructedBases))
9818 return true;
9819
9820 if (SMI.shouldDeleteForAllConstMembers())
9821 return true;
9822
9823 if (getLangOpts().CUDA) {
9824 // We should delete the special member in CUDA mode if target inference
9825 // failed.
9826 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9827 // is treated as certain special member, which may not reflect what special
9828 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9829 // expects CSM to match MD, therefore recalculate CSM.
9830 assert(ICI || CSM == getSpecialMember(MD));
9831 auto RealCSM = CSM;
9832 if (ICI)
9833 RealCSM = getSpecialMember(MD);
9834
9835 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9836 SMI.ConstArg, Diagnose);
9837 }
9838
9839 return false;
9840 }
9841
DiagnoseDeletedDefaultedFunction(FunctionDecl * FD)9842 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9843 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9844 assert(DFK && "not a defaultable function");
9845 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9846
9847 if (DFK.isSpecialMember()) {
9848 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9849 nullptr, /*Diagnose=*/true);
9850 } else {
9851 DefaultedComparisonAnalyzer(
9852 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9853 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9854 .visit();
9855 }
9856 }
9857
9858 /// Perform lookup for a special member of the specified kind, and determine
9859 /// whether it is trivial. If the triviality can be determined without the
9860 /// lookup, skip it. This is intended for use when determining whether a
9861 /// special member of a containing object is trivial, and thus does not ever
9862 /// perform overload resolution for default constructors.
9863 ///
9864 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9865 /// member that was most likely to be intended to be trivial, if any.
9866 ///
9867 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9868 /// determine whether the special member is trivial.
findTrivialSpecialMember(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,Sema::TrivialABIHandling TAH,CXXMethodDecl ** Selected)9869 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9870 Sema::CXXSpecialMember CSM, unsigned Quals,
9871 bool ConstRHS,
9872 Sema::TrivialABIHandling TAH,
9873 CXXMethodDecl **Selected) {
9874 if (Selected)
9875 *Selected = nullptr;
9876
9877 switch (CSM) {
9878 case Sema::CXXInvalid:
9879 llvm_unreachable("not a special member");
9880
9881 case Sema::CXXDefaultConstructor:
9882 // C++11 [class.ctor]p5:
9883 // A default constructor is trivial if:
9884 // - all the [direct subobjects] have trivial default constructors
9885 //
9886 // Note, no overload resolution is performed in this case.
9887 if (RD->hasTrivialDefaultConstructor())
9888 return true;
9889
9890 if (Selected) {
9891 // If there's a default constructor which could have been trivial, dig it
9892 // out. Otherwise, if there's any user-provided default constructor, point
9893 // to that as an example of why there's not a trivial one.
9894 CXXConstructorDecl *DefCtor = nullptr;
9895 if (RD->needsImplicitDefaultConstructor())
9896 S.DeclareImplicitDefaultConstructor(RD);
9897 for (auto *CI : RD->ctors()) {
9898 if (!CI->isDefaultConstructor())
9899 continue;
9900 DefCtor = CI;
9901 if (!DefCtor->isUserProvided())
9902 break;
9903 }
9904
9905 *Selected = DefCtor;
9906 }
9907
9908 return false;
9909
9910 case Sema::CXXDestructor:
9911 // C++11 [class.dtor]p5:
9912 // A destructor is trivial if:
9913 // - all the direct [subobjects] have trivial destructors
9914 if (RD->hasTrivialDestructor() ||
9915 (TAH == Sema::TAH_ConsiderTrivialABI &&
9916 RD->hasTrivialDestructorForCall()))
9917 return true;
9918
9919 if (Selected) {
9920 if (RD->needsImplicitDestructor())
9921 S.DeclareImplicitDestructor(RD);
9922 *Selected = RD->getDestructor();
9923 }
9924
9925 return false;
9926
9927 case Sema::CXXCopyConstructor:
9928 // C++11 [class.copy]p12:
9929 // A copy constructor is trivial if:
9930 // - the constructor selected to copy each direct [subobject] is trivial
9931 if (RD->hasTrivialCopyConstructor() ||
9932 (TAH == Sema::TAH_ConsiderTrivialABI &&
9933 RD->hasTrivialCopyConstructorForCall())) {
9934 if (Quals == Qualifiers::Const)
9935 // We must either select the trivial copy constructor or reach an
9936 // ambiguity; no need to actually perform overload resolution.
9937 return true;
9938 } else if (!Selected) {
9939 return false;
9940 }
9941 // In C++98, we are not supposed to perform overload resolution here, but we
9942 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9943 // cases like B as having a non-trivial copy constructor:
9944 // struct A { template<typename T> A(T&); };
9945 // struct B { mutable A a; };
9946 goto NeedOverloadResolution;
9947
9948 case Sema::CXXCopyAssignment:
9949 // C++11 [class.copy]p25:
9950 // A copy assignment operator is trivial if:
9951 // - the assignment operator selected to copy each direct [subobject] is
9952 // trivial
9953 if (RD->hasTrivialCopyAssignment()) {
9954 if (Quals == Qualifiers::Const)
9955 return true;
9956 } else if (!Selected) {
9957 return false;
9958 }
9959 // In C++98, we are not supposed to perform overload resolution here, but we
9960 // treat that as a language defect.
9961 goto NeedOverloadResolution;
9962
9963 case Sema::CXXMoveConstructor:
9964 case Sema::CXXMoveAssignment:
9965 NeedOverloadResolution:
9966 Sema::SpecialMemberOverloadResult SMOR =
9967 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9968
9969 // The standard doesn't describe how to behave if the lookup is ambiguous.
9970 // We treat it as not making the member non-trivial, just like the standard
9971 // mandates for the default constructor. This should rarely matter, because
9972 // the member will also be deleted.
9973 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9974 return true;
9975
9976 if (!SMOR.getMethod()) {
9977 assert(SMOR.getKind() ==
9978 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9979 return false;
9980 }
9981
9982 // We deliberately don't check if we found a deleted special member. We're
9983 // not supposed to!
9984 if (Selected)
9985 *Selected = SMOR.getMethod();
9986
9987 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9988 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9989 return SMOR.getMethod()->isTrivialForCall();
9990 return SMOR.getMethod()->isTrivial();
9991 }
9992
9993 llvm_unreachable("unknown special method kind");
9994 }
9995
findUserDeclaredCtor(CXXRecordDecl * RD)9996 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9997 for (auto *CI : RD->ctors())
9998 if (!CI->isImplicit())
9999 return CI;
10000
10001 // Look for constructor templates.
10002 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10003 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10004 if (CXXConstructorDecl *CD =
10005 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10006 return CD;
10007 }
10008
10009 return nullptr;
10010 }
10011
10012 /// The kind of subobject we are checking for triviality. The values of this
10013 /// enumeration are used in diagnostics.
10014 enum TrivialSubobjectKind {
10015 /// The subobject is a base class.
10016 TSK_BaseClass,
10017 /// The subobject is a non-static data member.
10018 TSK_Field,
10019 /// The object is actually the complete object.
10020 TSK_CompleteObject
10021 };
10022
10023 /// Check whether the special member selected for a given type would be trivial.
checkTrivialSubobjectCall(Sema & S,SourceLocation SubobjLoc,QualType SubType,bool ConstRHS,Sema::CXXSpecialMember CSM,TrivialSubobjectKind Kind,Sema::TrivialABIHandling TAH,bool Diagnose)10024 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10025 QualType SubType, bool ConstRHS,
10026 Sema::CXXSpecialMember CSM,
10027 TrivialSubobjectKind Kind,
10028 Sema::TrivialABIHandling TAH, bool Diagnose) {
10029 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10030 if (!SubRD)
10031 return true;
10032
10033 CXXMethodDecl *Selected;
10034 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10035 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10036 return true;
10037
10038 if (Diagnose) {
10039 if (ConstRHS)
10040 SubType.addConst();
10041
10042 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
10043 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10044 << Kind << SubType.getUnqualifiedType();
10045 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10046 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10047 } else if (!Selected)
10048 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10049 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10050 else if (Selected->isUserProvided()) {
10051 if (Kind == TSK_CompleteObject)
10052 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10053 << Kind << SubType.getUnqualifiedType() << CSM;
10054 else {
10055 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10056 << Kind << SubType.getUnqualifiedType() << CSM;
10057 S.Diag(Selected->getLocation(), diag::note_declared_at);
10058 }
10059 } else {
10060 if (Kind != TSK_CompleteObject)
10061 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10062 << Kind << SubType.getUnqualifiedType() << CSM;
10063
10064 // Explain why the defaulted or deleted special member isn't trivial.
10065 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
10066 Diagnose);
10067 }
10068 }
10069
10070 return false;
10071 }
10072
10073 /// Check whether the members of a class type allow a special member to be
10074 /// trivial.
checkTrivialClassMembers(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,bool ConstArg,Sema::TrivialABIHandling TAH,bool Diagnose)10075 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10076 Sema::CXXSpecialMember CSM,
10077 bool ConstArg,
10078 Sema::TrivialABIHandling TAH,
10079 bool Diagnose) {
10080 for (const auto *FI : RD->fields()) {
10081 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
10082 continue;
10083
10084 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10085
10086 // Pretend anonymous struct or union members are members of this class.
10087 if (FI->isAnonymousStructOrUnion()) {
10088 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10089 CSM, ConstArg, TAH, Diagnose))
10090 return false;
10091 continue;
10092 }
10093
10094 // C++11 [class.ctor]p5:
10095 // A default constructor is trivial if [...]
10096 // -- no non-static data member of its class has a
10097 // brace-or-equal-initializer
10098 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
10099 if (Diagnose)
10100 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10101 << FI;
10102 return false;
10103 }
10104
10105 // Objective C ARC 4.3.5:
10106 // [...] nontrivally ownership-qualified types are [...] not trivially
10107 // default constructible, copy constructible, move constructible, copy
10108 // assignable, move assignable, or destructible [...]
10109 if (FieldType.hasNonTrivialObjCLifetime()) {
10110 if (Diagnose)
10111 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10112 << RD << FieldType.getObjCLifetime();
10113 return false;
10114 }
10115
10116 bool ConstRHS = ConstArg && !FI->isMutable();
10117 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10118 CSM, TSK_Field, TAH, Diagnose))
10119 return false;
10120 }
10121
10122 return true;
10123 }
10124
10125 /// Diagnose why the specified class does not have a trivial special member of
10126 /// the given kind.
DiagnoseNontrivial(const CXXRecordDecl * RD,CXXSpecialMember CSM)10127 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
10128 QualType Ty = Context.getRecordType(RD);
10129
10130 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
10131 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10132 TSK_CompleteObject, TAH_IgnoreTrivialABI,
10133 /*Diagnose*/true);
10134 }
10135
10136 /// Determine whether a defaulted or deleted special member function is trivial,
10137 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10138 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
SpecialMemberIsTrivial(CXXMethodDecl * MD,CXXSpecialMember CSM,TrivialABIHandling TAH,bool Diagnose)10139 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
10140 TrivialABIHandling TAH, bool Diagnose) {
10141 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
10142
10143 CXXRecordDecl *RD = MD->getParent();
10144
10145 bool ConstArg = false;
10146
10147 // C++11 [class.copy]p12, p25: [DR1593]
10148 // A [special member] is trivial if [...] its parameter-type-list is
10149 // equivalent to the parameter-type-list of an implicit declaration [...]
10150 switch (CSM) {
10151 case CXXDefaultConstructor:
10152 case CXXDestructor:
10153 // Trivial default constructors and destructors cannot have parameters.
10154 break;
10155
10156 case CXXCopyConstructor:
10157 case CXXCopyAssignment: {
10158 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10159 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10160
10161 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10162 // if they are not user-provided and their parameter-type-list is equivalent
10163 // to the parameter-type-list of an implicit declaration. This maintains the
10164 // behavior before dr2171 was implemented.
10165 //
10166 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10167 // trivial, if they are not user-provided, regardless of the qualifiers on
10168 // the reference type.
10169 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10170 LangOptions::ClangABI::Ver14;
10171 if (!RT ||
10172 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10173 ClangABICompat14)) {
10174 if (Diagnose)
10175 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10176 << Param0->getSourceRange() << Param0->getType()
10177 << Context.getLValueReferenceType(
10178 Context.getRecordType(RD).withConst());
10179 return false;
10180 }
10181
10182 ConstArg = RT->getPointeeType().isConstQualified();
10183 break;
10184 }
10185
10186 case CXXMoveConstructor:
10187 case CXXMoveAssignment: {
10188 // Trivial move operations always have non-cv-qualified parameters.
10189 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10190 const RValueReferenceType *RT =
10191 Param0->getType()->getAs<RValueReferenceType>();
10192 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10193 if (Diagnose)
10194 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10195 << Param0->getSourceRange() << Param0->getType()
10196 << Context.getRValueReferenceType(Context.getRecordType(RD));
10197 return false;
10198 }
10199 break;
10200 }
10201
10202 case CXXInvalid:
10203 llvm_unreachable("not a special member");
10204 }
10205
10206 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10207 if (Diagnose)
10208 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10209 diag::note_nontrivial_default_arg)
10210 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10211 return false;
10212 }
10213 if (MD->isVariadic()) {
10214 if (Diagnose)
10215 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10216 return false;
10217 }
10218
10219 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10220 // A copy/move [constructor or assignment operator] is trivial if
10221 // -- the [member] selected to copy/move each direct base class subobject
10222 // is trivial
10223 //
10224 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10225 // A [default constructor or destructor] is trivial if
10226 // -- all the direct base classes have trivial [default constructors or
10227 // destructors]
10228 for (const auto &BI : RD->bases())
10229 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10230 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10231 return false;
10232
10233 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10234 // A copy/move [constructor or assignment operator] for a class X is
10235 // trivial if
10236 // -- for each non-static data member of X that is of class type (or array
10237 // thereof), the constructor selected to copy/move that member is
10238 // trivial
10239 //
10240 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10241 // A [default constructor or destructor] is trivial if
10242 // -- for all of the non-static data members of its class that are of class
10243 // type (or array thereof), each such class has a trivial [default
10244 // constructor or destructor]
10245 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10246 return false;
10247
10248 // C++11 [class.dtor]p5:
10249 // A destructor is trivial if [...]
10250 // -- the destructor is not virtual
10251 if (CSM == CXXDestructor && MD->isVirtual()) {
10252 if (Diagnose)
10253 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10254 return false;
10255 }
10256
10257 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10258 // A [special member] for class X is trivial if [...]
10259 // -- class X has no virtual functions and no virtual base classes
10260 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
10261 if (!Diagnose)
10262 return false;
10263
10264 if (RD->getNumVBases()) {
10265 // Check for virtual bases. We already know that the corresponding
10266 // member in all bases is trivial, so vbases must all be direct.
10267 CXXBaseSpecifier &BS = *RD->vbases_begin();
10268 assert(BS.isVirtual());
10269 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10270 return false;
10271 }
10272
10273 // Must have a virtual method.
10274 for (const auto *MI : RD->methods()) {
10275 if (MI->isVirtual()) {
10276 SourceLocation MLoc = MI->getBeginLoc();
10277 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10278 return false;
10279 }
10280 }
10281
10282 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10283 }
10284
10285 // Looks like it's trivial!
10286 return true;
10287 }
10288
10289 namespace {
10290 struct FindHiddenVirtualMethod {
10291 Sema *S;
10292 CXXMethodDecl *Method;
10293 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10294 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10295
10296 private:
10297 /// Check whether any most overridden method from MD in Methods
CheckMostOverridenMethods__anon067e66482711::FindHiddenVirtualMethod10298 static bool CheckMostOverridenMethods(
10299 const CXXMethodDecl *MD,
10300 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10301 if (MD->size_overridden_methods() == 0)
10302 return Methods.count(MD->getCanonicalDecl());
10303 for (const CXXMethodDecl *O : MD->overridden_methods())
10304 if (CheckMostOverridenMethods(O, Methods))
10305 return true;
10306 return false;
10307 }
10308
10309 public:
10310 /// Member lookup function that determines whether a given C++
10311 /// method overloads virtual methods in a base class without overriding any,
10312 /// to be used with CXXRecordDecl::lookupInBases().
operator ()__anon067e66482711::FindHiddenVirtualMethod10313 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10314 RecordDecl *BaseRecord =
10315 Specifier->getType()->castAs<RecordType>()->getDecl();
10316
10317 DeclarationName Name = Method->getDeclName();
10318 assert(Name.getNameKind() == DeclarationName::Identifier);
10319
10320 bool foundSameNameMethod = false;
10321 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10322 for (Path.Decls = BaseRecord->lookup(Name).begin();
10323 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10324 NamedDecl *D = *Path.Decls;
10325 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10326 MD = MD->getCanonicalDecl();
10327 foundSameNameMethod = true;
10328 // Interested only in hidden virtual methods.
10329 if (!MD->isVirtual())
10330 continue;
10331 // If the method we are checking overrides a method from its base
10332 // don't warn about the other overloaded methods. Clang deviates from
10333 // GCC by only diagnosing overloads of inherited virtual functions that
10334 // do not override any other virtual functions in the base. GCC's
10335 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10336 // function from a base class. These cases may be better served by a
10337 // warning (not specific to virtual functions) on call sites when the
10338 // call would select a different function from the base class, were it
10339 // visible.
10340 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10341 if (!S->IsOverload(Method, MD, false))
10342 return true;
10343 // Collect the overload only if its hidden.
10344 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10345 overloadedMethods.push_back(MD);
10346 }
10347 }
10348
10349 if (foundSameNameMethod)
10350 OverloadedMethods.append(overloadedMethods.begin(),
10351 overloadedMethods.end());
10352 return foundSameNameMethod;
10353 }
10354 };
10355 } // end anonymous namespace
10356
10357 /// Add the most overridden methods from MD to Methods
AddMostOverridenMethods(const CXXMethodDecl * MD,llvm::SmallPtrSetImpl<const CXXMethodDecl * > & Methods)10358 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10359 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10360 if (MD->size_overridden_methods() == 0)
10361 Methods.insert(MD->getCanonicalDecl());
10362 else
10363 for (const CXXMethodDecl *O : MD->overridden_methods())
10364 AddMostOverridenMethods(O, Methods);
10365 }
10366
10367 /// Check if a method overloads virtual methods in a base class without
10368 /// overriding any.
FindHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)10369 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10370 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10371 if (!MD->getDeclName().isIdentifier())
10372 return;
10373
10374 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10375 /*bool RecordPaths=*/false,
10376 /*bool DetectVirtual=*/false);
10377 FindHiddenVirtualMethod FHVM;
10378 FHVM.Method = MD;
10379 FHVM.S = this;
10380
10381 // Keep the base methods that were overridden or introduced in the subclass
10382 // by 'using' in a set. A base method not in this set is hidden.
10383 CXXRecordDecl *DC = MD->getParent();
10384 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10385 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10386 NamedDecl *ND = *I;
10387 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10388 ND = shad->getTargetDecl();
10389 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10390 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10391 }
10392
10393 if (DC->lookupInBases(FHVM, Paths))
10394 OverloadedMethods = FHVM.OverloadedMethods;
10395 }
10396
NoteHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)10397 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10398 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10399 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10400 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10401 PartialDiagnostic PD = PDiag(
10402 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10403 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10404 Diag(overloadedMD->getLocation(), PD);
10405 }
10406 }
10407
10408 /// Diagnose methods which overload virtual methods in a base class
10409 /// without overriding any.
DiagnoseHiddenVirtualMethods(CXXMethodDecl * MD)10410 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10411 if (MD->isInvalidDecl())
10412 return;
10413
10414 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10415 return;
10416
10417 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10418 FindHiddenVirtualMethods(MD, OverloadedMethods);
10419 if (!OverloadedMethods.empty()) {
10420 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10421 << MD << (OverloadedMethods.size() > 1);
10422
10423 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10424 }
10425 }
10426
checkIllFormedTrivialABIStruct(CXXRecordDecl & RD)10427 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10428 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10429 // No diagnostics if this is a template instantiation.
10430 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10431 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10432 diag::ext_cannot_use_trivial_abi) << &RD;
10433 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10434 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10435 }
10436 RD.dropAttr<TrivialABIAttr>();
10437 };
10438
10439 // Ill-formed if the copy and move constructors are deleted.
10440 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10441 // If the type is dependent, then assume it might have
10442 // implicit copy or move ctor because we won't know yet at this point.
10443 if (RD.isDependentType())
10444 return true;
10445 if (RD.needsImplicitCopyConstructor() &&
10446 !RD.defaultedCopyConstructorIsDeleted())
10447 return true;
10448 if (RD.needsImplicitMoveConstructor() &&
10449 !RD.defaultedMoveConstructorIsDeleted())
10450 return true;
10451 for (const CXXConstructorDecl *CD : RD.ctors())
10452 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10453 return true;
10454 return false;
10455 };
10456
10457 if (!HasNonDeletedCopyOrMoveConstructor()) {
10458 PrintDiagAndRemoveAttr(0);
10459 return;
10460 }
10461
10462 // Ill-formed if the struct has virtual functions.
10463 if (RD.isPolymorphic()) {
10464 PrintDiagAndRemoveAttr(1);
10465 return;
10466 }
10467
10468 for (const auto &B : RD.bases()) {
10469 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10470 // virtual base.
10471 if (!B.getType()->isDependentType() &&
10472 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10473 PrintDiagAndRemoveAttr(2);
10474 return;
10475 }
10476
10477 if (B.isVirtual()) {
10478 PrintDiagAndRemoveAttr(3);
10479 return;
10480 }
10481 }
10482
10483 for (const auto *FD : RD.fields()) {
10484 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10485 // non-trivial for the purpose of calls.
10486 QualType FT = FD->getType();
10487 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10488 PrintDiagAndRemoveAttr(4);
10489 return;
10490 }
10491
10492 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10493 if (!RT->isDependentType() &&
10494 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10495 PrintDiagAndRemoveAttr(5);
10496 return;
10497 }
10498 }
10499 }
10500
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & AttrList)10501 void Sema::ActOnFinishCXXMemberSpecification(
10502 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10503 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10504 if (!TagDecl)
10505 return;
10506
10507 AdjustDeclIfTemplate(TagDecl);
10508
10509 for (const ParsedAttr &AL : AttrList) {
10510 if (AL.getKind() != ParsedAttr::AT_Visibility)
10511 continue;
10512 AL.setInvalid();
10513 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10514 }
10515
10516 ActOnFields(S, RLoc, TagDecl,
10517 llvm::ArrayRef(
10518 // strict aliasing violation!
10519 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10520 FieldCollector->getCurNumFields()),
10521 LBrac, RBrac, AttrList);
10522
10523 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10524 }
10525
10526 /// Find the equality comparison functions that should be implicitly declared
10527 /// in a given class definition, per C++2a [class.compare.default]p3.
findImplicitlyDeclaredEqualityComparisons(ASTContext & Ctx,CXXRecordDecl * RD,llvm::SmallVectorImpl<FunctionDecl * > & Spaceships)10528 static void findImplicitlyDeclaredEqualityComparisons(
10529 ASTContext &Ctx, CXXRecordDecl *RD,
10530 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10531 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10532 if (!RD->lookup(EqEq).empty())
10533 // Member operator== explicitly declared: no implicit operator==s.
10534 return;
10535
10536 // Traverse friends looking for an '==' or a '<=>'.
10537 for (FriendDecl *Friend : RD->friends()) {
10538 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10539 if (!FD) continue;
10540
10541 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10542 // Friend operator== explicitly declared: no implicit operator==s.
10543 Spaceships.clear();
10544 return;
10545 }
10546
10547 if (FD->getOverloadedOperator() == OO_Spaceship &&
10548 FD->isExplicitlyDefaulted())
10549 Spaceships.push_back(FD);
10550 }
10551
10552 // Look for members named 'operator<=>'.
10553 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10554 for (NamedDecl *ND : RD->lookup(Cmp)) {
10555 // Note that we could find a non-function here (either a function template
10556 // or a using-declaration). Neither case results in an implicit
10557 // 'operator=='.
10558 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10559 if (FD->isExplicitlyDefaulted())
10560 Spaceships.push_back(FD);
10561 }
10562 }
10563
10564 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10565 /// special functions, such as the default constructor, copy
10566 /// constructor, or destructor, to the given C++ class (C++
10567 /// [special]p1). This routine can only be executed just before the
10568 /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)10569 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10570 // Don't add implicit special members to templated classes.
10571 // FIXME: This means unqualified lookups for 'operator=' within a class
10572 // template don't work properly.
10573 if (!ClassDecl->isDependentType()) {
10574 if (ClassDecl->needsImplicitDefaultConstructor()) {
10575 ++getASTContext().NumImplicitDefaultConstructors;
10576
10577 if (ClassDecl->hasInheritedConstructor())
10578 DeclareImplicitDefaultConstructor(ClassDecl);
10579 }
10580
10581 if (ClassDecl->needsImplicitCopyConstructor()) {
10582 ++getASTContext().NumImplicitCopyConstructors;
10583
10584 // If the properties or semantics of the copy constructor couldn't be
10585 // determined while the class was being declared, force a declaration
10586 // of it now.
10587 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10588 ClassDecl->hasInheritedConstructor())
10589 DeclareImplicitCopyConstructor(ClassDecl);
10590 // For the MS ABI we need to know whether the copy ctor is deleted. A
10591 // prerequisite for deleting the implicit copy ctor is that the class has
10592 // a move ctor or move assignment that is either user-declared or whose
10593 // semantics are inherited from a subobject. FIXME: We should provide a
10594 // more direct way for CodeGen to ask whether the constructor was deleted.
10595 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10596 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10597 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10598 ClassDecl->hasUserDeclaredMoveAssignment() ||
10599 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10600 DeclareImplicitCopyConstructor(ClassDecl);
10601 }
10602
10603 if (getLangOpts().CPlusPlus11 &&
10604 ClassDecl->needsImplicitMoveConstructor()) {
10605 ++getASTContext().NumImplicitMoveConstructors;
10606
10607 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10608 ClassDecl->hasInheritedConstructor())
10609 DeclareImplicitMoveConstructor(ClassDecl);
10610 }
10611
10612 if (ClassDecl->needsImplicitCopyAssignment()) {
10613 ++getASTContext().NumImplicitCopyAssignmentOperators;
10614
10615 // If we have a dynamic class, then the copy assignment operator may be
10616 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10617 // it shows up in the right place in the vtable and that we diagnose
10618 // problems with the implicit exception specification.
10619 if (ClassDecl->isDynamicClass() ||
10620 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10621 ClassDecl->hasInheritedAssignment())
10622 DeclareImplicitCopyAssignment(ClassDecl);
10623 }
10624
10625 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10626 ++getASTContext().NumImplicitMoveAssignmentOperators;
10627
10628 // Likewise for the move assignment operator.
10629 if (ClassDecl->isDynamicClass() ||
10630 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10631 ClassDecl->hasInheritedAssignment())
10632 DeclareImplicitMoveAssignment(ClassDecl);
10633 }
10634
10635 if (ClassDecl->needsImplicitDestructor()) {
10636 ++getASTContext().NumImplicitDestructors;
10637
10638 // If we have a dynamic class, then the destructor may be virtual, so we
10639 // have to declare the destructor immediately. This ensures that, e.g., it
10640 // shows up in the right place in the vtable and that we diagnose problems
10641 // with the implicit exception specification.
10642 if (ClassDecl->isDynamicClass() ||
10643 ClassDecl->needsOverloadResolutionForDestructor())
10644 DeclareImplicitDestructor(ClassDecl);
10645 }
10646 }
10647
10648 // C++2a [class.compare.default]p3:
10649 // If the member-specification does not explicitly declare any member or
10650 // friend named operator==, an == operator function is declared implicitly
10651 // for each defaulted three-way comparison operator function defined in
10652 // the member-specification
10653 // FIXME: Consider doing this lazily.
10654 // We do this during the initial parse for a class template, not during
10655 // instantiation, so that we can handle unqualified lookups for 'operator=='
10656 // when parsing the template.
10657 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10658 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10659 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10660 DefaultedSpaceships);
10661 for (auto *FD : DefaultedSpaceships)
10662 DeclareImplicitEqualityComparison(ClassDecl, FD);
10663 }
10664 }
10665
10666 unsigned
ActOnReenterTemplateScope(Decl * D,llvm::function_ref<Scope * ()> EnterScope)10667 Sema::ActOnReenterTemplateScope(Decl *D,
10668 llvm::function_ref<Scope *()> EnterScope) {
10669 if (!D)
10670 return 0;
10671 AdjustDeclIfTemplate(D);
10672
10673 // In order to get name lookup right, reenter template scopes in order from
10674 // outermost to innermost.
10675 SmallVector<TemplateParameterList *, 4> ParameterLists;
10676 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10677
10678 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10679 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10680 ParameterLists.push_back(DD->getTemplateParameterList(i));
10681
10682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10683 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10684 ParameterLists.push_back(FTD->getTemplateParameters());
10685 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10686 LookupDC = VD->getDeclContext();
10687
10688 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10689 ParameterLists.push_back(VTD->getTemplateParameters());
10690 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10691 ParameterLists.push_back(PSD->getTemplateParameters());
10692 }
10693 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10694 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10695 ParameterLists.push_back(TD->getTemplateParameterList(i));
10696
10697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10698 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10699 ParameterLists.push_back(CTD->getTemplateParameters());
10700 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10701 ParameterLists.push_back(PSD->getTemplateParameters());
10702 }
10703 }
10704 // FIXME: Alias declarations and concepts.
10705
10706 unsigned Count = 0;
10707 Scope *InnermostTemplateScope = nullptr;
10708 for (TemplateParameterList *Params : ParameterLists) {
10709 // Ignore explicit specializations; they don't contribute to the template
10710 // depth.
10711 if (Params->size() == 0)
10712 continue;
10713
10714 InnermostTemplateScope = EnterScope();
10715 for (NamedDecl *Param : *Params) {
10716 if (Param->getDeclName()) {
10717 InnermostTemplateScope->AddDecl(Param);
10718 IdResolver.AddDecl(Param);
10719 }
10720 }
10721 ++Count;
10722 }
10723
10724 // Associate the new template scopes with the corresponding entities.
10725 if (InnermostTemplateScope) {
10726 assert(LookupDC && "no enclosing DeclContext for template lookup");
10727 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10728 }
10729
10730 return Count;
10731 }
10732
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)10733 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10734 if (!RecordD) return;
10735 AdjustDeclIfTemplate(RecordD);
10736 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10737 PushDeclContext(S, Record);
10738 }
10739
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)10740 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10741 if (!RecordD) return;
10742 PopDeclContext();
10743 }
10744
10745 /// This is used to implement the constant expression evaluation part of the
10746 /// attribute enable_if extension. There is nothing in standard C++ which would
10747 /// require reentering parameters.
ActOnReenterCXXMethodParameter(Scope * S,ParmVarDecl * Param)10748 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10749 if (!Param)
10750 return;
10751
10752 S->AddDecl(Param);
10753 if (Param->getDeclName())
10754 IdResolver.AddDecl(Param);
10755 }
10756
10757 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10758 /// parsing a top-level (non-nested) C++ class, and we are now
10759 /// parsing those parts of the given Method declaration that could
10760 /// not be parsed earlier (C++ [class.mem]p2), such as default
10761 /// arguments. This action should enter the scope of the given
10762 /// Method declaration as if we had just parsed the qualified method
10763 /// name. However, it should not bring the parameters into scope;
10764 /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)10765 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10766 }
10767
10768 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10769 /// C++ method declaration. We're (re-)introducing the given
10770 /// function parameter into scope for use in parsing later parts of
10771 /// the method declaration. For example, we could see an
10772 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)10773 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10774 if (!ParamD)
10775 return;
10776
10777 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10778
10779 S->AddDecl(Param);
10780 if (Param->getDeclName())
10781 IdResolver.AddDecl(Param);
10782 }
10783
10784 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10785 /// processing the delayed method declaration for Method. The method
10786 /// declaration is now considered finished. There may be a separate
10787 /// ActOnStartOfFunctionDef action later (not necessarily
10788 /// immediately!) for this method, if it was also defined inside the
10789 /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)10790 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10791 if (!MethodD)
10792 return;
10793
10794 AdjustDeclIfTemplate(MethodD);
10795
10796 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10797
10798 // Now that we have our default arguments, check the constructor
10799 // again. It could produce additional diagnostics or affect whether
10800 // the class has implicitly-declared destructors, among other
10801 // things.
10802 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10803 CheckConstructor(Constructor);
10804
10805 // Check the default arguments, which we may have added.
10806 if (!Method->isInvalidDecl())
10807 CheckCXXDefaultArguments(Method);
10808 }
10809
10810 // Emit the given diagnostic for each non-address-space qualifier.
10811 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
checkMethodTypeQualifiers(Sema & S,Declarator & D,unsigned DiagID)10812 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10813 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10814 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10815 bool DiagOccured = false;
10816 FTI.MethodQualifiers->forEachQualifier(
10817 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10818 SourceLocation SL) {
10819 // This diagnostic should be emitted on any qualifier except an addr
10820 // space qualifier. However, forEachQualifier currently doesn't visit
10821 // addr space qualifiers, so there's no way to write this condition
10822 // right now; we just diagnose on everything.
10823 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10824 DiagOccured = true;
10825 });
10826 if (DiagOccured)
10827 D.setInvalidType();
10828 }
10829 }
10830
10831 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10832 /// the well-formedness of the constructor declarator @p D with type @p
10833 /// R. If there are any errors in the declarator, this routine will
10834 /// emit diagnostics and set the invalid bit to true. In any case, the type
10835 /// will be updated to reflect a well-formed type for the constructor and
10836 /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)10837 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10838 StorageClass &SC) {
10839 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10840
10841 // C++ [class.ctor]p3:
10842 // A constructor shall not be virtual (10.3) or static (9.4). A
10843 // constructor can be invoked for a const, volatile or const
10844 // volatile object. A constructor shall not be declared const,
10845 // volatile, or const volatile (9.3.2).
10846 if (isVirtual) {
10847 if (!D.isInvalidType())
10848 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10849 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10850 << SourceRange(D.getIdentifierLoc());
10851 D.setInvalidType();
10852 }
10853 if (SC == SC_Static) {
10854 if (!D.isInvalidType())
10855 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10856 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10857 << SourceRange(D.getIdentifierLoc());
10858 D.setInvalidType();
10859 SC = SC_None;
10860 }
10861
10862 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10863 diagnoseIgnoredQualifiers(
10864 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10865 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10866 D.getDeclSpec().getRestrictSpecLoc(),
10867 D.getDeclSpec().getAtomicSpecLoc());
10868 D.setInvalidType();
10869 }
10870
10871 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10872
10873 // C++0x [class.ctor]p4:
10874 // A constructor shall not be declared with a ref-qualifier.
10875 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10876 if (FTI.hasRefQualifier()) {
10877 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10878 << FTI.RefQualifierIsLValueRef
10879 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10880 D.setInvalidType();
10881 }
10882
10883 // Rebuild the function type "R" without any type qualifiers (in
10884 // case any of the errors above fired) and with "void" as the
10885 // return type, since constructors don't have return types.
10886 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10887 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10888 return R;
10889
10890 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10891 EPI.TypeQuals = Qualifiers();
10892 EPI.RefQualifier = RQ_None;
10893
10894 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10895 }
10896
10897 /// CheckConstructor - Checks a fully-formed constructor for
10898 /// well-formedness, issuing any diagnostics required. Returns true if
10899 /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)10900 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10901 CXXRecordDecl *ClassDecl
10902 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10903 if (!ClassDecl)
10904 return Constructor->setInvalidDecl();
10905
10906 // C++ [class.copy]p3:
10907 // A declaration of a constructor for a class X is ill-formed if
10908 // its first parameter is of type (optionally cv-qualified) X and
10909 // either there are no other parameters or else all other
10910 // parameters have default arguments.
10911 if (!Constructor->isInvalidDecl() &&
10912 Constructor->hasOneParamOrDefaultArgs() &&
10913 Constructor->getTemplateSpecializationKind() !=
10914 TSK_ImplicitInstantiation) {
10915 QualType ParamType = Constructor->getParamDecl(0)->getType();
10916 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10917 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10918 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10919 const char *ConstRef
10920 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10921 : " const &";
10922 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10923 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10924
10925 // FIXME: Rather that making the constructor invalid, we should endeavor
10926 // to fix the type.
10927 Constructor->setInvalidDecl();
10928 }
10929 }
10930 }
10931
10932 /// CheckDestructor - Checks a fully-formed destructor definition for
10933 /// well-formedness, issuing any diagnostics required. Returns true
10934 /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)10935 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10936 CXXRecordDecl *RD = Destructor->getParent();
10937
10938 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10939 SourceLocation Loc;
10940
10941 if (!Destructor->isImplicit())
10942 Loc = Destructor->getLocation();
10943 else
10944 Loc = RD->getLocation();
10945
10946 // If we have a virtual destructor, look up the deallocation function
10947 if (FunctionDecl *OperatorDelete =
10948 FindDeallocationFunctionForDestructor(Loc, RD)) {
10949 Expr *ThisArg = nullptr;
10950
10951 // If the notional 'delete this' expression requires a non-trivial
10952 // conversion from 'this' to the type of a destroying operator delete's
10953 // first parameter, perform that conversion now.
10954 if (OperatorDelete->isDestroyingOperatorDelete()) {
10955 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10956 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10957 // C++ [class.dtor]p13:
10958 // ... as if for the expression 'delete this' appearing in a
10959 // non-virtual destructor of the destructor's class.
10960 ContextRAII SwitchContext(*this, Destructor);
10961 ExprResult This =
10962 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10963 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10964 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10965 if (This.isInvalid()) {
10966 // FIXME: Register this as a context note so that it comes out
10967 // in the right order.
10968 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10969 return true;
10970 }
10971 ThisArg = This.get();
10972 }
10973 }
10974
10975 DiagnoseUseOfDecl(OperatorDelete, Loc);
10976 MarkFunctionReferenced(Loc, OperatorDelete);
10977 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10978 }
10979 }
10980
10981 return false;
10982 }
10983
10984 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10985 /// the well-formednes of the destructor declarator @p D with type @p
10986 /// R. If there are any errors in the declarator, this routine will
10987 /// emit diagnostics and set the declarator to invalid. Even if this happens,
10988 /// will be updated to reflect a well-formed type for the destructor and
10989 /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)10990 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10991 StorageClass& SC) {
10992 // C++ [class.dtor]p1:
10993 // [...] A typedef-name that names a class is a class-name
10994 // (7.1.3); however, a typedef-name that names a class shall not
10995 // be used as the identifier in the declarator for a destructor
10996 // declaration.
10997 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10998 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10999 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11000 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11001 else if (const TemplateSpecializationType *TST =
11002 DeclaratorType->getAs<TemplateSpecializationType>())
11003 if (TST->isTypeAlias())
11004 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11005 << DeclaratorType << 1;
11006
11007 // C++ [class.dtor]p2:
11008 // A destructor is used to destroy objects of its class type. A
11009 // destructor takes no parameters, and no return type can be
11010 // specified for it (not even void). The address of a destructor
11011 // shall not be taken. A destructor shall not be static. A
11012 // destructor can be invoked for a const, volatile or const
11013 // volatile object. A destructor shall not be declared const,
11014 // volatile or const volatile (9.3.2).
11015 if (SC == SC_Static) {
11016 if (!D.isInvalidType())
11017 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11018 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11019 << SourceRange(D.getIdentifierLoc())
11020 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11021
11022 SC = SC_None;
11023 }
11024 if (!D.isInvalidType()) {
11025 // Destructors don't have return types, but the parser will
11026 // happily parse something like:
11027 //
11028 // class X {
11029 // float ~X();
11030 // };
11031 //
11032 // The return type will be eliminated later.
11033 if (D.getDeclSpec().hasTypeSpecifier())
11034 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11035 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11036 << SourceRange(D.getIdentifierLoc());
11037 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11038 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11039 SourceLocation(),
11040 D.getDeclSpec().getConstSpecLoc(),
11041 D.getDeclSpec().getVolatileSpecLoc(),
11042 D.getDeclSpec().getRestrictSpecLoc(),
11043 D.getDeclSpec().getAtomicSpecLoc());
11044 D.setInvalidType();
11045 }
11046 }
11047
11048 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11049
11050 // C++0x [class.dtor]p2:
11051 // A destructor shall not be declared with a ref-qualifier.
11052 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11053 if (FTI.hasRefQualifier()) {
11054 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11055 << FTI.RefQualifierIsLValueRef
11056 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11057 D.setInvalidType();
11058 }
11059
11060 // Make sure we don't have any parameters.
11061 if (FTIHasNonVoidParameters(FTI)) {
11062 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11063
11064 // Delete the parameters.
11065 FTI.freeParams();
11066 D.setInvalidType();
11067 }
11068
11069 // Make sure the destructor isn't variadic.
11070 if (FTI.isVariadic) {
11071 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11072 D.setInvalidType();
11073 }
11074
11075 // Rebuild the function type "R" without any type qualifiers or
11076 // parameters (in case any of the errors above fired) and with
11077 // "void" as the return type, since destructors don't have return
11078 // types.
11079 if (!D.isInvalidType())
11080 return R;
11081
11082 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11083 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11084 EPI.Variadic = false;
11085 EPI.TypeQuals = Qualifiers();
11086 EPI.RefQualifier = RQ_None;
11087 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11088 }
11089
extendLeft(SourceRange & R,SourceRange Before)11090 static void extendLeft(SourceRange &R, SourceRange Before) {
11091 if (Before.isInvalid())
11092 return;
11093 R.setBegin(Before.getBegin());
11094 if (R.getEnd().isInvalid())
11095 R.setEnd(Before.getEnd());
11096 }
11097
extendRight(SourceRange & R,SourceRange After)11098 static void extendRight(SourceRange &R, SourceRange After) {
11099 if (After.isInvalid())
11100 return;
11101 if (R.getBegin().isInvalid())
11102 R.setBegin(After.getBegin());
11103 R.setEnd(After.getEnd());
11104 }
11105
11106 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11107 /// well-formednes of the conversion function declarator @p D with
11108 /// type @p R. If there are any errors in the declarator, this routine
11109 /// will emit diagnostics and return true. Otherwise, it will return
11110 /// false. Either way, the type @p R will be updated to reflect a
11111 /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)11112 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11113 StorageClass& SC) {
11114 // C++ [class.conv.fct]p1:
11115 // Neither parameter types nor return type can be specified. The
11116 // type of a conversion function (8.3.5) is "function taking no
11117 // parameter returning conversion-type-id."
11118 if (SC == SC_Static) {
11119 if (!D.isInvalidType())
11120 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11121 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11122 << D.getName().getSourceRange();
11123 D.setInvalidType();
11124 SC = SC_None;
11125 }
11126
11127 TypeSourceInfo *ConvTSI = nullptr;
11128 QualType ConvType =
11129 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11130
11131 const DeclSpec &DS = D.getDeclSpec();
11132 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11133 // Conversion functions don't have return types, but the parser will
11134 // happily parse something like:
11135 //
11136 // class X {
11137 // float operator bool();
11138 // };
11139 //
11140 // The return type will be changed later anyway.
11141 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11142 << SourceRange(DS.getTypeSpecTypeLoc())
11143 << SourceRange(D.getIdentifierLoc());
11144 D.setInvalidType();
11145 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11146 // It's also plausible that the user writes type qualifiers in the wrong
11147 // place, such as:
11148 // struct S { const operator int(); };
11149 // FIXME: we could provide a fixit to move the qualifiers onto the
11150 // conversion type.
11151 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11152 << SourceRange(D.getIdentifierLoc()) << 0;
11153 D.setInvalidType();
11154 }
11155 const auto *Proto = R->castAs<FunctionProtoType>();
11156 // Make sure we don't have any parameters.
11157 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11158 unsigned NumParam = Proto->getNumParams();
11159
11160 // [C++2b]
11161 // A conversion function shall have no non-object parameters.
11162 if (NumParam == 1) {
11163 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11164 if (const auto *First =
11165 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11166 First && First->isExplicitObjectParameter())
11167 NumParam--;
11168 }
11169
11170 if (NumParam != 0) {
11171 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11172 // Delete the parameters.
11173 FTI.freeParams();
11174 D.setInvalidType();
11175 } else if (Proto->isVariadic()) {
11176 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11177 D.setInvalidType();
11178 }
11179
11180 // Diagnose "&operator bool()" and other such nonsense. This
11181 // is actually a gcc extension which we don't support.
11182 if (Proto->getReturnType() != ConvType) {
11183 bool NeedsTypedef = false;
11184 SourceRange Before, After;
11185
11186 // Walk the chunks and extract information on them for our diagnostic.
11187 bool PastFunctionChunk = false;
11188 for (auto &Chunk : D.type_objects()) {
11189 switch (Chunk.Kind) {
11190 case DeclaratorChunk::Function:
11191 if (!PastFunctionChunk) {
11192 if (Chunk.Fun.HasTrailingReturnType) {
11193 TypeSourceInfo *TRT = nullptr;
11194 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11195 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11196 }
11197 PastFunctionChunk = true;
11198 break;
11199 }
11200 [[fallthrough]];
11201 case DeclaratorChunk::Array:
11202 NeedsTypedef = true;
11203 extendRight(After, Chunk.getSourceRange());
11204 break;
11205
11206 case DeclaratorChunk::Pointer:
11207 case DeclaratorChunk::BlockPointer:
11208 case DeclaratorChunk::Reference:
11209 case DeclaratorChunk::MemberPointer:
11210 case DeclaratorChunk::Pipe:
11211 extendLeft(Before, Chunk.getSourceRange());
11212 break;
11213
11214 case DeclaratorChunk::Paren:
11215 extendLeft(Before, Chunk.Loc);
11216 extendRight(After, Chunk.EndLoc);
11217 break;
11218 }
11219 }
11220
11221 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11222 After.isValid() ? After.getBegin() :
11223 D.getIdentifierLoc();
11224 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11225 DB << Before << After;
11226
11227 if (!NeedsTypedef) {
11228 DB << /*don't need a typedef*/0;
11229
11230 // If we can provide a correct fix-it hint, do so.
11231 if (After.isInvalid() && ConvTSI) {
11232 SourceLocation InsertLoc =
11233 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11234 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11235 << FixItHint::CreateInsertionFromRange(
11236 InsertLoc, CharSourceRange::getTokenRange(Before))
11237 << FixItHint::CreateRemoval(Before);
11238 }
11239 } else if (!Proto->getReturnType()->isDependentType()) {
11240 DB << /*typedef*/1 << Proto->getReturnType();
11241 } else if (getLangOpts().CPlusPlus11) {
11242 DB << /*alias template*/2 << Proto->getReturnType();
11243 } else {
11244 DB << /*might not be fixable*/3;
11245 }
11246
11247 // Recover by incorporating the other type chunks into the result type.
11248 // Note, this does *not* change the name of the function. This is compatible
11249 // with the GCC extension:
11250 // struct S { &operator int(); } s;
11251 // int &r = s.operator int(); // ok in GCC
11252 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11253 ConvType = Proto->getReturnType();
11254 }
11255
11256 // C++ [class.conv.fct]p4:
11257 // The conversion-type-id shall not represent a function type nor
11258 // an array type.
11259 if (ConvType->isArrayType()) {
11260 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11261 ConvType = Context.getPointerType(ConvType);
11262 D.setInvalidType();
11263 } else if (ConvType->isFunctionType()) {
11264 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11265 ConvType = Context.getPointerType(ConvType);
11266 D.setInvalidType();
11267 }
11268
11269 // Rebuild the function type "R" without any parameters (in case any
11270 // of the errors above fired) and with the conversion type as the
11271 // return type.
11272 if (D.isInvalidType())
11273 R = Context.getFunctionType(ConvType, std::nullopt,
11274 Proto->getExtProtoInfo());
11275
11276 // C++0x explicit conversion operators.
11277 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11278 Diag(DS.getExplicitSpecLoc(),
11279 getLangOpts().CPlusPlus11
11280 ? diag::warn_cxx98_compat_explicit_conversion_functions
11281 : diag::ext_explicit_conversion_functions)
11282 << SourceRange(DS.getExplicitSpecRange());
11283 }
11284
11285 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11286 /// the declaration of the given C++ conversion function. This routine
11287 /// is responsible for recording the conversion function in the C++
11288 /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)11289 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11290 assert(Conversion && "Expected to receive a conversion function declaration");
11291
11292 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11293
11294 // Make sure we aren't redeclaring the conversion function.
11295 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11296 // C++ [class.conv.fct]p1:
11297 // [...] A conversion function is never used to convert a
11298 // (possibly cv-qualified) object to the (possibly cv-qualified)
11299 // same object type (or a reference to it), to a (possibly
11300 // cv-qualified) base class of that type (or a reference to it),
11301 // or to (possibly cv-qualified) void.
11302 QualType ClassType
11303 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11304 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11305 ConvType = ConvTypeRef->getPointeeType();
11306 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11307 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11308 /* Suppress diagnostics for instantiations. */;
11309 else if (Conversion->size_overridden_methods() != 0)
11310 /* Suppress diagnostics for overriding virtual function in a base class. */;
11311 else if (ConvType->isRecordType()) {
11312 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11313 if (ConvType == ClassType)
11314 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11315 << ClassType;
11316 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11317 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11318 << ClassType << ConvType;
11319 } else if (ConvType->isVoidType()) {
11320 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11321 << ClassType << ConvType;
11322 }
11323
11324 if (FunctionTemplateDecl *ConversionTemplate =
11325 Conversion->getDescribedFunctionTemplate()) {
11326 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11327 ConvType = ConvTypePtr->getPointeeType();
11328 }
11329 if (ConvType->isUndeducedAutoType()) {
11330 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11331 << getReturnTypeLoc(Conversion).getSourceRange()
11332 << llvm::to_underlying(ConvType->getAs<AutoType>()->getKeyword())
11333 << /* in declaration of conversion function template= */ 24;
11334 }
11335
11336 return ConversionTemplate;
11337 }
11338
11339 return Conversion;
11340 }
11341
CheckExplicitObjectMemberFunction(DeclContext * DC,Declarator & D,DeclarationName Name,QualType R)11342 void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11343 DeclarationName Name, QualType R) {
11344 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11345 }
11346
CheckExplicitObjectLambda(Declarator & D)11347 void Sema::CheckExplicitObjectLambda(Declarator &D) {
11348 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11349 }
11350
CheckExplicitObjectMemberFunction(Declarator & D,DeclarationName Name,QualType R,bool IsLambda,DeclContext * DC)11351 void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11352 DeclarationName Name, QualType R,
11353 bool IsLambda, DeclContext *DC) {
11354 if (!D.isFunctionDeclarator())
11355 return;
11356
11357 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11358 if (FTI.NumParams == 0)
11359 return;
11360 ParmVarDecl *ExplicitObjectParam = nullptr;
11361 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11362 const auto &ParamInfo = FTI.Params[Idx];
11363 if (!ParamInfo.Param)
11364 continue;
11365 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11366 if (!Param->isExplicitObjectParameter())
11367 continue;
11368 if (Idx == 0) {
11369 ExplicitObjectParam = Param;
11370 continue;
11371 } else {
11372 Diag(Param->getLocation(),
11373 diag::err_explicit_object_parameter_must_be_first)
11374 << IsLambda << Param->getSourceRange();
11375 }
11376 }
11377 if (!ExplicitObjectParam)
11378 return;
11379
11380 if (ExplicitObjectParam->hasDefaultArg()) {
11381 Diag(ExplicitObjectParam->getLocation(),
11382 diag::err_explicit_object_default_arg)
11383 << ExplicitObjectParam->getSourceRange();
11384 }
11385
11386 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
11387 Diag(ExplicitObjectParam->getBeginLoc(),
11388 diag::err_explicit_object_parameter_nonmember)
11389 << D.getSourceRange() << /*static=*/0 << IsLambda;
11390 D.setInvalidType();
11391 }
11392
11393 if (D.getDeclSpec().isVirtualSpecified()) {
11394 Diag(ExplicitObjectParam->getBeginLoc(),
11395 diag::err_explicit_object_parameter_nonmember)
11396 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11397 D.setInvalidType();
11398 }
11399
11400 if (IsLambda && FTI.hasMutableQualifier()) {
11401 Diag(ExplicitObjectParam->getBeginLoc(),
11402 diag::err_explicit_object_parameter_mutable)
11403 << D.getSourceRange();
11404 }
11405
11406 if (IsLambda)
11407 return;
11408
11409 if (!DC || !DC->isRecord()) {
11410 Diag(ExplicitObjectParam->getLocation(),
11411 diag::err_explicit_object_parameter_nonmember)
11412 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11413 D.setInvalidType();
11414 return;
11415 }
11416
11417 // CWG2674: constructors and destructors cannot have explicit parameters.
11418 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11419 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11420 Diag(ExplicitObjectParam->getBeginLoc(),
11421 diag::err_explicit_object_parameter_constructor)
11422 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11423 << D.getSourceRange();
11424 D.setInvalidType();
11425 }
11426 }
11427
11428 namespace {
11429 /// Utility class to accumulate and print a diagnostic listing the invalid
11430 /// specifier(s) on a declaration.
11431 struct BadSpecifierDiagnoser {
BadSpecifierDiagnoser__anon067e66482b11::BadSpecifierDiagnoser11432 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11433 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
~BadSpecifierDiagnoser__anon067e66482b11::BadSpecifierDiagnoser11434 ~BadSpecifierDiagnoser() {
11435 Diagnostic << Specifiers;
11436 }
11437
check__anon067e66482b11::BadSpecifierDiagnoser11438 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11439 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11440 }
check__anon067e66482b11::BadSpecifierDiagnoser11441 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11442 return check(SpecLoc,
11443 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11444 }
check__anon067e66482b11::BadSpecifierDiagnoser11445 void check(SourceLocation SpecLoc, const char *Spec) {
11446 if (SpecLoc.isInvalid()) return;
11447 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11448 if (!Specifiers.empty()) Specifiers += " ";
11449 Specifiers += Spec;
11450 }
11451
11452 Sema &S;
11453 Sema::SemaDiagnosticBuilder Diagnostic;
11454 std::string Specifiers;
11455 };
11456 }
11457
11458 /// Check the validity of a declarator that we parsed for a deduction-guide.
11459 /// These aren't actually declarators in the grammar, so we need to check that
11460 /// the user didn't specify any pieces that are not part of the deduction-guide
11461 /// grammar. Return true on invalid deduction-guide.
CheckDeductionGuideDeclarator(Declarator & D,QualType & R,StorageClass & SC)11462 bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11463 StorageClass &SC) {
11464 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11465 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11466 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11467
11468 // C++ [temp.deduct.guide]p3:
11469 // A deduction-gide shall be declared in the same scope as the
11470 // corresponding class template.
11471 if (!CurContext->getRedeclContext()->Equals(
11472 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11473 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11474 << GuidedTemplateDecl;
11475 NoteTemplateLocation(*GuidedTemplateDecl);
11476 }
11477
11478 auto &DS = D.getMutableDeclSpec();
11479 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11480 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11481 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11482 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11483 BadSpecifierDiagnoser Diagnoser(
11484 *this, D.getIdentifierLoc(),
11485 diag::err_deduction_guide_invalid_specifier);
11486
11487 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11488 DS.ClearStorageClassSpecs();
11489 SC = SC_None;
11490
11491 // 'explicit' is permitted.
11492 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11493 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11494 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11495 DS.ClearConstexprSpec();
11496
11497 Diagnoser.check(DS.getConstSpecLoc(), "const");
11498 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11499 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11500 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11501 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11502 DS.ClearTypeQualifiers();
11503
11504 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11505 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11506 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11507 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11508 DS.ClearTypeSpecType();
11509 }
11510
11511 if (D.isInvalidType())
11512 return true;
11513
11514 // Check the declarator is simple enough.
11515 bool FoundFunction = false;
11516 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11517 if (Chunk.Kind == DeclaratorChunk::Paren)
11518 continue;
11519 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11520 Diag(D.getDeclSpec().getBeginLoc(),
11521 diag::err_deduction_guide_with_complex_decl)
11522 << D.getSourceRange();
11523 break;
11524 }
11525 if (!Chunk.Fun.hasTrailingReturnType())
11526 return Diag(D.getName().getBeginLoc(),
11527 diag::err_deduction_guide_no_trailing_return_type);
11528
11529 // Check that the return type is written as a specialization of
11530 // the template specified as the deduction-guide's name.
11531 // The template name may not be qualified. [temp.deduct.guide]
11532 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11533 TypeSourceInfo *TSI = nullptr;
11534 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11535 assert(TSI && "deduction guide has valid type but invalid return type?");
11536 bool AcceptableReturnType = false;
11537 bool MightInstantiateToSpecialization = false;
11538 if (auto RetTST =
11539 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11540 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11541 bool TemplateMatches =
11542 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11543 auto TKind = SpecifiedName.getKind();
11544 // A Using TemplateName can't actually be valid (either it's qualified, or
11545 // we're in the wrong scope). But we have diagnosed these problems
11546 // already.
11547 bool SimplyWritten = TKind == TemplateName::Template ||
11548 TKind == TemplateName::UsingTemplate;
11549 if (SimplyWritten && TemplateMatches)
11550 AcceptableReturnType = true;
11551 else {
11552 // This could still instantiate to the right type, unless we know it
11553 // names the wrong class template.
11554 auto *TD = SpecifiedName.getAsTemplateDecl();
11555 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11556 !TemplateMatches);
11557 }
11558 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11559 MightInstantiateToSpecialization = true;
11560 }
11561
11562 if (!AcceptableReturnType)
11563 return Diag(TSI->getTypeLoc().getBeginLoc(),
11564 diag::err_deduction_guide_bad_trailing_return_type)
11565 << GuidedTemplate << TSI->getType()
11566 << MightInstantiateToSpecialization
11567 << TSI->getTypeLoc().getSourceRange();
11568
11569 // Keep going to check that we don't have any inner declarator pieces (we
11570 // could still have a function returning a pointer to a function).
11571 FoundFunction = true;
11572 }
11573
11574 if (D.isFunctionDefinition())
11575 // we can still create a valid deduction guide here.
11576 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11577 return false;
11578 }
11579
11580 //===----------------------------------------------------------------------===//
11581 // Namespace Handling
11582 //===----------------------------------------------------------------------===//
11583
11584 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11585 /// reopened.
DiagnoseNamespaceInlineMismatch(Sema & S,SourceLocation KeywordLoc,SourceLocation Loc,IdentifierInfo * II,bool * IsInline,NamespaceDecl * PrevNS)11586 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11587 SourceLocation Loc,
11588 IdentifierInfo *II, bool *IsInline,
11589 NamespaceDecl *PrevNS) {
11590 assert(*IsInline != PrevNS->isInline());
11591
11592 // 'inline' must appear on the original definition, but not necessarily
11593 // on all extension definitions, so the note should point to the first
11594 // definition to avoid confusion.
11595 PrevNS = PrevNS->getFirstDecl();
11596
11597 if (PrevNS->isInline())
11598 // The user probably just forgot the 'inline', so suggest that it
11599 // be added back.
11600 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11601 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11602 else
11603 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11604
11605 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11606 *IsInline = PrevNS->isInline();
11607 }
11608
11609 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11610 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,const ParsedAttributesView & AttrList,UsingDirectiveDecl * & UD,bool IsNested)11611 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11612 SourceLocation InlineLoc,
11613 SourceLocation NamespaceLoc,
11614 SourceLocation IdentLoc, IdentifierInfo *II,
11615 SourceLocation LBrace,
11616 const ParsedAttributesView &AttrList,
11617 UsingDirectiveDecl *&UD, bool IsNested) {
11618 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11619 // For anonymous namespace, take the location of the left brace.
11620 SourceLocation Loc = II ? IdentLoc : LBrace;
11621 bool IsInline = InlineLoc.isValid();
11622 bool IsInvalid = false;
11623 bool IsStd = false;
11624 bool AddToKnown = false;
11625 Scope *DeclRegionScope = NamespcScope->getParent();
11626
11627 NamespaceDecl *PrevNS = nullptr;
11628 if (II) {
11629 // C++ [namespace.std]p7:
11630 // A translation unit shall not declare namespace std to be an inline
11631 // namespace (9.8.2).
11632 //
11633 // Precondition: the std namespace is in the file scope and is declared to
11634 // be inline
11635 auto DiagnoseInlineStdNS = [&]() {
11636 assert(IsInline && II->isStr("std") &&
11637 CurContext->getRedeclContext()->isTranslationUnit() &&
11638 "Precondition of DiagnoseInlineStdNS not met");
11639 Diag(InlineLoc, diag::err_inline_namespace_std)
11640 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11641 IsInline = false;
11642 };
11643 // C++ [namespace.def]p2:
11644 // The identifier in an original-namespace-definition shall not
11645 // have been previously defined in the declarative region in
11646 // which the original-namespace-definition appears. The
11647 // identifier in an original-namespace-definition is the name of
11648 // the namespace. Subsequently in that declarative region, it is
11649 // treated as an original-namespace-name.
11650 //
11651 // Since namespace names are unique in their scope, and we don't
11652 // look through using directives, just look for any ordinary names
11653 // as if by qualified name lookup.
11654 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11655 ForExternalRedeclaration);
11656 LookupQualifiedName(R, CurContext->getRedeclContext());
11657 NamedDecl *PrevDecl =
11658 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11659 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11660
11661 if (PrevNS) {
11662 // This is an extended namespace definition.
11663 if (IsInline && II->isStr("std") &&
11664 CurContext->getRedeclContext()->isTranslationUnit())
11665 DiagnoseInlineStdNS();
11666 else if (IsInline != PrevNS->isInline())
11667 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11668 &IsInline, PrevNS);
11669 } else if (PrevDecl) {
11670 // This is an invalid name redefinition.
11671 Diag(Loc, diag::err_redefinition_different_kind)
11672 << II;
11673 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11674 IsInvalid = true;
11675 // Continue on to push Namespc as current DeclContext and return it.
11676 } else if (II->isStr("std") &&
11677 CurContext->getRedeclContext()->isTranslationUnit()) {
11678 if (IsInline)
11679 DiagnoseInlineStdNS();
11680 // This is the first "real" definition of the namespace "std", so update
11681 // our cache of the "std" namespace to point at this definition.
11682 PrevNS = getStdNamespace();
11683 IsStd = true;
11684 AddToKnown = !IsInline;
11685 } else {
11686 // We've seen this namespace for the first time.
11687 AddToKnown = !IsInline;
11688 }
11689 } else {
11690 // Anonymous namespaces.
11691
11692 // Determine whether the parent already has an anonymous namespace.
11693 DeclContext *Parent = CurContext->getRedeclContext();
11694 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11695 PrevNS = TU->getAnonymousNamespace();
11696 } else {
11697 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11698 PrevNS = ND->getAnonymousNamespace();
11699 }
11700
11701 if (PrevNS && IsInline != PrevNS->isInline())
11702 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11703 &IsInline, PrevNS);
11704 }
11705
11706 NamespaceDecl *Namespc = NamespaceDecl::Create(
11707 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11708 if (IsInvalid)
11709 Namespc->setInvalidDecl();
11710
11711 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11712 AddPragmaAttributes(DeclRegionScope, Namespc);
11713
11714 // FIXME: Should we be merging attributes?
11715 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11716 PushNamespaceVisibilityAttr(Attr, Loc);
11717
11718 if (IsStd)
11719 StdNamespace = Namespc;
11720 if (AddToKnown)
11721 KnownNamespaces[Namespc] = false;
11722
11723 if (II) {
11724 PushOnScopeChains(Namespc, DeclRegionScope);
11725 } else {
11726 // Link the anonymous namespace into its parent.
11727 DeclContext *Parent = CurContext->getRedeclContext();
11728 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11729 TU->setAnonymousNamespace(Namespc);
11730 } else {
11731 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11732 }
11733
11734 CurContext->addDecl(Namespc);
11735
11736 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11737 // behaves as if it were replaced by
11738 // namespace unique { /* empty body */ }
11739 // using namespace unique;
11740 // namespace unique { namespace-body }
11741 // where all occurrences of 'unique' in a translation unit are
11742 // replaced by the same identifier and this identifier differs
11743 // from all other identifiers in the entire program.
11744
11745 // We just create the namespace with an empty name and then add an
11746 // implicit using declaration, just like the standard suggests.
11747 //
11748 // CodeGen enforces the "universally unique" aspect by giving all
11749 // declarations semantically contained within an anonymous
11750 // namespace internal linkage.
11751
11752 if (!PrevNS) {
11753 UD = UsingDirectiveDecl::Create(Context, Parent,
11754 /* 'using' */ LBrace,
11755 /* 'namespace' */ SourceLocation(),
11756 /* qualifier */ NestedNameSpecifierLoc(),
11757 /* identifier */ SourceLocation(),
11758 Namespc,
11759 /* Ancestor */ Parent);
11760 UD->setImplicit();
11761 Parent->addDecl(UD);
11762 }
11763 }
11764
11765 ActOnDocumentableDecl(Namespc);
11766
11767 // Although we could have an invalid decl (i.e. the namespace name is a
11768 // redefinition), push it as current DeclContext and try to continue parsing.
11769 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11770 // for the namespace has the declarations that showed up in that particular
11771 // namespace definition.
11772 PushDeclContext(NamespcScope, Namespc);
11773 return Namespc;
11774 }
11775
11776 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11777 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)11778 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11779 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11780 return AD->getNamespace();
11781 return dyn_cast_or_null<NamespaceDecl>(D);
11782 }
11783
11784 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11785 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)11786 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11787 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11788 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11789 Namespc->setRBraceLoc(RBrace);
11790 PopDeclContext();
11791 if (Namespc->hasAttr<VisibilityAttr>())
11792 PopPragmaVisibility(true, RBrace);
11793 // If this namespace contains an export-declaration, export it now.
11794 if (DeferredExportedNamespaces.erase(Namespc))
11795 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11796 }
11797
getStdBadAlloc() const11798 CXXRecordDecl *Sema::getStdBadAlloc() const {
11799 return cast_or_null<CXXRecordDecl>(
11800 StdBadAlloc.get(Context.getExternalSource()));
11801 }
11802
getStdAlignValT() const11803 EnumDecl *Sema::getStdAlignValT() const {
11804 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11805 }
11806
getStdNamespace() const11807 NamespaceDecl *Sema::getStdNamespace() const {
11808 return cast_or_null<NamespaceDecl>(
11809 StdNamespace.get(Context.getExternalSource()));
11810 }
11811 namespace {
11812
11813 enum UnsupportedSTLSelect {
11814 USS_InvalidMember,
11815 USS_MissingMember,
11816 USS_NonTrivial,
11817 USS_Other
11818 };
11819
11820 struct InvalidSTLDiagnoser {
11821 Sema &S;
11822 SourceLocation Loc;
11823 QualType TyForDiags;
11824
operator ()__anon067e66482d11::InvalidSTLDiagnoser11825 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11826 const VarDecl *VD = nullptr) {
11827 {
11828 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11829 << TyForDiags << ((int)Sel);
11830 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11831 assert(!Name.empty());
11832 D << Name;
11833 }
11834 }
11835 if (Sel == USS_InvalidMember) {
11836 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11837 << VD << VD->getSourceRange();
11838 }
11839 return QualType();
11840 }
11841 };
11842 } // namespace
11843
CheckComparisonCategoryType(ComparisonCategoryType Kind,SourceLocation Loc,ComparisonCategoryUsage Usage)11844 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11845 SourceLocation Loc,
11846 ComparisonCategoryUsage Usage) {
11847 assert(getLangOpts().CPlusPlus &&
11848 "Looking for comparison category type outside of C++.");
11849
11850 // Use an elaborated type for diagnostics which has a name containing the
11851 // prepended 'std' namespace but not any inline namespace names.
11852 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11853 auto *NNS =
11854 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11855 return Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,
11856 Info->getType());
11857 };
11858
11859 // Check if we've already successfully checked the comparison category type
11860 // before. If so, skip checking it again.
11861 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11862 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11863 // The only thing we need to check is that the type has a reachable
11864 // definition in the current context.
11865 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11866 return QualType();
11867
11868 return Info->getType();
11869 }
11870
11871 // If lookup failed
11872 if (!Info) {
11873 std::string NameForDiags = "std::";
11874 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11875 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11876 << NameForDiags << (int)Usage;
11877 return QualType();
11878 }
11879
11880 assert(Info->Kind == Kind);
11881 assert(Info->Record);
11882
11883 // Update the Record decl in case we encountered a forward declaration on our
11884 // first pass. FIXME: This is a bit of a hack.
11885 if (Info->Record->hasDefinition())
11886 Info->Record = Info->Record->getDefinition();
11887
11888 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11889 return QualType();
11890
11891 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11892
11893 if (!Info->Record->isTriviallyCopyable())
11894 return UnsupportedSTLError(USS_NonTrivial);
11895
11896 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11897 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11898 // Tolerate empty base classes.
11899 if (Base->isEmpty())
11900 continue;
11901 // Reject STL implementations which have at least one non-empty base.
11902 return UnsupportedSTLError();
11903 }
11904
11905 // Check that the STL has implemented the types using a single integer field.
11906 // This expectation allows better codegen for builtin operators. We require:
11907 // (1) The class has exactly one field.
11908 // (2) The field is an integral or enumeration type.
11909 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11910 if (std::distance(FIt, FEnd) != 1 ||
11911 !FIt->getType()->isIntegralOrEnumerationType()) {
11912 return UnsupportedSTLError();
11913 }
11914
11915 // Build each of the require values and store them in Info.
11916 for (ComparisonCategoryResult CCR :
11917 ComparisonCategories::getPossibleResultsForType(Kind)) {
11918 StringRef MemName = ComparisonCategories::getResultString(CCR);
11919 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11920
11921 if (!ValInfo)
11922 return UnsupportedSTLError(USS_MissingMember, MemName);
11923
11924 VarDecl *VD = ValInfo->VD;
11925 assert(VD && "should not be null!");
11926
11927 // Attempt to diagnose reasons why the STL definition of this type
11928 // might be foobar, including it failing to be a constant expression.
11929 // TODO Handle more ways the lookup or result can be invalid.
11930 if (!VD->isStaticDataMember() ||
11931 !VD->isUsableInConstantExpressions(Context))
11932 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11933
11934 // Attempt to evaluate the var decl as a constant expression and extract
11935 // the value of its first field as a ICE. If this fails, the STL
11936 // implementation is not supported.
11937 if (!ValInfo->hasValidIntValue())
11938 return UnsupportedSTLError();
11939
11940 MarkVariableReferenced(Loc, VD);
11941 }
11942
11943 // We've successfully built the required types and expressions. Update
11944 // the cache and return the newly cached value.
11945 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11946 return Info->getType();
11947 }
11948
11949 /// Retrieve the special "std" namespace, which may require us to
11950 /// implicitly define the namespace.
getOrCreateStdNamespace()11951 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11952 if (!StdNamespace) {
11953 // The "std" namespace has not yet been defined, so build one implicitly.
11954 StdNamespace = NamespaceDecl::Create(
11955 Context, Context.getTranslationUnitDecl(),
11956 /*Inline=*/false, SourceLocation(), SourceLocation(),
11957 &PP.getIdentifierTable().get("std"),
11958 /*PrevDecl=*/nullptr, /*Nested=*/false);
11959 getStdNamespace()->setImplicit(true);
11960 // We want the created NamespaceDecl to be available for redeclaration
11961 // lookups, but not for regular name lookups.
11962 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
11963 getStdNamespace()->clearIdentifierNamespace();
11964 }
11965
11966 return getStdNamespace();
11967 }
11968
isStdInitializerList(QualType Ty,QualType * Element)11969 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11970 assert(getLangOpts().CPlusPlus &&
11971 "Looking for std::initializer_list outside of C++.");
11972
11973 // We're looking for implicit instantiations of
11974 // template <typename E> class std::initializer_list.
11975
11976 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11977 return false;
11978
11979 ClassTemplateDecl *Template = nullptr;
11980 const TemplateArgument *Arguments = nullptr;
11981
11982 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11983
11984 ClassTemplateSpecializationDecl *Specialization =
11985 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11986 if (!Specialization)
11987 return false;
11988
11989 Template = Specialization->getSpecializedTemplate();
11990 Arguments = Specialization->getTemplateArgs().data();
11991 } else if (const TemplateSpecializationType *TST =
11992 Ty->getAs<TemplateSpecializationType>()) {
11993 Template = dyn_cast_or_null<ClassTemplateDecl>(
11994 TST->getTemplateName().getAsTemplateDecl());
11995 Arguments = TST->template_arguments().begin();
11996 }
11997 if (!Template)
11998 return false;
11999
12000 if (!StdInitializerList) {
12001 // Haven't recognized std::initializer_list yet, maybe this is it.
12002 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12003 if (TemplateClass->getIdentifier() !=
12004 &PP.getIdentifierTable().get("initializer_list") ||
12005 !getStdNamespace()->InEnclosingNamespaceSetOf(
12006 TemplateClass->getDeclContext()))
12007 return false;
12008 // This is a template called std::initializer_list, but is it the right
12009 // template?
12010 TemplateParameterList *Params = Template->getTemplateParameters();
12011 if (Params->getMinRequiredArguments() != 1)
12012 return false;
12013 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12014 return false;
12015
12016 // It's the right template.
12017 StdInitializerList = Template;
12018 }
12019
12020 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
12021 return false;
12022
12023 // This is an instance of std::initializer_list. Find the argument type.
12024 if (Element)
12025 *Element = Arguments[0].getAsType();
12026 return true;
12027 }
12028
LookupStdInitializerList(Sema & S,SourceLocation Loc)12029 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
12030 NamespaceDecl *Std = S.getStdNamespace();
12031 if (!Std) {
12032 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12033 return nullptr;
12034 }
12035
12036 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12037 Loc, Sema::LookupOrdinaryName);
12038 if (!S.LookupQualifiedName(Result, Std)) {
12039 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12040 return nullptr;
12041 }
12042 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12043 if (!Template) {
12044 Result.suppressDiagnostics();
12045 // We found something weird. Complain about the first thing we found.
12046 NamedDecl *Found = *Result.begin();
12047 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12048 return nullptr;
12049 }
12050
12051 // We found some template called std::initializer_list. Now verify that it's
12052 // correct.
12053 TemplateParameterList *Params = Template->getTemplateParameters();
12054 if (Params->getMinRequiredArguments() != 1 ||
12055 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12056 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12057 return nullptr;
12058 }
12059
12060 return Template;
12061 }
12062
BuildStdInitializerList(QualType Element,SourceLocation Loc)12063 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12064 if (!StdInitializerList) {
12065 StdInitializerList = LookupStdInitializerList(*this, Loc);
12066 if (!StdInitializerList)
12067 return QualType();
12068 }
12069
12070 TemplateArgumentListInfo Args(Loc, Loc);
12071 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
12072 Context.getTrivialTypeSourceInfo(Element,
12073 Loc)));
12074 return Context.getElaboratedType(
12075 ElaboratedTypeKeyword::None,
12076 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
12077 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
12078 }
12079
isInitListConstructor(const FunctionDecl * Ctor)12080 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12081 // C++ [dcl.init.list]p2:
12082 // A constructor is an initializer-list constructor if its first parameter
12083 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12084 // std::initializer_list<E> for some type E, and either there are no other
12085 // parameters or else all other parameters have default arguments.
12086 if (!Ctor->hasOneParamOrDefaultArgs())
12087 return false;
12088
12089 QualType ArgType = Ctor->getParamDecl(0)->getType();
12090 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12091 ArgType = RT->getPointeeType().getUnqualifiedType();
12092
12093 return isStdInitializerList(ArgType, nullptr);
12094 }
12095
12096 /// Determine whether a using statement is in a context where it will be
12097 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)12098 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12099 switch (CurContext->getDeclKind()) {
12100 case Decl::TranslationUnit:
12101 return true;
12102 case Decl::LinkageSpec:
12103 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12104 default:
12105 return false;
12106 }
12107 }
12108
12109 namespace {
12110
12111 // Callback to only accept typo corrections that are namespaces.
12112 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12113 public:
ValidateCandidate(const TypoCorrection & candidate)12114 bool ValidateCandidate(const TypoCorrection &candidate) override {
12115 if (NamedDecl *ND = candidate.getCorrectionDecl())
12116 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12117 return false;
12118 }
12119
clone()12120 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12121 return std::make_unique<NamespaceValidatorCCC>(*this);
12122 }
12123 };
12124
12125 }
12126
DiagnoseInvisibleNamespace(const TypoCorrection & Corrected,Sema & S)12127 static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12128 Sema &S) {
12129 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12130 Module *M = ND->getOwningModule();
12131 assert(M && "hidden namespace definition not in a module?");
12132
12133 if (M->isExplicitGlobalModule())
12134 S.Diag(Corrected.getCorrectionRange().getBegin(),
12135 diag::err_module_unimported_use_header)
12136 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12137 << /*Header Name*/ false;
12138 else
12139 S.Diag(Corrected.getCorrectionRange().getBegin(),
12140 diag::err_module_unimported_use)
12141 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12142 << M->getTopLevelModuleName();
12143 }
12144
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)12145 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12146 CXXScopeSpec &SS,
12147 SourceLocation IdentLoc,
12148 IdentifierInfo *Ident) {
12149 R.clear();
12150 NamespaceValidatorCCC CCC{};
12151 if (TypoCorrection Corrected =
12152 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12153 Sema::CTK_ErrorRecovery)) {
12154 // Generally we find it is confusing more than helpful to diagnose the
12155 // invisible namespace.
12156 // See https://github.com/llvm/llvm-project/issues/73893.
12157 //
12158 // However, we should diagnose when the users are trying to using an
12159 // invisible namespace. So we handle the case specially here.
12160 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12161 Corrected.requiresImport()) {
12162 DiagnoseInvisibleNamespace(Corrected, S);
12163 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12164 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12165 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
12166 Ident->getName().equals(CorrectedStr);
12167 S.diagnoseTypo(Corrected,
12168 S.PDiag(diag::err_using_directive_member_suggest)
12169 << Ident << DC << DroppedSpecifier << SS.getRange(),
12170 S.PDiag(diag::note_namespace_defined_here));
12171 } else {
12172 S.diagnoseTypo(Corrected,
12173 S.PDiag(diag::err_using_directive_suggest) << Ident,
12174 S.PDiag(diag::note_namespace_defined_here));
12175 }
12176 R.addDecl(Corrected.getFoundDecl());
12177 return true;
12178 }
12179 return false;
12180 }
12181
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,const ParsedAttributesView & AttrList)12182 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12183 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12184 SourceLocation IdentLoc,
12185 IdentifierInfo *NamespcName,
12186 const ParsedAttributesView &AttrList) {
12187 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12188 assert(NamespcName && "Invalid NamespcName.");
12189 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12190
12191 // This can only happen along a recovery path.
12192 while (S->isTemplateParamScope())
12193 S = S->getParent();
12194 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12195
12196 UsingDirectiveDecl *UDir = nullptr;
12197 NestedNameSpecifier *Qualifier = nullptr;
12198 if (SS.isSet())
12199 Qualifier = SS.getScopeRep();
12200
12201 // Lookup namespace name.
12202 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12203 LookupParsedName(R, S, &SS);
12204 if (R.isAmbiguous())
12205 return nullptr;
12206
12207 if (R.empty()) {
12208 R.clear();
12209 // Allow "using namespace std;" or "using namespace ::std;" even if
12210 // "std" hasn't been defined yet, for GCC compatibility.
12211 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12212 NamespcName->isStr("std")) {
12213 Diag(IdentLoc, diag::ext_using_undefined_std);
12214 R.addDecl(getOrCreateStdNamespace());
12215 R.resolveKind();
12216 }
12217 // Otherwise, attempt typo correction.
12218 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12219 }
12220
12221 if (!R.empty()) {
12222 NamedDecl *Named = R.getRepresentativeDecl();
12223 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12224 assert(NS && "expected namespace decl");
12225
12226 // The use of a nested name specifier may trigger deprecation warnings.
12227 DiagnoseUseOfDecl(Named, IdentLoc);
12228
12229 // C++ [namespace.udir]p1:
12230 // A using-directive specifies that the names in the nominated
12231 // namespace can be used in the scope in which the
12232 // using-directive appears after the using-directive. During
12233 // unqualified name lookup (3.4.1), the names appear as if they
12234 // were declared in the nearest enclosing namespace which
12235 // contains both the using-directive and the nominated
12236 // namespace. [Note: in this context, "contains" means "contains
12237 // directly or indirectly". ]
12238
12239 // Find enclosing context containing both using-directive and
12240 // nominated namespace.
12241 DeclContext *CommonAncestor = NS;
12242 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12243 CommonAncestor = CommonAncestor->getParent();
12244
12245 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12246 SS.getWithLocInContext(Context),
12247 IdentLoc, Named, CommonAncestor);
12248
12249 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12250 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12251 Diag(IdentLoc, diag::warn_using_directive_in_header);
12252 }
12253
12254 PushUsingDirective(S, UDir);
12255 } else {
12256 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12257 }
12258
12259 if (UDir)
12260 ProcessDeclAttributeList(S, UDir, AttrList);
12261
12262 return UDir;
12263 }
12264
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)12265 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12266 // If the scope has an associated entity and the using directive is at
12267 // namespace or translation unit scope, add the UsingDirectiveDecl into
12268 // its lookup structure so qualified name lookup can find it.
12269 DeclContext *Ctx = S->getEntity();
12270 if (Ctx && !Ctx->isFunctionOrMethod())
12271 Ctx->addDecl(UDir);
12272 else
12273 // Otherwise, it is at block scope. The using-directives will affect lookup
12274 // only to the end of the scope.
12275 S->PushUsingDirective(UDir);
12276 }
12277
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation TypenameLoc,CXXScopeSpec & SS,UnqualifiedId & Name,SourceLocation EllipsisLoc,const ParsedAttributesView & AttrList)12278 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12279 SourceLocation UsingLoc,
12280 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12281 UnqualifiedId &Name,
12282 SourceLocation EllipsisLoc,
12283 const ParsedAttributesView &AttrList) {
12284 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12285
12286 if (SS.isEmpty()) {
12287 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12288 return nullptr;
12289 }
12290
12291 switch (Name.getKind()) {
12292 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12293 case UnqualifiedIdKind::IK_Identifier:
12294 case UnqualifiedIdKind::IK_OperatorFunctionId:
12295 case UnqualifiedIdKind::IK_LiteralOperatorId:
12296 case UnqualifiedIdKind::IK_ConversionFunctionId:
12297 break;
12298
12299 case UnqualifiedIdKind::IK_ConstructorName:
12300 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12301 // C++11 inheriting constructors.
12302 Diag(Name.getBeginLoc(),
12303 getLangOpts().CPlusPlus11
12304 ? diag::warn_cxx98_compat_using_decl_constructor
12305 : diag::err_using_decl_constructor)
12306 << SS.getRange();
12307
12308 if (getLangOpts().CPlusPlus11) break;
12309
12310 return nullptr;
12311
12312 case UnqualifiedIdKind::IK_DestructorName:
12313 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12314 return nullptr;
12315
12316 case UnqualifiedIdKind::IK_TemplateId:
12317 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12318 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12319 return nullptr;
12320
12321 case UnqualifiedIdKind::IK_DeductionGuideName:
12322 llvm_unreachable("cannot parse qualified deduction guide name");
12323 }
12324
12325 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12326 DeclarationName TargetName = TargetNameInfo.getName();
12327 if (!TargetName)
12328 return nullptr;
12329
12330 // Warn about access declarations.
12331 if (UsingLoc.isInvalid()) {
12332 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12333 ? diag::err_access_decl
12334 : diag::warn_access_decl_deprecated)
12335 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12336 }
12337
12338 if (EllipsisLoc.isInvalid()) {
12339 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12340 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12341 return nullptr;
12342 } else {
12343 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12344 !TargetNameInfo.containsUnexpandedParameterPack()) {
12345 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12346 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12347 EllipsisLoc = SourceLocation();
12348 }
12349 }
12350
12351 NamedDecl *UD =
12352 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12353 SS, TargetNameInfo, EllipsisLoc, AttrList,
12354 /*IsInstantiation*/ false,
12355 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12356 if (UD)
12357 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12358
12359 return UD;
12360 }
12361
ActOnUsingEnumDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation EnumLoc,SourceLocation IdentLoc,IdentifierInfo & II,CXXScopeSpec * SS)12362 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12363 SourceLocation UsingLoc,
12364 SourceLocation EnumLoc,
12365 SourceLocation IdentLoc,
12366 IdentifierInfo &II, CXXScopeSpec *SS) {
12367 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12368 TypeSourceInfo *TSI = nullptr;
12369 QualType EnumTy = GetTypeFromParser(
12370 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12371 /*HasTrailingDot=*/false,
12372 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12373 /*WantNontrivialTypeSourceInfo=*/true),
12374 &TSI);
12375 if (EnumTy.isNull()) {
12376 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12377 ? diag::err_using_enum_is_dependent
12378 : diag::err_unknown_typename)
12379 << II.getName()
12380 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12381 return nullptr;
12382 }
12383
12384 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12385 if (!Enum) {
12386 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12387 return nullptr;
12388 }
12389
12390 if (auto *Def = Enum->getDefinition())
12391 Enum = Def;
12392
12393 if (TSI == nullptr)
12394 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12395
12396 auto *UD =
12397 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12398
12399 if (UD)
12400 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12401
12402 return UD;
12403 }
12404
12405 /// Determine whether a using declaration considers the given
12406 /// declarations as "equivalent", e.g., if they are redeclarations of
12407 /// the same entity or are both typedefs of the same type.
12408 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2)12409 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12410 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12411 return true;
12412
12413 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12414 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12415 return Context.hasSameType(TD1->getUnderlyingType(),
12416 TD2->getUnderlyingType());
12417
12418 // Two using_if_exists using-declarations are equivalent if both are
12419 // unresolved.
12420 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12421 isa<UnresolvedUsingIfExistsDecl>(D2))
12422 return true;
12423
12424 return false;
12425 }
12426
12427
12428 /// Determines whether to create a using shadow decl for a particular
12429 /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(BaseUsingDecl * BUD,NamedDecl * Orig,const LookupResult & Previous,UsingShadowDecl * & PrevShadow)12430 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12431 const LookupResult &Previous,
12432 UsingShadowDecl *&PrevShadow) {
12433 // Diagnose finding a decl which is not from a base class of the
12434 // current class. We do this now because there are cases where this
12435 // function will silently decide not to build a shadow decl, which
12436 // will pre-empt further diagnostics.
12437 //
12438 // We don't need to do this in C++11 because we do the check once on
12439 // the qualifier.
12440 //
12441 // FIXME: diagnose the following if we care enough:
12442 // struct A { int foo; };
12443 // struct B : A { using A::foo; };
12444 // template <class T> struct C : A {};
12445 // template <class T> struct D : C<T> { using B::foo; } // <---
12446 // This is invalid (during instantiation) in C++03 because B::foo
12447 // resolves to the using decl in B, which is not a base class of D<T>.
12448 // We can't diagnose it immediately because C<T> is an unknown
12449 // specialization. The UsingShadowDecl in D<T> then points directly
12450 // to A::foo, which will look well-formed when we instantiate.
12451 // The right solution is to not collapse the shadow-decl chain.
12452 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12453 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12454 DeclContext *OrigDC = Orig->getDeclContext();
12455
12456 // Handle enums and anonymous structs.
12457 if (isa<EnumDecl>(OrigDC))
12458 OrigDC = OrigDC->getParent();
12459 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12460 while (OrigRec->isAnonymousStructOrUnion())
12461 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12462
12463 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12464 if (OrigDC == CurContext) {
12465 Diag(Using->getLocation(),
12466 diag::err_using_decl_nested_name_specifier_is_current_class)
12467 << Using->getQualifierLoc().getSourceRange();
12468 Diag(Orig->getLocation(), diag::note_using_decl_target);
12469 Using->setInvalidDecl();
12470 return true;
12471 }
12472
12473 Diag(Using->getQualifierLoc().getBeginLoc(),
12474 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12475 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12476 << Using->getQualifierLoc().getSourceRange();
12477 Diag(Orig->getLocation(), diag::note_using_decl_target);
12478 Using->setInvalidDecl();
12479 return true;
12480 }
12481 }
12482
12483 if (Previous.empty()) return false;
12484
12485 NamedDecl *Target = Orig;
12486 if (isa<UsingShadowDecl>(Target))
12487 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12488
12489 // If the target happens to be one of the previous declarations, we
12490 // don't have a conflict.
12491 //
12492 // FIXME: but we might be increasing its access, in which case we
12493 // should redeclare it.
12494 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12495 bool FoundEquivalentDecl = false;
12496 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12497 I != E; ++I) {
12498 NamedDecl *D = (*I)->getUnderlyingDecl();
12499 // We can have UsingDecls in our Previous results because we use the same
12500 // LookupResult for checking whether the UsingDecl itself is a valid
12501 // redeclaration.
12502 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12503 continue;
12504
12505 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12506 // C++ [class.mem]p19:
12507 // If T is the name of a class, then [every named member other than
12508 // a non-static data member] shall have a name different from T
12509 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12510 !isa<IndirectFieldDecl>(Target) &&
12511 !isa<UnresolvedUsingValueDecl>(Target) &&
12512 DiagnoseClassNameShadow(
12513 CurContext,
12514 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12515 return true;
12516 }
12517
12518 if (IsEquivalentForUsingDecl(Context, D, Target)) {
12519 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12520 PrevShadow = Shadow;
12521 FoundEquivalentDecl = true;
12522 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12523 // We don't conflict with an existing using shadow decl of an equivalent
12524 // declaration, but we're not a redeclaration of it.
12525 FoundEquivalentDecl = true;
12526 }
12527
12528 if (isVisible(D))
12529 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12530 }
12531
12532 if (FoundEquivalentDecl)
12533 return false;
12534
12535 // Always emit a diagnostic for a mismatch between an unresolved
12536 // using_if_exists and a resolved using declaration in either direction.
12537 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12538 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12539 if (!NonTag && !Tag)
12540 return false;
12541 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12542 Diag(Target->getLocation(), diag::note_using_decl_target);
12543 Diag((NonTag ? NonTag : Tag)->getLocation(),
12544 diag::note_using_decl_conflict);
12545 BUD->setInvalidDecl();
12546 return true;
12547 }
12548
12549 if (FunctionDecl *FD = Target->getAsFunction()) {
12550 NamedDecl *OldDecl = nullptr;
12551 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12552 /*IsForUsingDecl*/ true)) {
12553 case Ovl_Overload:
12554 return false;
12555
12556 case Ovl_NonFunction:
12557 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12558 break;
12559
12560 // We found a decl with the exact signature.
12561 case Ovl_Match:
12562 // If we're in a record, we want to hide the target, so we
12563 // return true (without a diagnostic) to tell the caller not to
12564 // build a shadow decl.
12565 if (CurContext->isRecord())
12566 return true;
12567
12568 // If we're not in a record, this is an error.
12569 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12570 break;
12571 }
12572
12573 Diag(Target->getLocation(), diag::note_using_decl_target);
12574 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12575 BUD->setInvalidDecl();
12576 return true;
12577 }
12578
12579 // Target is not a function.
12580
12581 if (isa<TagDecl>(Target)) {
12582 // No conflict between a tag and a non-tag.
12583 if (!Tag) return false;
12584
12585 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12586 Diag(Target->getLocation(), diag::note_using_decl_target);
12587 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12588 BUD->setInvalidDecl();
12589 return true;
12590 }
12591
12592 // No conflict between a tag and a non-tag.
12593 if (!NonTag) return false;
12594
12595 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12596 Diag(Target->getLocation(), diag::note_using_decl_target);
12597 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12598 BUD->setInvalidDecl();
12599 return true;
12600 }
12601
12602 /// Determine whether a direct base class is a virtual base class.
isVirtualDirectBase(CXXRecordDecl * Derived,CXXRecordDecl * Base)12603 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12604 if (!Derived->getNumVBases())
12605 return false;
12606 for (auto &B : Derived->bases())
12607 if (B.getType()->getAsCXXRecordDecl() == Base)
12608 return B.isVirtual();
12609 llvm_unreachable("not a direct base class");
12610 }
12611
12612 /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,BaseUsingDecl * BUD,NamedDecl * Orig,UsingShadowDecl * PrevDecl)12613 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12614 NamedDecl *Orig,
12615 UsingShadowDecl *PrevDecl) {
12616 // If we resolved to another shadow declaration, just coalesce them.
12617 NamedDecl *Target = Orig;
12618 if (isa<UsingShadowDecl>(Target)) {
12619 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12620 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12621 }
12622
12623 NamedDecl *NonTemplateTarget = Target;
12624 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12625 NonTemplateTarget = TargetTD->getTemplatedDecl();
12626
12627 UsingShadowDecl *Shadow;
12628 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12629 UsingDecl *Using = cast<UsingDecl>(BUD);
12630 bool IsVirtualBase =
12631 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12632 Using->getQualifier()->getAsRecordDecl());
12633 Shadow = ConstructorUsingShadowDecl::Create(
12634 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12635 } else {
12636 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12637 Target->getDeclName(), BUD, Target);
12638 }
12639 BUD->addShadowDecl(Shadow);
12640
12641 Shadow->setAccess(BUD->getAccess());
12642 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12643 Shadow->setInvalidDecl();
12644
12645 Shadow->setPreviousDecl(PrevDecl);
12646
12647 if (S)
12648 PushOnScopeChains(Shadow, S);
12649 else
12650 CurContext->addDecl(Shadow);
12651
12652
12653 return Shadow;
12654 }
12655
12656 /// Hides a using shadow declaration. This is required by the current
12657 /// using-decl implementation when a resolvable using declaration in a
12658 /// class is followed by a declaration which would hide or override
12659 /// one or more of the using decl's targets; for example:
12660 ///
12661 /// struct Base { void foo(int); };
12662 /// struct Derived : Base {
12663 /// using Base::foo;
12664 /// void foo(int);
12665 /// };
12666 ///
12667 /// The governing language is C++03 [namespace.udecl]p12:
12668 ///
12669 /// When a using-declaration brings names from a base class into a
12670 /// derived class scope, member functions in the derived class
12671 /// override and/or hide member functions with the same name and
12672 /// parameter types in a base class (rather than conflicting).
12673 ///
12674 /// There are two ways to implement this:
12675 /// (1) optimistically create shadow decls when they're not hidden
12676 /// by existing declarations, or
12677 /// (2) don't create any shadow decls (or at least don't make them
12678 /// visible) until we've fully parsed/instantiated the class.
12679 /// The problem with (1) is that we might have to retroactively remove
12680 /// a shadow decl, which requires several O(n) operations because the
12681 /// decl structures are (very reasonably) not designed for removal.
12682 /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)12683 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12684 if (Shadow->getDeclName().getNameKind() ==
12685 DeclarationName::CXXConversionFunctionName)
12686 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12687
12688 // Remove it from the DeclContext...
12689 Shadow->getDeclContext()->removeDecl(Shadow);
12690
12691 // ...and the scope, if applicable...
12692 if (S) {
12693 S->RemoveDecl(Shadow);
12694 IdResolver.RemoveDecl(Shadow);
12695 }
12696
12697 // ...and the using decl.
12698 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12699
12700 // TODO: complain somehow if Shadow was used. It shouldn't
12701 // be possible for this to happen, because...?
12702 }
12703
12704 /// Find the base specifier for a base class with the given type.
findDirectBaseWithType(CXXRecordDecl * Derived,QualType DesiredBase,bool & AnyDependentBases)12705 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12706 QualType DesiredBase,
12707 bool &AnyDependentBases) {
12708 // Check whether the named type is a direct base class.
12709 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12710 .getUnqualifiedType();
12711 for (auto &Base : Derived->bases()) {
12712 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12713 if (CanonicalDesiredBase == BaseType)
12714 return &Base;
12715 if (BaseType->isDependentType())
12716 AnyDependentBases = true;
12717 }
12718 return nullptr;
12719 }
12720
12721 namespace {
12722 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12723 public:
UsingValidatorCCC(bool HasTypenameKeyword,bool IsInstantiation,NestedNameSpecifier * NNS,CXXRecordDecl * RequireMemberOf)12724 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12725 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12726 : HasTypenameKeyword(HasTypenameKeyword),
12727 IsInstantiation(IsInstantiation), OldNNS(NNS),
12728 RequireMemberOf(RequireMemberOf) {}
12729
ValidateCandidate(const TypoCorrection & Candidate)12730 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12731 NamedDecl *ND = Candidate.getCorrectionDecl();
12732
12733 // Keywords are not valid here.
12734 if (!ND || isa<NamespaceDecl>(ND))
12735 return false;
12736
12737 // Completely unqualified names are invalid for a 'using' declaration.
12738 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12739 return false;
12740
12741 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12742 // reject.
12743
12744 if (RequireMemberOf) {
12745 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12746 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12747 // No-one ever wants a using-declaration to name an injected-class-name
12748 // of a base class, unless they're declaring an inheriting constructor.
12749 ASTContext &Ctx = ND->getASTContext();
12750 if (!Ctx.getLangOpts().CPlusPlus11)
12751 return false;
12752 QualType FoundType = Ctx.getRecordType(FoundRecord);
12753
12754 // Check that the injected-class-name is named as a member of its own
12755 // type; we don't want to suggest 'using Derived::Base;', since that
12756 // means something else.
12757 NestedNameSpecifier *Specifier =
12758 Candidate.WillReplaceSpecifier()
12759 ? Candidate.getCorrectionSpecifier()
12760 : OldNNS;
12761 if (!Specifier->getAsType() ||
12762 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12763 return false;
12764
12765 // Check that this inheriting constructor declaration actually names a
12766 // direct base class of the current class.
12767 bool AnyDependentBases = false;
12768 if (!findDirectBaseWithType(RequireMemberOf,
12769 Ctx.getRecordType(FoundRecord),
12770 AnyDependentBases) &&
12771 !AnyDependentBases)
12772 return false;
12773 } else {
12774 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12775 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12776 return false;
12777
12778 // FIXME: Check that the base class member is accessible?
12779 }
12780 } else {
12781 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12782 if (FoundRecord && FoundRecord->isInjectedClassName())
12783 return false;
12784 }
12785
12786 if (isa<TypeDecl>(ND))
12787 return HasTypenameKeyword || !IsInstantiation;
12788
12789 return !HasTypenameKeyword;
12790 }
12791
clone()12792 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12793 return std::make_unique<UsingValidatorCCC>(*this);
12794 }
12795
12796 private:
12797 bool HasTypenameKeyword;
12798 bool IsInstantiation;
12799 NestedNameSpecifier *OldNNS;
12800 CXXRecordDecl *RequireMemberOf;
12801 };
12802 } // end anonymous namespace
12803
12804 /// Remove decls we can't actually see from a lookup being used to declare
12805 /// shadow using decls.
12806 ///
12807 /// \param S - The scope of the potential shadow decl
12808 /// \param Previous - The lookup of a potential shadow decl's name.
FilterUsingLookup(Scope * S,LookupResult & Previous)12809 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12810 // It is really dumb that we have to do this.
12811 LookupResult::Filter F = Previous.makeFilter();
12812 while (F.hasNext()) {
12813 NamedDecl *D = F.next();
12814 if (!isDeclInScope(D, CurContext, S))
12815 F.erase();
12816 // If we found a local extern declaration that's not ordinarily visible,
12817 // and this declaration is being added to a non-block scope, ignore it.
12818 // We're only checking for scope conflicts here, not also for violations
12819 // of the linkage rules.
12820 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12821 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12822 F.erase();
12823 }
12824 F.done();
12825 }
12826
12827 /// Builds a using declaration.
12828 ///
12829 /// \param IsInstantiation - Whether this call arises from an
12830 /// instantiation of an unresolved using declaration. We treat
12831 /// the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,bool HasTypenameKeyword,SourceLocation TypenameLoc,CXXScopeSpec & SS,DeclarationNameInfo NameInfo,SourceLocation EllipsisLoc,const ParsedAttributesView & AttrList,bool IsInstantiation,bool IsUsingIfExists)12832 NamedDecl *Sema::BuildUsingDeclaration(
12833 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12834 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12835 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12836 const ParsedAttributesView &AttrList, bool IsInstantiation,
12837 bool IsUsingIfExists) {
12838 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12839 SourceLocation IdentLoc = NameInfo.getLoc();
12840 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12841
12842 // FIXME: We ignore attributes for now.
12843
12844 // For an inheriting constructor declaration, the name of the using
12845 // declaration is the name of a constructor in this class, not in the
12846 // base class.
12847 DeclarationNameInfo UsingName = NameInfo;
12848 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12849 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12850 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12851 Context.getCanonicalType(Context.getRecordType(RD))));
12852
12853 // Do the redeclaration lookup in the current scope.
12854 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12855 ForVisibleRedeclaration);
12856 Previous.setHideTags(false);
12857 if (S) {
12858 LookupName(Previous, S);
12859
12860 FilterUsingLookup(S, Previous);
12861 } else {
12862 assert(IsInstantiation && "no scope in non-instantiation");
12863 if (CurContext->isRecord())
12864 LookupQualifiedName(Previous, CurContext);
12865 else {
12866 // No redeclaration check is needed here; in non-member contexts we
12867 // diagnosed all possible conflicts with other using-declarations when
12868 // building the template:
12869 //
12870 // For a dependent non-type using declaration, the only valid case is
12871 // if we instantiate to a single enumerator. We check for conflicts
12872 // between shadow declarations we introduce, and we check in the template
12873 // definition for conflicts between a non-type using declaration and any
12874 // other declaration, which together covers all cases.
12875 //
12876 // A dependent typename using declaration will never successfully
12877 // instantiate, since it will always name a class member, so we reject
12878 // that in the template definition.
12879 }
12880 }
12881
12882 // Check for invalid redeclarations.
12883 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12884 SS, IdentLoc, Previous))
12885 return nullptr;
12886
12887 // 'using_if_exists' doesn't make sense on an inherited constructor.
12888 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12889 DeclarationName::CXXConstructorName) {
12890 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12891 return nullptr;
12892 }
12893
12894 DeclContext *LookupContext = computeDeclContext(SS);
12895 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12896 if (!LookupContext || EllipsisLoc.isValid()) {
12897 NamedDecl *D;
12898 // Dependent scope, or an unexpanded pack
12899 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12900 SS, NameInfo, IdentLoc))
12901 return nullptr;
12902
12903 if (HasTypenameKeyword) {
12904 // FIXME: not all declaration name kinds are legal here
12905 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12906 UsingLoc, TypenameLoc,
12907 QualifierLoc,
12908 IdentLoc, NameInfo.getName(),
12909 EllipsisLoc);
12910 } else {
12911 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12912 QualifierLoc, NameInfo, EllipsisLoc);
12913 }
12914 D->setAccess(AS);
12915 CurContext->addDecl(D);
12916 ProcessDeclAttributeList(S, D, AttrList);
12917 return D;
12918 }
12919
12920 auto Build = [&](bool Invalid) {
12921 UsingDecl *UD =
12922 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12923 UsingName, HasTypenameKeyword);
12924 UD->setAccess(AS);
12925 CurContext->addDecl(UD);
12926 ProcessDeclAttributeList(S, UD, AttrList);
12927 UD->setInvalidDecl(Invalid);
12928 return UD;
12929 };
12930 auto BuildInvalid = [&]{ return Build(true); };
12931 auto BuildValid = [&]{ return Build(false); };
12932
12933 if (RequireCompleteDeclContext(SS, LookupContext))
12934 return BuildInvalid();
12935
12936 // Look up the target name.
12937 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12938
12939 // Unlike most lookups, we don't always want to hide tag
12940 // declarations: tag names are visible through the using declaration
12941 // even if hidden by ordinary names, *except* in a dependent context
12942 // where they may be used by two-phase lookup.
12943 if (!IsInstantiation)
12944 R.setHideTags(false);
12945
12946 // For the purposes of this lookup, we have a base object type
12947 // equal to that of the current context.
12948 if (CurContext->isRecord()) {
12949 R.setBaseObjectType(
12950 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12951 }
12952
12953 LookupQualifiedName(R, LookupContext);
12954
12955 // Validate the context, now we have a lookup
12956 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12957 IdentLoc, &R))
12958 return nullptr;
12959
12960 if (R.empty() && IsUsingIfExists)
12961 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12962 UsingName.getName()),
12963 AS_public);
12964
12965 // Try to correct typos if possible. If constructor name lookup finds no
12966 // results, that means the named class has no explicit constructors, and we
12967 // suppressed declaring implicit ones (probably because it's dependent or
12968 // invalid).
12969 if (R.empty() &&
12970 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12971 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12972 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12973 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12974 auto *II = NameInfo.getName().getAsIdentifierInfo();
12975 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12976 CurContext->isStdNamespace() &&
12977 isa<TranslationUnitDecl>(LookupContext) &&
12978 getSourceManager().isInSystemHeader(UsingLoc))
12979 return nullptr;
12980 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12981 dyn_cast<CXXRecordDecl>(CurContext));
12982 if (TypoCorrection Corrected =
12983 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12984 CTK_ErrorRecovery)) {
12985 // We reject candidates where DroppedSpecifier == true, hence the
12986 // literal '0' below.
12987 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12988 << NameInfo.getName() << LookupContext << 0
12989 << SS.getRange());
12990
12991 // If we picked a correction with no attached Decl we can't do anything
12992 // useful with it, bail out.
12993 NamedDecl *ND = Corrected.getCorrectionDecl();
12994 if (!ND)
12995 return BuildInvalid();
12996
12997 // If we corrected to an inheriting constructor, handle it as one.
12998 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12999 if (RD && RD->isInjectedClassName()) {
13000 // The parent of the injected class name is the class itself.
13001 RD = cast<CXXRecordDecl>(RD->getParent());
13002
13003 // Fix up the information we'll use to build the using declaration.
13004 if (Corrected.WillReplaceSpecifier()) {
13005 NestedNameSpecifierLocBuilder Builder;
13006 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13007 QualifierLoc.getSourceRange());
13008 QualifierLoc = Builder.getWithLocInContext(Context);
13009 }
13010
13011 // In this case, the name we introduce is the name of a derived class
13012 // constructor.
13013 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13014 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13015 Context.getCanonicalType(Context.getRecordType(CurClass))));
13016 UsingName.setNamedTypeInfo(nullptr);
13017 for (auto *Ctor : LookupConstructors(RD))
13018 R.addDecl(Ctor);
13019 R.resolveKind();
13020 } else {
13021 // FIXME: Pick up all the declarations if we found an overloaded
13022 // function.
13023 UsingName.setName(ND->getDeclName());
13024 R.addDecl(ND);
13025 }
13026 } else {
13027 Diag(IdentLoc, diag::err_no_member)
13028 << NameInfo.getName() << LookupContext << SS.getRange();
13029 return BuildInvalid();
13030 }
13031 }
13032
13033 if (R.isAmbiguous())
13034 return BuildInvalid();
13035
13036 if (HasTypenameKeyword) {
13037 // If we asked for a typename and got a non-type decl, error out.
13038 if (!R.getAsSingle<TypeDecl>() &&
13039 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13040 Diag(IdentLoc, diag::err_using_typename_non_type);
13041 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13042 Diag((*I)->getUnderlyingDecl()->getLocation(),
13043 diag::note_using_decl_target);
13044 return BuildInvalid();
13045 }
13046 } else {
13047 // If we asked for a non-typename and we got a type, error out,
13048 // but only if this is an instantiation of an unresolved using
13049 // decl. Otherwise just silently find the type name.
13050 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13051 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13052 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13053 return BuildInvalid();
13054 }
13055 }
13056
13057 // C++14 [namespace.udecl]p6:
13058 // A using-declaration shall not name a namespace.
13059 if (R.getAsSingle<NamespaceDecl>()) {
13060 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13061 << SS.getRange();
13062 return BuildInvalid();
13063 }
13064
13065 UsingDecl *UD = BuildValid();
13066
13067 // Some additional rules apply to inheriting constructors.
13068 if (UsingName.getName().getNameKind() ==
13069 DeclarationName::CXXConstructorName) {
13070 // Suppress access diagnostics; the access check is instead performed at the
13071 // point of use for an inheriting constructor.
13072 R.suppressDiagnostics();
13073 if (CheckInheritingConstructorUsingDecl(UD))
13074 return UD;
13075 }
13076
13077 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13078 UsingShadowDecl *PrevDecl = nullptr;
13079 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13080 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13081 }
13082
13083 return UD;
13084 }
13085
BuildUsingEnumDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,SourceLocation EnumLoc,SourceLocation NameLoc,TypeSourceInfo * EnumType,EnumDecl * ED)13086 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13087 SourceLocation UsingLoc,
13088 SourceLocation EnumLoc,
13089 SourceLocation NameLoc,
13090 TypeSourceInfo *EnumType,
13091 EnumDecl *ED) {
13092 bool Invalid = false;
13093
13094 if (CurContext->getRedeclContext()->isRecord()) {
13095 /// In class scope, check if this is a duplicate, for better a diagnostic.
13096 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13097 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13098 ForVisibleRedeclaration);
13099
13100 LookupName(Previous, S);
13101
13102 for (NamedDecl *D : Previous)
13103 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13104 if (UED->getEnumDecl() == ED) {
13105 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13106 << SourceRange(EnumLoc, NameLoc);
13107 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13108 Invalid = true;
13109 break;
13110 }
13111 }
13112
13113 if (RequireCompleteEnumDecl(ED, NameLoc))
13114 Invalid = true;
13115
13116 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
13117 EnumLoc, NameLoc, EnumType);
13118 UD->setAccess(AS);
13119 CurContext->addDecl(UD);
13120
13121 if (Invalid) {
13122 UD->setInvalidDecl();
13123 return UD;
13124 }
13125
13126 // Create the shadow decls for each enumerator
13127 for (EnumConstantDecl *EC : ED->enumerators()) {
13128 UsingShadowDecl *PrevDecl = nullptr;
13129 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13130 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13131 ForVisibleRedeclaration);
13132 LookupName(Previous, S);
13133 FilterUsingLookup(S, Previous);
13134
13135 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13136 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13137 }
13138
13139 return UD;
13140 }
13141
BuildUsingPackDecl(NamedDecl * InstantiatedFrom,ArrayRef<NamedDecl * > Expansions)13142 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13143 ArrayRef<NamedDecl *> Expansions) {
13144 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13145 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13146 isa<UsingPackDecl>(InstantiatedFrom));
13147
13148 auto *UPD =
13149 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13150 UPD->setAccess(InstantiatedFrom->getAccess());
13151 CurContext->addDecl(UPD);
13152 return UPD;
13153 }
13154
13155 /// Additional checks for a using declaration referring to a constructor name.
CheckInheritingConstructorUsingDecl(UsingDecl * UD)13156 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13157 assert(!UD->hasTypename() && "expecting a constructor name");
13158
13159 const Type *SourceType = UD->getQualifier()->getAsType();
13160 assert(SourceType &&
13161 "Using decl naming constructor doesn't have type in scope spec.");
13162 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13163
13164 // Check whether the named type is a direct base class.
13165 bool AnyDependentBases = false;
13166 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13167 AnyDependentBases);
13168 if (!Base && !AnyDependentBases) {
13169 Diag(UD->getUsingLoc(),
13170 diag::err_using_decl_constructor_not_in_direct_base)
13171 << UD->getNameInfo().getSourceRange()
13172 << QualType(SourceType, 0) << TargetClass;
13173 UD->setInvalidDecl();
13174 return true;
13175 }
13176
13177 if (Base)
13178 Base->setInheritConstructors();
13179
13180 return false;
13181 }
13182
13183 /// Checks that the given using declaration is not an invalid
13184 /// redeclaration. Note that this is checking only for the using decl
13185 /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool HasTypenameKeyword,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)13186 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13187 bool HasTypenameKeyword,
13188 const CXXScopeSpec &SS,
13189 SourceLocation NameLoc,
13190 const LookupResult &Prev) {
13191 NestedNameSpecifier *Qual = SS.getScopeRep();
13192
13193 // C++03 [namespace.udecl]p8:
13194 // C++0x [namespace.udecl]p10:
13195 // A using-declaration is a declaration and can therefore be used
13196 // repeatedly where (and only where) multiple declarations are
13197 // allowed.
13198 //
13199 // That's in non-member contexts.
13200 if (!CurContext->getRedeclContext()->isRecord()) {
13201 // A dependent qualifier outside a class can only ever resolve to an
13202 // enumeration type. Therefore it conflicts with any other non-type
13203 // declaration in the same scope.
13204 // FIXME: How should we check for dependent type-type conflicts at block
13205 // scope?
13206 if (Qual->isDependent() && !HasTypenameKeyword) {
13207 for (auto *D : Prev) {
13208 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13209 bool OldCouldBeEnumerator =
13210 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13211 Diag(NameLoc,
13212 OldCouldBeEnumerator ? diag::err_redefinition
13213 : diag::err_redefinition_different_kind)
13214 << Prev.getLookupName();
13215 Diag(D->getLocation(), diag::note_previous_definition);
13216 return true;
13217 }
13218 }
13219 }
13220 return false;
13221 }
13222
13223 const NestedNameSpecifier *CNNS =
13224 Context.getCanonicalNestedNameSpecifier(Qual);
13225 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13226 NamedDecl *D = *I;
13227
13228 bool DTypename;
13229 NestedNameSpecifier *DQual;
13230 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13231 DTypename = UD->hasTypename();
13232 DQual = UD->getQualifier();
13233 } else if (UnresolvedUsingValueDecl *UD
13234 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13235 DTypename = false;
13236 DQual = UD->getQualifier();
13237 } else if (UnresolvedUsingTypenameDecl *UD
13238 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13239 DTypename = true;
13240 DQual = UD->getQualifier();
13241 } else continue;
13242
13243 // using decls differ if one says 'typename' and the other doesn't.
13244 // FIXME: non-dependent using decls?
13245 if (HasTypenameKeyword != DTypename) continue;
13246
13247 // using decls differ if they name different scopes (but note that
13248 // template instantiation can cause this check to trigger when it
13249 // didn't before instantiation).
13250 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13251 continue;
13252
13253 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13254 Diag(D->getLocation(), diag::note_using_decl) << 1;
13255 return true;
13256 }
13257
13258 return false;
13259 }
13260
13261 /// Checks that the given nested-name qualifier used in a using decl
13262 /// in the current context is appropriately related to the current
13263 /// scope. If an error is found, diagnoses it and returns true.
13264 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13265 /// result of that lookup. UD is likewise nullptr, except when we have an
13266 /// already-populated UsingDecl whose shadow decls contain the same information
13267 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
CheckUsingDeclQualifier(SourceLocation UsingLoc,bool HasTypename,const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,SourceLocation NameLoc,const LookupResult * R,const UsingDecl * UD)13268 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13269 const CXXScopeSpec &SS,
13270 const DeclarationNameInfo &NameInfo,
13271 SourceLocation NameLoc,
13272 const LookupResult *R, const UsingDecl *UD) {
13273 DeclContext *NamedContext = computeDeclContext(SS);
13274 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13275 "resolvable context must have exactly one set of decls");
13276
13277 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13278 // relationship.
13279 bool Cxx20Enumerator = false;
13280 if (NamedContext) {
13281 EnumConstantDecl *EC = nullptr;
13282 if (R)
13283 EC = R->getAsSingle<EnumConstantDecl>();
13284 else if (UD && UD->shadow_size() == 1)
13285 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13286 if (EC)
13287 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13288
13289 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13290 // C++14 [namespace.udecl]p7:
13291 // A using-declaration shall not name a scoped enumerator.
13292 // C++20 p1099 permits enumerators.
13293 if (EC && R && ED->isScoped())
13294 Diag(SS.getBeginLoc(),
13295 getLangOpts().CPlusPlus20
13296 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13297 : diag::ext_using_decl_scoped_enumerator)
13298 << SS.getRange();
13299
13300 // We want to consider the scope of the enumerator
13301 NamedContext = ED->getDeclContext();
13302 }
13303 }
13304
13305 if (!CurContext->isRecord()) {
13306 // C++03 [namespace.udecl]p3:
13307 // C++0x [namespace.udecl]p8:
13308 // A using-declaration for a class member shall be a member-declaration.
13309 // C++20 [namespace.udecl]p7
13310 // ... other than an enumerator ...
13311
13312 // If we weren't able to compute a valid scope, it might validly be a
13313 // dependent class or enumeration scope. If we have a 'typename' keyword,
13314 // the scope must resolve to a class type.
13315 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13316 : !HasTypename)
13317 return false; // OK
13318
13319 Diag(NameLoc,
13320 Cxx20Enumerator
13321 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13322 : diag::err_using_decl_can_not_refer_to_class_member)
13323 << SS.getRange();
13324
13325 if (Cxx20Enumerator)
13326 return false; // OK
13327
13328 auto *RD = NamedContext
13329 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13330 : nullptr;
13331 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13332 // See if there's a helpful fixit
13333
13334 if (!R) {
13335 // We will have already diagnosed the problem on the template
13336 // definition, Maybe we should do so again?
13337 } else if (R->getAsSingle<TypeDecl>()) {
13338 if (getLangOpts().CPlusPlus11) {
13339 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13340 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13341 << 0 // alias declaration
13342 << FixItHint::CreateInsertion(SS.getBeginLoc(),
13343 NameInfo.getName().getAsString() +
13344 " = ");
13345 } else {
13346 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13347 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13348 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13349 << 1 // typedef declaration
13350 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13351 << FixItHint::CreateInsertion(
13352 InsertLoc, " " + NameInfo.getName().getAsString());
13353 }
13354 } else if (R->getAsSingle<VarDecl>()) {
13355 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13356 // repeating the type of the static data member here.
13357 FixItHint FixIt;
13358 if (getLangOpts().CPlusPlus11) {
13359 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13360 FixIt = FixItHint::CreateReplacement(
13361 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13362 }
13363
13364 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13365 << 2 // reference declaration
13366 << FixIt;
13367 } else if (R->getAsSingle<EnumConstantDecl>()) {
13368 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13369 // repeating the type of the enumeration here, and we can't do so if
13370 // the type is anonymous.
13371 FixItHint FixIt;
13372 if (getLangOpts().CPlusPlus11) {
13373 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13374 FixIt = FixItHint::CreateReplacement(
13375 UsingLoc,
13376 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13377 }
13378
13379 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13380 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13381 << FixIt;
13382 }
13383 }
13384
13385 return true; // Fail
13386 }
13387
13388 // If the named context is dependent, we can't decide much.
13389 if (!NamedContext) {
13390 // FIXME: in C++0x, we can diagnose if we can prove that the
13391 // nested-name-specifier does not refer to a base class, which is
13392 // still possible in some cases.
13393
13394 // Otherwise we have to conservatively report that things might be
13395 // okay.
13396 return false;
13397 }
13398
13399 // The current scope is a record.
13400 if (!NamedContext->isRecord()) {
13401 // Ideally this would point at the last name in the specifier,
13402 // but we don't have that level of source info.
13403 Diag(SS.getBeginLoc(),
13404 Cxx20Enumerator
13405 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13406 : diag::err_using_decl_nested_name_specifier_is_not_class)
13407 << SS.getScopeRep() << SS.getRange();
13408
13409 if (Cxx20Enumerator)
13410 return false; // OK
13411
13412 return true;
13413 }
13414
13415 if (!NamedContext->isDependentContext() &&
13416 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13417 return true;
13418
13419 if (getLangOpts().CPlusPlus11) {
13420 // C++11 [namespace.udecl]p3:
13421 // In a using-declaration used as a member-declaration, the
13422 // nested-name-specifier shall name a base class of the class
13423 // being defined.
13424
13425 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13426 cast<CXXRecordDecl>(NamedContext))) {
13427
13428 if (Cxx20Enumerator) {
13429 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13430 << SS.getRange();
13431 return false;
13432 }
13433
13434 if (CurContext == NamedContext) {
13435 Diag(SS.getBeginLoc(),
13436 diag::err_using_decl_nested_name_specifier_is_current_class)
13437 << SS.getRange();
13438 return !getLangOpts().CPlusPlus20;
13439 }
13440
13441 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13442 Diag(SS.getBeginLoc(),
13443 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13444 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13445 << SS.getRange();
13446 }
13447 return true;
13448 }
13449
13450 return false;
13451 }
13452
13453 // C++03 [namespace.udecl]p4:
13454 // A using-declaration used as a member-declaration shall refer
13455 // to a member of a base class of the class being defined [etc.].
13456
13457 // Salient point: SS doesn't have to name a base class as long as
13458 // lookup only finds members from base classes. Therefore we can
13459 // diagnose here only if we can prove that can't happen,
13460 // i.e. if the class hierarchies provably don't intersect.
13461
13462 // TODO: it would be nice if "definitely valid" results were cached
13463 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13464 // need to be repeated.
13465
13466 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13467 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13468 Bases.insert(Base);
13469 return true;
13470 };
13471
13472 // Collect all bases. Return false if we find a dependent base.
13473 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13474 return false;
13475
13476 // Returns true if the base is dependent or is one of the accumulated base
13477 // classes.
13478 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13479 return !Bases.count(Base);
13480 };
13481
13482 // Return false if the class has a dependent base or if it or one
13483 // of its bases is present in the base set of the current context.
13484 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13485 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13486 return false;
13487
13488 Diag(SS.getRange().getBegin(),
13489 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13490 << SS.getScopeRep()
13491 << cast<CXXRecordDecl>(CurContext)
13492 << SS.getRange();
13493
13494 return true;
13495 }
13496
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,const ParsedAttributesView & AttrList,TypeResult Type,Decl * DeclFromDeclSpec)13497 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13498 MultiTemplateParamsArg TemplateParamLists,
13499 SourceLocation UsingLoc, UnqualifiedId &Name,
13500 const ParsedAttributesView &AttrList,
13501 TypeResult Type, Decl *DeclFromDeclSpec) {
13502 // Skip up to the relevant declaration scope.
13503 while (S->isTemplateParamScope())
13504 S = S->getParent();
13505 assert((S->getFlags() & Scope::DeclScope) &&
13506 "got alias-declaration outside of declaration scope");
13507
13508 if (Type.isInvalid())
13509 return nullptr;
13510
13511 bool Invalid = false;
13512 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13513 TypeSourceInfo *TInfo = nullptr;
13514 GetTypeFromParser(Type.get(), &TInfo);
13515
13516 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13517 return nullptr;
13518
13519 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13520 UPPC_DeclarationType)) {
13521 Invalid = true;
13522 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13523 TInfo->getTypeLoc().getBeginLoc());
13524 }
13525
13526 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13527 TemplateParamLists.size()
13528 ? forRedeclarationInCurContext()
13529 : ForVisibleRedeclaration);
13530 LookupName(Previous, S);
13531
13532 // Warn about shadowing the name of a template parameter.
13533 if (Previous.isSingleResult() &&
13534 Previous.getFoundDecl()->isTemplateParameter()) {
13535 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13536 Previous.clear();
13537 }
13538
13539 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13540 "name in alias declaration must be an identifier");
13541 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13542 Name.StartLocation,
13543 Name.Identifier, TInfo);
13544
13545 NewTD->setAccess(AS);
13546
13547 if (Invalid)
13548 NewTD->setInvalidDecl();
13549
13550 ProcessDeclAttributeList(S, NewTD, AttrList);
13551 AddPragmaAttributes(S, NewTD);
13552
13553 CheckTypedefForVariablyModifiedType(S, NewTD);
13554 Invalid |= NewTD->isInvalidDecl();
13555
13556 bool Redeclaration = false;
13557
13558 NamedDecl *NewND;
13559 if (TemplateParamLists.size()) {
13560 TypeAliasTemplateDecl *OldDecl = nullptr;
13561 TemplateParameterList *OldTemplateParams = nullptr;
13562
13563 if (TemplateParamLists.size() != 1) {
13564 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13565 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13566 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13567 }
13568 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13569
13570 // Check that we can declare a template here.
13571 if (CheckTemplateDeclScope(S, TemplateParams))
13572 return nullptr;
13573
13574 // Only consider previous declarations in the same scope.
13575 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13576 /*ExplicitInstantiationOrSpecialization*/false);
13577 if (!Previous.empty()) {
13578 Redeclaration = true;
13579
13580 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13581 if (!OldDecl && !Invalid) {
13582 Diag(UsingLoc, diag::err_redefinition_different_kind)
13583 << Name.Identifier;
13584
13585 NamedDecl *OldD = Previous.getRepresentativeDecl();
13586 if (OldD->getLocation().isValid())
13587 Diag(OldD->getLocation(), diag::note_previous_definition);
13588
13589 Invalid = true;
13590 }
13591
13592 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13593 if (TemplateParameterListsAreEqual(TemplateParams,
13594 OldDecl->getTemplateParameters(),
13595 /*Complain=*/true,
13596 TPL_TemplateMatch))
13597 OldTemplateParams =
13598 OldDecl->getMostRecentDecl()->getTemplateParameters();
13599 else
13600 Invalid = true;
13601
13602 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13603 if (!Invalid &&
13604 !Context.hasSameType(OldTD->getUnderlyingType(),
13605 NewTD->getUnderlyingType())) {
13606 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13607 // but we can't reasonably accept it.
13608 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13609 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13610 if (OldTD->getLocation().isValid())
13611 Diag(OldTD->getLocation(), diag::note_previous_definition);
13612 Invalid = true;
13613 }
13614 }
13615 }
13616
13617 // Merge any previous default template arguments into our parameters,
13618 // and check the parameter list.
13619 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13620 TPC_TypeAliasTemplate))
13621 return nullptr;
13622
13623 TypeAliasTemplateDecl *NewDecl =
13624 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13625 Name.Identifier, TemplateParams,
13626 NewTD);
13627 NewTD->setDescribedAliasTemplate(NewDecl);
13628
13629 NewDecl->setAccess(AS);
13630
13631 if (Invalid)
13632 NewDecl->setInvalidDecl();
13633 else if (OldDecl) {
13634 NewDecl->setPreviousDecl(OldDecl);
13635 CheckRedeclarationInModule(NewDecl, OldDecl);
13636 }
13637
13638 NewND = NewDecl;
13639 } else {
13640 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13641 setTagNameForLinkagePurposes(TD, NewTD);
13642 handleTagNumbering(TD, S);
13643 }
13644 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13645 NewND = NewTD;
13646 }
13647
13648 PushOnScopeChains(NewND, S);
13649 ActOnDocumentableDecl(NewND);
13650 return NewND;
13651 }
13652
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)13653 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13654 SourceLocation AliasLoc,
13655 IdentifierInfo *Alias, CXXScopeSpec &SS,
13656 SourceLocation IdentLoc,
13657 IdentifierInfo *Ident) {
13658
13659 // Lookup the namespace name.
13660 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13661 LookupParsedName(R, S, &SS);
13662
13663 if (R.isAmbiguous())
13664 return nullptr;
13665
13666 if (R.empty()) {
13667 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13668 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13669 return nullptr;
13670 }
13671 }
13672 assert(!R.isAmbiguous() && !R.empty());
13673 NamedDecl *ND = R.getRepresentativeDecl();
13674
13675 // Check if we have a previous declaration with the same name.
13676 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13677 ForVisibleRedeclaration);
13678 LookupName(PrevR, S);
13679
13680 // Check we're not shadowing a template parameter.
13681 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13682 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13683 PrevR.clear();
13684 }
13685
13686 // Filter out any other lookup result from an enclosing scope.
13687 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13688 /*AllowInlineNamespace*/false);
13689
13690 // Find the previous declaration and check that we can redeclare it.
13691 NamespaceAliasDecl *Prev = nullptr;
13692 if (PrevR.isSingleResult()) {
13693 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13694 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13695 // We already have an alias with the same name that points to the same
13696 // namespace; check that it matches.
13697 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13698 Prev = AD;
13699 } else if (isVisible(PrevDecl)) {
13700 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13701 << Alias;
13702 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13703 << AD->getNamespace();
13704 return nullptr;
13705 }
13706 } else if (isVisible(PrevDecl)) {
13707 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13708 ? diag::err_redefinition
13709 : diag::err_redefinition_different_kind;
13710 Diag(AliasLoc, DiagID) << Alias;
13711 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13712 return nullptr;
13713 }
13714 }
13715
13716 // The use of a nested name specifier may trigger deprecation warnings.
13717 DiagnoseUseOfDecl(ND, IdentLoc);
13718
13719 NamespaceAliasDecl *AliasDecl =
13720 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13721 Alias, SS.getWithLocInContext(Context),
13722 IdentLoc, ND);
13723 if (Prev)
13724 AliasDecl->setPreviousDecl(Prev);
13725
13726 PushOnScopeChains(AliasDecl, S);
13727 return AliasDecl;
13728 }
13729
13730 namespace {
13731 struct SpecialMemberExceptionSpecInfo
13732 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13733 SourceLocation Loc;
13734 Sema::ImplicitExceptionSpecification ExceptSpec;
13735
SpecialMemberExceptionSpecInfo__anon067e66483611::SpecialMemberExceptionSpecInfo13736 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13737 Sema::CXXSpecialMember CSM,
13738 Sema::InheritedConstructorInfo *ICI,
13739 SourceLocation Loc)
13740 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13741
13742 bool visitBase(CXXBaseSpecifier *Base);
13743 bool visitField(FieldDecl *FD);
13744
13745 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13746 unsigned Quals);
13747
13748 void visitSubobjectCall(Subobject Subobj,
13749 Sema::SpecialMemberOverloadResult SMOR);
13750 };
13751 }
13752
visitBase(CXXBaseSpecifier * Base)13753 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13754 auto *RT = Base->getType()->getAs<RecordType>();
13755 if (!RT)
13756 return false;
13757
13758 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13759 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13760 if (auto *BaseCtor = SMOR.getMethod()) {
13761 visitSubobjectCall(Base, BaseCtor);
13762 return false;
13763 }
13764
13765 visitClassSubobject(BaseClass, Base, 0);
13766 return false;
13767 }
13768
visitField(FieldDecl * FD)13769 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13770 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13771 Expr *E = FD->getInClassInitializer();
13772 if (!E)
13773 // FIXME: It's a little wasteful to build and throw away a
13774 // CXXDefaultInitExpr here.
13775 // FIXME: We should have a single context note pointing at Loc, and
13776 // this location should be MD->getLocation() instead, since that's
13777 // the location where we actually use the default init expression.
13778 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13779 if (E)
13780 ExceptSpec.CalledExpr(E);
13781 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13782 ->getAs<RecordType>()) {
13783 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13784 FD->getType().getCVRQualifiers());
13785 }
13786 return false;
13787 }
13788
visitClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)13789 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13790 Subobject Subobj,
13791 unsigned Quals) {
13792 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13793 bool IsMutable = Field && Field->isMutable();
13794 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13795 }
13796
visitSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult SMOR)13797 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13798 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13799 // Note, if lookup fails, it doesn't matter what exception specification we
13800 // choose because the special member will be deleted.
13801 if (CXXMethodDecl *MD = SMOR.getMethod())
13802 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13803 }
13804
tryResolveExplicitSpecifier(ExplicitSpecifier & ExplicitSpec)13805 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13806 llvm::APSInt Result;
13807 ExprResult Converted = CheckConvertedConstantExpression(
13808 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13809 ExplicitSpec.setExpr(Converted.get());
13810 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13811 ExplicitSpec.setKind(Result.getBoolValue()
13812 ? ExplicitSpecKind::ResolvedTrue
13813 : ExplicitSpecKind::ResolvedFalse);
13814 return true;
13815 }
13816 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13817 return false;
13818 }
13819
ActOnExplicitBoolSpecifier(Expr * ExplicitExpr)13820 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13821 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13822 if (!ExplicitExpr->isTypeDependent())
13823 tryResolveExplicitSpecifier(ES);
13824 return ES;
13825 }
13826
13827 static Sema::ImplicitExceptionSpecification
ComputeDefaultedSpecialMemberExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD,Sema::CXXSpecialMember CSM,Sema::InheritedConstructorInfo * ICI)13828 ComputeDefaultedSpecialMemberExceptionSpec(
13829 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13830 Sema::InheritedConstructorInfo *ICI) {
13831 ComputingExceptionSpec CES(S, MD, Loc);
13832
13833 CXXRecordDecl *ClassDecl = MD->getParent();
13834
13835 // C++ [except.spec]p14:
13836 // An implicitly declared special member function (Clause 12) shall have an
13837 // exception-specification. [...]
13838 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13839 if (ClassDecl->isInvalidDecl())
13840 return Info.ExceptSpec;
13841
13842 // FIXME: If this diagnostic fires, we're probably missing a check for
13843 // attempting to resolve an exception specification before it's known
13844 // at a higher level.
13845 if (S.RequireCompleteType(MD->getLocation(),
13846 S.Context.getRecordType(ClassDecl),
13847 diag::err_exception_spec_incomplete_type))
13848 return Info.ExceptSpec;
13849
13850 // C++1z [except.spec]p7:
13851 // [Look for exceptions thrown by] a constructor selected [...] to
13852 // initialize a potentially constructed subobject,
13853 // C++1z [except.spec]p8:
13854 // The exception specification for an implicitly-declared destructor, or a
13855 // destructor without a noexcept-specifier, is potentially-throwing if and
13856 // only if any of the destructors for any of its potentially constructed
13857 // subojects is potentially throwing.
13858 // FIXME: We respect the first rule but ignore the "potentially constructed"
13859 // in the second rule to resolve a core issue (no number yet) that would have
13860 // us reject:
13861 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13862 // struct B : A {};
13863 // struct C : B { void f(); };
13864 // ... due to giving B::~B() a non-throwing exception specification.
13865 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13866 : Info.VisitAllBases);
13867
13868 return Info.ExceptSpec;
13869 }
13870
13871 namespace {
13872 /// RAII object to register a special member as being currently declared.
13873 struct DeclaringSpecialMember {
13874 Sema &S;
13875 Sema::SpecialMemberDecl D;
13876 Sema::ContextRAII SavedContext;
13877 bool WasAlreadyBeingDeclared;
13878
DeclaringSpecialMember__anon067e66483711::DeclaringSpecialMember13879 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13880 : S(S), D(RD, CSM), SavedContext(S, RD) {
13881 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13882 if (WasAlreadyBeingDeclared)
13883 // This almost never happens, but if it does, ensure that our cache
13884 // doesn't contain a stale result.
13885 S.SpecialMemberCache.clear();
13886 else {
13887 // Register a note to be produced if we encounter an error while
13888 // declaring the special member.
13889 Sema::CodeSynthesisContext Ctx;
13890 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13891 // FIXME: We don't have a location to use here. Using the class's
13892 // location maintains the fiction that we declare all special members
13893 // with the class, but (1) it's not clear that lying about that helps our
13894 // users understand what's going on, and (2) there may be outer contexts
13895 // on the stack (some of which are relevant) and printing them exposes
13896 // our lies.
13897 Ctx.PointOfInstantiation = RD->getLocation();
13898 Ctx.Entity = RD;
13899 Ctx.SpecialMember = CSM;
13900 S.pushCodeSynthesisContext(Ctx);
13901 }
13902 }
~DeclaringSpecialMember__anon067e66483711::DeclaringSpecialMember13903 ~DeclaringSpecialMember() {
13904 if (!WasAlreadyBeingDeclared) {
13905 S.SpecialMembersBeingDeclared.erase(D);
13906 S.popCodeSynthesisContext();
13907 }
13908 }
13909
13910 /// Are we already trying to declare this special member?
isAlreadyBeingDeclared__anon067e66483711::DeclaringSpecialMember13911 bool isAlreadyBeingDeclared() const {
13912 return WasAlreadyBeingDeclared;
13913 }
13914 };
13915 }
13916
CheckImplicitSpecialMemberDeclaration(Scope * S,FunctionDecl * FD)13917 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13918 // Look up any existing declarations, but don't trigger declaration of all
13919 // implicit special members with this name.
13920 DeclarationName Name = FD->getDeclName();
13921 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13922 ForExternalRedeclaration);
13923 for (auto *D : FD->getParent()->lookup(Name))
13924 if (auto *Acceptable = R.getAcceptableDecl(D))
13925 R.addDecl(Acceptable);
13926 R.resolveKind();
13927 R.suppressDiagnostics();
13928
13929 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13930 FD->isThisDeclarationADefinition());
13931 }
13932
setupImplicitSpecialMemberType(CXXMethodDecl * SpecialMem,QualType ResultTy,ArrayRef<QualType> Args)13933 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13934 QualType ResultTy,
13935 ArrayRef<QualType> Args) {
13936 // Build an exception specification pointing back at this constructor.
13937 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13938
13939 LangAS AS = getDefaultCXXMethodAddrSpace();
13940 if (AS != LangAS::Default) {
13941 EPI.TypeQuals.addAddressSpace(AS);
13942 }
13943
13944 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13945 SpecialMem->setType(QT);
13946
13947 // During template instantiation of implicit special member functions we need
13948 // a reliable TypeSourceInfo for the function prototype in order to allow
13949 // functions to be substituted.
13950 if (inTemplateInstantiation() &&
13951 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13952 TypeSourceInfo *TSI =
13953 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13954 SpecialMem->setTypeSourceInfo(TSI);
13955 }
13956 }
13957
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)13958 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13959 CXXRecordDecl *ClassDecl) {
13960 // C++ [class.ctor]p5:
13961 // A default constructor for a class X is a constructor of class X
13962 // that can be called without an argument. If there is no
13963 // user-declared constructor for class X, a default constructor is
13964 // implicitly declared. An implicitly-declared default constructor
13965 // is an inline public member of its class.
13966 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13967 "Should not build implicit default constructor!");
13968
13969 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13970 if (DSM.isAlreadyBeingDeclared())
13971 return nullptr;
13972
13973 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13974 CXXDefaultConstructor,
13975 false);
13976
13977 // Create the actual constructor declaration.
13978 CanQualType ClassType
13979 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13980 SourceLocation ClassLoc = ClassDecl->getLocation();
13981 DeclarationName Name
13982 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13983 DeclarationNameInfo NameInfo(Name, ClassLoc);
13984 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13985 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13986 /*TInfo=*/nullptr, ExplicitSpecifier(),
13987 getCurFPFeatures().isFPConstrained(),
13988 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13989 Constexpr ? ConstexprSpecKind::Constexpr
13990 : ConstexprSpecKind::Unspecified);
13991 DefaultCon->setAccess(AS_public);
13992 DefaultCon->setDefaulted();
13993
13994 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13995
13996 if (getLangOpts().CUDA)
13997 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13998 DefaultCon,
13999 /* ConstRHS */ false,
14000 /* Diagnose */ false);
14001
14002 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14003 // constructors is easy to compute.
14004 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14005
14006 // Note that we have declared this constructor.
14007 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14008
14009 Scope *S = getScopeForContext(ClassDecl);
14010 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
14011
14012 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
14013 SetDeclDeleted(DefaultCon, ClassLoc);
14014
14015 if (S)
14016 PushOnScopeChains(DefaultCon, S, false);
14017 ClassDecl->addDecl(DefaultCon);
14018
14019 return DefaultCon;
14020 }
14021
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)14022 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14023 CXXConstructorDecl *Constructor) {
14024 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14025 !Constructor->doesThisDeclarationHaveABody() &&
14026 !Constructor->isDeleted()) &&
14027 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14028 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14029 return;
14030
14031 CXXRecordDecl *ClassDecl = Constructor->getParent();
14032 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14033
14034 SynthesizedFunctionScope Scope(*this, Constructor);
14035
14036 // The exception specification is needed because we are defining the
14037 // function.
14038 ResolveExceptionSpec(CurrentLocation,
14039 Constructor->getType()->castAs<FunctionProtoType>());
14040 MarkVTableUsed(CurrentLocation, ClassDecl);
14041
14042 // Add a context note for diagnostics produced after this point.
14043 Scope.addContextNote(CurrentLocation);
14044
14045 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14046 Constructor->setInvalidDecl();
14047 return;
14048 }
14049
14050 SourceLocation Loc = Constructor->getEndLoc().isValid()
14051 ? Constructor->getEndLoc()
14052 : Constructor->getLocation();
14053 Constructor->setBody(new (Context) CompoundStmt(Loc));
14054 Constructor->markUsed(Context);
14055
14056 if (ASTMutationListener *L = getASTMutationListener()) {
14057 L->CompletedImplicitDefinition(Constructor);
14058 }
14059
14060 DiagnoseUninitializedFields(*this, Constructor);
14061 }
14062
ActOnFinishDelayedMemberInitializers(Decl * D)14063 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14064 // Perform any delayed checks on exception specifications.
14065 CheckDelayedMemberExceptionSpecs();
14066 }
14067
14068 /// Find or create the fake constructor we synthesize to model constructing an
14069 /// object of a derived class via a constructor of a base class.
14070 CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc,CXXConstructorDecl * BaseCtor,ConstructorUsingShadowDecl * Shadow)14071 Sema::findInheritingConstructor(SourceLocation Loc,
14072 CXXConstructorDecl *BaseCtor,
14073 ConstructorUsingShadowDecl *Shadow) {
14074 CXXRecordDecl *Derived = Shadow->getParent();
14075 SourceLocation UsingLoc = Shadow->getLocation();
14076
14077 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14078 // For now we use the name of the base class constructor as a member of the
14079 // derived class to indicate a (fake) inherited constructor name.
14080 DeclarationName Name = BaseCtor->getDeclName();
14081
14082 // Check to see if we already have a fake constructor for this inherited
14083 // constructor call.
14084 for (NamedDecl *Ctor : Derived->lookup(Name))
14085 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14086 ->getInheritedConstructor()
14087 .getConstructor(),
14088 BaseCtor))
14089 return cast<CXXConstructorDecl>(Ctor);
14090
14091 DeclarationNameInfo NameInfo(Name, UsingLoc);
14092 TypeSourceInfo *TInfo =
14093 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14094 FunctionProtoTypeLoc ProtoLoc =
14095 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14096
14097 // Check the inherited constructor is valid and find the list of base classes
14098 // from which it was inherited.
14099 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14100
14101 bool Constexpr =
14102 BaseCtor->isConstexpr() &&
14103 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
14104 false, BaseCtor, &ICI);
14105
14106 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14107 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14108 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14109 /*isInline=*/true,
14110 /*isImplicitlyDeclared=*/true,
14111 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14112 InheritedConstructor(Shadow, BaseCtor),
14113 BaseCtor->getTrailingRequiresClause());
14114 if (Shadow->isInvalidDecl())
14115 DerivedCtor->setInvalidDecl();
14116
14117 // Build an unevaluated exception specification for this fake constructor.
14118 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14119 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14120 EPI.ExceptionSpec.Type = EST_Unevaluated;
14121 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14122 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14123 FPT->getParamTypes(), EPI));
14124
14125 // Build the parameter declarations.
14126 SmallVector<ParmVarDecl *, 16> ParamDecls;
14127 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14128 TypeSourceInfo *TInfo =
14129 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14130 ParmVarDecl *PD = ParmVarDecl::Create(
14131 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14132 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14133 PD->setScopeInfo(0, I);
14134 PD->setImplicit();
14135 // Ensure attributes are propagated onto parameters (this matters for
14136 // format, pass_object_size, ...).
14137 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14138 ParamDecls.push_back(PD);
14139 ProtoLoc.setParam(I, PD);
14140 }
14141
14142 // Set up the new constructor.
14143 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14144 DerivedCtor->setAccess(BaseCtor->getAccess());
14145 DerivedCtor->setParams(ParamDecls);
14146 Derived->addDecl(DerivedCtor);
14147
14148 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
14149 SetDeclDeleted(DerivedCtor, UsingLoc);
14150
14151 return DerivedCtor;
14152 }
14153
NoteDeletedInheritingConstructor(CXXConstructorDecl * Ctor)14154 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14155 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14156 Ctor->getInheritedConstructor().getShadowDecl());
14157 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
14158 /*Diagnose*/true);
14159 }
14160
DefineInheritingConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)14161 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14162 CXXConstructorDecl *Constructor) {
14163 CXXRecordDecl *ClassDecl = Constructor->getParent();
14164 assert(Constructor->getInheritedConstructor() &&
14165 !Constructor->doesThisDeclarationHaveABody() &&
14166 !Constructor->isDeleted());
14167 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14168 return;
14169
14170 // Initializations are performed "as if by a defaulted default constructor",
14171 // so enter the appropriate scope.
14172 SynthesizedFunctionScope Scope(*this, Constructor);
14173
14174 // The exception specification is needed because we are defining the
14175 // function.
14176 ResolveExceptionSpec(CurrentLocation,
14177 Constructor->getType()->castAs<FunctionProtoType>());
14178 MarkVTableUsed(CurrentLocation, ClassDecl);
14179
14180 // Add a context note for diagnostics produced after this point.
14181 Scope.addContextNote(CurrentLocation);
14182
14183 ConstructorUsingShadowDecl *Shadow =
14184 Constructor->getInheritedConstructor().getShadowDecl();
14185 CXXConstructorDecl *InheritedCtor =
14186 Constructor->getInheritedConstructor().getConstructor();
14187
14188 // [class.inhctor.init]p1:
14189 // initialization proceeds as if a defaulted default constructor is used to
14190 // initialize the D object and each base class subobject from which the
14191 // constructor was inherited
14192
14193 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14194 CXXRecordDecl *RD = Shadow->getParent();
14195 SourceLocation InitLoc = Shadow->getLocation();
14196
14197 // Build explicit initializers for all base classes from which the
14198 // constructor was inherited.
14199 SmallVector<CXXCtorInitializer*, 8> Inits;
14200 for (bool VBase : {false, true}) {
14201 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14202 if (B.isVirtual() != VBase)
14203 continue;
14204
14205 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14206 if (!BaseRD)
14207 continue;
14208
14209 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14210 if (!BaseCtor.first)
14211 continue;
14212
14213 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14214 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14215 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14216
14217 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14218 Inits.push_back(new (Context) CXXCtorInitializer(
14219 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14220 SourceLocation()));
14221 }
14222 }
14223
14224 // We now proceed as if for a defaulted default constructor, with the relevant
14225 // initializers replaced.
14226
14227 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14228 Constructor->setInvalidDecl();
14229 return;
14230 }
14231
14232 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14233 Constructor->markUsed(Context);
14234
14235 if (ASTMutationListener *L = getASTMutationListener()) {
14236 L->CompletedImplicitDefinition(Constructor);
14237 }
14238
14239 DiagnoseUninitializedFields(*this, Constructor);
14240 }
14241
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)14242 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14243 // C++ [class.dtor]p2:
14244 // If a class has no user-declared destructor, a destructor is
14245 // declared implicitly. An implicitly-declared destructor is an
14246 // inline public member of its class.
14247 assert(ClassDecl->needsImplicitDestructor());
14248
14249 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
14250 if (DSM.isAlreadyBeingDeclared())
14251 return nullptr;
14252
14253 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14254 CXXDestructor,
14255 false);
14256
14257 // Create the actual destructor declaration.
14258 CanQualType ClassType
14259 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
14260 SourceLocation ClassLoc = ClassDecl->getLocation();
14261 DeclarationName Name
14262 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14263 DeclarationNameInfo NameInfo(Name, ClassLoc);
14264 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14265 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14266 getCurFPFeatures().isFPConstrained(),
14267 /*isInline=*/true,
14268 /*isImplicitlyDeclared=*/true,
14269 Constexpr ? ConstexprSpecKind::Constexpr
14270 : ConstexprSpecKind::Unspecified);
14271 Destructor->setAccess(AS_public);
14272 Destructor->setDefaulted();
14273
14274 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14275
14276 if (getLangOpts().CUDA)
14277 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
14278 Destructor,
14279 /* ConstRHS */ false,
14280 /* Diagnose */ false);
14281
14282 // We don't need to use SpecialMemberIsTrivial here; triviality for
14283 // destructors is easy to compute.
14284 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14285 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14286 ClassDecl->hasTrivialDestructorForCall());
14287
14288 // Note that we have declared this destructor.
14289 ++getASTContext().NumImplicitDestructorsDeclared;
14290
14291 Scope *S = getScopeForContext(ClassDecl);
14292 CheckImplicitSpecialMemberDeclaration(S, Destructor);
14293
14294 // We can't check whether an implicit destructor is deleted before we complete
14295 // the definition of the class, because its validity depends on the alignment
14296 // of the class. We'll check this from ActOnFields once the class is complete.
14297 if (ClassDecl->isCompleteDefinition() &&
14298 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
14299 SetDeclDeleted(Destructor, ClassLoc);
14300
14301 // Introduce this destructor into its scope.
14302 if (S)
14303 PushOnScopeChains(Destructor, S, false);
14304 ClassDecl->addDecl(Destructor);
14305
14306 return Destructor;
14307 }
14308
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)14309 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14310 CXXDestructorDecl *Destructor) {
14311 assert((Destructor->isDefaulted() &&
14312 !Destructor->doesThisDeclarationHaveABody() &&
14313 !Destructor->isDeleted()) &&
14314 "DefineImplicitDestructor - call it for implicit default dtor");
14315 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14316 return;
14317
14318 CXXRecordDecl *ClassDecl = Destructor->getParent();
14319 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14320
14321 SynthesizedFunctionScope Scope(*this, Destructor);
14322
14323 // The exception specification is needed because we are defining the
14324 // function.
14325 ResolveExceptionSpec(CurrentLocation,
14326 Destructor->getType()->castAs<FunctionProtoType>());
14327 MarkVTableUsed(CurrentLocation, ClassDecl);
14328
14329 // Add a context note for diagnostics produced after this point.
14330 Scope.addContextNote(CurrentLocation);
14331
14332 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14333 Destructor->getParent());
14334
14335 if (CheckDestructor(Destructor)) {
14336 Destructor->setInvalidDecl();
14337 return;
14338 }
14339
14340 SourceLocation Loc = Destructor->getEndLoc().isValid()
14341 ? Destructor->getEndLoc()
14342 : Destructor->getLocation();
14343 Destructor->setBody(new (Context) CompoundStmt(Loc));
14344 Destructor->markUsed(Context);
14345
14346 if (ASTMutationListener *L = getASTMutationListener()) {
14347 L->CompletedImplicitDefinition(Destructor);
14348 }
14349 }
14350
CheckCompleteDestructorVariant(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)14351 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14352 CXXDestructorDecl *Destructor) {
14353 if (Destructor->isInvalidDecl())
14354 return;
14355
14356 CXXRecordDecl *ClassDecl = Destructor->getParent();
14357 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14358 "implicit complete dtors unneeded outside MS ABI");
14359 assert(ClassDecl->getNumVBases() > 0 &&
14360 "complete dtor only exists for classes with vbases");
14361
14362 SynthesizedFunctionScope Scope(*this, Destructor);
14363
14364 // Add a context note for diagnostics produced after this point.
14365 Scope.addContextNote(CurrentLocation);
14366
14367 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14368 }
14369
14370 /// Perform any semantic analysis which needs to be delayed until all
14371 /// pending class member declarations have been parsed.
ActOnFinishCXXMemberDecls()14372 void Sema::ActOnFinishCXXMemberDecls() {
14373 // If the context is an invalid C++ class, just suppress these checks.
14374 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14375 if (Record->isInvalidDecl()) {
14376 DelayedOverridingExceptionSpecChecks.clear();
14377 DelayedEquivalentExceptionSpecChecks.clear();
14378 return;
14379 }
14380 checkForMultipleExportedDefaultConstructors(*this, Record);
14381 }
14382 }
14383
ActOnFinishCXXNonNestedClass()14384 void Sema::ActOnFinishCXXNonNestedClass() {
14385 referenceDLLExportedClassMethods();
14386
14387 if (!DelayedDllExportMemberFunctions.empty()) {
14388 SmallVector<CXXMethodDecl*, 4> WorkList;
14389 std::swap(DelayedDllExportMemberFunctions, WorkList);
14390 for (CXXMethodDecl *M : WorkList) {
14391 DefineDefaultedFunction(*this, M, M->getLocation());
14392
14393 // Pass the method to the consumer to get emitted. This is not necessary
14394 // for explicit instantiation definitions, as they will get emitted
14395 // anyway.
14396 if (M->getParent()->getTemplateSpecializationKind() !=
14397 TSK_ExplicitInstantiationDefinition)
14398 ActOnFinishInlineFunctionDef(M);
14399 }
14400 }
14401 }
14402
referenceDLLExportedClassMethods()14403 void Sema::referenceDLLExportedClassMethods() {
14404 if (!DelayedDllExportClasses.empty()) {
14405 // Calling ReferenceDllExportedMembers might cause the current function to
14406 // be called again, so use a local copy of DelayedDllExportClasses.
14407 SmallVector<CXXRecordDecl *, 4> WorkList;
14408 std::swap(DelayedDllExportClasses, WorkList);
14409 for (CXXRecordDecl *Class : WorkList)
14410 ReferenceDllExportedMembers(*this, Class);
14411 }
14412 }
14413
AdjustDestructorExceptionSpec(CXXDestructorDecl * Destructor)14414 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14415 assert(getLangOpts().CPlusPlus11 &&
14416 "adjusting dtor exception specs was introduced in c++11");
14417
14418 if (Destructor->isDependentContext())
14419 return;
14420
14421 // C++11 [class.dtor]p3:
14422 // A declaration of a destructor that does not have an exception-
14423 // specification is implicitly considered to have the same exception-
14424 // specification as an implicit declaration.
14425 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14426 if (DtorType->hasExceptionSpec())
14427 return;
14428
14429 // Replace the destructor's type, building off the existing one. Fortunately,
14430 // the only thing of interest in the destructor type is its extended info.
14431 // The return and arguments are fixed.
14432 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14433 EPI.ExceptionSpec.Type = EST_Unevaluated;
14434 EPI.ExceptionSpec.SourceDecl = Destructor;
14435 Destructor->setType(
14436 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14437
14438 // FIXME: If the destructor has a body that could throw, and the newly created
14439 // spec doesn't allow exceptions, we should emit a warning, because this
14440 // change in behavior can break conforming C++03 programs at runtime.
14441 // However, we don't have a body or an exception specification yet, so it
14442 // needs to be done somewhere else.
14443 }
14444
14445 namespace {
14446 /// An abstract base class for all helper classes used in building the
14447 // copy/move operators. These classes serve as factory functions and help us
14448 // avoid using the same Expr* in the AST twice.
14449 class ExprBuilder {
14450 ExprBuilder(const ExprBuilder&) = delete;
14451 ExprBuilder &operator=(const ExprBuilder&) = delete;
14452
14453 protected:
assertNotNull(Expr * E)14454 static Expr *assertNotNull(Expr *E) {
14455 assert(E && "Expression construction must not fail.");
14456 return E;
14457 }
14458
14459 public:
ExprBuilder()14460 ExprBuilder() {}
~ExprBuilder()14461 virtual ~ExprBuilder() {}
14462
14463 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14464 };
14465
14466 class RefBuilder: public ExprBuilder {
14467 VarDecl *Var;
14468 QualType VarType;
14469
14470 public:
build(Sema & S,SourceLocation Loc) const14471 Expr *build(Sema &S, SourceLocation Loc) const override {
14472 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14473 }
14474
RefBuilder(VarDecl * Var,QualType VarType)14475 RefBuilder(VarDecl *Var, QualType VarType)
14476 : Var(Var), VarType(VarType) {}
14477 };
14478
14479 class ThisBuilder: public ExprBuilder {
14480 public:
build(Sema & S,SourceLocation Loc) const14481 Expr *build(Sema &S, SourceLocation Loc) const override {
14482 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14483 }
14484 };
14485
14486 class CastBuilder: public ExprBuilder {
14487 const ExprBuilder &Builder;
14488 QualType Type;
14489 ExprValueKind Kind;
14490 const CXXCastPath &Path;
14491
14492 public:
build(Sema & S,SourceLocation Loc) const14493 Expr *build(Sema &S, SourceLocation Loc) const override {
14494 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14495 CK_UncheckedDerivedToBase, Kind,
14496 &Path).get());
14497 }
14498
CastBuilder(const ExprBuilder & Builder,QualType Type,ExprValueKind Kind,const CXXCastPath & Path)14499 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14500 const CXXCastPath &Path)
14501 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14502 };
14503
14504 class DerefBuilder: public ExprBuilder {
14505 const ExprBuilder &Builder;
14506
14507 public:
build(Sema & S,SourceLocation Loc) const14508 Expr *build(Sema &S, SourceLocation Loc) const override {
14509 return assertNotNull(
14510 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14511 }
14512
DerefBuilder(const ExprBuilder & Builder)14513 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14514 };
14515
14516 class MemberBuilder: public ExprBuilder {
14517 const ExprBuilder &Builder;
14518 QualType Type;
14519 CXXScopeSpec SS;
14520 bool IsArrow;
14521 LookupResult &MemberLookup;
14522
14523 public:
build(Sema & S,SourceLocation Loc) const14524 Expr *build(Sema &S, SourceLocation Loc) const override {
14525 return assertNotNull(S.BuildMemberReferenceExpr(
14526 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14527 nullptr, MemberLookup, nullptr, nullptr).get());
14528 }
14529
MemberBuilder(const ExprBuilder & Builder,QualType Type,bool IsArrow,LookupResult & MemberLookup)14530 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14531 LookupResult &MemberLookup)
14532 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14533 MemberLookup(MemberLookup) {}
14534 };
14535
14536 class MoveCastBuilder: public ExprBuilder {
14537 const ExprBuilder &Builder;
14538
14539 public:
build(Sema & S,SourceLocation Loc) const14540 Expr *build(Sema &S, SourceLocation Loc) const override {
14541 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14542 }
14543
MoveCastBuilder(const ExprBuilder & Builder)14544 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14545 };
14546
14547 class LvalueConvBuilder: public ExprBuilder {
14548 const ExprBuilder &Builder;
14549
14550 public:
build(Sema & S,SourceLocation Loc) const14551 Expr *build(Sema &S, SourceLocation Loc) const override {
14552 return assertNotNull(
14553 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14554 }
14555
LvalueConvBuilder(const ExprBuilder & Builder)14556 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14557 };
14558
14559 class SubscriptBuilder: public ExprBuilder {
14560 const ExprBuilder &Base;
14561 const ExprBuilder &Index;
14562
14563 public:
build(Sema & S,SourceLocation Loc) const14564 Expr *build(Sema &S, SourceLocation Loc) const override {
14565 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14566 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14567 }
14568
SubscriptBuilder(const ExprBuilder & Base,const ExprBuilder & Index)14569 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14570 : Base(Base), Index(Index) {}
14571 };
14572
14573 } // end anonymous namespace
14574
14575 /// When generating a defaulted copy or move assignment operator, if a field
14576 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14577 /// do so. This optimization only applies for arrays of scalars, and for arrays
14578 /// of class type where the selected copy/move-assignment operator is trivial.
14579 static StmtResult
buildMemcpyForAssignmentOp(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & ToB,const ExprBuilder & FromB)14580 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14581 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14582 // Compute the size of the memory buffer to be copied.
14583 QualType SizeType = S.Context.getSizeType();
14584 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14585 S.Context.getTypeSizeInChars(T).getQuantity());
14586
14587 // Take the address of the field references for "from" and "to". We
14588 // directly construct UnaryOperators here because semantic analysis
14589 // does not permit us to take the address of an xvalue.
14590 Expr *From = FromB.build(S, Loc);
14591 From = UnaryOperator::Create(
14592 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14593 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14594 Expr *To = ToB.build(S, Loc);
14595 To = UnaryOperator::Create(
14596 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14597 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14598
14599 const Type *E = T->getBaseElementTypeUnsafe();
14600 bool NeedsCollectableMemCpy =
14601 E->isRecordType() &&
14602 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14603
14604 // Create a reference to the __builtin_objc_memmove_collectable function
14605 StringRef MemCpyName = NeedsCollectableMemCpy ?
14606 "__builtin_objc_memmove_collectable" :
14607 "__builtin_memcpy";
14608 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14609 Sema::LookupOrdinaryName);
14610 S.LookupName(R, S.TUScope, true);
14611
14612 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14613 if (!MemCpy)
14614 // Something went horribly wrong earlier, and we will have complained
14615 // about it.
14616 return StmtError();
14617
14618 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14619 VK_PRValue, Loc, nullptr);
14620 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14621
14622 Expr *CallArgs[] = {
14623 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14624 };
14625 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14626 Loc, CallArgs, Loc);
14627
14628 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14629 return Call.getAs<Stmt>();
14630 }
14631
14632 /// Builds a statement that copies/moves the given entity from \p From to
14633 /// \c To.
14634 ///
14635 /// This routine is used to copy/move the members of a class with an
14636 /// implicitly-declared copy/move assignment operator. When the entities being
14637 /// copied are arrays, this routine builds for loops to copy them.
14638 ///
14639 /// \param S The Sema object used for type-checking.
14640 ///
14641 /// \param Loc The location where the implicit copy/move is being generated.
14642 ///
14643 /// \param T The type of the expressions being copied/moved. Both expressions
14644 /// must have this type.
14645 ///
14646 /// \param To The expression we are copying/moving to.
14647 ///
14648 /// \param From The expression we are copying/moving from.
14649 ///
14650 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14651 /// Otherwise, it's a non-static member subobject.
14652 ///
14653 /// \param Copying Whether we're copying or moving.
14654 ///
14655 /// \param Depth Internal parameter recording the depth of the recursion.
14656 ///
14657 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14658 /// if a memcpy should be used instead.
14659 static StmtResult
buildSingleCopyAssignRecursively(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)14660 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14661 const ExprBuilder &To, const ExprBuilder &From,
14662 bool CopyingBaseSubobject, bool Copying,
14663 unsigned Depth = 0) {
14664 // C++11 [class.copy]p28:
14665 // Each subobject is assigned in the manner appropriate to its type:
14666 //
14667 // - if the subobject is of class type, as if by a call to operator= with
14668 // the subobject as the object expression and the corresponding
14669 // subobject of x as a single function argument (as if by explicit
14670 // qualification; that is, ignoring any possible virtual overriding
14671 // functions in more derived classes);
14672 //
14673 // C++03 [class.copy]p13:
14674 // - if the subobject is of class type, the copy assignment operator for
14675 // the class is used (as if by explicit qualification; that is,
14676 // ignoring any possible virtual overriding functions in more derived
14677 // classes);
14678 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14679 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14680
14681 // Look for operator=.
14682 DeclarationName Name
14683 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14684 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14685 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14686
14687 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14688 // operator.
14689 if (!S.getLangOpts().CPlusPlus11) {
14690 LookupResult::Filter F = OpLookup.makeFilter();
14691 while (F.hasNext()) {
14692 NamedDecl *D = F.next();
14693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14694 if (Method->isCopyAssignmentOperator() ||
14695 (!Copying && Method->isMoveAssignmentOperator()))
14696 continue;
14697
14698 F.erase();
14699 }
14700 F.done();
14701 }
14702
14703 // Suppress the protected check (C++ [class.protected]) for each of the
14704 // assignment operators we found. This strange dance is required when
14705 // we're assigning via a base classes's copy-assignment operator. To
14706 // ensure that we're getting the right base class subobject (without
14707 // ambiguities), we need to cast "this" to that subobject type; to
14708 // ensure that we don't go through the virtual call mechanism, we need
14709 // to qualify the operator= name with the base class (see below). However,
14710 // this means that if the base class has a protected copy assignment
14711 // operator, the protected member access check will fail. So, we
14712 // rewrite "protected" access to "public" access in this case, since we
14713 // know by construction that we're calling from a derived class.
14714 if (CopyingBaseSubobject) {
14715 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14716 L != LEnd; ++L) {
14717 if (L.getAccess() == AS_protected)
14718 L.setAccess(AS_public);
14719 }
14720 }
14721
14722 // Create the nested-name-specifier that will be used to qualify the
14723 // reference to operator=; this is required to suppress the virtual
14724 // call mechanism.
14725 CXXScopeSpec SS;
14726 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14727 SS.MakeTrivial(S.Context,
14728 NestedNameSpecifier::Create(S.Context, nullptr, false,
14729 CanonicalT),
14730 Loc);
14731
14732 // Create the reference to operator=.
14733 ExprResult OpEqualRef
14734 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14735 SS, /*TemplateKWLoc=*/SourceLocation(),
14736 /*FirstQualifierInScope=*/nullptr,
14737 OpLookup,
14738 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14739 /*SuppressQualifierCheck=*/true);
14740 if (OpEqualRef.isInvalid())
14741 return StmtError();
14742
14743 // Build the call to the assignment operator.
14744
14745 Expr *FromInst = From.build(S, Loc);
14746 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14747 OpEqualRef.getAs<Expr>(),
14748 Loc, FromInst, Loc);
14749 if (Call.isInvalid())
14750 return StmtError();
14751
14752 // If we built a call to a trivial 'operator=' while copying an array,
14753 // bail out. We'll replace the whole shebang with a memcpy.
14754 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14755 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14756 return StmtResult((Stmt*)nullptr);
14757
14758 // Convert to an expression-statement, and clean up any produced
14759 // temporaries.
14760 return S.ActOnExprStmt(Call);
14761 }
14762
14763 // - if the subobject is of scalar type, the built-in assignment
14764 // operator is used.
14765 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14766 if (!ArrayTy) {
14767 ExprResult Assignment = S.CreateBuiltinBinOp(
14768 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14769 if (Assignment.isInvalid())
14770 return StmtError();
14771 return S.ActOnExprStmt(Assignment);
14772 }
14773
14774 // - if the subobject is an array, each element is assigned, in the
14775 // manner appropriate to the element type;
14776
14777 // Construct a loop over the array bounds, e.g.,
14778 //
14779 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14780 //
14781 // that will copy each of the array elements.
14782 QualType SizeType = S.Context.getSizeType();
14783
14784 // Create the iteration variable.
14785 IdentifierInfo *IterationVarName = nullptr;
14786 {
14787 SmallString<8> Str;
14788 llvm::raw_svector_ostream OS(Str);
14789 OS << "__i" << Depth;
14790 IterationVarName = &S.Context.Idents.get(OS.str());
14791 }
14792 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14793 IterationVarName, SizeType,
14794 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14795 SC_None);
14796
14797 // Initialize the iteration variable to zero.
14798 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14799 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14800
14801 // Creates a reference to the iteration variable.
14802 RefBuilder IterationVarRef(IterationVar, SizeType);
14803 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14804
14805 // Create the DeclStmt that holds the iteration variable.
14806 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14807
14808 // Subscript the "from" and "to" expressions with the iteration variable.
14809 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14810 MoveCastBuilder FromIndexMove(FromIndexCopy);
14811 const ExprBuilder *FromIndex;
14812 if (Copying)
14813 FromIndex = &FromIndexCopy;
14814 else
14815 FromIndex = &FromIndexMove;
14816
14817 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14818
14819 // Build the copy/move for an individual element of the array.
14820 StmtResult Copy =
14821 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14822 ToIndex, *FromIndex, CopyingBaseSubobject,
14823 Copying, Depth + 1);
14824 // Bail out if copying fails or if we determined that we should use memcpy.
14825 if (Copy.isInvalid() || !Copy.get())
14826 return Copy;
14827
14828 // Create the comparison against the array bound.
14829 llvm::APInt Upper
14830 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14831 Expr *Comparison = BinaryOperator::Create(
14832 S.Context, IterationVarRefRVal.build(S, Loc),
14833 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14834 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14835 S.CurFPFeatureOverrides());
14836
14837 // Create the pre-increment of the iteration variable. We can determine
14838 // whether the increment will overflow based on the value of the array
14839 // bound.
14840 Expr *Increment = UnaryOperator::Create(
14841 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14842 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14843
14844 // Construct the loop that copies all elements of this array.
14845 return S.ActOnForStmt(
14846 Loc, Loc, InitStmt,
14847 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14848 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14849 }
14850
14851 static StmtResult
buildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying)14852 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14853 const ExprBuilder &To, const ExprBuilder &From,
14854 bool CopyingBaseSubobject, bool Copying) {
14855 // Maybe we should use a memcpy?
14856 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14857 T.isTriviallyCopyableType(S.Context))
14858 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14859
14860 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14861 CopyingBaseSubobject,
14862 Copying, 0));
14863
14864 // If we ended up picking a trivial assignment operator for an array of a
14865 // non-trivially-copyable class type, just emit a memcpy.
14866 if (!Result.isInvalid() && !Result.get())
14867 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14868
14869 return Result;
14870 }
14871
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)14872 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14873 // Note: The following rules are largely analoguous to the copy
14874 // constructor rules. Note that virtual bases are not taken into account
14875 // for determining the argument type of the operator. Note also that
14876 // operators taking an object instead of a reference are allowed.
14877 assert(ClassDecl->needsImplicitCopyAssignment());
14878
14879 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14880 if (DSM.isAlreadyBeingDeclared())
14881 return nullptr;
14882
14883 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14884 ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
14885 ArgType, nullptr);
14886 LangAS AS = getDefaultCXXMethodAddrSpace();
14887 if (AS != LangAS::Default)
14888 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14889 QualType RetType = Context.getLValueReferenceType(ArgType);
14890 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14891 if (Const)
14892 ArgType = ArgType.withConst();
14893
14894 ArgType = Context.getLValueReferenceType(ArgType);
14895
14896 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14897 CXXCopyAssignment,
14898 Const);
14899
14900 // An implicitly-declared copy assignment operator is an inline public
14901 // member of its class.
14902 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14903 SourceLocation ClassLoc = ClassDecl->getLocation();
14904 DeclarationNameInfo NameInfo(Name, ClassLoc);
14905 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14906 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14907 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14908 getCurFPFeatures().isFPConstrained(),
14909 /*isInline=*/true,
14910 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14911 SourceLocation());
14912 CopyAssignment->setAccess(AS_public);
14913 CopyAssignment->setDefaulted();
14914 CopyAssignment->setImplicit();
14915
14916 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14917
14918 if (getLangOpts().CUDA)
14919 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14920 CopyAssignment,
14921 /* ConstRHS */ Const,
14922 /* Diagnose */ false);
14923
14924 // Add the parameter to the operator.
14925 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14926 ClassLoc, ClassLoc,
14927 /*Id=*/nullptr, ArgType,
14928 /*TInfo=*/nullptr, SC_None,
14929 nullptr);
14930 CopyAssignment->setParams(FromParam);
14931
14932 CopyAssignment->setTrivial(
14933 ClassDecl->needsOverloadResolutionForCopyAssignment()
14934 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14935 : ClassDecl->hasTrivialCopyAssignment());
14936
14937 // Note that we have added this copy-assignment operator.
14938 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14939
14940 Scope *S = getScopeForContext(ClassDecl);
14941 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14942
14943 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14944 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14945 SetDeclDeleted(CopyAssignment, ClassLoc);
14946 }
14947
14948 if (S)
14949 PushOnScopeChains(CopyAssignment, S, false);
14950 ClassDecl->addDecl(CopyAssignment);
14951
14952 return CopyAssignment;
14953 }
14954
14955 /// Diagnose an implicit copy operation for a class which is odr-used, but
14956 /// which is deprecated because the class has a user-declared copy constructor,
14957 /// copy assignment operator, or destructor.
diagnoseDeprecatedCopyOperation(Sema & S,CXXMethodDecl * CopyOp)14958 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14959 assert(CopyOp->isImplicit());
14960
14961 CXXRecordDecl *RD = CopyOp->getParent();
14962 CXXMethodDecl *UserDeclaredOperation = nullptr;
14963
14964 if (RD->hasUserDeclaredDestructor()) {
14965 UserDeclaredOperation = RD->getDestructor();
14966 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14967 RD->hasUserDeclaredCopyConstructor()) {
14968 // Find any user-declared copy constructor.
14969 for (auto *I : RD->ctors()) {
14970 if (I->isCopyConstructor()) {
14971 UserDeclaredOperation = I;
14972 break;
14973 }
14974 }
14975 assert(UserDeclaredOperation);
14976 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14977 RD->hasUserDeclaredCopyAssignment()) {
14978 // Find any user-declared move assignment operator.
14979 for (auto *I : RD->methods()) {
14980 if (I->isCopyAssignmentOperator()) {
14981 UserDeclaredOperation = I;
14982 break;
14983 }
14984 }
14985 assert(UserDeclaredOperation);
14986 }
14987
14988 if (UserDeclaredOperation) {
14989 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14990 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14991 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14992 unsigned DiagID =
14993 (UDOIsUserProvided && UDOIsDestructor)
14994 ? diag::warn_deprecated_copy_with_user_provided_dtor
14995 : (UDOIsUserProvided && !UDOIsDestructor)
14996 ? diag::warn_deprecated_copy_with_user_provided_copy
14997 : (!UDOIsUserProvided && UDOIsDestructor)
14998 ? diag::warn_deprecated_copy_with_dtor
14999 : diag::warn_deprecated_copy;
15000 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15001 << RD << IsCopyAssignment;
15002 }
15003 }
15004
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)15005 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15006 CXXMethodDecl *CopyAssignOperator) {
15007 assert((CopyAssignOperator->isDefaulted() &&
15008 CopyAssignOperator->isOverloadedOperator() &&
15009 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15010 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15011 !CopyAssignOperator->isDeleted()) &&
15012 "DefineImplicitCopyAssignment called for wrong function");
15013 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15014 return;
15015
15016 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15017 if (ClassDecl->isInvalidDecl()) {
15018 CopyAssignOperator->setInvalidDecl();
15019 return;
15020 }
15021
15022 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15023
15024 // The exception specification is needed because we are defining the
15025 // function.
15026 ResolveExceptionSpec(CurrentLocation,
15027 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15028
15029 // Add a context note for diagnostics produced after this point.
15030 Scope.addContextNote(CurrentLocation);
15031
15032 // C++11 [class.copy]p18:
15033 // The [definition of an implicitly declared copy assignment operator] is
15034 // deprecated if the class has a user-declared copy constructor or a
15035 // user-declared destructor.
15036 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15037 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15038
15039 // C++0x [class.copy]p30:
15040 // The implicitly-defined or explicitly-defaulted copy assignment operator
15041 // for a non-union class X performs memberwise copy assignment of its
15042 // subobjects. The direct base classes of X are assigned first, in the
15043 // order of their declaration in the base-specifier-list, and then the
15044 // immediate non-static data members of X are assigned, in the order in
15045 // which they were declared in the class definition.
15046
15047 // The statements that form the synthesized function body.
15048 SmallVector<Stmt*, 8> Statements;
15049
15050 // The parameter for the "other" object, which we are copying from.
15051 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15052 Qualifiers OtherQuals = Other->getType().getQualifiers();
15053 QualType OtherRefType = Other->getType();
15054 if (OtherRefType->isLValueReferenceType()) {
15055 OtherRefType = OtherRefType->getPointeeType();
15056 OtherQuals = OtherRefType.getQualifiers();
15057 }
15058
15059 // Our location for everything implicitly-generated.
15060 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15061 ? CopyAssignOperator->getEndLoc()
15062 : CopyAssignOperator->getLocation();
15063
15064 // Builds a DeclRefExpr for the "other" object.
15065 RefBuilder OtherRef(Other, OtherRefType);
15066
15067 // Builds the function object parameter.
15068 std::optional<ThisBuilder> This;
15069 std::optional<DerefBuilder> DerefThis;
15070 std::optional<RefBuilder> ExplicitObject;
15071 bool IsArrow = false;
15072 QualType ObjectType;
15073 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15074 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15075 if (ObjectType->isReferenceType())
15076 ObjectType = ObjectType->getPointeeType();
15077 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15078 } else {
15079 ObjectType = getCurrentThisType();
15080 This.emplace();
15081 DerefThis.emplace(*This);
15082 IsArrow = !LangOpts.HLSL;
15083 }
15084 ExprBuilder &ObjectParameter =
15085 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15086 : static_cast<ExprBuilder &>(*This);
15087
15088 // Assign base classes.
15089 bool Invalid = false;
15090 for (auto &Base : ClassDecl->bases()) {
15091 // Form the assignment:
15092 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15093 QualType BaseType = Base.getType().getUnqualifiedType();
15094 if (!BaseType->isRecordType()) {
15095 Invalid = true;
15096 continue;
15097 }
15098
15099 CXXCastPath BasePath;
15100 BasePath.push_back(&Base);
15101
15102 // Construct the "from" expression, which is an implicit cast to the
15103 // appropriately-qualified base type.
15104 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15105 VK_LValue, BasePath);
15106
15107 // Dereference "this".
15108 CastBuilder To(
15109 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15110 : static_cast<ExprBuilder &>(*DerefThis),
15111 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15112 VK_LValue, BasePath);
15113
15114 // Build the copy.
15115 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15116 To, From,
15117 /*CopyingBaseSubobject=*/true,
15118 /*Copying=*/true);
15119 if (Copy.isInvalid()) {
15120 CopyAssignOperator->setInvalidDecl();
15121 return;
15122 }
15123
15124 // Success! Record the copy.
15125 Statements.push_back(Copy.getAs<Expr>());
15126 }
15127
15128 // Assign non-static members.
15129 for (auto *Field : ClassDecl->fields()) {
15130 // FIXME: We should form some kind of AST representation for the implied
15131 // memcpy in a union copy operation.
15132 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15133 continue;
15134
15135 if (Field->isInvalidDecl()) {
15136 Invalid = true;
15137 continue;
15138 }
15139
15140 // Check for members of reference type; we can't copy those.
15141 if (Field->getType()->isReferenceType()) {
15142 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15143 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15144 Diag(Field->getLocation(), diag::note_declared_at);
15145 Invalid = true;
15146 continue;
15147 }
15148
15149 // Check for members of const-qualified, non-class type.
15150 QualType BaseType = Context.getBaseElementType(Field->getType());
15151 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15152 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15153 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15154 Diag(Field->getLocation(), diag::note_declared_at);
15155 Invalid = true;
15156 continue;
15157 }
15158
15159 // Suppress assigning zero-width bitfields.
15160 if (Field->isZeroLengthBitField(Context))
15161 continue;
15162
15163 QualType FieldType = Field->getType().getNonReferenceType();
15164 if (FieldType->isIncompleteArrayType()) {
15165 assert(ClassDecl->hasFlexibleArrayMember() &&
15166 "Incomplete array type is not valid");
15167 continue;
15168 }
15169
15170 // Build references to the field in the object we're copying from and to.
15171 CXXScopeSpec SS; // Intentionally empty
15172 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15173 LookupMemberName);
15174 MemberLookup.addDecl(Field);
15175 MemberLookup.resolveKind();
15176
15177 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15178 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15179 // Build the copy of this field.
15180 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15181 To, From,
15182 /*CopyingBaseSubobject=*/false,
15183 /*Copying=*/true);
15184 if (Copy.isInvalid()) {
15185 CopyAssignOperator->setInvalidDecl();
15186 return;
15187 }
15188
15189 // Success! Record the copy.
15190 Statements.push_back(Copy.getAs<Stmt>());
15191 }
15192
15193 if (!Invalid) {
15194 // Add a "return *this;"
15195 Expr *ThisExpr =
15196 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15197 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15198 : static_cast<ExprBuilder &>(*DerefThis))
15199 .build(*this, Loc);
15200 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15201 if (Return.isInvalid())
15202 Invalid = true;
15203 else
15204 Statements.push_back(Return.getAs<Stmt>());
15205 }
15206
15207 if (Invalid) {
15208 CopyAssignOperator->setInvalidDecl();
15209 return;
15210 }
15211
15212 StmtResult Body;
15213 {
15214 CompoundScopeRAII CompoundScope(*this);
15215 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15216 /*isStmtExpr=*/false);
15217 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15218 }
15219 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15220 CopyAssignOperator->markUsed(Context);
15221
15222 if (ASTMutationListener *L = getASTMutationListener()) {
15223 L->CompletedImplicitDefinition(CopyAssignOperator);
15224 }
15225 }
15226
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)15227 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15228 assert(ClassDecl->needsImplicitMoveAssignment());
15229
15230 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
15231 if (DSM.isAlreadyBeingDeclared())
15232 return nullptr;
15233
15234 // Note: The following rules are largely analoguous to the move
15235 // constructor rules.
15236
15237 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15238 ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15239 ArgType, nullptr);
15240 LangAS AS = getDefaultCXXMethodAddrSpace();
15241 if (AS != LangAS::Default)
15242 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15243 QualType RetType = Context.getLValueReferenceType(ArgType);
15244 ArgType = Context.getRValueReferenceType(ArgType);
15245
15246 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15247 CXXMoveAssignment,
15248 false);
15249
15250 // An implicitly-declared move assignment operator is an inline public
15251 // member of its class.
15252 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15253 SourceLocation ClassLoc = ClassDecl->getLocation();
15254 DeclarationNameInfo NameInfo(Name, ClassLoc);
15255 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15256 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15257 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15258 getCurFPFeatures().isFPConstrained(),
15259 /*isInline=*/true,
15260 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15261 SourceLocation());
15262 MoveAssignment->setAccess(AS_public);
15263 MoveAssignment->setDefaulted();
15264 MoveAssignment->setImplicit();
15265
15266 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15267
15268 if (getLangOpts().CUDA)
15269 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
15270 MoveAssignment,
15271 /* ConstRHS */ false,
15272 /* Diagnose */ false);
15273
15274 // Add the parameter to the operator.
15275 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15276 ClassLoc, ClassLoc,
15277 /*Id=*/nullptr, ArgType,
15278 /*TInfo=*/nullptr, SC_None,
15279 nullptr);
15280 MoveAssignment->setParams(FromParam);
15281
15282 MoveAssignment->setTrivial(
15283 ClassDecl->needsOverloadResolutionForMoveAssignment()
15284 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
15285 : ClassDecl->hasTrivialMoveAssignment());
15286
15287 // Note that we have added this copy-assignment operator.
15288 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15289
15290 Scope *S = getScopeForContext(ClassDecl);
15291 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15292
15293 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
15294 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15295 SetDeclDeleted(MoveAssignment, ClassLoc);
15296 }
15297
15298 if (S)
15299 PushOnScopeChains(MoveAssignment, S, false);
15300 ClassDecl->addDecl(MoveAssignment);
15301
15302 return MoveAssignment;
15303 }
15304
15305 /// Check if we're implicitly defining a move assignment operator for a class
15306 /// with virtual bases. Such a move assignment might move-assign the virtual
15307 /// base multiple times.
checkMoveAssignmentForRepeatedMove(Sema & S,CXXRecordDecl * Class,SourceLocation CurrentLocation)15308 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15309 SourceLocation CurrentLocation) {
15310 assert(!Class->isDependentContext() && "should not define dependent move");
15311
15312 // Only a virtual base could get implicitly move-assigned multiple times.
15313 // Only a non-trivial move assignment can observe this. We only want to
15314 // diagnose if we implicitly define an assignment operator that assigns
15315 // two base classes, both of which move-assign the same virtual base.
15316 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15317 Class->getNumBases() < 2)
15318 return;
15319
15320 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15321 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15322 VBaseMap VBases;
15323
15324 for (auto &BI : Class->bases()) {
15325 Worklist.push_back(&BI);
15326 while (!Worklist.empty()) {
15327 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15328 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15329
15330 // If the base has no non-trivial move assignment operators,
15331 // we don't care about moves from it.
15332 if (!Base->hasNonTrivialMoveAssignment())
15333 continue;
15334
15335 // If there's nothing virtual here, skip it.
15336 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15337 continue;
15338
15339 // If we're not actually going to call a move assignment for this base,
15340 // or the selected move assignment is trivial, skip it.
15341 Sema::SpecialMemberOverloadResult SMOR =
15342 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
15343 /*ConstArg*/false, /*VolatileArg*/false,
15344 /*RValueThis*/true, /*ConstThis*/false,
15345 /*VolatileThis*/false);
15346 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15347 !SMOR.getMethod()->isMoveAssignmentOperator())
15348 continue;
15349
15350 if (BaseSpec->isVirtual()) {
15351 // We're going to move-assign this virtual base, and its move
15352 // assignment operator is not trivial. If this can happen for
15353 // multiple distinct direct bases of Class, diagnose it. (If it
15354 // only happens in one base, we'll diagnose it when synthesizing
15355 // that base class's move assignment operator.)
15356 CXXBaseSpecifier *&Existing =
15357 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15358 .first->second;
15359 if (Existing && Existing != &BI) {
15360 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15361 << Class << Base;
15362 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15363 << (Base->getCanonicalDecl() ==
15364 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15365 << Base << Existing->getType() << Existing->getSourceRange();
15366 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15367 << (Base->getCanonicalDecl() ==
15368 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15369 << Base << BI.getType() << BaseSpec->getSourceRange();
15370
15371 // Only diagnose each vbase once.
15372 Existing = nullptr;
15373 }
15374 } else {
15375 // Only walk over bases that have defaulted move assignment operators.
15376 // We assume that any user-provided move assignment operator handles
15377 // the multiple-moves-of-vbase case itself somehow.
15378 if (!SMOR.getMethod()->isDefaulted())
15379 continue;
15380
15381 // We're going to move the base classes of Base. Add them to the list.
15382 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15383 }
15384 }
15385 }
15386 }
15387
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)15388 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15389 CXXMethodDecl *MoveAssignOperator) {
15390 assert((MoveAssignOperator->isDefaulted() &&
15391 MoveAssignOperator->isOverloadedOperator() &&
15392 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15393 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15394 !MoveAssignOperator->isDeleted()) &&
15395 "DefineImplicitMoveAssignment called for wrong function");
15396 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15397 return;
15398
15399 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15400 if (ClassDecl->isInvalidDecl()) {
15401 MoveAssignOperator->setInvalidDecl();
15402 return;
15403 }
15404
15405 // C++0x [class.copy]p28:
15406 // The implicitly-defined or move assignment operator for a non-union class
15407 // X performs memberwise move assignment of its subobjects. The direct base
15408 // classes of X are assigned first, in the order of their declaration in the
15409 // base-specifier-list, and then the immediate non-static data members of X
15410 // are assigned, in the order in which they were declared in the class
15411 // definition.
15412
15413 // Issue a warning if our implicit move assignment operator will move
15414 // from a virtual base more than once.
15415 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15416
15417 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15418
15419 // The exception specification is needed because we are defining the
15420 // function.
15421 ResolveExceptionSpec(CurrentLocation,
15422 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15423
15424 // Add a context note for diagnostics produced after this point.
15425 Scope.addContextNote(CurrentLocation);
15426
15427 // The statements that form the synthesized function body.
15428 SmallVector<Stmt*, 8> Statements;
15429
15430 // The parameter for the "other" object, which we are move from.
15431 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15432 QualType OtherRefType =
15433 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15434
15435 // Our location for everything implicitly-generated.
15436 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15437 ? MoveAssignOperator->getEndLoc()
15438 : MoveAssignOperator->getLocation();
15439
15440 // Builds a reference to the "other" object.
15441 RefBuilder OtherRef(Other, OtherRefType);
15442 // Cast to rvalue.
15443 MoveCastBuilder MoveOther(OtherRef);
15444
15445 // Builds the function object parameter.
15446 std::optional<ThisBuilder> This;
15447 std::optional<DerefBuilder> DerefThis;
15448 std::optional<RefBuilder> ExplicitObject;
15449 QualType ObjectType;
15450 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15451 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15452 if (ObjectType->isReferenceType())
15453 ObjectType = ObjectType->getPointeeType();
15454 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15455 } else {
15456 ObjectType = getCurrentThisType();
15457 This.emplace();
15458 DerefThis.emplace(*This);
15459 }
15460 ExprBuilder &ObjectParameter =
15461 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15462
15463 // Assign base classes.
15464 bool Invalid = false;
15465 for (auto &Base : ClassDecl->bases()) {
15466 // C++11 [class.copy]p28:
15467 // It is unspecified whether subobjects representing virtual base classes
15468 // are assigned more than once by the implicitly-defined copy assignment
15469 // operator.
15470 // FIXME: Do not assign to a vbase that will be assigned by some other base
15471 // class. For a move-assignment, this can result in the vbase being moved
15472 // multiple times.
15473
15474 // Form the assignment:
15475 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15476 QualType BaseType = Base.getType().getUnqualifiedType();
15477 if (!BaseType->isRecordType()) {
15478 Invalid = true;
15479 continue;
15480 }
15481
15482 CXXCastPath BasePath;
15483 BasePath.push_back(&Base);
15484
15485 // Construct the "from" expression, which is an implicit cast to the
15486 // appropriately-qualified base type.
15487 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15488
15489 // Implicitly cast "this" to the appropriately-qualified base type.
15490 // Dereference "this".
15491 CastBuilder To(
15492 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15493 : static_cast<ExprBuilder &>(*DerefThis),
15494 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15495 VK_LValue, BasePath);
15496
15497 // Build the move.
15498 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15499 To, From,
15500 /*CopyingBaseSubobject=*/true,
15501 /*Copying=*/false);
15502 if (Move.isInvalid()) {
15503 MoveAssignOperator->setInvalidDecl();
15504 return;
15505 }
15506
15507 // Success! Record the move.
15508 Statements.push_back(Move.getAs<Expr>());
15509 }
15510
15511 // Assign non-static members.
15512 for (auto *Field : ClassDecl->fields()) {
15513 // FIXME: We should form some kind of AST representation for the implied
15514 // memcpy in a union copy operation.
15515 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15516 continue;
15517
15518 if (Field->isInvalidDecl()) {
15519 Invalid = true;
15520 continue;
15521 }
15522
15523 // Check for members of reference type; we can't move those.
15524 if (Field->getType()->isReferenceType()) {
15525 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15526 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15527 Diag(Field->getLocation(), diag::note_declared_at);
15528 Invalid = true;
15529 continue;
15530 }
15531
15532 // Check for members of const-qualified, non-class type.
15533 QualType BaseType = Context.getBaseElementType(Field->getType());
15534 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15535 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15536 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15537 Diag(Field->getLocation(), diag::note_declared_at);
15538 Invalid = true;
15539 continue;
15540 }
15541
15542 // Suppress assigning zero-width bitfields.
15543 if (Field->isZeroLengthBitField(Context))
15544 continue;
15545
15546 QualType FieldType = Field->getType().getNonReferenceType();
15547 if (FieldType->isIncompleteArrayType()) {
15548 assert(ClassDecl->hasFlexibleArrayMember() &&
15549 "Incomplete array type is not valid");
15550 continue;
15551 }
15552
15553 // Build references to the field in the object we're copying from and to.
15554 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15555 LookupMemberName);
15556 MemberLookup.addDecl(Field);
15557 MemberLookup.resolveKind();
15558 MemberBuilder From(MoveOther, OtherRefType,
15559 /*IsArrow=*/false, MemberLookup);
15560 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15561 MemberLookup);
15562
15563 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15564 "Member reference with rvalue base must be rvalue except for reference "
15565 "members, which aren't allowed for move assignment.");
15566
15567 // Build the move of this field.
15568 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15569 To, From,
15570 /*CopyingBaseSubobject=*/false,
15571 /*Copying=*/false);
15572 if (Move.isInvalid()) {
15573 MoveAssignOperator->setInvalidDecl();
15574 return;
15575 }
15576
15577 // Success! Record the copy.
15578 Statements.push_back(Move.getAs<Stmt>());
15579 }
15580
15581 if (!Invalid) {
15582 // Add a "return *this;"
15583 Expr *ThisExpr =
15584 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15585 : static_cast<ExprBuilder &>(*DerefThis))
15586 .build(*this, Loc);
15587
15588 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15589 if (Return.isInvalid())
15590 Invalid = true;
15591 else
15592 Statements.push_back(Return.getAs<Stmt>());
15593 }
15594
15595 if (Invalid) {
15596 MoveAssignOperator->setInvalidDecl();
15597 return;
15598 }
15599
15600 StmtResult Body;
15601 {
15602 CompoundScopeRAII CompoundScope(*this);
15603 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15604 /*isStmtExpr=*/false);
15605 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15606 }
15607 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15608 MoveAssignOperator->markUsed(Context);
15609
15610 if (ASTMutationListener *L = getASTMutationListener()) {
15611 L->CompletedImplicitDefinition(MoveAssignOperator);
15612 }
15613 }
15614
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)15615 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15616 CXXRecordDecl *ClassDecl) {
15617 // C++ [class.copy]p4:
15618 // If the class definition does not explicitly declare a copy
15619 // constructor, one is declared implicitly.
15620 assert(ClassDecl->needsImplicitCopyConstructor());
15621
15622 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15623 if (DSM.isAlreadyBeingDeclared())
15624 return nullptr;
15625
15626 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15627 QualType ArgType = ClassType;
15628 ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15629 ArgType, nullptr);
15630 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15631 if (Const)
15632 ArgType = ArgType.withConst();
15633
15634 LangAS AS = getDefaultCXXMethodAddrSpace();
15635 if (AS != LangAS::Default)
15636 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15637
15638 ArgType = Context.getLValueReferenceType(ArgType);
15639
15640 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15641 CXXCopyConstructor,
15642 Const);
15643
15644 DeclarationName Name
15645 = Context.DeclarationNames.getCXXConstructorName(
15646 Context.getCanonicalType(ClassType));
15647 SourceLocation ClassLoc = ClassDecl->getLocation();
15648 DeclarationNameInfo NameInfo(Name, ClassLoc);
15649
15650 // An implicitly-declared copy constructor is an inline public
15651 // member of its class.
15652 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15653 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15654 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15655 /*isInline=*/true,
15656 /*isImplicitlyDeclared=*/true,
15657 Constexpr ? ConstexprSpecKind::Constexpr
15658 : ConstexprSpecKind::Unspecified);
15659 CopyConstructor->setAccess(AS_public);
15660 CopyConstructor->setDefaulted();
15661
15662 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15663
15664 if (getLangOpts().CUDA)
15665 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15666 CopyConstructor,
15667 /* ConstRHS */ Const,
15668 /* Diagnose */ false);
15669
15670 // During template instantiation of special member functions we need a
15671 // reliable TypeSourceInfo for the parameter types in order to allow functions
15672 // to be substituted.
15673 TypeSourceInfo *TSI = nullptr;
15674 if (inTemplateInstantiation() && ClassDecl->isLambda())
15675 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15676
15677 // Add the parameter to the constructor.
15678 ParmVarDecl *FromParam =
15679 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15680 /*IdentifierInfo=*/nullptr, ArgType,
15681 /*TInfo=*/TSI, SC_None, nullptr);
15682 CopyConstructor->setParams(FromParam);
15683
15684 CopyConstructor->setTrivial(
15685 ClassDecl->needsOverloadResolutionForCopyConstructor()
15686 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15687 : ClassDecl->hasTrivialCopyConstructor());
15688
15689 CopyConstructor->setTrivialForCall(
15690 ClassDecl->hasAttr<TrivialABIAttr>() ||
15691 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15692 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15693 TAH_ConsiderTrivialABI)
15694 : ClassDecl->hasTrivialCopyConstructorForCall()));
15695
15696 // Note that we have declared this constructor.
15697 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15698
15699 Scope *S = getScopeForContext(ClassDecl);
15700 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15701
15702 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15703 ClassDecl->setImplicitCopyConstructorIsDeleted();
15704 SetDeclDeleted(CopyConstructor, ClassLoc);
15705 }
15706
15707 if (S)
15708 PushOnScopeChains(CopyConstructor, S, false);
15709 ClassDecl->addDecl(CopyConstructor);
15710
15711 return CopyConstructor;
15712 }
15713
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)15714 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15715 CXXConstructorDecl *CopyConstructor) {
15716 assert((CopyConstructor->isDefaulted() &&
15717 CopyConstructor->isCopyConstructor() &&
15718 !CopyConstructor->doesThisDeclarationHaveABody() &&
15719 !CopyConstructor->isDeleted()) &&
15720 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15721 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15722 return;
15723
15724 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15725 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15726
15727 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15728
15729 // The exception specification is needed because we are defining the
15730 // function.
15731 ResolveExceptionSpec(CurrentLocation,
15732 CopyConstructor->getType()->castAs<FunctionProtoType>());
15733 MarkVTableUsed(CurrentLocation, ClassDecl);
15734
15735 // Add a context note for diagnostics produced after this point.
15736 Scope.addContextNote(CurrentLocation);
15737
15738 // C++11 [class.copy]p7:
15739 // The [definition of an implicitly declared copy constructor] is
15740 // deprecated if the class has a user-declared copy assignment operator
15741 // or a user-declared destructor.
15742 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15743 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15744
15745 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15746 CopyConstructor->setInvalidDecl();
15747 } else {
15748 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15749 ? CopyConstructor->getEndLoc()
15750 : CopyConstructor->getLocation();
15751 Sema::CompoundScopeRAII CompoundScope(*this);
15752 CopyConstructor->setBody(
15753 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15754 .getAs<Stmt>());
15755 CopyConstructor->markUsed(Context);
15756 }
15757
15758 if (ASTMutationListener *L = getASTMutationListener()) {
15759 L->CompletedImplicitDefinition(CopyConstructor);
15760 }
15761 }
15762
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)15763 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15764 CXXRecordDecl *ClassDecl) {
15765 assert(ClassDecl->needsImplicitMoveConstructor());
15766
15767 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15768 if (DSM.isAlreadyBeingDeclared())
15769 return nullptr;
15770
15771 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15772
15773 QualType ArgType = ClassType;
15774 ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15775 ArgType, nullptr);
15776 LangAS AS = getDefaultCXXMethodAddrSpace();
15777 if (AS != LangAS::Default)
15778 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15779 ArgType = Context.getRValueReferenceType(ArgType);
15780
15781 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15782 CXXMoveConstructor,
15783 false);
15784
15785 DeclarationName Name
15786 = Context.DeclarationNames.getCXXConstructorName(
15787 Context.getCanonicalType(ClassType));
15788 SourceLocation ClassLoc = ClassDecl->getLocation();
15789 DeclarationNameInfo NameInfo(Name, ClassLoc);
15790
15791 // C++11 [class.copy]p11:
15792 // An implicitly-declared copy/move constructor is an inline public
15793 // member of its class.
15794 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15795 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15796 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15797 /*isInline=*/true,
15798 /*isImplicitlyDeclared=*/true,
15799 Constexpr ? ConstexprSpecKind::Constexpr
15800 : ConstexprSpecKind::Unspecified);
15801 MoveConstructor->setAccess(AS_public);
15802 MoveConstructor->setDefaulted();
15803
15804 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15805
15806 if (getLangOpts().CUDA)
15807 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15808 MoveConstructor,
15809 /* ConstRHS */ false,
15810 /* Diagnose */ false);
15811
15812 // Add the parameter to the constructor.
15813 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15814 ClassLoc, ClassLoc,
15815 /*IdentifierInfo=*/nullptr,
15816 ArgType, /*TInfo=*/nullptr,
15817 SC_None, nullptr);
15818 MoveConstructor->setParams(FromParam);
15819
15820 MoveConstructor->setTrivial(
15821 ClassDecl->needsOverloadResolutionForMoveConstructor()
15822 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15823 : ClassDecl->hasTrivialMoveConstructor());
15824
15825 MoveConstructor->setTrivialForCall(
15826 ClassDecl->hasAttr<TrivialABIAttr>() ||
15827 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15828 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15829 TAH_ConsiderTrivialABI)
15830 : ClassDecl->hasTrivialMoveConstructorForCall()));
15831
15832 // Note that we have declared this constructor.
15833 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15834
15835 Scope *S = getScopeForContext(ClassDecl);
15836 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15837
15838 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15839 ClassDecl->setImplicitMoveConstructorIsDeleted();
15840 SetDeclDeleted(MoveConstructor, ClassLoc);
15841 }
15842
15843 if (S)
15844 PushOnScopeChains(MoveConstructor, S, false);
15845 ClassDecl->addDecl(MoveConstructor);
15846
15847 return MoveConstructor;
15848 }
15849
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)15850 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15851 CXXConstructorDecl *MoveConstructor) {
15852 assert((MoveConstructor->isDefaulted() &&
15853 MoveConstructor->isMoveConstructor() &&
15854 !MoveConstructor->doesThisDeclarationHaveABody() &&
15855 !MoveConstructor->isDeleted()) &&
15856 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15857 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15858 return;
15859
15860 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15861 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15862
15863 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15864
15865 // The exception specification is needed because we are defining the
15866 // function.
15867 ResolveExceptionSpec(CurrentLocation,
15868 MoveConstructor->getType()->castAs<FunctionProtoType>());
15869 MarkVTableUsed(CurrentLocation, ClassDecl);
15870
15871 // Add a context note for diagnostics produced after this point.
15872 Scope.addContextNote(CurrentLocation);
15873
15874 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15875 MoveConstructor->setInvalidDecl();
15876 } else {
15877 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15878 ? MoveConstructor->getEndLoc()
15879 : MoveConstructor->getLocation();
15880 Sema::CompoundScopeRAII CompoundScope(*this);
15881 MoveConstructor->setBody(
15882 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15883 .getAs<Stmt>());
15884 MoveConstructor->markUsed(Context);
15885 }
15886
15887 if (ASTMutationListener *L = getASTMutationListener()) {
15888 L->CompletedImplicitDefinition(MoveConstructor);
15889 }
15890 }
15891
isImplicitlyDeleted(FunctionDecl * FD)15892 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15893 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15894 }
15895
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)15896 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15897 SourceLocation CurrentLocation,
15898 CXXConversionDecl *Conv) {
15899 SynthesizedFunctionScope Scope(*this, Conv);
15900 assert(!Conv->getReturnType()->isUndeducedType());
15901
15902 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15903 CallingConv CC =
15904 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15905
15906 CXXRecordDecl *Lambda = Conv->getParent();
15907 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15908 FunctionDecl *Invoker =
15909 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15910 ? CallOp
15911 : Lambda->getLambdaStaticInvoker(CC);
15912
15913 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15914 CallOp = InstantiateFunctionDeclaration(
15915 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15916 if (!CallOp)
15917 return;
15918
15919 if (CallOp != Invoker) {
15920 Invoker = InstantiateFunctionDeclaration(
15921 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15922 CurrentLocation);
15923 if (!Invoker)
15924 return;
15925 }
15926 }
15927
15928 if (CallOp->isInvalidDecl())
15929 return;
15930
15931 // Mark the call operator referenced (and add to pending instantiations
15932 // if necessary).
15933 // For both the conversion and static-invoker template specializations
15934 // we construct their body's in this function, so no need to add them
15935 // to the PendingInstantiations.
15936 MarkFunctionReferenced(CurrentLocation, CallOp);
15937
15938 if (Invoker != CallOp) {
15939 // Fill in the __invoke function with a dummy implementation. IR generation
15940 // will fill in the actual details. Update its type in case it contained
15941 // an 'auto'.
15942 Invoker->markUsed(Context);
15943 Invoker->setReferenced();
15944 Invoker->setType(Conv->getReturnType()->getPointeeType());
15945 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15946 }
15947
15948 // Construct the body of the conversion function { return __invoke; }.
15949 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15950 Conv->getLocation());
15951 assert(FunctionRef && "Can't refer to __invoke function?");
15952 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15953 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15954 Conv->getLocation(), Conv->getLocation()));
15955 Conv->markUsed(Context);
15956 Conv->setReferenced();
15957
15958 if (ASTMutationListener *L = getASTMutationListener()) {
15959 L->CompletedImplicitDefinition(Conv);
15960 if (Invoker != CallOp)
15961 L->CompletedImplicitDefinition(Invoker);
15962 }
15963 }
15964
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)15965 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15966 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15967 assert(!Conv->getParent()->isGenericLambda());
15968
15969 SynthesizedFunctionScope Scope(*this, Conv);
15970
15971 // Copy-initialize the lambda object as needed to capture it.
15972 Expr *This = ActOnCXXThis(CurrentLocation).get();
15973 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15974
15975 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15976 Conv->getLocation(),
15977 Conv, DerefThis);
15978
15979 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15980 // behavior. Note that only the general conversion function does this
15981 // (since it's unusable otherwise); in the case where we inline the
15982 // block literal, it has block literal lifetime semantics.
15983 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15984 BuildBlock = ImplicitCastExpr::Create(
15985 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15986 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15987
15988 if (BuildBlock.isInvalid()) {
15989 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15990 Conv->setInvalidDecl();
15991 return;
15992 }
15993
15994 // Create the return statement that returns the block from the conversion
15995 // function.
15996 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15997 if (Return.isInvalid()) {
15998 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15999 Conv->setInvalidDecl();
16000 return;
16001 }
16002
16003 // Set the body of the conversion function.
16004 Stmt *ReturnS = Return.get();
16005 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
16006 Conv->getLocation(), Conv->getLocation()));
16007 Conv->markUsed(Context);
16008
16009 // We're done; notify the mutation listener, if any.
16010 if (ASTMutationListener *L = getASTMutationListener()) {
16011 L->CompletedImplicitDefinition(Conv);
16012 }
16013 }
16014
16015 /// Determine whether the given list arguments contains exactly one
16016 /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)16017 static bool hasOneRealArgument(MultiExprArg Args) {
16018 switch (Args.size()) {
16019 case 0:
16020 return false;
16021
16022 default:
16023 if (!Args[1]->isDefaultArgument())
16024 return false;
16025
16026 [[fallthrough]];
16027 case 1:
16028 return !Args[0]->isDefaultArgument();
16029 }
16030
16031 return false;
16032 }
16033
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,CXXConstructionKind ConstructKind,SourceRange ParenRange)16034 ExprResult Sema::BuildCXXConstructExpr(
16035 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16036 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16037 bool HadMultipleCandidates, bool IsListInitialization,
16038 bool IsStdInitListInitialization, bool RequiresZeroInit,
16039 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16040 bool Elidable = false;
16041
16042 // C++0x [class.copy]p34:
16043 // When certain criteria are met, an implementation is allowed to
16044 // omit the copy/move construction of a class object, even if the
16045 // copy/move constructor and/or destructor for the object have
16046 // side effects. [...]
16047 // - when a temporary class object that has not been bound to a
16048 // reference (12.2) would be copied/moved to a class object
16049 // with the same cv-unqualified type, the copy/move operation
16050 // can be omitted by constructing the temporary object
16051 // directly into the target of the omitted copy/move
16052 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16053 // FIXME: Converting constructors should also be accepted.
16054 // But to fix this, the logic that digs down into a CXXConstructExpr
16055 // to find the source object needs to handle it.
16056 // Right now it assumes the source object is passed directly as the
16057 // first argument.
16058 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16059 Expr *SubExpr = ExprArgs[0];
16060 // FIXME: Per above, this is also incorrect if we want to accept
16061 // converting constructors, as isTemporaryObject will
16062 // reject temporaries with different type from the
16063 // CXXRecord itself.
16064 Elidable = SubExpr->isTemporaryObject(
16065 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16066 }
16067
16068 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16069 FoundDecl, Constructor,
16070 Elidable, ExprArgs, HadMultipleCandidates,
16071 IsListInitialization,
16072 IsStdInitListInitialization, RequiresZeroInit,
16073 ConstructKind, ParenRange);
16074 }
16075
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)16076 ExprResult Sema::BuildCXXConstructExpr(
16077 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16078 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16079 bool HadMultipleCandidates, bool IsListInitialization,
16080 bool IsStdInitListInitialization, bool RequiresZeroInit,
16081 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16082 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16083 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16084 // The only way to get here is if we did overlaod resolution to find the
16085 // shadow decl, so we don't need to worry about re-checking the trailing
16086 // requires clause.
16087 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16088 return ExprError();
16089 }
16090
16091 return BuildCXXConstructExpr(
16092 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16093 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16094 RequiresZeroInit, ConstructKind, ParenRange);
16095 }
16096
16097 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
16098 /// 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)16099 ExprResult Sema::BuildCXXConstructExpr(
16100 SourceLocation ConstructLoc, QualType DeclInitType,
16101 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16102 bool HadMultipleCandidates, bool IsListInitialization,
16103 bool IsStdInitListInitialization, bool RequiresZeroInit,
16104 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16105 assert(declaresSameEntity(
16106 Constructor->getParent(),
16107 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16108 "given constructor for wrong type");
16109 MarkFunctionReferenced(ConstructLoc, Constructor);
16110 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
16111 return ExprError();
16112
16113 return CheckForImmediateInvocation(
16114 CXXConstructExpr::Create(
16115 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16116 HadMultipleCandidates, IsListInitialization,
16117 IsStdInitListInitialization, RequiresZeroInit,
16118 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16119 Constructor);
16120 }
16121
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)16122 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16123 if (VD->isInvalidDecl()) return;
16124 // If initializing the variable failed, don't also diagnose problems with
16125 // the destructor, they're likely related.
16126 if (VD->getInit() && VD->getInit()->containsErrors())
16127 return;
16128
16129 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16130 if (ClassDecl->isInvalidDecl()) return;
16131 if (ClassDecl->hasIrrelevantDestructor()) return;
16132 if (ClassDecl->isDependentContext()) return;
16133
16134 if (VD->isNoDestroy(getASTContext()))
16135 return;
16136
16137 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16138 // The result of `LookupDestructor` might be nullptr if the destructor is
16139 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16140 // will not be selected by `CXXRecordDecl::getDestructor()`.
16141 if (!Destructor)
16142 return;
16143 // If this is an array, we'll require the destructor during initialization, so
16144 // we can skip over this. We still want to emit exit-time destructor warnings
16145 // though.
16146 if (!VD->getType()->isArrayType()) {
16147 MarkFunctionReferenced(VD->getLocation(), Destructor);
16148 CheckDestructorAccess(VD->getLocation(), Destructor,
16149 PDiag(diag::err_access_dtor_var)
16150 << VD->getDeclName() << VD->getType());
16151 DiagnoseUseOfDecl(Destructor, VD->getLocation());
16152 }
16153
16154 if (Destructor->isTrivial()) return;
16155
16156 // If the destructor is constexpr, check whether the variable has constant
16157 // destruction now.
16158 if (Destructor->isConstexpr()) {
16159 bool HasConstantInit = false;
16160 if (VD->getInit() && !VD->getInit()->isValueDependent())
16161 HasConstantInit = VD->evaluateValue();
16162 SmallVector<PartialDiagnosticAt, 8> Notes;
16163 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16164 HasConstantInit) {
16165 Diag(VD->getLocation(),
16166 diag::err_constexpr_var_requires_const_destruction) << VD;
16167 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16168 Diag(Notes[I].first, Notes[I].second);
16169 }
16170 }
16171
16172 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16173 return;
16174
16175 // Emit warning for non-trivial dtor in global scope (a real global,
16176 // class-static, function-static).
16177 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16178
16179 // TODO: this should be re-enabled for static locals by !CXAAtExit
16180 if (!VD->isStaticLocal())
16181 Diag(VD->getLocation(), diag::warn_global_destructor);
16182 }
16183
16184 /// Given a constructor and the set of arguments provided for the
16185 /// constructor, convert the arguments and add any required default arguments
16186 /// to form a proper call to this constructor.
16187 ///
16188 /// \returns true if an error occurred, false otherwise.
CompleteConstructorCall(CXXConstructorDecl * Constructor,QualType DeclInitType,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit,bool IsListInitialization)16189 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16190 QualType DeclInitType, MultiExprArg ArgsPtr,
16191 SourceLocation Loc,
16192 SmallVectorImpl<Expr *> &ConvertedArgs,
16193 bool AllowExplicit,
16194 bool IsListInitialization) {
16195 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16196 unsigned NumArgs = ArgsPtr.size();
16197 Expr **Args = ArgsPtr.data();
16198
16199 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16200 unsigned NumParams = Proto->getNumParams();
16201
16202 // If too few arguments are available, we'll fill in the rest with defaults.
16203 if (NumArgs < NumParams)
16204 ConvertedArgs.reserve(NumParams);
16205 else
16206 ConvertedArgs.reserve(NumArgs);
16207
16208 VariadicCallType CallType =
16209 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16210 SmallVector<Expr *, 8> AllArgs;
16211 bool Invalid = GatherArgumentsForCall(
16212 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16213 CallType, AllowExplicit, IsListInitialization);
16214 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16215
16216 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16217
16218 CheckConstructorCall(Constructor, DeclInitType,
16219 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16220 Loc);
16221
16222 return Invalid;
16223 }
16224
16225 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)16226 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16227 const FunctionDecl *FnDecl) {
16228 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16229 if (isa<NamespaceDecl>(DC)) {
16230 return SemaRef.Diag(FnDecl->getLocation(),
16231 diag::err_operator_new_delete_declared_in_namespace)
16232 << FnDecl->getDeclName();
16233 }
16234
16235 if (isa<TranslationUnitDecl>(DC) &&
16236 FnDecl->getStorageClass() == SC_Static) {
16237 return SemaRef.Diag(FnDecl->getLocation(),
16238 diag::err_operator_new_delete_declared_static)
16239 << FnDecl->getDeclName();
16240 }
16241
16242 return false;
16243 }
16244
RemoveAddressSpaceFromPtr(Sema & SemaRef,const PointerType * PtrTy)16245 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16246 const PointerType *PtrTy) {
16247 auto &Ctx = SemaRef.Context;
16248 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16249 PtrQuals.removeAddressSpace();
16250 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16251 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16252 }
16253
16254 static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)16255 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
16256 CanQualType ExpectedResultType,
16257 CanQualType ExpectedFirstParamType,
16258 unsigned DependentParamTypeDiag,
16259 unsigned InvalidParamTypeDiag) {
16260 QualType ResultType =
16261 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16262
16263 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16264 // The operator is valid on any address space for OpenCL.
16265 // Drop address space from actual and expected result types.
16266 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16267 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16268
16269 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16270 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16271 }
16272
16273 // Check that the result type is what we expect.
16274 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16275 // Reject even if the type is dependent; an operator delete function is
16276 // required to have a non-dependent result type.
16277 return SemaRef.Diag(
16278 FnDecl->getLocation(),
16279 ResultType->isDependentType()
16280 ? diag::err_operator_new_delete_dependent_result_type
16281 : diag::err_operator_new_delete_invalid_result_type)
16282 << FnDecl->getDeclName() << ExpectedResultType;
16283 }
16284
16285 // A function template must have at least 2 parameters.
16286 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16287 return SemaRef.Diag(FnDecl->getLocation(),
16288 diag::err_operator_new_delete_template_too_few_parameters)
16289 << FnDecl->getDeclName();
16290
16291 // The function decl must have at least 1 parameter.
16292 if (FnDecl->getNumParams() == 0)
16293 return SemaRef.Diag(FnDecl->getLocation(),
16294 diag::err_operator_new_delete_too_few_parameters)
16295 << FnDecl->getDeclName();
16296
16297 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16298 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16299 // The operator is valid on any address space for OpenCL.
16300 // Drop address space from actual and expected first parameter types.
16301 if (const auto *PtrTy =
16302 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16303 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16304
16305 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16306 ExpectedFirstParamType =
16307 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16308 }
16309
16310 // Check that the first parameter type is what we expect.
16311 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16312 ExpectedFirstParamType) {
16313 // The first parameter type is not allowed to be dependent. As a tentative
16314 // DR resolution, we allow a dependent parameter type if it is the right
16315 // type anyway, to allow destroying operator delete in class templates.
16316 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16317 ? DependentParamTypeDiag
16318 : InvalidParamTypeDiag)
16319 << FnDecl->getDeclName() << ExpectedFirstParamType;
16320 }
16321
16322 return false;
16323 }
16324
16325 static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)16326 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
16327 // C++ [basic.stc.dynamic.allocation]p1:
16328 // A program is ill-formed if an allocation function is declared in a
16329 // namespace scope other than global scope or declared static in global
16330 // scope.
16331 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16332 return true;
16333
16334 CanQualType SizeTy =
16335 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16336
16337 // C++ [basic.stc.dynamic.allocation]p1:
16338 // The return type shall be void*. The first parameter shall have type
16339 // std::size_t.
16340 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16341 SizeTy,
16342 diag::err_operator_new_dependent_param_type,
16343 diag::err_operator_new_param_type))
16344 return true;
16345
16346 // C++ [basic.stc.dynamic.allocation]p1:
16347 // The first parameter shall not have an associated default argument.
16348 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16349 return SemaRef.Diag(FnDecl->getLocation(),
16350 diag::err_operator_new_default_arg)
16351 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16352
16353 return false;
16354 }
16355
16356 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)16357 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16358 // C++ [basic.stc.dynamic.deallocation]p1:
16359 // A program is ill-formed if deallocation functions are declared in a
16360 // namespace scope other than global scope or declared static in global
16361 // scope.
16362 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16363 return true;
16364
16365 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16366
16367 // C++ P0722:
16368 // Within a class C, the first parameter of a destroying operator delete
16369 // shall be of type C *. The first parameter of any other deallocation
16370 // function shall be of type void *.
16371 CanQualType ExpectedFirstParamType =
16372 MD && MD->isDestroyingOperatorDelete()
16373 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16374 SemaRef.Context.getRecordType(MD->getParent())))
16375 : SemaRef.Context.VoidPtrTy;
16376
16377 // C++ [basic.stc.dynamic.deallocation]p2:
16378 // Each deallocation function shall return void
16379 if (CheckOperatorNewDeleteTypes(
16380 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16381 diag::err_operator_delete_dependent_param_type,
16382 diag::err_operator_delete_param_type))
16383 return true;
16384
16385 // C++ P0722:
16386 // A destroying operator delete shall be a usual deallocation function.
16387 if (MD && !MD->getParent()->isDependentContext() &&
16388 MD->isDestroyingOperatorDelete() &&
16389 !SemaRef.isUsualDeallocationFunction(MD)) {
16390 SemaRef.Diag(MD->getLocation(),
16391 diag::err_destroying_operator_delete_not_usual);
16392 return true;
16393 }
16394
16395 return false;
16396 }
16397
16398 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
16399 /// of this overloaded operator is well-formed. If so, returns false;
16400 /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)16401 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16402 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16403 "Expected an overloaded operator declaration");
16404
16405 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16406
16407 // C++ [over.oper]p5:
16408 // The allocation and deallocation functions, operator new,
16409 // operator new[], operator delete and operator delete[], are
16410 // described completely in 3.7.3. The attributes and restrictions
16411 // found in the rest of this subclause do not apply to them unless
16412 // explicitly stated in 3.7.3.
16413 if (Op == OO_Delete || Op == OO_Array_Delete)
16414 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16415
16416 if (Op == OO_New || Op == OO_Array_New)
16417 return CheckOperatorNewDeclaration(*this, FnDecl);
16418
16419 // C++ [over.oper]p7:
16420 // An operator function shall either be a member function or
16421 // be a non-member function and have at least one parameter
16422 // whose type is a class, a reference to a class, an enumeration,
16423 // or a reference to an enumeration.
16424 // Note: Before C++23, a member function could not be static. The only member
16425 // function allowed to be static is the call operator function.
16426 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16427 if (MethodDecl->isStatic()) {
16428 if (Op == OO_Call || Op == OO_Subscript)
16429 Diag(FnDecl->getLocation(),
16430 (LangOpts.CPlusPlus23
16431 ? diag::warn_cxx20_compat_operator_overload_static
16432 : diag::ext_operator_overload_static))
16433 << FnDecl;
16434 else
16435 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16436 << FnDecl;
16437 }
16438 } else {
16439 bool ClassOrEnumParam = false;
16440 for (auto *Param : FnDecl->parameters()) {
16441 QualType ParamType = Param->getType().getNonReferenceType();
16442 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16443 ParamType->isEnumeralType()) {
16444 ClassOrEnumParam = true;
16445 break;
16446 }
16447 }
16448
16449 if (!ClassOrEnumParam)
16450 return Diag(FnDecl->getLocation(),
16451 diag::err_operator_overload_needs_class_or_enum)
16452 << FnDecl->getDeclName();
16453 }
16454
16455 // C++ [over.oper]p8:
16456 // An operator function cannot have default arguments (8.3.6),
16457 // except where explicitly stated below.
16458 //
16459 // Only the function-call operator (C++ [over.call]p1) and the subscript
16460 // operator (CWG2507) allow default arguments.
16461 if (Op != OO_Call) {
16462 ParmVarDecl *FirstDefaultedParam = nullptr;
16463 for (auto *Param : FnDecl->parameters()) {
16464 if (Param->hasDefaultArg()) {
16465 FirstDefaultedParam = Param;
16466 break;
16467 }
16468 }
16469 if (FirstDefaultedParam) {
16470 if (Op == OO_Subscript) {
16471 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16472 ? diag::ext_subscript_overload
16473 : diag::error_subscript_overload)
16474 << FnDecl->getDeclName() << 1
16475 << FirstDefaultedParam->getDefaultArgRange();
16476 } else {
16477 return Diag(FirstDefaultedParam->getLocation(),
16478 diag::err_operator_overload_default_arg)
16479 << FnDecl->getDeclName()
16480 << FirstDefaultedParam->getDefaultArgRange();
16481 }
16482 }
16483 }
16484
16485 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16486 { false, false, false }
16487 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16488 , { Unary, Binary, MemberOnly }
16489 #include "clang/Basic/OperatorKinds.def"
16490 };
16491
16492 bool CanBeUnaryOperator = OperatorUses[Op][0];
16493 bool CanBeBinaryOperator = OperatorUses[Op][1];
16494 bool MustBeMemberOperator = OperatorUses[Op][2];
16495
16496 // C++ [over.oper]p8:
16497 // [...] Operator functions cannot have more or fewer parameters
16498 // than the number required for the corresponding operator, as
16499 // described in the rest of this subclause.
16500 unsigned NumParams = FnDecl->getNumParams() +
16501 (isa<CXXMethodDecl>(FnDecl) &&
16502 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16503 ? 1
16504 : 0);
16505 if (Op != OO_Call && Op != OO_Subscript &&
16506 ((NumParams == 1 && !CanBeUnaryOperator) ||
16507 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16508 (NumParams > 2))) {
16509 // We have the wrong number of parameters.
16510 unsigned ErrorKind;
16511 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16512 ErrorKind = 2; // 2 -> unary or binary.
16513 } else if (CanBeUnaryOperator) {
16514 ErrorKind = 0; // 0 -> unary
16515 } else {
16516 assert(CanBeBinaryOperator &&
16517 "All non-call overloaded operators are unary or binary!");
16518 ErrorKind = 1; // 1 -> binary
16519 }
16520 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16521 << FnDecl->getDeclName() << NumParams << ErrorKind;
16522 }
16523
16524 if (Op == OO_Subscript && NumParams != 2) {
16525 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16526 ? diag::ext_subscript_overload
16527 : diag::error_subscript_overload)
16528 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16529 }
16530
16531 // Overloaded operators other than operator() and operator[] cannot be
16532 // variadic.
16533 if (Op != OO_Call &&
16534 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16535 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16536 << FnDecl->getDeclName();
16537 }
16538
16539 // Some operators must be member functions.
16540 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16541 return Diag(FnDecl->getLocation(),
16542 diag::err_operator_overload_must_be_member)
16543 << FnDecl->getDeclName();
16544 }
16545
16546 // C++ [over.inc]p1:
16547 // The user-defined function called operator++ implements the
16548 // prefix and postfix ++ operator. If this function is a member
16549 // function with no parameters, or a non-member function with one
16550 // parameter of class or enumeration type, it defines the prefix
16551 // increment operator ++ for objects of that type. If the function
16552 // is a member function with one parameter (which shall be of type
16553 // int) or a non-member function with two parameters (the second
16554 // of which shall be of type int), it defines the postfix
16555 // increment operator ++ for objects of that type.
16556 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16557 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16558 QualType ParamType = LastParam->getType();
16559
16560 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16561 !ParamType->isDependentType())
16562 return Diag(LastParam->getLocation(),
16563 diag::err_operator_overload_post_incdec_must_be_int)
16564 << LastParam->getType() << (Op == OO_MinusMinus);
16565 }
16566
16567 return false;
16568 }
16569
16570 static bool
checkLiteralOperatorTemplateParameterList(Sema & SemaRef,FunctionTemplateDecl * TpDecl)16571 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16572 FunctionTemplateDecl *TpDecl) {
16573 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16574
16575 // Must have one or two template parameters.
16576 if (TemplateParams->size() == 1) {
16577 NonTypeTemplateParmDecl *PmDecl =
16578 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16579
16580 // The template parameter must be a char parameter pack.
16581 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16582 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16583 return false;
16584
16585 // C++20 [over.literal]p5:
16586 // A string literal operator template is a literal operator template
16587 // whose template-parameter-list comprises a single non-type
16588 // template-parameter of class type.
16589 //
16590 // As a DR resolution, we also allow placeholders for deduced class
16591 // template specializations.
16592 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16593 !PmDecl->isTemplateParameterPack() &&
16594 (PmDecl->getType()->isRecordType() ||
16595 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16596 return false;
16597 } else if (TemplateParams->size() == 2) {
16598 TemplateTypeParmDecl *PmType =
16599 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16600 NonTypeTemplateParmDecl *PmArgs =
16601 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16602
16603 // The second template parameter must be a parameter pack with the
16604 // first template parameter as its type.
16605 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16606 PmArgs->isTemplateParameterPack()) {
16607 const TemplateTypeParmType *TArgs =
16608 PmArgs->getType()->getAs<TemplateTypeParmType>();
16609 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16610 TArgs->getIndex() == PmType->getIndex()) {
16611 if (!SemaRef.inTemplateInstantiation())
16612 SemaRef.Diag(TpDecl->getLocation(),
16613 diag::ext_string_literal_operator_template);
16614 return false;
16615 }
16616 }
16617 }
16618
16619 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16620 diag::err_literal_operator_template)
16621 << TpDecl->getTemplateParameters()->getSourceRange();
16622 return true;
16623 }
16624
16625 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16626 /// of this literal operator function is well-formed. If so, returns
16627 /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)16628 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16629 if (isa<CXXMethodDecl>(FnDecl)) {
16630 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16631 << FnDecl->getDeclName();
16632 return true;
16633 }
16634
16635 if (FnDecl->isExternC()) {
16636 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16637 if (const LinkageSpecDecl *LSD =
16638 FnDecl->getDeclContext()->getExternCContext())
16639 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16640 return true;
16641 }
16642
16643 // This might be the definition of a literal operator template.
16644 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16645
16646 // This might be a specialization of a literal operator template.
16647 if (!TpDecl)
16648 TpDecl = FnDecl->getPrimaryTemplate();
16649
16650 // template <char...> type operator "" name() and
16651 // template <class T, T...> type operator "" name() are the only valid
16652 // template signatures, and the only valid signatures with no parameters.
16653 //
16654 // C++20 also allows template <SomeClass T> type operator "" name().
16655 if (TpDecl) {
16656 if (FnDecl->param_size() != 0) {
16657 Diag(FnDecl->getLocation(),
16658 diag::err_literal_operator_template_with_params);
16659 return true;
16660 }
16661
16662 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16663 return true;
16664
16665 } else if (FnDecl->param_size() == 1) {
16666 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16667
16668 QualType ParamType = Param->getType().getUnqualifiedType();
16669
16670 // Only unsigned long long int, long double, any character type, and const
16671 // char * are allowed as the only parameters.
16672 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16673 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16674 Context.hasSameType(ParamType, Context.CharTy) ||
16675 Context.hasSameType(ParamType, Context.WideCharTy) ||
16676 Context.hasSameType(ParamType, Context.Char8Ty) ||
16677 Context.hasSameType(ParamType, Context.Char16Ty) ||
16678 Context.hasSameType(ParamType, Context.Char32Ty)) {
16679 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16680 QualType InnerType = Ptr->getPointeeType();
16681
16682 // Pointer parameter must be a const char *.
16683 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16684 Context.CharTy) &&
16685 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16686 Diag(Param->getSourceRange().getBegin(),
16687 diag::err_literal_operator_param)
16688 << ParamType << "'const char *'" << Param->getSourceRange();
16689 return true;
16690 }
16691
16692 } else if (ParamType->isRealFloatingType()) {
16693 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16694 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16695 return true;
16696
16697 } else if (ParamType->isIntegerType()) {
16698 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16699 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16700 return true;
16701
16702 } else {
16703 Diag(Param->getSourceRange().getBegin(),
16704 diag::err_literal_operator_invalid_param)
16705 << ParamType << Param->getSourceRange();
16706 return true;
16707 }
16708
16709 } else if (FnDecl->param_size() == 2) {
16710 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16711
16712 // First, verify that the first parameter is correct.
16713
16714 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16715
16716 // Two parameter function must have a pointer to const as a
16717 // first parameter; let's strip those qualifiers.
16718 const PointerType *PT = FirstParamType->getAs<PointerType>();
16719
16720 if (!PT) {
16721 Diag((*Param)->getSourceRange().getBegin(),
16722 diag::err_literal_operator_param)
16723 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16724 return true;
16725 }
16726
16727 QualType PointeeType = PT->getPointeeType();
16728 // First parameter must be const
16729 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16730 Diag((*Param)->getSourceRange().getBegin(),
16731 diag::err_literal_operator_param)
16732 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16733 return true;
16734 }
16735
16736 QualType InnerType = PointeeType.getUnqualifiedType();
16737 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16738 // const char32_t* are allowed as the first parameter to a two-parameter
16739 // function
16740 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16741 Context.hasSameType(InnerType, Context.WideCharTy) ||
16742 Context.hasSameType(InnerType, Context.Char8Ty) ||
16743 Context.hasSameType(InnerType, Context.Char16Ty) ||
16744 Context.hasSameType(InnerType, Context.Char32Ty))) {
16745 Diag((*Param)->getSourceRange().getBegin(),
16746 diag::err_literal_operator_param)
16747 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16748 return true;
16749 }
16750
16751 // Move on to the second and final parameter.
16752 ++Param;
16753
16754 // The second parameter must be a std::size_t.
16755 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16756 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16757 Diag((*Param)->getSourceRange().getBegin(),
16758 diag::err_literal_operator_param)
16759 << SecondParamType << Context.getSizeType()
16760 << (*Param)->getSourceRange();
16761 return true;
16762 }
16763 } else {
16764 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16765 return true;
16766 }
16767
16768 // Parameters are good.
16769
16770 // A parameter-declaration-clause containing a default argument is not
16771 // equivalent to any of the permitted forms.
16772 for (auto *Param : FnDecl->parameters()) {
16773 if (Param->hasDefaultArg()) {
16774 Diag(Param->getDefaultArgRange().getBegin(),
16775 diag::err_literal_operator_default_argument)
16776 << Param->getDefaultArgRange();
16777 break;
16778 }
16779 }
16780
16781 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16782 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
16783 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
16784 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16785 // C++23 [usrlit.suffix]p1:
16786 // Literal suffix identifiers that do not start with an underscore are
16787 // reserved for future standardization. Literal suffix identifiers that
16788 // contain a double underscore __ are reserved for use by C++
16789 // implementations.
16790 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16791 << static_cast<int>(Status)
16792 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
16793 }
16794
16795 return false;
16796 }
16797
16798 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16799 /// linkage specification, including the language and (if present)
16800 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16801 /// language string literal. LBraceLoc, if valid, provides the location of
16802 /// the '{' brace. Otherwise, this linkage specification does not
16803 /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,Expr * LangStr,SourceLocation LBraceLoc)16804 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16805 Expr *LangStr,
16806 SourceLocation LBraceLoc) {
16807 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16808 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16809
16810 StringRef Lang = Lit->getString();
16811 LinkageSpecLanguageIDs Language;
16812 if (Lang == "C")
16813 Language = LinkageSpecLanguageIDs::C;
16814 else if (Lang == "C++")
16815 Language = LinkageSpecLanguageIDs::CXX;
16816 else {
16817 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16818 << LangStr->getSourceRange();
16819 return nullptr;
16820 }
16821
16822 // FIXME: Add all the various semantics of linkage specifications
16823
16824 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16825 LangStr->getExprLoc(), Language,
16826 LBraceLoc.isValid());
16827
16828 /// C++ [module.unit]p7.2.3
16829 /// - Otherwise, if the declaration
16830 /// - ...
16831 /// - ...
16832 /// - appears within a linkage-specification,
16833 /// it is attached to the global module.
16834 ///
16835 /// If the declaration is already in global module fragment, we don't
16836 /// need to attach it again.
16837 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16838 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16839 D->setLocalOwningModule(GlobalModule);
16840 }
16841
16842 CurContext->addDecl(D);
16843 PushDeclContext(S, D);
16844 return D;
16845 }
16846
16847 /// ActOnFinishLinkageSpecification - Complete the definition of
16848 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16849 /// valid, it's the position of the closing '}' brace in a linkage
16850 /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)16851 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16852 Decl *LinkageSpec,
16853 SourceLocation RBraceLoc) {
16854 if (RBraceLoc.isValid()) {
16855 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16856 LSDecl->setRBraceLoc(RBraceLoc);
16857 }
16858
16859 // If the current module doesn't has Parent, it implies that the
16860 // LinkageSpec isn't in the module created by itself. So we don't
16861 // need to pop it.
16862 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16863 getCurrentModule()->isImplicitGlobalModule() &&
16864 getCurrentModule()->Parent)
16865 PopImplicitGlobalModuleFragment();
16866
16867 PopDeclContext();
16868 return LinkageSpec;
16869 }
16870
ActOnEmptyDeclaration(Scope * S,const ParsedAttributesView & AttrList,SourceLocation SemiLoc)16871 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16872 const ParsedAttributesView &AttrList,
16873 SourceLocation SemiLoc) {
16874 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16875 // Attribute declarations appertain to empty declaration so we handle
16876 // them here.
16877 ProcessDeclAttributeList(S, ED, AttrList);
16878
16879 CurContext->addDecl(ED);
16880 return ED;
16881 }
16882
16883 /// Perform semantic analysis for the variable declaration that
16884 /// occurs within a C++ catch clause, returning the newly-created
16885 /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)16886 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16887 TypeSourceInfo *TInfo,
16888 SourceLocation StartLoc,
16889 SourceLocation Loc,
16890 IdentifierInfo *Name) {
16891 bool Invalid = false;
16892 QualType ExDeclType = TInfo->getType();
16893
16894 // Arrays and functions decay.
16895 if (ExDeclType->isArrayType())
16896 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16897 else if (ExDeclType->isFunctionType())
16898 ExDeclType = Context.getPointerType(ExDeclType);
16899
16900 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16901 // The exception-declaration shall not denote a pointer or reference to an
16902 // incomplete type, other than [cv] void*.
16903 // N2844 forbids rvalue references.
16904 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16905 Diag(Loc, diag::err_catch_rvalue_ref);
16906 Invalid = true;
16907 }
16908
16909 if (ExDeclType->isVariablyModifiedType()) {
16910 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16911 Invalid = true;
16912 }
16913
16914 QualType BaseType = ExDeclType;
16915 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16916 unsigned DK = diag::err_catch_incomplete;
16917 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16918 BaseType = Ptr->getPointeeType();
16919 Mode = 1;
16920 DK = diag::err_catch_incomplete_ptr;
16921 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16922 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16923 BaseType = Ref->getPointeeType();
16924 Mode = 2;
16925 DK = diag::err_catch_incomplete_ref;
16926 }
16927 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16928 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16929 Invalid = true;
16930
16931 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16932 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16933 Invalid = true;
16934 }
16935
16936 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16937 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16938 Invalid = true;
16939 }
16940
16941 if (!Invalid && !ExDeclType->isDependentType() &&
16942 RequireNonAbstractType(Loc, ExDeclType,
16943 diag::err_abstract_type_in_decl,
16944 AbstractVariableType))
16945 Invalid = true;
16946
16947 // Only the non-fragile NeXT runtime currently supports C++ catches
16948 // of ObjC types, and no runtime supports catching ObjC types by value.
16949 if (!Invalid && getLangOpts().ObjC) {
16950 QualType T = ExDeclType;
16951 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16952 T = RT->getPointeeType();
16953
16954 if (T->isObjCObjectType()) {
16955 Diag(Loc, diag::err_objc_object_catch);
16956 Invalid = true;
16957 } else if (T->isObjCObjectPointerType()) {
16958 // FIXME: should this be a test for macosx-fragile specifically?
16959 if (getLangOpts().ObjCRuntime.isFragile())
16960 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16961 }
16962 }
16963
16964 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16965 ExDeclType, TInfo, SC_None);
16966 ExDecl->setExceptionVariable(true);
16967
16968 // In ARC, infer 'retaining' for variables of retainable type.
16969 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16970 Invalid = true;
16971
16972 if (!Invalid && !ExDeclType->isDependentType()) {
16973 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16974 // Insulate this from anything else we might currently be parsing.
16975 EnterExpressionEvaluationContext scope(
16976 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16977
16978 // C++ [except.handle]p16:
16979 // The object declared in an exception-declaration or, if the
16980 // exception-declaration does not specify a name, a temporary (12.2) is
16981 // copy-initialized (8.5) from the exception object. [...]
16982 // The object is destroyed when the handler exits, after the destruction
16983 // of any automatic objects initialized within the handler.
16984 //
16985 // We just pretend to initialize the object with itself, then make sure
16986 // it can be destroyed later.
16987 QualType initType = Context.getExceptionObjectType(ExDeclType);
16988
16989 InitializedEntity entity =
16990 InitializedEntity::InitializeVariable(ExDecl);
16991 InitializationKind initKind =
16992 InitializationKind::CreateCopy(Loc, SourceLocation());
16993
16994 Expr *opaqueValue =
16995 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16996 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16997 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16998 if (result.isInvalid())
16999 Invalid = true;
17000 else {
17001 // If the constructor used was non-trivial, set this as the
17002 // "initializer".
17003 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17004 if (!construct->getConstructor()->isTrivial()) {
17005 Expr *init = MaybeCreateExprWithCleanups(construct);
17006 ExDecl->setInit(init);
17007 }
17008
17009 // And make sure it's destructable.
17010 FinalizeVarWithDestructor(ExDecl, recordType);
17011 }
17012 }
17013 }
17014
17015 if (Invalid)
17016 ExDecl->setInvalidDecl();
17017
17018 return ExDecl;
17019 }
17020
17021 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17022 /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)17023 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17024 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17025 bool Invalid = D.isInvalidType();
17026
17027 // Check for unexpanded parameter packs.
17028 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17029 UPPC_ExceptionType)) {
17030 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17031 D.getIdentifierLoc());
17032 Invalid = true;
17033 }
17034
17035 IdentifierInfo *II = D.getIdentifier();
17036 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
17037 LookupOrdinaryName,
17038 ForVisibleRedeclaration)) {
17039 // The scope should be freshly made just for us. There is just no way
17040 // it contains any previous declaration, except for function parameters in
17041 // a function-try-block's catch statement.
17042 assert(!S->isDeclScope(PrevDecl));
17043 if (isDeclInScope(PrevDecl, CurContext, S)) {
17044 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17045 << D.getIdentifier();
17046 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17047 Invalid = true;
17048 } else if (PrevDecl->isTemplateParameter())
17049 // Maybe we will complain about the shadowed template parameter.
17050 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17051 }
17052
17053 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17054 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17055 << D.getCXXScopeSpec().getRange();
17056 Invalid = true;
17057 }
17058
17059 VarDecl *ExDecl = BuildExceptionDeclaration(
17060 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17061 if (Invalid)
17062 ExDecl->setInvalidDecl();
17063
17064 // Add the exception declaration into this scope.
17065 if (II)
17066 PushOnScopeChains(ExDecl, S);
17067 else
17068 CurContext->addDecl(ExDecl);
17069
17070 ProcessDeclAttributes(S, ExDecl, D);
17071 return ExDecl;
17072 }
17073
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)17074 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17075 Expr *AssertExpr,
17076 Expr *AssertMessageExpr,
17077 SourceLocation RParenLoc) {
17078 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
17079 return nullptr;
17080
17081 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17082 AssertMessageExpr, RParenLoc, false);
17083 }
17084
WriteCharTypePrefix(BuiltinType::Kind BTK,llvm::raw_ostream & OS)17085 static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17086 switch (BTK) {
17087 case BuiltinType::Char_S:
17088 case BuiltinType::Char_U:
17089 break;
17090 case BuiltinType::Char8:
17091 OS << "u8";
17092 break;
17093 case BuiltinType::Char16:
17094 OS << 'u';
17095 break;
17096 case BuiltinType::Char32:
17097 OS << 'U';
17098 break;
17099 case BuiltinType::WChar_S:
17100 case BuiltinType::WChar_U:
17101 OS << 'L';
17102 break;
17103 default:
17104 llvm_unreachable("Non-character type");
17105 }
17106 }
17107
17108 /// Convert character's value, interpreted as a code unit, to a string.
17109 /// The value needs to be zero-extended to 32-bits.
17110 /// FIXME: This assumes Unicode literal encodings
WriteCharValueForDiagnostic(uint32_t Value,const BuiltinType * BTy,unsigned TyWidth,SmallVectorImpl<char> & Str)17111 static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17112 unsigned TyWidth,
17113 SmallVectorImpl<char> &Str) {
17114 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17115 char *Ptr = Arr;
17116 BuiltinType::Kind K = BTy->getKind();
17117 llvm::raw_svector_ostream OS(Str);
17118
17119 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17120 // other types.
17121 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17122 K == BuiltinType::Char8 || Value <= 0x7F) {
17123 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17124 if (!Escaped.empty())
17125 EscapeStringForDiagnostic(Escaped, Str);
17126 else
17127 OS << static_cast<char>(Value);
17128 return;
17129 }
17130
17131 switch (K) {
17132 case BuiltinType::Char16:
17133 case BuiltinType::Char32:
17134 case BuiltinType::WChar_S:
17135 case BuiltinType::WChar_U: {
17136 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17137 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17138 else
17139 OS << "\\x"
17140 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17141 break;
17142 }
17143 default:
17144 llvm_unreachable("Non-character type is passed");
17145 }
17146 }
17147
17148 /// Convert \V to a string we can present to the user in a diagnostic
17149 /// \T is the type of the expression that has been evaluated into \V
ConvertAPValueToString(const APValue & V,QualType T,SmallVectorImpl<char> & Str,ASTContext & Context)17150 static bool ConvertAPValueToString(const APValue &V, QualType T,
17151 SmallVectorImpl<char> &Str,
17152 ASTContext &Context) {
17153 if (!V.hasValue())
17154 return false;
17155
17156 switch (V.getKind()) {
17157 case APValue::ValueKind::Int:
17158 if (T->isBooleanType()) {
17159 // Bools are reduced to ints during evaluation, but for
17160 // diagnostic purposes we want to print them as
17161 // true or false.
17162 int64_t BoolValue = V.getInt().getExtValue();
17163 assert((BoolValue == 0 || BoolValue == 1) &&
17164 "Bool type, but value is not 0 or 1");
17165 llvm::raw_svector_ostream OS(Str);
17166 OS << (BoolValue ? "true" : "false");
17167 } else {
17168 llvm::raw_svector_ostream OS(Str);
17169 // Same is true for chars.
17170 // We want to print the character representation for textual types
17171 const auto *BTy = T->getAs<BuiltinType>();
17172 if (BTy) {
17173 switch (BTy->getKind()) {
17174 case BuiltinType::Char_S:
17175 case BuiltinType::Char_U:
17176 case BuiltinType::Char8:
17177 case BuiltinType::Char16:
17178 case BuiltinType::Char32:
17179 case BuiltinType::WChar_S:
17180 case BuiltinType::WChar_U: {
17181 unsigned TyWidth = Context.getIntWidth(T);
17182 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17183 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17184 WriteCharTypePrefix(BTy->getKind(), OS);
17185 OS << '\'';
17186 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17187 OS << "' (0x"
17188 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17189 /*Upper=*/true)
17190 << ", " << V.getInt() << ')';
17191 return true;
17192 }
17193 default:
17194 break;
17195 }
17196 }
17197 V.getInt().toString(Str);
17198 }
17199
17200 break;
17201
17202 case APValue::ValueKind::Float:
17203 V.getFloat().toString(Str);
17204 break;
17205
17206 case APValue::ValueKind::LValue:
17207 if (V.isNullPointer()) {
17208 llvm::raw_svector_ostream OS(Str);
17209 OS << "nullptr";
17210 } else
17211 return false;
17212 break;
17213
17214 case APValue::ValueKind::ComplexFloat: {
17215 llvm::raw_svector_ostream OS(Str);
17216 OS << '(';
17217 V.getComplexFloatReal().toString(Str);
17218 OS << " + ";
17219 V.getComplexFloatImag().toString(Str);
17220 OS << "i)";
17221 } break;
17222
17223 case APValue::ValueKind::ComplexInt: {
17224 llvm::raw_svector_ostream OS(Str);
17225 OS << '(';
17226 V.getComplexIntReal().toString(Str);
17227 OS << " + ";
17228 V.getComplexIntImag().toString(Str);
17229 OS << "i)";
17230 } break;
17231
17232 default:
17233 return false;
17234 }
17235
17236 return true;
17237 }
17238
17239 /// Some Expression types are not useful to print notes about,
17240 /// e.g. literals and values that have already been expanded
17241 /// before such as int-valued template parameters.
UsefulToPrintExpr(const Expr * E)17242 static bool UsefulToPrintExpr(const Expr *E) {
17243 E = E->IgnoreParenImpCasts();
17244 // Literals are pretty easy for humans to understand.
17245 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17246 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
17247 return false;
17248
17249 // These have been substituted from template parameters
17250 // and appear as literals in the static assert error.
17251 if (isa<SubstNonTypeTemplateParmExpr>(E))
17252 return false;
17253
17254 // -5 is also simple to understand.
17255 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17256 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17257
17258 // Only print nested arithmetic operators.
17259 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17260 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17261 BO->isBitwiseOp());
17262
17263 return true;
17264 }
17265
17266 /// Try to print more useful information about a failed static_assert
17267 /// with expression \E
DiagnoseStaticAssertDetails(const Expr * E)17268 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17269 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17270 Op && Op->getOpcode() != BO_LOr) {
17271 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17272 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17273
17274 // Ignore comparisons of boolean expressions with a boolean literal.
17275 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17276 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17277 return;
17278
17279 // Don't print obvious expressions.
17280 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17281 return;
17282
17283 struct {
17284 const clang::Expr *Cond;
17285 Expr::EvalResult Result;
17286 SmallString<12> ValueString;
17287 bool Print;
17288 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17289 {RHS, Expr::EvalResult(), {}, false}};
17290 for (unsigned I = 0; I < 2; I++) {
17291 const Expr *Side = DiagSide[I].Cond;
17292
17293 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17294
17295 DiagSide[I].Print =
17296 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17297 DiagSide[I].ValueString, Context);
17298 }
17299 if (DiagSide[0].Print && DiagSide[1].Print) {
17300 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17301 << DiagSide[0].ValueString << Op->getOpcodeStr()
17302 << DiagSide[1].ValueString << Op->getSourceRange();
17303 }
17304 }
17305 }
17306
EvaluateStaticAssertMessageAsString(Expr * Message,std::string & Result,ASTContext & Ctx,bool ErrorOnInvalidMessage)17307 bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,
17308 std::string &Result,
17309 ASTContext &Ctx,
17310 bool ErrorOnInvalidMessage) {
17311 assert(Message);
17312 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17313 "can't evaluate a dependant static assert message");
17314
17315 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17316 assert(SL->isUnevaluated() && "expected an unevaluated string");
17317 Result.assign(SL->getString().begin(), SL->getString().end());
17318 return true;
17319 }
17320
17321 SourceLocation Loc = Message->getBeginLoc();
17322 QualType T = Message->getType().getNonReferenceType();
17323 auto *RD = T->getAsCXXRecordDecl();
17324 if (!RD) {
17325 Diag(Loc, diag::err_static_assert_invalid_message);
17326 return false;
17327 }
17328
17329 auto FindMember = [&](StringRef Member, bool &Empty,
17330 bool Diag = false) -> std::optional<LookupResult> {
17331 DeclarationName DN = PP.getIdentifierInfo(Member);
17332 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17333 LookupQualifiedName(MemberLookup, RD);
17334 Empty = MemberLookup.empty();
17335 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17336 OverloadCandidateSet::CSK_Normal);
17337 if (MemberLookup.empty())
17338 return std::nullopt;
17339 return std::move(MemberLookup);
17340 };
17341
17342 bool SizeNotFound, DataNotFound;
17343 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17344 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17345 if (SizeNotFound || DataNotFound) {
17346 Diag(Loc, diag::err_static_assert_missing_member_function)
17347 << ((SizeNotFound && DataNotFound) ? 2
17348 : SizeNotFound ? 0
17349 : 1);
17350 return false;
17351 }
17352
17353 if (!SizeMember || !DataMember) {
17354 if (!SizeMember)
17355 FindMember("size", SizeNotFound, /*Diag=*/true);
17356 if (!DataMember)
17357 FindMember("data", DataNotFound, /*Diag=*/true);
17358 return false;
17359 }
17360
17361 auto BuildExpr = [&](LookupResult &LR) {
17362 ExprResult Res = BuildMemberReferenceExpr(
17363 Message, Message->getType(), Message->getBeginLoc(), false,
17364 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17365 if (Res.isInvalid())
17366 return ExprError();
17367 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17368 false, true);
17369 if (Res.isInvalid())
17370 return ExprError();
17371 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17372 return ExprError();
17373 return TemporaryMaterializationConversion(Res.get());
17374 };
17375
17376 ExprResult SizeE = BuildExpr(*SizeMember);
17377 ExprResult DataE = BuildExpr(*DataMember);
17378
17379 QualType SizeT = Context.getSizeType();
17380 QualType ConstCharPtr =
17381 Context.getPointerType(Context.getConstType(Context.CharTy));
17382
17383 ExprResult EvaluatedSize =
17384 SizeE.isInvalid() ? ExprError()
17385 : BuildConvertedConstantExpression(
17386 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17387 if (EvaluatedSize.isInvalid()) {
17388 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17389 return false;
17390 }
17391
17392 ExprResult EvaluatedData =
17393 DataE.isInvalid()
17394 ? ExprError()
17395 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17396 CCEK_StaticAssertMessageData);
17397 if (EvaluatedData.isInvalid()) {
17398 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17399 return false;
17400 }
17401
17402 if (!ErrorOnInvalidMessage &&
17403 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17404 return true;
17405
17406 Expr::EvalResult Status;
17407 SmallVector<PartialDiagnosticAt, 8> Notes;
17408 Status.Diag = &Notes;
17409 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17410 EvaluatedData.get(), Ctx, Status) ||
17411 !Notes.empty()) {
17412 Diag(Message->getBeginLoc(),
17413 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17414 : diag::warn_static_assert_message_constexpr);
17415 for (const auto &Note : Notes)
17416 Diag(Note.first, Note.second);
17417 return !ErrorOnInvalidMessage;
17418 }
17419 return true;
17420 }
17421
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessage,SourceLocation RParenLoc,bool Failed)17422 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17423 Expr *AssertExpr, Expr *AssertMessage,
17424 SourceLocation RParenLoc,
17425 bool Failed) {
17426 assert(AssertExpr != nullptr && "Expected non-null condition");
17427 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17428 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17429 !AssertMessage->isValueDependent())) &&
17430 !Failed) {
17431 // In a static_assert-declaration, the constant-expression shall be a
17432 // constant expression that can be contextually converted to bool.
17433 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17434 if (Converted.isInvalid())
17435 Failed = true;
17436
17437 ExprResult FullAssertExpr =
17438 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17439 /*DiscardedValue*/ false,
17440 /*IsConstexpr*/ true);
17441 if (FullAssertExpr.isInvalid())
17442 Failed = true;
17443 else
17444 AssertExpr = FullAssertExpr.get();
17445
17446 llvm::APSInt Cond;
17447 Expr *BaseExpr = AssertExpr;
17448 AllowFoldKind FoldKind = NoFold;
17449
17450 if (!getLangOpts().CPlusPlus) {
17451 // In C mode, allow folding as an extension for better compatibility with
17452 // C++ in terms of expressions like static_assert("test") or
17453 // static_assert(nullptr).
17454 FoldKind = AllowFold;
17455 }
17456
17457 if (!Failed && VerifyIntegerConstantExpression(
17458 BaseExpr, &Cond,
17459 diag::err_static_assert_expression_is_not_constant,
17460 FoldKind).isInvalid())
17461 Failed = true;
17462
17463 // If the static_assert passes, only verify that
17464 // the message is grammatically valid without evaluating it.
17465 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17466 std::string Str;
17467 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17468 /*ErrorOnInvalidMessage=*/false);
17469 }
17470
17471 // CWG2518
17472 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17473 // template definition, the declaration has no effect.
17474 bool InTemplateDefinition =
17475 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17476
17477 if (!Failed && !Cond && !InTemplateDefinition) {
17478 SmallString<256> MsgBuffer;
17479 llvm::raw_svector_ostream Msg(MsgBuffer);
17480 bool HasMessage = AssertMessage;
17481 if (AssertMessage) {
17482 std::string Str;
17483 HasMessage =
17484 EvaluateStaticAssertMessageAsString(
17485 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17486 !Str.empty();
17487 Msg << Str;
17488 }
17489 Expr *InnerCond = nullptr;
17490 std::string InnerCondDescription;
17491 std::tie(InnerCond, InnerCondDescription) =
17492 findFailedBooleanCondition(Converted.get());
17493 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17494 // Drill down into concept specialization expressions to see why they
17495 // weren't satisfied.
17496 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17497 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17498 ConstraintSatisfaction Satisfaction;
17499 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17500 DiagnoseUnsatisfiedConstraint(Satisfaction);
17501 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17502 && !isa<IntegerLiteral>(InnerCond)) {
17503 Diag(InnerCond->getBeginLoc(),
17504 diag::err_static_assert_requirement_failed)
17505 << InnerCondDescription << !HasMessage << Msg.str()
17506 << InnerCond->getSourceRange();
17507 DiagnoseStaticAssertDetails(InnerCond);
17508 } else {
17509 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17510 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17511 PrintContextStack();
17512 }
17513 Failed = true;
17514 }
17515 } else {
17516 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17517 /*DiscardedValue*/false,
17518 /*IsConstexpr*/true);
17519 if (FullAssertExpr.isInvalid())
17520 Failed = true;
17521 else
17522 AssertExpr = FullAssertExpr.get();
17523 }
17524
17525 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17526 AssertExpr, AssertMessage, RParenLoc,
17527 Failed);
17528
17529 CurContext->addDecl(Decl);
17530 return Decl;
17531 }
17532
17533 /// Perform semantic analysis of the given friend type declaration.
17534 ///
17535 /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation LocStart,SourceLocation FriendLoc,TypeSourceInfo * TSInfo)17536 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
17537 SourceLocation FriendLoc,
17538 TypeSourceInfo *TSInfo) {
17539 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
17540
17541 QualType T = TSInfo->getType();
17542 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
17543
17544 // C++03 [class.friend]p2:
17545 // An elaborated-type-specifier shall be used in a friend declaration
17546 // for a class.*
17547 //
17548 // * The class-key of the elaborated-type-specifier is required.
17549 if (!CodeSynthesisContexts.empty()) {
17550 // Do not complain about the form of friend template types during any kind
17551 // of code synthesis. For template instantiation, we will have complained
17552 // when the template was defined.
17553 } else {
17554 if (!T->isElaboratedTypeSpecifier()) {
17555 // If we evaluated the type to a record type, suggest putting
17556 // a tag in front.
17557 if (const RecordType *RT = T->getAs<RecordType>()) {
17558 RecordDecl *RD = RT->getDecl();
17559
17560 SmallString<16> InsertionText(" ");
17561 InsertionText += RD->getKindName();
17562
17563 Diag(TypeRange.getBegin(),
17564 getLangOpts().CPlusPlus11 ?
17565 diag::warn_cxx98_compat_unelaborated_friend_type :
17566 diag::ext_unelaborated_friend_type)
17567 << (unsigned) RD->getTagKind()
17568 << T
17569 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
17570 InsertionText);
17571 } else {
17572 Diag(FriendLoc,
17573 getLangOpts().CPlusPlus11 ?
17574 diag::warn_cxx98_compat_nonclass_type_friend :
17575 diag::ext_nonclass_type_friend)
17576 << T
17577 << TypeRange;
17578 }
17579 } else if (T->getAs<EnumType>()) {
17580 Diag(FriendLoc,
17581 getLangOpts().CPlusPlus11 ?
17582 diag::warn_cxx98_compat_enum_friend :
17583 diag::ext_enum_friend)
17584 << T
17585 << TypeRange;
17586 }
17587
17588 // C++11 [class.friend]p3:
17589 // A friend declaration that does not declare a function shall have one
17590 // of the following forms:
17591 // friend elaborated-type-specifier ;
17592 // friend simple-type-specifier ;
17593 // friend typename-specifier ;
17594 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
17595 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
17596 }
17597
17598 // If the type specifier in a friend declaration designates a (possibly
17599 // cv-qualified) class type, that class is declared as a friend; otherwise,
17600 // the friend declaration is ignored.
17601 return FriendDecl::Create(Context, CurContext,
17602 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
17603 FriendLoc);
17604 }
17605
17606 /// Handle a friend tag declaration where the scope specifier was
17607 /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr,MultiTemplateParamsArg TempParamLists)17608 DeclResult Sema::ActOnTemplatedFriendTag(
17609 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17610 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17611 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17612 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17613
17614 bool IsMemberSpecialization = false;
17615 bool Invalid = false;
17616
17617 if (TemplateParameterList *TemplateParams =
17618 MatchTemplateParametersToScopeSpecifier(
17619 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17620 IsMemberSpecialization, Invalid)) {
17621 if (TemplateParams->size() > 0) {
17622 // This is a declaration of a class template.
17623 if (Invalid)
17624 return true;
17625
17626 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17627 NameLoc, Attr, TemplateParams, AS_public,
17628 /*ModulePrivateLoc=*/SourceLocation(),
17629 FriendLoc, TempParamLists.size() - 1,
17630 TempParamLists.data()).get();
17631 } else {
17632 // The "template<>" header is extraneous.
17633 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17634 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17635 IsMemberSpecialization = true;
17636 }
17637 }
17638
17639 if (Invalid) return true;
17640
17641 bool isAllExplicitSpecializations = true;
17642 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17643 if (TempParamLists[I]->size()) {
17644 isAllExplicitSpecializations = false;
17645 break;
17646 }
17647 }
17648
17649 // FIXME: don't ignore attributes.
17650
17651 // If it's explicit specializations all the way down, just forget
17652 // about the template header and build an appropriate non-templated
17653 // friend. TODO: for source fidelity, remember the headers.
17654 if (isAllExplicitSpecializations) {
17655 if (SS.isEmpty()) {
17656 bool Owned = false;
17657 bool IsDependent = false;
17658 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17659 AS_public,
17660 /*ModulePrivateLoc=*/SourceLocation(),
17661 MultiTemplateParamsArg(), Owned, IsDependent,
17662 /*ScopedEnumKWLoc=*/SourceLocation(),
17663 /*ScopedEnumUsesClassTag=*/false,
17664 /*UnderlyingType=*/TypeResult(),
17665 /*IsTypeSpecifier=*/false,
17666 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17667 }
17668
17669 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17670 ElaboratedTypeKeyword Keyword
17671 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17672 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17673 *Name, NameLoc);
17674 if (T.isNull())
17675 return true;
17676
17677 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17678 if (isa<DependentNameType>(T)) {
17679 DependentNameTypeLoc TL =
17680 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17681 TL.setElaboratedKeywordLoc(TagLoc);
17682 TL.setQualifierLoc(QualifierLoc);
17683 TL.setNameLoc(NameLoc);
17684 } else {
17685 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17686 TL.setElaboratedKeywordLoc(TagLoc);
17687 TL.setQualifierLoc(QualifierLoc);
17688 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17689 }
17690
17691 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17692 TSI, FriendLoc, TempParamLists);
17693 Friend->setAccess(AS_public);
17694 CurContext->addDecl(Friend);
17695 return Friend;
17696 }
17697
17698 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17699
17700
17701
17702 // Handle the case of a templated-scope friend class. e.g.
17703 // template <class T> class A<T>::B;
17704 // FIXME: we don't support these right now.
17705 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17706 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17707 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17708 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17709 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17710 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17711 TL.setElaboratedKeywordLoc(TagLoc);
17712 TL.setQualifierLoc(SS.getWithLocInContext(Context));
17713 TL.setNameLoc(NameLoc);
17714
17715 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17716 TSI, FriendLoc, TempParamLists);
17717 Friend->setAccess(AS_public);
17718 Friend->setUnsupportedFriend(true);
17719 CurContext->addDecl(Friend);
17720 return Friend;
17721 }
17722
17723 /// Handle a friend type declaration. This works in tandem with
17724 /// ActOnTag.
17725 ///
17726 /// Notes on friend class templates:
17727 ///
17728 /// We generally treat friend class declarations as if they were
17729 /// declaring a class. So, for example, the elaborated type specifier
17730 /// in a friend declaration is required to obey the restrictions of a
17731 /// class-head (i.e. no typedefs in the scope chain), template
17732 /// parameters are required to match up with simple template-ids, &c.
17733 /// However, unlike when declaring a template specialization, it's
17734 /// okay to refer to a template specialization without an empty
17735 /// template parameter declaration, e.g.
17736 /// friend class A<T>::B<unsigned>;
17737 /// We permit this as a special case; if there are any template
17738 /// parameters present at all, require proper matching, i.e.
17739 /// template <> template \<class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)17740 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17741 MultiTemplateParamsArg TempParams) {
17742 SourceLocation Loc = DS.getBeginLoc();
17743
17744 assert(DS.isFriendSpecified());
17745 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17746
17747 // C++ [class.friend]p3:
17748 // A friend declaration that does not declare a function shall have one of
17749 // the following forms:
17750 // friend elaborated-type-specifier ;
17751 // friend simple-type-specifier ;
17752 // friend typename-specifier ;
17753 //
17754 // Any declaration with a type qualifier does not have that form. (It's
17755 // legal to specify a qualified type as a friend, you just can't write the
17756 // keywords.)
17757 if (DS.getTypeQualifiers()) {
17758 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17759 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17760 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17761 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17762 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17763 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17764 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17765 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17766 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17767 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17768 }
17769
17770 // Try to convert the decl specifier to a type. This works for
17771 // friend templates because ActOnTag never produces a ClassTemplateDecl
17772 // for a TUK_Friend.
17773 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17774 DeclaratorContext::Member);
17775 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17776 QualType T = TSI->getType();
17777 if (TheDeclarator.isInvalidType())
17778 return nullptr;
17779
17780 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17781 return nullptr;
17782
17783 // This is definitely an error in C++98. It's probably meant to
17784 // be forbidden in C++0x, too, but the specification is just
17785 // poorly written.
17786 //
17787 // The problem is with declarations like the following:
17788 // template <T> friend A<T>::foo;
17789 // where deciding whether a class C is a friend or not now hinges
17790 // on whether there exists an instantiation of A that causes
17791 // 'foo' to equal C. There are restrictions on class-heads
17792 // (which we declare (by fiat) elaborated friend declarations to
17793 // be) that makes this tractable.
17794 //
17795 // FIXME: handle "template <> friend class A<T>;", which
17796 // is possibly well-formed? Who even knows?
17797 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17798 Diag(Loc, diag::err_tagless_friend_type_template)
17799 << DS.getSourceRange();
17800 return nullptr;
17801 }
17802
17803 // C++98 [class.friend]p1: A friend of a class is a function
17804 // or class that is not a member of the class . . .
17805 // This is fixed in DR77, which just barely didn't make the C++03
17806 // deadline. It's also a very silly restriction that seriously
17807 // affects inner classes and which nobody else seems to implement;
17808 // thus we never diagnose it, not even in -pedantic.
17809 //
17810 // But note that we could warn about it: it's always useless to
17811 // friend one of your own members (it's not, however, worthless to
17812 // friend a member of an arbitrary specialization of your template).
17813
17814 Decl *D;
17815 if (!TempParams.empty())
17816 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17817 TempParams,
17818 TSI,
17819 DS.getFriendSpecLoc());
17820 else
17821 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17822
17823 if (!D)
17824 return nullptr;
17825
17826 D->setAccess(AS_public);
17827 CurContext->addDecl(D);
17828
17829 return D;
17830 }
17831
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)17832 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17833 MultiTemplateParamsArg TemplateParams) {
17834 const DeclSpec &DS = D.getDeclSpec();
17835
17836 assert(DS.isFriendSpecified());
17837 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17838
17839 SourceLocation Loc = D.getIdentifierLoc();
17840 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17841
17842 // C++ [class.friend]p1
17843 // A friend of a class is a function or class....
17844 // Note that this sees through typedefs, which is intended.
17845 // It *doesn't* see through dependent types, which is correct
17846 // according to [temp.arg.type]p3:
17847 // If a declaration acquires a function type through a
17848 // type dependent on a template-parameter and this causes
17849 // a declaration that does not use the syntactic form of a
17850 // function declarator to have a function type, the program
17851 // is ill-formed.
17852 if (!TInfo->getType()->isFunctionType()) {
17853 Diag(Loc, diag::err_unexpected_friend);
17854
17855 // It might be worthwhile to try to recover by creating an
17856 // appropriate declaration.
17857 return nullptr;
17858 }
17859
17860 // C++ [namespace.memdef]p3
17861 // - If a friend declaration in a non-local class first declares a
17862 // class or function, the friend class or function is a member
17863 // of the innermost enclosing namespace.
17864 // - The name of the friend is not found by simple name lookup
17865 // until a matching declaration is provided in that namespace
17866 // scope (either before or after the class declaration granting
17867 // friendship).
17868 // - If a friend function is called, its name may be found by the
17869 // name lookup that considers functions from namespaces and
17870 // classes associated with the types of the function arguments.
17871 // - When looking for a prior declaration of a class or a function
17872 // declared as a friend, scopes outside the innermost enclosing
17873 // namespace scope are not considered.
17874
17875 CXXScopeSpec &SS = D.getCXXScopeSpec();
17876 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17877 assert(NameInfo.getName());
17878
17879 // Check for unexpanded parameter packs.
17880 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17881 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17882 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17883 return nullptr;
17884
17885 // The context we found the declaration in, or in which we should
17886 // create the declaration.
17887 DeclContext *DC;
17888 Scope *DCScope = S;
17889 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17890 ForExternalRedeclaration);
17891
17892 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17893
17894 // There are five cases here.
17895 // - There's no scope specifier and we're in a local class. Only look
17896 // for functions declared in the immediately-enclosing block scope.
17897 // We recover from invalid scope qualifiers as if they just weren't there.
17898 FunctionDecl *FunctionContainingLocalClass = nullptr;
17899 if ((SS.isInvalid() || !SS.isSet()) &&
17900 (FunctionContainingLocalClass =
17901 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17902 // C++11 [class.friend]p11:
17903 // If a friend declaration appears in a local class and the name
17904 // specified is an unqualified name, a prior declaration is
17905 // looked up without considering scopes that are outside the
17906 // innermost enclosing non-class scope. For a friend function
17907 // declaration, if there is no prior declaration, the program is
17908 // ill-formed.
17909
17910 // Find the innermost enclosing non-class scope. This is the block
17911 // scope containing the local class definition (or for a nested class,
17912 // the outer local class).
17913 DCScope = S->getFnParent();
17914
17915 // Look up the function name in the scope.
17916 Previous.clear(LookupLocalFriendName);
17917 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17918
17919 if (!Previous.empty()) {
17920 // All possible previous declarations must have the same context:
17921 // either they were declared at block scope or they are members of
17922 // one of the enclosing local classes.
17923 DC = Previous.getRepresentativeDecl()->getDeclContext();
17924 } else {
17925 // This is ill-formed, but provide the context that we would have
17926 // declared the function in, if we were permitted to, for error recovery.
17927 DC = FunctionContainingLocalClass;
17928 }
17929 adjustContextForLocalExternDecl(DC);
17930
17931 // - There's no scope specifier, in which case we just go to the
17932 // appropriate scope and look for a function or function template
17933 // there as appropriate.
17934 } else if (SS.isInvalid() || !SS.isSet()) {
17935 // C++11 [namespace.memdef]p3:
17936 // If the name in a friend declaration is neither qualified nor
17937 // a template-id and the declaration is a function or an
17938 // elaborated-type-specifier, the lookup to determine whether
17939 // the entity has been previously declared shall not consider
17940 // any scopes outside the innermost enclosing namespace.
17941
17942 // Find the appropriate context according to the above.
17943 DC = CurContext;
17944
17945 // Skip class contexts. If someone can cite chapter and verse
17946 // for this behavior, that would be nice --- it's what GCC and
17947 // EDG do, and it seems like a reasonable intent, but the spec
17948 // really only says that checks for unqualified existing
17949 // declarations should stop at the nearest enclosing namespace,
17950 // not that they should only consider the nearest enclosing
17951 // namespace.
17952 while (DC->isRecord())
17953 DC = DC->getParent();
17954
17955 DeclContext *LookupDC = DC->getNonTransparentContext();
17956 while (true) {
17957 LookupQualifiedName(Previous, LookupDC);
17958
17959 if (!Previous.empty()) {
17960 DC = LookupDC;
17961 break;
17962 }
17963
17964 if (isTemplateId) {
17965 if (isa<TranslationUnitDecl>(LookupDC)) break;
17966 } else {
17967 if (LookupDC->isFileContext()) break;
17968 }
17969 LookupDC = LookupDC->getParent();
17970 }
17971
17972 DCScope = getScopeForDeclContext(S, DC);
17973
17974 // - There's a non-dependent scope specifier, in which case we
17975 // compute it and do a previous lookup there for a function
17976 // or function template.
17977 } else if (!SS.getScopeRep()->isDependent()) {
17978 DC = computeDeclContext(SS);
17979 if (!DC) return nullptr;
17980
17981 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17982
17983 LookupQualifiedName(Previous, DC);
17984
17985 // C++ [class.friend]p1: A friend of a class is a function or
17986 // class that is not a member of the class . . .
17987 if (DC->Equals(CurContext))
17988 Diag(DS.getFriendSpecLoc(),
17989 getLangOpts().CPlusPlus11 ?
17990 diag::warn_cxx98_compat_friend_is_member :
17991 diag::err_friend_is_member);
17992
17993 // - There's a scope specifier that does not match any template
17994 // parameter lists, in which case we use some arbitrary context,
17995 // create a method or method template, and wait for instantiation.
17996 // - There's a scope specifier that does match some template
17997 // parameter lists, which we don't handle right now.
17998 } else {
17999 DC = CurContext;
18000 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18001 }
18002
18003 if (!DC->isRecord()) {
18004 int DiagArg = -1;
18005 switch (D.getName().getKind()) {
18006 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18007 case UnqualifiedIdKind::IK_ConstructorName:
18008 DiagArg = 0;
18009 break;
18010 case UnqualifiedIdKind::IK_DestructorName:
18011 DiagArg = 1;
18012 break;
18013 case UnqualifiedIdKind::IK_ConversionFunctionId:
18014 DiagArg = 2;
18015 break;
18016 case UnqualifiedIdKind::IK_DeductionGuideName:
18017 DiagArg = 3;
18018 break;
18019 case UnqualifiedIdKind::IK_Identifier:
18020 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18021 case UnqualifiedIdKind::IK_LiteralOperatorId:
18022 case UnqualifiedIdKind::IK_OperatorFunctionId:
18023 case UnqualifiedIdKind::IK_TemplateId:
18024 break;
18025 }
18026 // This implies that it has to be an operator or function.
18027 if (DiagArg >= 0) {
18028 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18029 return nullptr;
18030 }
18031 }
18032
18033 // FIXME: This is an egregious hack to cope with cases where the scope stack
18034 // does not contain the declaration context, i.e., in an out-of-line
18035 // definition of a class.
18036 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18037 if (!DCScope) {
18038 FakeDCScope.setEntity(DC);
18039 DCScope = &FakeDCScope;
18040 }
18041
18042 bool AddToScope = true;
18043 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18044 TemplateParams, AddToScope);
18045 if (!ND) return nullptr;
18046
18047 assert(ND->getLexicalDeclContext() == CurContext);
18048
18049 // If we performed typo correction, we might have added a scope specifier
18050 // and changed the decl context.
18051 DC = ND->getDeclContext();
18052
18053 // Add the function declaration to the appropriate lookup tables,
18054 // adjusting the redeclarations list as necessary. We don't
18055 // want to do this yet if the friending class is dependent.
18056 //
18057 // Also update the scope-based lookup if the target context's
18058 // lookup context is in lexical scope.
18059 if (!CurContext->isDependentContext()) {
18060 DC = DC->getRedeclContext();
18061 DC->makeDeclVisibleInContext(ND);
18062 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18063 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18064 }
18065
18066 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
18067 D.getIdentifierLoc(), ND,
18068 DS.getFriendSpecLoc());
18069 FrD->setAccess(AS_public);
18070 CurContext->addDecl(FrD);
18071
18072 if (ND->isInvalidDecl()) {
18073 FrD->setInvalidDecl();
18074 } else {
18075 if (DC->isRecord()) CheckFriendAccess(ND);
18076
18077 FunctionDecl *FD;
18078 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18079 FD = FTD->getTemplatedDecl();
18080 else
18081 FD = cast<FunctionDecl>(ND);
18082
18083 // C++ [class.friend]p6:
18084 // A function may be defined in a friend declaration of a class if and
18085 // only if the class is a non-local class, and the function name is
18086 // unqualified.
18087 if (D.isFunctionDefinition()) {
18088 // Qualified friend function definition.
18089 if (SS.isNotEmpty()) {
18090 // FIXME: We should only do this if the scope specifier names the
18091 // innermost enclosing namespace; otherwise the fixit changes the
18092 // meaning of the code.
18093 SemaDiagnosticBuilder DB =
18094 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18095
18096 DB << SS.getScopeRep();
18097 if (DC->isFileContext())
18098 DB << FixItHint::CreateRemoval(SS.getRange());
18099
18100 // Friend function defined in a local class.
18101 } else if (FunctionContainingLocalClass) {
18102 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18103
18104 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18105 // a template-id, the function name is not unqualified because these is
18106 // no name. While the wording requires some reading in-between the
18107 // lines, GCC, MSVC, and EDG all consider a friend function
18108 // specialization definitions // to be de facto explicit specialization
18109 // and diagnose them as such.
18110 } else if (isTemplateId) {
18111 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18112 }
18113 }
18114
18115 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18116 // default argument expression, that declaration shall be a definition
18117 // and shall be the only declaration of the function or function
18118 // template in the translation unit.
18119 if (functionDeclHasDefaultArgument(FD)) {
18120 // We can't look at FD->getPreviousDecl() because it may not have been set
18121 // if we're in a dependent context. If the function is known to be a
18122 // redeclaration, we will have narrowed Previous down to the right decl.
18123 if (D.isRedeclaration()) {
18124 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18125 Diag(Previous.getRepresentativeDecl()->getLocation(),
18126 diag::note_previous_declaration);
18127 } else if (!D.isFunctionDefinition())
18128 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18129 }
18130
18131 // Mark templated-scope function declarations as unsupported.
18132 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18133 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18134 << SS.getScopeRep() << SS.getRange()
18135 << cast<CXXRecordDecl>(CurContext);
18136 FrD->setUnsupportedFriend(true);
18137 }
18138 }
18139
18140 warnOnReservedIdentifier(ND);
18141
18142 return ND;
18143 }
18144
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)18145 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
18146 AdjustDeclIfTemplate(Dcl);
18147
18148 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18149 if (!Fn) {
18150 Diag(DelLoc, diag::err_deleted_non_function);
18151 return;
18152 }
18153
18154 // Deleted function does not have a body.
18155 Fn->setWillHaveBody(false);
18156
18157 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18158 // Don't consider the implicit declaration we generate for explicit
18159 // specializations. FIXME: Do not generate these implicit declarations.
18160 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18161 Prev->getPreviousDecl()) &&
18162 !Prev->isDefined()) {
18163 Diag(DelLoc, diag::err_deleted_decl_not_first);
18164 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18165 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18166 : diag::note_previous_declaration);
18167 // We can't recover from this; the declaration might have already
18168 // been used.
18169 Fn->setInvalidDecl();
18170 return;
18171 }
18172
18173 // To maintain the invariant that functions are only deleted on their first
18174 // declaration, mark the implicitly-instantiated declaration of the
18175 // explicitly-specialized function as deleted instead of marking the
18176 // instantiated redeclaration.
18177 Fn = Fn->getCanonicalDecl();
18178 }
18179
18180 // dllimport/dllexport cannot be deleted.
18181 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18182 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18183 Fn->setInvalidDecl();
18184 }
18185
18186 // C++11 [basic.start.main]p3:
18187 // A program that defines main as deleted [...] is ill-formed.
18188 if (Fn->isMain())
18189 Diag(DelLoc, diag::err_deleted_main);
18190
18191 // C++11 [dcl.fct.def.delete]p4:
18192 // A deleted function is implicitly inline.
18193 Fn->setImplicitlyInline();
18194 Fn->setDeletedAsWritten();
18195 }
18196
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)18197 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18198 if (!Dcl || Dcl->isInvalidDecl())
18199 return;
18200
18201 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18202 if (!FD) {
18203 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18204 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18205 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18206 return;
18207 }
18208 }
18209
18210 Diag(DefaultLoc, diag::err_default_special_members)
18211 << getLangOpts().CPlusPlus20;
18212 return;
18213 }
18214
18215 // Reject if this can't possibly be a defaultable function.
18216 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18217 if (!DefKind &&
18218 // A dependent function that doesn't locally look defaultable can
18219 // still instantiate to a defaultable function if it's a constructor
18220 // or assignment operator.
18221 (!FD->isDependentContext() ||
18222 (!isa<CXXConstructorDecl>(FD) &&
18223 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18224 Diag(DefaultLoc, diag::err_default_special_members)
18225 << getLangOpts().CPlusPlus20;
18226 return;
18227 }
18228
18229 // Issue compatibility warning. We already warned if the operator is
18230 // 'operator<=>' when parsing the '<=>' token.
18231 if (DefKind.isComparison() &&
18232 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18233 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18234 ? diag::warn_cxx17_compat_defaulted_comparison
18235 : diag::ext_defaulted_comparison);
18236 }
18237
18238 FD->setDefaulted();
18239 FD->setExplicitlyDefaulted();
18240 FD->setDefaultLoc(DefaultLoc);
18241
18242 // Defer checking functions that are defaulted in a dependent context.
18243 if (FD->isDependentContext())
18244 return;
18245
18246 // Unset that we will have a body for this function. We might not,
18247 // if it turns out to be trivial, and we don't need this marking now
18248 // that we've marked it as defaulted.
18249 FD->setWillHaveBody(false);
18250
18251 if (DefKind.isComparison()) {
18252 // If this comparison's defaulting occurs within the definition of its
18253 // lexical class context, we have to do the checking when complete.
18254 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18255 if (!RD->isCompleteDefinition())
18256 return;
18257 }
18258
18259 // If this member fn was defaulted on its first declaration, we will have
18260 // already performed the checking in CheckCompletedCXXClass. Such a
18261 // declaration doesn't trigger an implicit definition.
18262 if (isa<CXXMethodDecl>(FD)) {
18263 const FunctionDecl *Primary = FD;
18264 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18265 // Ask the template instantiation pattern that actually had the
18266 // '= default' on it.
18267 Primary = Pattern;
18268 if (Primary->getCanonicalDecl()->isDefaulted())
18269 return;
18270 }
18271
18272 if (DefKind.isComparison()) {
18273 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18274 FD->setInvalidDecl();
18275 else
18276 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18277 } else {
18278 auto *MD = cast<CXXMethodDecl>(FD);
18279
18280 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
18281 DefaultLoc))
18282 MD->setInvalidDecl();
18283 else
18284 DefineDefaultedFunction(*this, MD, DefaultLoc);
18285 }
18286 }
18287
SearchForReturnInStmt(Sema & Self,Stmt * S)18288 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18289 for (Stmt *SubStmt : S->children()) {
18290 if (!SubStmt)
18291 continue;
18292 if (isa<ReturnStmt>(SubStmt))
18293 Self.Diag(SubStmt->getBeginLoc(),
18294 diag::err_return_in_constructor_handler);
18295 if (!isa<Expr>(SubStmt))
18296 SearchForReturnInStmt(Self, SubStmt);
18297 }
18298 }
18299
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)18300 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18301 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18302 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18303 SearchForReturnInStmt(*this, Handler);
18304 }
18305 }
18306
SetFunctionBodyKind(Decl * D,SourceLocation Loc,FnBodyKind BodyKind)18307 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
18308 FnBodyKind BodyKind) {
18309 switch (BodyKind) {
18310 case FnBodyKind::Delete:
18311 SetDeclDeleted(D, Loc);
18312 break;
18313 case FnBodyKind::Default:
18314 SetDeclDefaulted(D, Loc);
18315 break;
18316 case FnBodyKind::Other:
18317 llvm_unreachable(
18318 "Parsed function body should be '= delete;' or '= default;'");
18319 }
18320 }
18321
CheckOverridingFunctionAttributes(const CXXMethodDecl * New,const CXXMethodDecl * Old)18322 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
18323 const CXXMethodDecl *Old) {
18324 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18325 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18326
18327 if (OldFT->hasExtParameterInfos()) {
18328 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18329 // A parameter of the overriding method should be annotated with noescape
18330 // if the corresponding parameter of the overridden method is annotated.
18331 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18332 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18333 Diag(New->getParamDecl(I)->getLocation(),
18334 diag::warn_overriding_method_missing_noescape);
18335 Diag(Old->getParamDecl(I)->getLocation(),
18336 diag::note_overridden_marked_noescape);
18337 }
18338 }
18339
18340 // SME attributes must match when overriding a function declaration.
18341 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18342 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18343 << New << New->getType() << Old->getType();
18344 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18345 return true;
18346 }
18347
18348 // Virtual overrides must have the same code_seg.
18349 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18350 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18351 if ((NewCSA || OldCSA) &&
18352 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18353 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18354 Diag(Old->getLocation(), diag::note_previous_declaration);
18355 return true;
18356 }
18357
18358 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18359
18360 // If the calling conventions match, everything is fine
18361 if (NewCC == OldCC)
18362 return false;
18363
18364 // If the calling conventions mismatch because the new function is static,
18365 // suppress the calling convention mismatch error; the error about static
18366 // function override (err_static_overrides_virtual from
18367 // Sema::CheckFunctionDeclaration) is more clear.
18368 if (New->getStorageClass() == SC_Static)
18369 return false;
18370
18371 Diag(New->getLocation(),
18372 diag::err_conflicting_overriding_cc_attributes)
18373 << New->getDeclName() << New->getType() << Old->getType();
18374 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18375 return true;
18376 }
18377
CheckExplicitObjectOverride(CXXMethodDecl * New,const CXXMethodDecl * Old)18378 bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18379 const CXXMethodDecl *Old) {
18380 // CWG2553
18381 // A virtual function shall not be an explicit object member function.
18382 if (!New->isExplicitObjectMemberFunction())
18383 return true;
18384 Diag(New->getParamDecl(0)->getBeginLoc(),
18385 diag::err_explicit_object_parameter_nonmember)
18386 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18387 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18388 New->setInvalidDecl();
18389 return false;
18390 }
18391
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)18392 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18393 const CXXMethodDecl *Old) {
18394 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18395 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18396
18397 if (Context.hasSameType(NewTy, OldTy) ||
18398 NewTy->isDependentType() || OldTy->isDependentType())
18399 return false;
18400
18401 // Check if the return types are covariant
18402 QualType NewClassTy, OldClassTy;
18403
18404 /// Both types must be pointers or references to classes.
18405 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18406 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18407 NewClassTy = NewPT->getPointeeType();
18408 OldClassTy = OldPT->getPointeeType();
18409 }
18410 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18411 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18412 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18413 NewClassTy = NewRT->getPointeeType();
18414 OldClassTy = OldRT->getPointeeType();
18415 }
18416 }
18417 }
18418
18419 // The return types aren't either both pointers or references to a class type.
18420 if (NewClassTy.isNull()) {
18421 Diag(New->getLocation(),
18422 diag::err_different_return_type_for_overriding_virtual_function)
18423 << New->getDeclName() << NewTy << OldTy
18424 << New->getReturnTypeSourceRange();
18425 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18426 << Old->getReturnTypeSourceRange();
18427
18428 return true;
18429 }
18430
18431 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18432 // C++14 [class.virtual]p8:
18433 // If the class type in the covariant return type of D::f differs from
18434 // that of B::f, the class type in the return type of D::f shall be
18435 // complete at the point of declaration of D::f or shall be the class
18436 // type D.
18437 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18438 if (!RT->isBeingDefined() &&
18439 RequireCompleteType(New->getLocation(), NewClassTy,
18440 diag::err_covariant_return_incomplete,
18441 New->getDeclName()))
18442 return true;
18443 }
18444
18445 // Check if the new class derives from the old class.
18446 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18447 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18448 << New->getDeclName() << NewTy << OldTy
18449 << New->getReturnTypeSourceRange();
18450 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18451 << Old->getReturnTypeSourceRange();
18452 return true;
18453 }
18454
18455 // Check if we the conversion from derived to base is valid.
18456 if (CheckDerivedToBaseConversion(
18457 NewClassTy, OldClassTy,
18458 diag::err_covariant_return_inaccessible_base,
18459 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18460 New->getLocation(), New->getReturnTypeSourceRange(),
18461 New->getDeclName(), nullptr)) {
18462 // FIXME: this note won't trigger for delayed access control
18463 // diagnostics, and it's impossible to get an undelayed error
18464 // here from access control during the original parse because
18465 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18466 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18467 << Old->getReturnTypeSourceRange();
18468 return true;
18469 }
18470 }
18471
18472 // The qualifiers of the return types must be the same.
18473 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18474 Diag(New->getLocation(),
18475 diag::err_covariant_return_type_different_qualifications)
18476 << New->getDeclName() << NewTy << OldTy
18477 << New->getReturnTypeSourceRange();
18478 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18479 << Old->getReturnTypeSourceRange();
18480 return true;
18481 }
18482
18483
18484 // The new class type must have the same or less qualifiers as the old type.
18485 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18486 Diag(New->getLocation(),
18487 diag::err_covariant_return_type_class_type_more_qualified)
18488 << New->getDeclName() << NewTy << OldTy
18489 << New->getReturnTypeSourceRange();
18490 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18491 << Old->getReturnTypeSourceRange();
18492 return true;
18493 }
18494
18495 return false;
18496 }
18497
18498 /// Mark the given method pure.
18499 ///
18500 /// \param Method the method to be marked pure.
18501 ///
18502 /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)18503 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18504 SourceLocation EndLoc = InitRange.getEnd();
18505 if (EndLoc.isValid())
18506 Method->setRangeEnd(EndLoc);
18507
18508 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18509 Method->setIsPureVirtual();
18510 return false;
18511 }
18512
18513 if (!Method->isInvalidDecl())
18514 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18515 << Method->getDeclName() << InitRange;
18516 return true;
18517 }
18518
ActOnPureSpecifier(Decl * D,SourceLocation ZeroLoc)18519 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18520 if (D->getFriendObjectKind())
18521 Diag(D->getLocation(), diag::err_pure_friend);
18522 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18523 CheckPureMethod(M, ZeroLoc);
18524 else
18525 Diag(D->getLocation(), diag::err_illegal_initializer);
18526 }
18527
18528 /// Determine whether the given declaration is a global variable or
18529 /// static data member.
isNonlocalVariable(const Decl * D)18530 static bool isNonlocalVariable(const Decl *D) {
18531 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18532 return Var->hasGlobalStorage();
18533
18534 return false;
18535 }
18536
18537 /// Invoked when we are about to parse an initializer for the declaration
18538 /// 'Dcl'.
18539 ///
18540 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18541 /// static data member of class X, names should be looked up in the scope of
18542 /// class X. If the declaration had a scope specifier, a scope will have
18543 /// been created and passed in for this purpose. Otherwise, S will be null.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)18544 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18545 // If there is no declaration, there was an error parsing it.
18546 if (!D || D->isInvalidDecl())
18547 return;
18548
18549 // We will always have a nested name specifier here, but this declaration
18550 // might not be out of line if the specifier names the current namespace:
18551 // extern int n;
18552 // int ::n = 0;
18553 if (S && D->isOutOfLine())
18554 EnterDeclaratorContext(S, D->getDeclContext());
18555
18556 // If we are parsing the initializer for a static data member, push a
18557 // new expression evaluation context that is associated with this static
18558 // data member.
18559 if (isNonlocalVariable(D))
18560 PushExpressionEvaluationContext(
18561 ExpressionEvaluationContext::PotentiallyEvaluated, D);
18562 }
18563
18564 /// Invoked after we are finished parsing an initializer for the declaration D.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)18565 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18566 // If there is no declaration, there was an error parsing it.
18567 if (!D || D->isInvalidDecl())
18568 return;
18569
18570 if (isNonlocalVariable(D))
18571 PopExpressionEvaluationContext();
18572
18573 if (S && D->isOutOfLine())
18574 ExitDeclaratorContext(S);
18575 }
18576
18577 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18578 /// C++ if/switch/while/for statement.
18579 /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)18580 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18581 // C++ 6.4p2:
18582 // The declarator shall not specify a function or an array.
18583 // The type-specifier-seq shall not contain typedef and shall not declare a
18584 // new class or enumeration.
18585 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18586 "Parser allowed 'typedef' as storage class of condition decl.");
18587
18588 Decl *Dcl = ActOnDeclarator(S, D);
18589 if (!Dcl)
18590 return true;
18591
18592 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18593 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18594 << D.getSourceRange();
18595 return true;
18596 }
18597
18598 return Dcl;
18599 }
18600
LoadExternalVTableUses()18601 void Sema::LoadExternalVTableUses() {
18602 if (!ExternalSource)
18603 return;
18604
18605 SmallVector<ExternalVTableUse, 4> VTables;
18606 ExternalSource->ReadUsedVTables(VTables);
18607 SmallVector<VTableUse, 4> NewUses;
18608 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18609 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18610 = VTablesUsed.find(VTables[I].Record);
18611 // Even if a definition wasn't required before, it may be required now.
18612 if (Pos != VTablesUsed.end()) {
18613 if (!Pos->second && VTables[I].DefinitionRequired)
18614 Pos->second = true;
18615 continue;
18616 }
18617
18618 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18619 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18620 }
18621
18622 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18623 }
18624
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)18625 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18626 bool DefinitionRequired) {
18627 // Ignore any vtable uses in unevaluated operands or for classes that do
18628 // not have a vtable.
18629 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18630 CurContext->isDependentContext() || isUnevaluatedContext())
18631 return;
18632 // Do not mark as used if compiling for the device outside of the target
18633 // region.
18634 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18635 !isInOpenMPDeclareTargetContext() &&
18636 !isInOpenMPTargetExecutionDirective()) {
18637 if (!DefinitionRequired)
18638 MarkVirtualMembersReferenced(Loc, Class);
18639 return;
18640 }
18641
18642 // Try to insert this class into the map.
18643 LoadExternalVTableUses();
18644 Class = Class->getCanonicalDecl();
18645 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18646 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18647 if (!Pos.second) {
18648 // If we already had an entry, check to see if we are promoting this vtable
18649 // to require a definition. If so, we need to reappend to the VTableUses
18650 // list, since we may have already processed the first entry.
18651 if (DefinitionRequired && !Pos.first->second) {
18652 Pos.first->second = true;
18653 } else {
18654 // Otherwise, we can early exit.
18655 return;
18656 }
18657 } else {
18658 // The Microsoft ABI requires that we perform the destructor body
18659 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18660 // the deleting destructor is emitted with the vtable, not with the
18661 // destructor definition as in the Itanium ABI.
18662 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18663 CXXDestructorDecl *DD = Class->getDestructor();
18664 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18665 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18666 // If this is an out-of-line declaration, marking it referenced will
18667 // not do anything. Manually call CheckDestructor to look up operator
18668 // delete().
18669 ContextRAII SavedContext(*this, DD);
18670 CheckDestructor(DD);
18671 } else {
18672 MarkFunctionReferenced(Loc, Class->getDestructor());
18673 }
18674 }
18675 }
18676 }
18677
18678 // Local classes need to have their virtual members marked
18679 // immediately. For all other classes, we mark their virtual members
18680 // at the end of the translation unit.
18681 if (Class->isLocalClass())
18682 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18683 else
18684 VTableUses.push_back(std::make_pair(Class, Loc));
18685 }
18686
DefineUsedVTables()18687 bool Sema::DefineUsedVTables() {
18688 LoadExternalVTableUses();
18689 if (VTableUses.empty())
18690 return false;
18691
18692 // Note: The VTableUses vector could grow as a result of marking
18693 // the members of a class as "used", so we check the size each
18694 // time through the loop and prefer indices (which are stable) to
18695 // iterators (which are not).
18696 bool DefinedAnything = false;
18697 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18698 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18699 if (!Class)
18700 continue;
18701 TemplateSpecializationKind ClassTSK =
18702 Class->getTemplateSpecializationKind();
18703
18704 SourceLocation Loc = VTableUses[I].second;
18705
18706 bool DefineVTable = true;
18707
18708 // If this class has a key function, but that key function is
18709 // defined in another translation unit, we don't need to emit the
18710 // vtable even though we're using it.
18711 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18712 if (KeyFunction && !KeyFunction->hasBody()) {
18713 // The key function is in another translation unit.
18714 DefineVTable = false;
18715 TemplateSpecializationKind TSK =
18716 KeyFunction->getTemplateSpecializationKind();
18717 assert(TSK != TSK_ExplicitInstantiationDefinition &&
18718 TSK != TSK_ImplicitInstantiation &&
18719 "Instantiations don't have key functions");
18720 (void)TSK;
18721 } else if (!KeyFunction) {
18722 // If we have a class with no key function that is the subject
18723 // of an explicit instantiation declaration, suppress the
18724 // vtable; it will live with the explicit instantiation
18725 // definition.
18726 bool IsExplicitInstantiationDeclaration =
18727 ClassTSK == TSK_ExplicitInstantiationDeclaration;
18728 for (auto *R : Class->redecls()) {
18729 TemplateSpecializationKind TSK
18730 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18731 if (TSK == TSK_ExplicitInstantiationDeclaration)
18732 IsExplicitInstantiationDeclaration = true;
18733 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18734 IsExplicitInstantiationDeclaration = false;
18735 break;
18736 }
18737 }
18738
18739 if (IsExplicitInstantiationDeclaration)
18740 DefineVTable = false;
18741 }
18742
18743 // The exception specifications for all virtual members may be needed even
18744 // if we are not providing an authoritative form of the vtable in this TU.
18745 // We may choose to emit it available_externally anyway.
18746 if (!DefineVTable) {
18747 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18748 continue;
18749 }
18750
18751 // Mark all of the virtual members of this class as referenced, so
18752 // that we can build a vtable. Then, tell the AST consumer that a
18753 // vtable for this class is required.
18754 DefinedAnything = true;
18755 MarkVirtualMembersReferenced(Loc, Class);
18756 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18757 if (VTablesUsed[Canonical])
18758 Consumer.HandleVTable(Class);
18759
18760 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18761 // no key function or the key function is inlined. Don't warn in C++ ABIs
18762 // that lack key functions, since the user won't be able to make one.
18763 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18764 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18765 ClassTSK != TSK_ExplicitInstantiationDefinition) {
18766 const FunctionDecl *KeyFunctionDef = nullptr;
18767 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18768 KeyFunctionDef->isInlined()))
18769 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18770 }
18771 }
18772 VTableUses.clear();
18773
18774 return DefinedAnything;
18775 }
18776
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)18777 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18778 const CXXRecordDecl *RD) {
18779 for (const auto *I : RD->methods())
18780 if (I->isVirtual() && !I->isPureVirtual())
18781 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18782 }
18783
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD,bool ConstexprOnly)18784 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18785 const CXXRecordDecl *RD,
18786 bool ConstexprOnly) {
18787 // Mark all functions which will appear in RD's vtable as used.
18788 CXXFinalOverriderMap FinalOverriders;
18789 RD->getFinalOverriders(FinalOverriders);
18790 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18791 E = FinalOverriders.end();
18792 I != E; ++I) {
18793 for (OverridingMethods::const_iterator OI = I->second.begin(),
18794 OE = I->second.end();
18795 OI != OE; ++OI) {
18796 assert(OI->second.size() > 0 && "no final overrider");
18797 CXXMethodDecl *Overrider = OI->second.front().Method;
18798
18799 // C++ [basic.def.odr]p2:
18800 // [...] A virtual member function is used if it is not pure. [...]
18801 if (!Overrider->isPureVirtual() &&
18802 (!ConstexprOnly || Overrider->isConstexpr()))
18803 MarkFunctionReferenced(Loc, Overrider);
18804 }
18805 }
18806
18807 // Only classes that have virtual bases need a VTT.
18808 if (RD->getNumVBases() == 0)
18809 return;
18810
18811 for (const auto &I : RD->bases()) {
18812 const auto *Base =
18813 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18814 if (Base->getNumVBases() == 0)
18815 continue;
18816 MarkVirtualMembersReferenced(Loc, Base);
18817 }
18818 }
18819
18820 /// SetIvarInitializers - This routine builds initialization ASTs for the
18821 /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)18822 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18823 if (!getLangOpts().CPlusPlus)
18824 return;
18825 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18826 SmallVector<ObjCIvarDecl*, 8> ivars;
18827 CollectIvarsToConstructOrDestruct(OID, ivars);
18828 if (ivars.empty())
18829 return;
18830 SmallVector<CXXCtorInitializer*, 32> AllToInit;
18831 for (unsigned i = 0; i < ivars.size(); i++) {
18832 FieldDecl *Field = ivars[i];
18833 if (Field->isInvalidDecl())
18834 continue;
18835
18836 CXXCtorInitializer *Member;
18837 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18838 InitializationKind InitKind =
18839 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18840
18841 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18842 ExprResult MemberInit =
18843 InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18844 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18845 // Note, MemberInit could actually come back empty if no initialization
18846 // is required (e.g., because it would call a trivial default constructor)
18847 if (!MemberInit.get() || MemberInit.isInvalid())
18848 continue;
18849
18850 Member =
18851 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18852 SourceLocation(),
18853 MemberInit.getAs<Expr>(),
18854 SourceLocation());
18855 AllToInit.push_back(Member);
18856
18857 // Be sure that the destructor is accessible and is marked as referenced.
18858 if (const RecordType *RecordTy =
18859 Context.getBaseElementType(Field->getType())
18860 ->getAs<RecordType>()) {
18861 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18862 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18863 MarkFunctionReferenced(Field->getLocation(), Destructor);
18864 CheckDestructorAccess(Field->getLocation(), Destructor,
18865 PDiag(diag::err_access_dtor_ivar)
18866 << Context.getBaseElementType(Field->getType()));
18867 }
18868 }
18869 }
18870 ObjCImplementation->setIvarInitializers(Context,
18871 AllToInit.data(), AllToInit.size());
18872 }
18873 }
18874
18875 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Valid,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallPtrSet<CXXConstructorDecl *,4> & Current,Sema & S)18876 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18877 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18878 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18879 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18880 Sema &S) {
18881 if (Ctor->isInvalidDecl())
18882 return;
18883
18884 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18885
18886 // Target may not be determinable yet, for instance if this is a dependent
18887 // call in an uninstantiated template.
18888 if (Target) {
18889 const FunctionDecl *FNTarget = nullptr;
18890 (void)Target->hasBody(FNTarget);
18891 Target = const_cast<CXXConstructorDecl*>(
18892 cast_or_null<CXXConstructorDecl>(FNTarget));
18893 }
18894
18895 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18896 // Avoid dereferencing a null pointer here.
18897 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18898
18899 if (!Current.insert(Canonical).second)
18900 return;
18901
18902 // We know that beyond here, we aren't chaining into a cycle.
18903 if (!Target || !Target->isDelegatingConstructor() ||
18904 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18905 Valid.insert(Current.begin(), Current.end());
18906 Current.clear();
18907 // We've hit a cycle.
18908 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18909 Current.count(TCanonical)) {
18910 // If we haven't diagnosed this cycle yet, do so now.
18911 if (!Invalid.count(TCanonical)) {
18912 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18913 diag::warn_delegating_ctor_cycle)
18914 << Ctor;
18915
18916 // Don't add a note for a function delegating directly to itself.
18917 if (TCanonical != Canonical)
18918 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18919
18920 CXXConstructorDecl *C = Target;
18921 while (C->getCanonicalDecl() != Canonical) {
18922 const FunctionDecl *FNTarget = nullptr;
18923 (void)C->getTargetConstructor()->hasBody(FNTarget);
18924 assert(FNTarget && "Ctor cycle through bodiless function");
18925
18926 C = const_cast<CXXConstructorDecl*>(
18927 cast<CXXConstructorDecl>(FNTarget));
18928 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18929 }
18930 }
18931
18932 Invalid.insert(Current.begin(), Current.end());
18933 Current.clear();
18934 } else {
18935 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18936 }
18937 }
18938
18939
CheckDelegatingCtorCycles()18940 void Sema::CheckDelegatingCtorCycles() {
18941 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18942
18943 for (DelegatingCtorDeclsType::iterator
18944 I = DelegatingCtorDecls.begin(ExternalSource.get()),
18945 E = DelegatingCtorDecls.end();
18946 I != E; ++I)
18947 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18948
18949 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18950 (*CI)->setInvalidDecl();
18951 }
18952
18953 namespace {
18954 /// AST visitor that finds references to the 'this' expression.
18955 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18956 Sema &S;
18957
18958 public:
FindCXXThisExpr(Sema & S)18959 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18960
VisitCXXThisExpr(CXXThisExpr * E)18961 bool VisitCXXThisExpr(CXXThisExpr *E) {
18962 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18963 << E->isImplicit();
18964 return false;
18965 }
18966 };
18967 }
18968
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)18969 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18970 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18971 if (!TSInfo)
18972 return false;
18973
18974 TypeLoc TL = TSInfo->getTypeLoc();
18975 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18976 if (!ProtoTL)
18977 return false;
18978
18979 // C++11 [expr.prim.general]p3:
18980 // [The expression this] shall not appear before the optional
18981 // cv-qualifier-seq and it shall not appear within the declaration of a
18982 // static member function (although its type and value category are defined
18983 // within a static member function as they are within a non-static member
18984 // function). [ Note: this is because declaration matching does not occur
18985 // until the complete declarator is known. - end note ]
18986 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18987 FindCXXThisExpr Finder(*this);
18988
18989 // If the return type came after the cv-qualifier-seq, check it now.
18990 if (Proto->hasTrailingReturn() &&
18991 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18992 return true;
18993
18994 // Check the exception specification.
18995 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18996 return true;
18997
18998 // Check the trailing requires clause
18999 if (Expr *E = Method->getTrailingRequiresClause())
19000 if (!Finder.TraverseStmt(E))
19001 return true;
19002
19003 return checkThisInStaticMemberFunctionAttributes(Method);
19004 }
19005
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)19006 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19007 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19008 if (!TSInfo)
19009 return false;
19010
19011 TypeLoc TL = TSInfo->getTypeLoc();
19012 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19013 if (!ProtoTL)
19014 return false;
19015
19016 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19017 FindCXXThisExpr Finder(*this);
19018
19019 switch (Proto->getExceptionSpecType()) {
19020 case EST_Unparsed:
19021 case EST_Uninstantiated:
19022 case EST_Unevaluated:
19023 case EST_BasicNoexcept:
19024 case EST_NoThrow:
19025 case EST_DynamicNone:
19026 case EST_MSAny:
19027 case EST_None:
19028 break;
19029
19030 case EST_DependentNoexcept:
19031 case EST_NoexceptFalse:
19032 case EST_NoexceptTrue:
19033 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19034 return true;
19035 [[fallthrough]];
19036
19037 case EST_Dynamic:
19038 for (const auto &E : Proto->exceptions()) {
19039 if (!Finder.TraverseType(E))
19040 return true;
19041 }
19042 break;
19043 }
19044
19045 return false;
19046 }
19047
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)19048 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19049 FindCXXThisExpr Finder(*this);
19050
19051 // Check attributes.
19052 for (const auto *A : Method->attrs()) {
19053 // FIXME: This should be emitted by tblgen.
19054 Expr *Arg = nullptr;
19055 ArrayRef<Expr *> Args;
19056 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19057 Arg = G->getArg();
19058 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19059 Arg = G->getArg();
19060 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19061 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19062 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19063 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19064 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
19065 Arg = ETLF->getSuccessValue();
19066 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
19067 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
19068 Arg = STLF->getSuccessValue();
19069 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
19070 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19071 Arg = LR->getArg();
19072 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19073 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19074 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19075 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19076 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19077 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19078 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19079 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19080 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19081 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19082
19083 if (Arg && !Finder.TraverseStmt(Arg))
19084 return true;
19085
19086 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19087 if (!Finder.TraverseStmt(Args[I]))
19088 return true;
19089 }
19090 }
19091
19092 return false;
19093 }
19094
checkExceptionSpecification(bool IsTopLevel,ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExceptionSpecInfo & ESI)19095 void Sema::checkExceptionSpecification(
19096 bool IsTopLevel, ExceptionSpecificationType EST,
19097 ArrayRef<ParsedType> DynamicExceptions,
19098 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19099 SmallVectorImpl<QualType> &Exceptions,
19100 FunctionProtoType::ExceptionSpecInfo &ESI) {
19101 Exceptions.clear();
19102 ESI.Type = EST;
19103 if (EST == EST_Dynamic) {
19104 Exceptions.reserve(DynamicExceptions.size());
19105 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19106 // FIXME: Preserve type source info.
19107 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19108
19109 if (IsTopLevel) {
19110 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19111 collectUnexpandedParameterPacks(ET, Unexpanded);
19112 if (!Unexpanded.empty()) {
19113 DiagnoseUnexpandedParameterPacks(
19114 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19115 Unexpanded);
19116 continue;
19117 }
19118 }
19119
19120 // Check that the type is valid for an exception spec, and
19121 // drop it if not.
19122 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19123 Exceptions.push_back(ET);
19124 }
19125 ESI.Exceptions = Exceptions;
19126 return;
19127 }
19128
19129 if (isComputedNoexcept(EST)) {
19130 assert((NoexceptExpr->isTypeDependent() ||
19131 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19132 Context.BoolTy) &&
19133 "Parser should have made sure that the expression is boolean");
19134 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19135 ESI.Type = EST_BasicNoexcept;
19136 return;
19137 }
19138
19139 ESI.NoexceptExpr = NoexceptExpr;
19140 return;
19141 }
19142 }
19143
actOnDelayedExceptionSpecification(Decl * MethodD,ExceptionSpecificationType EST,SourceRange SpecificationRange,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr)19144 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
19145 ExceptionSpecificationType EST,
19146 SourceRange SpecificationRange,
19147 ArrayRef<ParsedType> DynamicExceptions,
19148 ArrayRef<SourceRange> DynamicExceptionRanges,
19149 Expr *NoexceptExpr) {
19150 if (!MethodD)
19151 return;
19152
19153 // Dig out the method we're referring to.
19154 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
19155 MethodD = FunTmpl->getTemplatedDecl();
19156
19157 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
19158 if (!Method)
19159 return;
19160
19161 // Check the exception specification.
19162 llvm::SmallVector<QualType, 4> Exceptions;
19163 FunctionProtoType::ExceptionSpecInfo ESI;
19164 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
19165 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19166 ESI);
19167
19168 // Update the exception specification on the function type.
19169 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
19170
19171 if (Method->isStatic())
19172 checkThisInStaticMemberFunctionExceptionSpec(Method);
19173
19174 if (Method->isVirtual()) {
19175 // Check overrides, which we previously had to delay.
19176 for (const CXXMethodDecl *O : Method->overridden_methods())
19177 CheckOverridingFunctionExceptionSpec(Method, O);
19178 }
19179 }
19180
19181 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19182 ///
HandleMSProperty(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS,const ParsedAttr & MSPropertyAttr)19183 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19184 SourceLocation DeclStart, Declarator &D,
19185 Expr *BitWidth,
19186 InClassInitStyle InitStyle,
19187 AccessSpecifier AS,
19188 const ParsedAttr &MSPropertyAttr) {
19189 IdentifierInfo *II = D.getIdentifier();
19190 if (!II) {
19191 Diag(DeclStart, diag::err_anonymous_property);
19192 return nullptr;
19193 }
19194 SourceLocation Loc = D.getIdentifierLoc();
19195
19196 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19197 QualType T = TInfo->getType();
19198 if (getLangOpts().CPlusPlus) {
19199 CheckExtraCXXDefaultArguments(D);
19200
19201 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19202 UPPC_DataMemberType)) {
19203 D.setInvalidType();
19204 T = Context.IntTy;
19205 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19206 }
19207 }
19208
19209 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19210
19211 if (D.getDeclSpec().isInlineSpecified())
19212 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19213 << getLangOpts().CPlusPlus17;
19214 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19215 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19216 diag::err_invalid_thread)
19217 << DeclSpec::getSpecifierName(TSCS);
19218
19219 // Check to see if this name was declared as a member previously
19220 NamedDecl *PrevDecl = nullptr;
19221 LookupResult Previous(*this, II, Loc, LookupMemberName,
19222 ForVisibleRedeclaration);
19223 LookupName(Previous, S);
19224 switch (Previous.getResultKind()) {
19225 case LookupResult::Found:
19226 case LookupResult::FoundUnresolvedValue:
19227 PrevDecl = Previous.getAsSingle<NamedDecl>();
19228 break;
19229
19230 case LookupResult::FoundOverloaded:
19231 PrevDecl = Previous.getRepresentativeDecl();
19232 break;
19233
19234 case LookupResult::NotFound:
19235 case LookupResult::NotFoundInCurrentInstantiation:
19236 case LookupResult::Ambiguous:
19237 break;
19238 }
19239
19240 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19241 // Maybe we will complain about the shadowed template parameter.
19242 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19243 // Just pretend that we didn't see the previous declaration.
19244 PrevDecl = nullptr;
19245 }
19246
19247 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19248 PrevDecl = nullptr;
19249
19250 SourceLocation TSSL = D.getBeginLoc();
19251 MSPropertyDecl *NewPD =
19252 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19253 MSPropertyAttr.getPropertyDataGetter(),
19254 MSPropertyAttr.getPropertyDataSetter());
19255 ProcessDeclAttributes(TUScope, NewPD, D);
19256 NewPD->setAccess(AS);
19257
19258 if (NewPD->isInvalidDecl())
19259 Record->setInvalidDecl();
19260
19261 if (D.getDeclSpec().isModulePrivateSpecified())
19262 NewPD->setModulePrivate();
19263
19264 if (NewPD->isInvalidDecl() && PrevDecl) {
19265 // Don't introduce NewFD into scope; there's already something
19266 // with the same name in the same scope.
19267 } else if (II) {
19268 PushOnScopeChains(NewPD, S);
19269 } else
19270 Record->addDecl(NewPD);
19271
19272 return NewPD;
19273 }
19274
ActOnStartFunctionDeclarationDeclarator(Declarator & Declarator,unsigned TemplateParameterDepth)19275 void Sema::ActOnStartFunctionDeclarationDeclarator(
19276 Declarator &Declarator, unsigned TemplateParameterDepth) {
19277 auto &Info = InventedParameterInfos.emplace_back();
19278 TemplateParameterList *ExplicitParams = nullptr;
19279 ArrayRef<TemplateParameterList *> ExplicitLists =
19280 Declarator.getTemplateParameterLists();
19281 if (!ExplicitLists.empty()) {
19282 bool IsMemberSpecialization, IsInvalid;
19283 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19284 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
19285 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19286 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19287 /*SuppressDiagnostic=*/true);
19288 }
19289 if (ExplicitParams) {
19290 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19291 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19292 Info.NumExplicitTemplateParams = ExplicitParams->size();
19293 } else {
19294 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19295 Info.NumExplicitTemplateParams = 0;
19296 }
19297 }
19298
ActOnFinishFunctionDeclarationDeclarator(Declarator & Declarator)19299 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19300 auto &FSI = InventedParameterInfos.back();
19301 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19302 if (FSI.NumExplicitTemplateParams != 0) {
19303 TemplateParameterList *ExplicitParams =
19304 Declarator.getTemplateParameterLists().back();
19305 Declarator.setInventedTemplateParameterList(
19306 TemplateParameterList::Create(
19307 Context, ExplicitParams->getTemplateLoc(),
19308 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19309 ExplicitParams->getRAngleLoc(),
19310 ExplicitParams->getRequiresClause()));
19311 } else {
19312 Declarator.setInventedTemplateParameterList(
19313 TemplateParameterList::Create(
19314 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19315 SourceLocation(), /*RequiresClause=*/nullptr));
19316 }
19317 }
19318 InventedParameterInfos.pop_back();
19319 }
19320