Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 5533, column 56
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-15-025533-4418-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp

/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp

1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/AttributeCommonInfo.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include <map>
46#include <set>
47
48using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// CheckDefaultArgumentVisitor
52//===----------------------------------------------------------------------===//
53
54namespace {
55/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56/// the default argument of a parameter to determine whether it
57/// contains any ill-formed subexpressions. For example, this will
58/// diagnose the use of local variables or parameters within the
59/// default argument expression.
60class CheckDefaultArgumentVisitor
61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62 Sema &S;
63 const Expr *DefaultArg;
64
65public:
66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67 : S(S), DefaultArg(DefaultArg) {}
68
69 bool VisitExpr(const Expr *Node);
70 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72 bool VisitLambdaExpr(const LambdaExpr *Lambda);
73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74};
75
76/// VisitExpr - Visit all of the children of this expression.
77bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78 bool IsInvalid = false;
79 for (const Stmt *SubStmt : Node->children())
80 IsInvalid |= Visit(SubStmt);
81 return IsInvalid;
82}
83
84/// VisitDeclRefExpr - Visit a reference to a declaration, to
85/// determine whether this declaration can be used in the default
86/// argument expression.
87bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88 const NamedDecl *Decl = DRE->getDecl();
89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90 // C++ [dcl.fct.default]p9:
91 // [...] parameters of a function shall not be used in default
92 // argument expressions, even if they are not evaluated. [...]
93 //
94 // C++17 [dcl.fct.default]p9 (by CWG 2082):
95 // [...] A parameter shall not appear as a potentially-evaluated
96 // expression in a default argument. [...]
97 //
98 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99 return S.Diag(DRE->getBeginLoc(),
100 diag::err_param_default_argument_references_param)
101 << Param->getDeclName() << DefaultArg->getSourceRange();
102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p7:
104 // Local variables shall not be used in default argument
105 // expressions.
106 //
107 // C++17 [dcl.fct.default]p7 (by CWG 2082):
108 // A local variable shall not appear as a potentially-evaluated
109 // expression in a default argument.
110 //
111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112 // Note: A local variable cannot be odr-used (6.3) in a default argument.
113 //
114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_local)
117 << VDecl->getDeclName() << DefaultArg->getSourceRange();
118 }
119
120 return false;
121}
122
123/// VisitCXXThisExpr - Visit a C++ "this" expression.
124bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125 // C++ [dcl.fct.default]p8:
126 // The keyword this shall not be used in a default argument of a
127 // member function.
128 return S.Diag(ThisE->getBeginLoc(),
129 diag::err_param_default_argument_references_this)
130 << ThisE->getSourceRange();
131}
132
133bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134 const PseudoObjectExpr *POE) {
135 bool Invalid = false;
136 for (const Expr *E : POE->semantics()) {
137 // Look through bindings.
138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139 E = OVE->getSourceExpr();
140 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 140, __PRETTY_FUNCTION__))
;
141 }
142
143 Invalid |= Visit(E);
144 }
145 return Invalid;
146}
147
148bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149 // C++11 [expr.lambda.prim]p13:
150 // A lambda-expression appearing in a default argument shall not
151 // implicitly or explicitly capture any entity.
152 if (Lambda->capture_begin() == Lambda->capture_end())
153 return false;
154
155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156}
157} // namespace
158
159void
160Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161 const CXXMethodDecl *Method) {
162 // If we have an MSAny spec already, don't bother.
163 if (!Method || ComputedEST == EST_MSAny)
164 return;
165
166 const FunctionProtoType *Proto
167 = Method->getType()->getAs<FunctionProtoType>();
168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169 if (!Proto)
170 return;
171
172 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
174 // If we have a throw-all spec at this point, ignore the function.
175 if (ComputedEST == EST_None)
176 return;
177
178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179 EST = EST_BasicNoexcept;
180
181 switch (EST) {
182 case EST_Unparsed:
183 case EST_Uninstantiated:
184 case EST_Unevaluated:
185 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 185)
;
186
187 // If this function can throw any exceptions, make a note of that.
188 case EST_MSAny:
189 case EST_None:
190 // FIXME: Whichever we see last of MSAny and None determines our result.
191 // We should make a consistent, order-independent choice here.
192 ClearExceptions();
193 ComputedEST = EST;
194 return;
195 case EST_NoexceptFalse:
196 ClearExceptions();
197 ComputedEST = EST_None;
198 return;
199 // FIXME: If the call to this decl is using any of its default arguments, we
200 // need to search them for potentially-throwing calls.
201 // If this function has a basic noexcept, it doesn't affect the outcome.
202 case EST_BasicNoexcept:
203 case EST_NoexceptTrue:
204 case EST_NoThrow:
205 return;
206 // If we're still at noexcept(true) and there's a throw() callee,
207 // change to that specification.
208 case EST_DynamicNone:
209 if (ComputedEST == EST_BasicNoexcept)
210 ComputedEST = EST_DynamicNone;
211 return;
212 case EST_DependentNoexcept:
213 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
214 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
;
215 case EST_Dynamic:
216 break;
217 }
218 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 218, __PRETTY_FUNCTION__))
;
219 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __PRETTY_FUNCTION__))
220 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __PRETTY_FUNCTION__))
;
221 ComputedEST = EST_Dynamic;
222 // Record the exceptions in this function's exception specification.
223 for (const auto &E : Proto->exceptions())
224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225 Exceptions.push_back(E);
226}
227
228void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229 if (!S || ComputedEST == EST_MSAny)
230 return;
231
232 // FIXME:
233 //
234 // C++0x [except.spec]p14:
235 // [An] implicit exception-specification specifies the type-id T if and
236 // only if T is allowed by the exception-specification of a function directly
237 // invoked by f's implicit definition; f shall allow all exceptions if any
238 // function it directly invokes allows all exceptions, and f shall allow no
239 // exceptions if every function it directly invokes allows no exceptions.
240 //
241 // Note in particular that if an implicit exception-specification is generated
242 // for a function containing a throw-expression, that specification can still
243 // be noexcept(true).
244 //
245 // Note also that 'directly invoked' is not defined in the standard, and there
246 // is no indication that we should only consider potentially-evaluated calls.
247 //
248 // Ultimately we should implement the intent of the standard: the exception
249 // specification should be the set of exceptions which can be thrown by the
250 // implicit definition. For now, we assume that any non-nothrow expression can
251 // throw any exception.
252
253 if (Self->canThrow(S))
254 ComputedEST = EST_None;
255}
256
257ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258 Expr *Arg,
259 SourceLocation EqualLoc) {
260 if (RequireCompleteType(Param->getLocation(), Param->getType(),
261 diag::err_typecheck_decl_incomplete_type))
262 return true;
263
264 // C++ [dcl.fct.default]p5
265 // A default argument expression is implicitly converted (clause
266 // 4) to the parameter type. The default argument expression has
267 // the same semantic constraints as the initializer expression in
268 // a declaration of a variable of the parameter type, using the
269 // copy-initialization semantics (8.5).
270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271 Param);
272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273 EqualLoc);
274 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276 if (Result.isInvalid())
277 return true;
278 Arg = Result.getAs<Expr>();
279
280 CheckCompletedExpr(Arg, EqualLoc);
281 Arg = MaybeCreateExprWithCleanups(Arg);
282
283 return Arg;
284}
285
286void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287 SourceLocation EqualLoc) {
288 // Add the default argument to the parameter
289 Param->setDefaultArg(Arg);
290
291 // We have already instantiated this parameter; provide each of the
292 // instantiations with the uninstantiated default argument.
293 UnparsedDefaultArgInstantiationsMap::iterator InstPos
294 = UnparsedDefaultArgInstantiations.find(Param);
295 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298
299 // We're done tracking this parameter's instantiations.
300 UnparsedDefaultArgInstantiations.erase(InstPos);
301 }
302}
303
304/// ActOnParamDefaultArgument - Check whether the default argument
305/// provided for a function parameter is well-formed. If so, attach it
306/// to the parameter declaration.
307void
308Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309 Expr *DefaultArg) {
310 if (!param || !DefaultArg)
311 return;
312
313 ParmVarDecl *Param = cast<ParmVarDecl>(param);
314 UnparsedDefaultArgLocs.erase(Param);
315
316 auto Fail = [&] {
317 Param->setInvalidDecl();
318 Param->setDefaultArg(new (Context) OpaqueValueExpr(
319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
320 };
321
322 // Default arguments are only permitted in C++
323 if (!getLangOpts().CPlusPlus) {
324 Diag(EqualLoc, diag::err_param_default_argument)
325 << DefaultArg->getSourceRange();
326 return Fail();
327 }
328
329 // Check for unexpanded parameter packs.
330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331 return Fail();
332 }
333
334 // C++11 [dcl.fct.default]p3
335 // A default argument expression [...] shall not be specified for a
336 // parameter pack.
337 if (Param->isParameterPack()) {
338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339 << DefaultArg->getSourceRange();
340 // Recover by discarding the default argument.
341 Param->setDefaultArg(nullptr);
342 return;
343 }
344
345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346 if (Result.isInvalid())
347 return Fail();
348
349 DefaultArg = Result.getAs<Expr>();
350
351 // Check that the default argument is well-formed
352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353 if (DefaultArgChecker.Visit(DefaultArg))
354 return Fail();
355
356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357}
358
359/// ActOnParamUnparsedDefaultArgument - We've seen a default
360/// argument for a function parameter, but we can't parse it yet
361/// because we're inside a class definition. Note that this default
362/// argument will be parsed later.
363void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364 SourceLocation EqualLoc,
365 SourceLocation ArgLoc) {
366 if (!param)
367 return;
368
369 ParmVarDecl *Param = cast<ParmVarDecl>(param);
370 Param->setUnparsedDefaultArg();
371 UnparsedDefaultArgLocs[Param] = ArgLoc;
372}
373
374/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375/// the default argument for the parameter param failed.
376void Sema::ActOnParamDefaultArgumentError(Decl *param,
377 SourceLocation EqualLoc) {
378 if (!param)
379 return;
380
381 ParmVarDecl *Param = cast<ParmVarDecl>(param);
382 Param->setInvalidDecl();
383 UnparsedDefaultArgLocs.erase(Param);
384 Param->setDefaultArg(new(Context)
385 OpaqueValueExpr(EqualLoc,
386 Param->getType().getNonReferenceType(),
387 VK_RValue));
388}
389
390/// CheckExtraCXXDefaultArguments - Check for any extra default
391/// arguments in the declarator, which is not a function declaration
392/// or definition and therefore is not permitted to have default
393/// arguments. This routine should be invoked for every declarator
394/// that is not a function declaration or definition.
395void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396 // C++ [dcl.fct.default]p3
397 // A default argument expression shall be specified only in the
398 // parameter-declaration-clause of a function declaration or in a
399 // template-parameter (14.1). It shall not be specified for a
400 // parameter pack. If it is specified in a
401 // parameter-declaration-clause, it shall not occur within a
402 // declarator or abstract-declarator of a parameter-declaration.
403 bool MightBeFunction = D.isFunctionDeclarationContext();
404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405 DeclaratorChunk &chunk = D.getTypeObject(i);
406 if (chunk.Kind == DeclaratorChunk::Function) {
407 if (MightBeFunction) {
408 // This is a function declaration. It can have default arguments, but
409 // keep looking in case its return type is a function type with default
410 // arguments.
411 MightBeFunction = false;
412 continue;
413 }
414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415 ++argIdx) {
416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417 if (Param->hasUnparsedDefaultArg()) {
418 std::unique_ptr<CachedTokens> Toks =
419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420 SourceRange SR;
421 if (Toks->size() > 1)
422 SR = SourceRange((*Toks)[1].getLocation(),
423 Toks->back().getLocation());
424 else
425 SR = UnparsedDefaultArgLocs[Param];
426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427 << SR;
428 } else if (Param->getDefaultArg()) {
429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430 << Param->getDefaultArg()->getSourceRange();
431 Param->setDefaultArg(nullptr);
432 }
433 }
434 } else if (chunk.Kind != DeclaratorChunk::Paren) {
435 MightBeFunction = false;
436 }
437 }
438}
439
440static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443 });
444}
445
446/// MergeCXXFunctionDecl - Merge two declarations of the same C++
447/// function, once we already know that they have the same
448/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449/// error, false otherwise.
450bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451 Scope *S) {
452 bool Invalid = false;
453
454 // The declaration context corresponding to the scope is the semantic
455 // parent, unless this is a local function declaration, in which case
456 // it is that surrounding function.
457 DeclContext *ScopeDC = New->isLocalExternDecl()
458 ? New->getLexicalDeclContext()
459 : New->getDeclContext();
460
461 // Find the previous declaration for the purpose of default arguments.
462 FunctionDecl *PrevForDefaultArgs = Old;
463 for (/**/; PrevForDefaultArgs;
464 // Don't bother looking back past the latest decl if this is a local
465 // extern declaration; nothing else could work.
466 PrevForDefaultArgs = New->isLocalExternDecl()
467 ? nullptr
468 : PrevForDefaultArgs->getPreviousDecl()) {
469 // Ignore hidden declarations.
470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471 continue;
472
473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474 !New->isCXXClassMember()) {
475 // Ignore default arguments of old decl if they are not in
476 // the same scope and this is not an out-of-line definition of
477 // a member function.
478 continue;
479 }
480
481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482 // If only one of these is a local function declaration, then they are
483 // declared in different scopes, even though isDeclInScope may think
484 // they're in the same scope. (If both are local, the scope check is
485 // sufficient, and if neither is local, then they are in the same scope.)
486 continue;
487 }
488
489 // We found the right previous declaration.
490 break;
491 }
492
493 // C++ [dcl.fct.default]p4:
494 // For non-template functions, default arguments can be added in
495 // later declarations of a function in the same
496 // scope. Declarations in different scopes have completely
497 // distinct sets of default arguments. That is, declarations in
498 // inner scopes do not acquire default arguments from
499 // declarations in outer scopes, and vice versa. In a given
500 // function declaration, all parameters subsequent to a
501 // parameter with a default argument shall have default
502 // arguments supplied in this or previous declarations. A
503 // default argument shall not be redefined by a later
504 // declaration (not even to the same value).
505 //
506 // C++ [dcl.fct.default]p6:
507 // Except for member functions of class templates, the default arguments
508 // in a member function definition that appears outside of the class
509 // definition are added to the set of default arguments provided by the
510 // member function declaration in the class definition.
511 for (unsigned p = 0, NumParams = PrevForDefaultArgs
512 ? PrevForDefaultArgs->getNumParams()
513 : 0;
514 p < NumParams; ++p) {
515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516 ParmVarDecl *NewParam = New->getParamDecl(p);
517
518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519 bool NewParamHasDfl = NewParam->hasDefaultArg();
520
521 if (OldParamHasDfl && NewParamHasDfl) {
522 unsigned DiagDefaultParamID =
523 diag::err_param_default_argument_redefinition;
524
525 // MSVC accepts that default parameters be redefined for member functions
526 // of template class. The new default parameter's value is ignored.
527 Invalid = true;
528 if (getLangOpts().MicrosoftExt) {
529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530 if (MD && MD->getParent()->getDescribedClassTemplate()) {
531 // Merge the old default argument into the new parameter.
532 NewParam->setHasInheritedDefaultArg();
533 if (OldParam->hasUninstantiatedDefaultArg())
534 NewParam->setUninstantiatedDefaultArg(
535 OldParam->getUninstantiatedDefaultArg());
536 else
537 NewParam->setDefaultArg(OldParam->getInit());
538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539 Invalid = false;
540 }
541 }
542
543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544 // hint here. Alternatively, we could walk the type-source information
545 // for NewParam to find the last source location in the type... but it
546 // isn't worth the effort right now. This is the kind of test case that
547 // is hard to get right:
548 // int f(int);
549 // void g(int (*fp)(int) = f);
550 // void g(int (*fp)(int) = &f);
551 Diag(NewParam->getLocation(), DiagDefaultParamID)
552 << NewParam->getDefaultArgRange();
553
554 // Look for the function declaration where the default argument was
555 // actually written, which may be a declaration prior to Old.
556 for (auto Older = PrevForDefaultArgs;
557 OldParam->hasInheritedDefaultArg(); /**/) {
558 Older = Older->getPreviousDecl();
559 OldParam = Older->getParamDecl(p);
560 }
561
562 Diag(OldParam->getLocation(), diag::note_previous_definition)
563 << OldParam->getDefaultArgRange();
564 } else if (OldParamHasDfl) {
565 // Merge the old default argument into the new parameter unless the new
566 // function is a friend declaration in a template class. In the latter
567 // case the default arguments will be inherited when the friend
568 // declaration will be instantiated.
569 if (New->getFriendObjectKind() == Decl::FOK_None ||
570 !New->getLexicalDeclContext()->isDependentContext()) {
571 // It's important to use getInit() here; getDefaultArg()
572 // strips off any top-level ExprWithCleanups.
573 NewParam->setHasInheritedDefaultArg();
574 if (OldParam->hasUnparsedDefaultArg())
575 NewParam->setUnparsedDefaultArg();
576 else if (OldParam->hasUninstantiatedDefaultArg())
577 NewParam->setUninstantiatedDefaultArg(
578 OldParam->getUninstantiatedDefaultArg());
579 else
580 NewParam->setDefaultArg(OldParam->getInit());
581 }
582 } else if (NewParamHasDfl) {
583 if (New->getDescribedFunctionTemplate()) {
584 // Paragraph 4, quoted above, only applies to non-template functions.
585 Diag(NewParam->getLocation(),
586 diag::err_param_default_argument_template_redecl)
587 << NewParam->getDefaultArgRange();
588 Diag(PrevForDefaultArgs->getLocation(),
589 diag::note_template_prev_declaration)
590 << false;
591 } else if (New->getTemplateSpecializationKind()
592 != TSK_ImplicitInstantiation &&
593 New->getTemplateSpecializationKind() != TSK_Undeclared) {
594 // C++ [temp.expr.spec]p21:
595 // Default function arguments shall not be specified in a declaration
596 // or a definition for one of the following explicit specializations:
597 // - the explicit specialization of a function template;
598 // - the explicit specialization of a member function template;
599 // - the explicit specialization of a member function of a class
600 // template where the class template specialization to which the
601 // member function specialization belongs is implicitly
602 // instantiated.
603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605 << New->getDeclName()
606 << NewParam->getDefaultArgRange();
607 } else if (New->getDeclContext()->isDependentContext()) {
608 // C++ [dcl.fct.default]p6 (DR217):
609 // Default arguments for a member function of a class template shall
610 // be specified on the initial declaration of the member function
611 // within the class template.
612 //
613 // Reading the tea leaves a bit in DR217 and its reference to DR205
614 // leads me to the conclusion that one cannot add default function
615 // arguments for an out-of-line definition of a member function of a
616 // dependent type.
617 int WhichKind = 2;
618 if (CXXRecordDecl *Record
619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620 if (Record->getDescribedClassTemplate())
621 WhichKind = 0;
622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623 WhichKind = 1;
624 else
625 WhichKind = 2;
626 }
627
628 Diag(NewParam->getLocation(),
629 diag::err_param_default_argument_member_template_redecl)
630 << WhichKind
631 << NewParam->getDefaultArgRange();
632 }
633 }
634 }
635
636 // DR1344: If a default argument is added outside a class definition and that
637 // default argument makes the function a special member function, the program
638 // is ill-formed. This can only happen for constructors.
639 if (isa<CXXConstructorDecl>(New) &&
640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643 if (NewSM != OldSM) {
644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645 assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 645, __PRETTY_FUNCTION__))
;
646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647 << NewParam->getDefaultArgRange() << NewSM;
648 Diag(Old->getLocation(), diag::note_previous_declaration);
649 }
650 }
651
652 const FunctionDecl *Def;
653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654 // template has a constexpr specifier then all its declarations shall
655 // contain the constexpr specifier.
656 if (New->getConstexprKind() != Old->getConstexprKind()) {
657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658 << New << static_cast<int>(New->getConstexprKind())
659 << static_cast<int>(Old->getConstexprKind());
660 Diag(Old->getLocation(), diag::note_previous_declaration);
661 Invalid = true;
662 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
663 Old->isDefined(Def) &&
664 // If a friend function is inlined but does not have 'inline'
665 // specifier, it is a definition. Do not report attribute conflict
666 // in this case, redefinition will be diagnosed later.
667 (New->isInlineSpecified() ||
668 New->getFriendObjectKind() == Decl::FOK_None)) {
669 // C++11 [dcl.fcn.spec]p4:
670 // If the definition of a function appears in a translation unit before its
671 // first declaration as inline, the program is ill-formed.
672 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
673 Diag(Def->getLocation(), diag::note_previous_definition);
674 Invalid = true;
675 }
676
677 // C++17 [temp.deduct.guide]p3:
678 // Two deduction guide declarations in the same translation unit
679 // for the same class template shall not have equivalent
680 // parameter-declaration-clauses.
681 if (isa<CXXDeductionGuideDecl>(New) &&
682 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
683 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
684 Diag(Old->getLocation(), diag::note_previous_declaration);
685 }
686
687 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
688 // argument expression, that declaration shall be a definition and shall be
689 // the only declaration of the function or function template in the
690 // translation unit.
691 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
692 functionDeclHasDefaultArgument(Old)) {
693 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
694 Diag(Old->getLocation(), diag::note_previous_declaration);
695 Invalid = true;
696 }
697
698 // C++11 [temp.friend]p4 (DR329):
699 // When a function is defined in a friend function declaration in a class
700 // template, the function is instantiated when the function is odr-used.
701 // The same restrictions on multiple declarations and definitions that
702 // apply to non-template function declarations and definitions also apply
703 // to these implicit definitions.
704 const FunctionDecl *OldDefinition = nullptr;
705 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
706 Old->isDefined(OldDefinition, true))
707 CheckForFunctionRedefinition(New, OldDefinition);
708
709 return Invalid;
710}
711
712NamedDecl *
713Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
714 MultiTemplateParamsArg TemplateParamLists) {
715 assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 715, __PRETTY_FUNCTION__))
;
716 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
717
718 // The syntax only allows a decomposition declarator as a simple-declaration,
719 // a for-range-declaration, or a condition in Clang, but we parse it in more
720 // cases than that.
721 if (!D.mayHaveDecompositionDeclarator()) {
722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
723 << Decomp.getSourceRange();
724 return nullptr;
725 }
726
727 if (!TemplateParamLists.empty()) {
728 // FIXME: There's no rule against this, but there are also no rules that
729 // would actually make it usable, so we reject it for now.
730 Diag(TemplateParamLists.front()->getTemplateLoc(),
731 diag::err_decomp_decl_template);
732 return nullptr;
733 }
734
735 Diag(Decomp.getLSquareLoc(),
736 !getLangOpts().CPlusPlus17
737 ? diag::ext_decomp_decl
738 : D.getContext() == DeclaratorContext::Condition
739 ? diag::ext_decomp_decl_cond
740 : diag::warn_cxx14_compat_decomp_decl)
741 << Decomp.getSourceRange();
742
743 // The semantic context is always just the current context.
744 DeclContext *const DC = CurContext;
745
746 // C++17 [dcl.dcl]/8:
747 // The decl-specifier-seq shall contain only the type-specifier auto
748 // and cv-qualifiers.
749 // C++2a [dcl.dcl]/8:
750 // If decl-specifier-seq contains any decl-specifier other than static,
751 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
752 auto &DS = D.getDeclSpec();
753 {
754 SmallVector<StringRef, 8> BadSpecifiers;
755 SmallVector<SourceLocation, 8> BadSpecifierLocs;
756 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
757 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
758 if (auto SCS = DS.getStorageClassSpec()) {
759 if (SCS == DeclSpec::SCS_static) {
760 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
761 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762 } else {
763 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
764 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
765 }
766 }
767 if (auto TSCS = DS.getThreadStorageClassSpec()) {
768 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
769 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
770 }
771 if (DS.hasConstexprSpecifier()) {
772 BadSpecifiers.push_back(
773 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
774 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
775 }
776 if (DS.isInlineSpecified()) {
777 BadSpecifiers.push_back("inline");
778 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
779 }
780 if (!BadSpecifiers.empty()) {
781 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
782 Err << (int)BadSpecifiers.size()
783 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
784 // Don't add FixItHints to remove the specifiers; we do still respect
785 // them when building the underlying variable.
786 for (auto Loc : BadSpecifierLocs)
787 Err << SourceRange(Loc, Loc);
788 } else if (!CPlusPlus20Specifiers.empty()) {
789 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
790 getLangOpts().CPlusPlus20
791 ? diag::warn_cxx17_compat_decomp_decl_spec
792 : diag::ext_decomp_decl_spec);
793 Warn << (int)CPlusPlus20Specifiers.size()
794 << llvm::join(CPlusPlus20Specifiers.begin(),
795 CPlusPlus20Specifiers.end(), " ");
796 for (auto Loc : CPlusPlus20SpecifierLocs)
797 Warn << SourceRange(Loc, Loc);
798 }
799 // We can't recover from it being declared as a typedef.
800 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
801 return nullptr;
802 }
803
804 // C++2a [dcl.struct.bind]p1:
805 // A cv that includes volatile is deprecated
806 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
807 getLangOpts().CPlusPlus20)
808 Diag(DS.getVolatileSpecLoc(),
809 diag::warn_deprecated_volatile_structured_binding);
810
811 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
812 QualType R = TInfo->getType();
813
814 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
815 UPPC_DeclarationType))
816 D.setInvalidType();
817
818 // The syntax only allows a single ref-qualifier prior to the decomposition
819 // declarator. No other declarator chunks are permitted. Also check the type
820 // specifier here.
821 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
822 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
823 (D.getNumTypeObjects() == 1 &&
824 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
825 Diag(Decomp.getLSquareLoc(),
826 (D.hasGroupingParens() ||
827 (D.getNumTypeObjects() &&
828 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
829 ? diag::err_decomp_decl_parens
830 : diag::err_decomp_decl_type)
831 << R;
832
833 // In most cases, there's no actual problem with an explicitly-specified
834 // type, but a function type won't work here, and ActOnVariableDeclarator
835 // shouldn't be called for such a type.
836 if (R->isFunctionType())
837 D.setInvalidType();
838 }
839
840 // Build the BindingDecls.
841 SmallVector<BindingDecl*, 8> Bindings;
842
843 // Build the BindingDecls.
844 for (auto &B : D.getDecompositionDeclarator().bindings()) {
845 // Check for name conflicts.
846 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848 ForVisibleRedeclaration);
849 LookupName(Previous, S,
850 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
851
852 // It's not permitted to shadow a template parameter name.
853 if (Previous.isSingleResult() &&
854 Previous.getFoundDecl()->isTemplateParameter()) {
855 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
856 Previous.getFoundDecl());
857 Previous.clear();
858 }
859
860 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
861 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
862 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
863 /*AllowInlineNamespace*/false);
864 if (!Previous.empty()) {
865 auto *Old = Previous.getRepresentativeDecl();
866 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
867 Diag(Old->getLocation(), diag::note_previous_definition);
868 }
869
870 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
871 PushOnScopeChains(BD, S, true);
872 Bindings.push_back(BD);
873 ParsingInitForAutoVars.insert(BD);
874 }
875
876 // There are no prior lookup results for the variable itself, because it
877 // is unnamed.
878 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
879 Decomp.getLSquareLoc());
880 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
881 ForVisibleRedeclaration);
882
883 // Build the variable that holds the non-decomposed object.
884 bool AddToScope = true;
885 NamedDecl *New =
886 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
887 MultiTemplateParamsArg(), AddToScope, Bindings);
888 if (AddToScope) {
889 S->AddDecl(New);
890 CurContext->addHiddenDecl(New);
891 }
892
893 if (isInOpenMPDeclareTargetContext())
894 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
895
896 return New;
897}
898
899static bool checkSimpleDecomposition(
900 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
901 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
902 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
903 if ((int64_t)Bindings.size() != NumElems) {
904 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
905 << DecompType << (unsigned)Bindings.size()
906 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U)) << NumElems.toString(10)
907 << (NumElems < Bindings.size());
908 return true;
909 }
910
911 unsigned I = 0;
912 for (auto *B : Bindings) {
913 SourceLocation Loc = B->getLocation();
914 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
915 if (E.isInvalid())
916 return true;
917 E = GetInit(Loc, E.get(), I++);
918 if (E.isInvalid())
919 return true;
920 B->setBinding(ElemType, E.get());
921 }
922
923 return false;
924}
925
926static bool checkArrayLikeDecomposition(Sema &S,
927 ArrayRef<BindingDecl *> Bindings,
928 ValueDecl *Src, QualType DecompType,
929 const llvm::APSInt &NumElems,
930 QualType ElemType) {
931 return checkSimpleDecomposition(
932 S, Bindings, Src, DecompType, NumElems, ElemType,
933 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
934 ExprResult E = S.ActOnIntegerConstant(Loc, I);
935 if (E.isInvalid())
936 return ExprError();
937 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
938 });
939}
940
941static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
942 ValueDecl *Src, QualType DecompType,
943 const ConstantArrayType *CAT) {
944 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
945 llvm::APSInt(CAT->getSize()),
946 CAT->getElementType());
947}
948
949static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
950 ValueDecl *Src, QualType DecompType,
951 const VectorType *VT) {
952 return checkArrayLikeDecomposition(
953 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
954 S.Context.getQualifiedType(VT->getElementType(),
955 DecompType.getQualifiers()));
956}
957
958static bool checkComplexDecomposition(Sema &S,
959 ArrayRef<BindingDecl *> Bindings,
960 ValueDecl *Src, QualType DecompType,
961 const ComplexType *CT) {
962 return checkSimpleDecomposition(
963 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
964 S.Context.getQualifiedType(CT->getElementType(),
965 DecompType.getQualifiers()),
966 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
967 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
968 });
969}
970
971static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
972 TemplateArgumentListInfo &Args) {
973 SmallString<128> SS;
974 llvm::raw_svector_ostream OS(SS);
975 bool First = true;
976 for (auto &Arg : Args.arguments()) {
977 if (!First)
978 OS << ", ";
979 Arg.getArgument().print(PrintingPolicy, OS);
980 First = false;
981 }
982 return std::string(OS.str());
983}
984
985static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
986 SourceLocation Loc, StringRef Trait,
987 TemplateArgumentListInfo &Args,
988 unsigned DiagID) {
989 auto DiagnoseMissing = [&] {
990 if (DiagID)
991 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
992 Args);
993 return true;
994 };
995
996 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
997 NamespaceDecl *Std = S.getStdNamespace();
998 if (!Std)
999 return DiagnoseMissing();
1000
1001 // Look up the trait itself, within namespace std. We can diagnose various
1002 // problems with this lookup even if we've been asked to not diagnose a
1003 // missing specialization, because this can only fail if the user has been
1004 // declaring their own names in namespace std or we don't support the
1005 // standard library implementation in use.
1006 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1007 Loc, Sema::LookupOrdinaryName);
1008 if (!S.LookupQualifiedName(Result, Std))
1009 return DiagnoseMissing();
1010 if (Result.isAmbiguous())
1011 return true;
1012
1013 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1014 if (!TraitTD) {
1015 Result.suppressDiagnostics();
1016 NamedDecl *Found = *Result.begin();
1017 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1018 S.Diag(Found->getLocation(), diag::note_declared_at);
1019 return true;
1020 }
1021
1022 // Build the template-id.
1023 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1024 if (TraitTy.isNull())
1025 return true;
1026 if (!S.isCompleteType(Loc, TraitTy)) {
1027 if (DiagID)
1028 S.RequireCompleteType(
1029 Loc, TraitTy, DiagID,
1030 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1031 return true;
1032 }
1033
1034 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1035 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
;
1036
1037 // Look up the member of the trait type.
1038 S.LookupQualifiedName(TraitMemberLookup, RD);
1039 return TraitMemberLookup.isAmbiguous();
1040}
1041
1042static TemplateArgumentLoc
1043getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1044 uint64_t I) {
1045 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1046 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1047}
1048
1049static TemplateArgumentLoc
1050getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1051 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1052}
1053
1054namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1055
1056static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1057 llvm::APSInt &Size) {
1058 EnterExpressionEvaluationContext ContextRAII(
1059 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1060
1061 DeclarationName Value = S.PP.getIdentifierInfo("value");
1062 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1063
1064 // Form template argument list for tuple_size<T>.
1065 TemplateArgumentListInfo Args(Loc, Loc);
1066 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1067
1068 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1069 // it's not tuple-like.
1070 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1071 R.empty())
1072 return IsTupleLike::NotTupleLike;
1073
1074 // If we get this far, we've committed to the tuple interpretation, but
1075 // we can still fail if there actually isn't a usable ::value.
1076
1077 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1078 LookupResult &R;
1079 TemplateArgumentListInfo &Args;
1080 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1081 : R(R), Args(Args) {}
1082 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1083 SourceLocation Loc) override {
1084 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1085 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1086 }
1087 } Diagnoser(R, Args);
1088
1089 ExprResult E =
1090 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1091 if (E.isInvalid())
1092 return IsTupleLike::Error;
1093
1094 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1095 if (E.isInvalid())
1096 return IsTupleLike::Error;
1097
1098 return IsTupleLike::TupleLike;
1099}
1100
1101/// \return std::tuple_element<I, T>::type.
1102static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1103 unsigned I, QualType T) {
1104 // Form template argument list for tuple_element<I, T>.
1105 TemplateArgumentListInfo Args(Loc, Loc);
1106 Args.addArgument(
1107 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1108 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1109
1110 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1111 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1112 if (lookupStdTypeTraitMember(
1113 S, R, Loc, "tuple_element", Args,
1114 diag::err_decomp_decl_std_tuple_element_not_specialized))
1115 return QualType();
1116
1117 auto *TD = R.getAsSingle<TypeDecl>();
1118 if (!TD) {
1119 R.suppressDiagnostics();
1120 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1121 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1122 if (!R.empty())
1123 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1124 return QualType();
1125 }
1126
1127 return S.Context.getTypeDeclType(TD);
1128}
1129
1130namespace {
1131struct InitializingBinding {
1132 Sema &S;
1133 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1134 Sema::CodeSynthesisContext Ctx;
1135 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1136 Ctx.PointOfInstantiation = BD->getLocation();
1137 Ctx.Entity = BD;
1138 S.pushCodeSynthesisContext(Ctx);
1139 }
1140 ~InitializingBinding() {
1141 S.popCodeSynthesisContext();
1142 }
1143};
1144}
1145
1146static bool checkTupleLikeDecomposition(Sema &S,
1147 ArrayRef<BindingDecl *> Bindings,
1148 VarDecl *Src, QualType DecompType,
1149 const llvm::APSInt &TupleSize) {
1150 if ((int64_t)Bindings.size() != TupleSize) {
1151 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1152 << DecompType << (unsigned)Bindings.size()
1153 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1154 << TupleSize.toString(10) << (TupleSize < Bindings.size());
1155 return true;
1156 }
1157
1158 if (Bindings.empty())
1159 return false;
1160
1161 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1162
1163 // [dcl.decomp]p3:
1164 // The unqualified-id get is looked up in the scope of E by class member
1165 // access lookup ...
1166 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1167 bool UseMemberGet = false;
1168 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1169 if (auto *RD = DecompType->getAsCXXRecordDecl())
1170 S.LookupQualifiedName(MemberGet, RD);
1171 if (MemberGet.isAmbiguous())
1172 return true;
1173 // ... and if that finds at least one declaration that is a function
1174 // template whose first template parameter is a non-type parameter ...
1175 for (NamedDecl *D : MemberGet) {
1176 if (FunctionTemplateDecl *FTD =
1177 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1178 TemplateParameterList *TPL = FTD->getTemplateParameters();
1179 if (TPL->size() != 0 &&
1180 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1181 // ... the initializer is e.get<i>().
1182 UseMemberGet = true;
1183 break;
1184 }
1185 }
1186 }
1187 }
1188
1189 unsigned I = 0;
1190 for (auto *B : Bindings) {
1191 InitializingBinding InitContext(S, B);
1192 SourceLocation Loc = B->getLocation();
1193
1194 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1195 if (E.isInvalid())
1196 return true;
1197
1198 // e is an lvalue if the type of the entity is an lvalue reference and
1199 // an xvalue otherwise
1200 if (!Src->getType()->isLValueReferenceType())
1201 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1202 E.get(), nullptr, VK_XValue,
1203 FPOptionsOverride());
1204
1205 TemplateArgumentListInfo Args(Loc, Loc);
1206 Args.addArgument(
1207 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1208
1209 if (UseMemberGet) {
1210 // if [lookup of member get] finds at least one declaration, the
1211 // initializer is e.get<i-1>().
1212 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1213 CXXScopeSpec(), SourceLocation(), nullptr,
1214 MemberGet, &Args, nullptr);
1215 if (E.isInvalid())
1216 return true;
1217
1218 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1219 } else {
1220 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1221 // in the associated namespaces.
1222 Expr *Get = UnresolvedLookupExpr::Create(
1223 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1224 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1225 UnresolvedSetIterator(), UnresolvedSetIterator());
1226
1227 Expr *Arg = E.get();
1228 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1229 }
1230 if (E.isInvalid())
1231 return true;
1232 Expr *Init = E.get();
1233
1234 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1235 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1236 if (T.isNull())
1237 return true;
1238
1239 // each vi is a variable of type "reference to T" initialized with the
1240 // initializer, where the reference is an lvalue reference if the
1241 // initializer is an lvalue and an rvalue reference otherwise
1242 QualType RefType =
1243 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1244 if (RefType.isNull())
1245 return true;
1246 auto *RefVD = VarDecl::Create(
1247 S.Context, Src->getDeclContext(), Loc, Loc,
1248 B->getDeclName().getAsIdentifierInfo(), RefType,
1249 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1250 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1251 RefVD->setTSCSpec(Src->getTSCSpec());
1252 RefVD->setImplicit();
1253 if (Src->isInlineSpecified())
1254 RefVD->setInlineSpecified();
1255 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1256
1257 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1258 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1259 InitializationSequence Seq(S, Entity, Kind, Init);
1260 E = Seq.Perform(S, Entity, Kind, Init);
1261 if (E.isInvalid())
1262 return true;
1263 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1264 if (E.isInvalid())
1265 return true;
1266 RefVD->setInit(E.get());
1267 S.CheckCompleteVariableDeclaration(RefVD);
1268
1269 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1270 DeclarationNameInfo(B->getDeclName(), Loc),
1271 RefVD);
1272 if (E.isInvalid())
1273 return true;
1274
1275 B->setBinding(T, E.get());
1276 I++;
1277 }
1278
1279 return false;
1280}
1281
1282/// Find the base class to decompose in a built-in decomposition of a class type.
1283/// This base class search is, unfortunately, not quite like any other that we
1284/// perform anywhere else in C++.
1285static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1286 const CXXRecordDecl *RD,
1287 CXXCastPath &BasePath) {
1288 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1289 CXXBasePath &Path) {
1290 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1291 };
1292
1293 const CXXRecordDecl *ClassWithFields = nullptr;
1294 AccessSpecifier AS = AS_public;
1295 if (RD->hasDirectFields())
1296 // [dcl.decomp]p4:
1297 // Otherwise, all of E's non-static data members shall be public direct
1298 // members of E ...
1299 ClassWithFields = RD;
1300 else {
1301 // ... or of ...
1302 CXXBasePaths Paths;
1303 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1304 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1305 // If no classes have fields, just decompose RD itself. (This will work
1306 // if and only if zero bindings were provided.)
1307 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1308 }
1309
1310 CXXBasePath *BestPath = nullptr;
1311 for (auto &P : Paths) {
1312 if (!BestPath)
1313 BestPath = &P;
1314 else if (!S.Context.hasSameType(P.back().Base->getType(),
1315 BestPath->back().Base->getType())) {
1316 // ... the same ...
1317 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1318 << false << RD << BestPath->back().Base->getType()
1319 << P.back().Base->getType();
1320 return DeclAccessPair();
1321 } else if (P.Access < BestPath->Access) {
1322 BestPath = &P;
1323 }
1324 }
1325
1326 // ... unambiguous ...
1327 QualType BaseType = BestPath->back().Base->getType();
1328 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1329 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1330 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1331 return DeclAccessPair();
1332 }
1333
1334 // ... [accessible, implied by other rules] base class of E.
1335 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1336 *BestPath, diag::err_decomp_decl_inaccessible_base);
1337 AS = BestPath->Access;
1338
1339 ClassWithFields = BaseType->getAsCXXRecordDecl();
1340 S.BuildBasePathArray(Paths, BasePath);
1341 }
1342
1343 // The above search did not check whether the selected class itself has base
1344 // classes with fields, so check that now.
1345 CXXBasePaths Paths;
1346 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1347 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1348 << (ClassWithFields == RD) << RD << ClassWithFields
1349 << Paths.front().back().Base->getType();
1350 return DeclAccessPair();
1351 }
1352
1353 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1354}
1355
1356static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1357 ValueDecl *Src, QualType DecompType,
1358 const CXXRecordDecl *OrigRD) {
1359 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1360 diag::err_incomplete_type))
1361 return true;
1362
1363 CXXCastPath BasePath;
1364 DeclAccessPair BasePair =
1365 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1366 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1367 if (!RD)
1368 return true;
1369 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1370 DecompType.getQualifiers());
1371
1372 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1373 unsigned NumFields =
1374 std::count_if(RD->field_begin(), RD->field_end(),
1375 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1376 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1376, __PRETTY_FUNCTION__))
;
1377 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1378 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1379 << (NumFields < Bindings.size());
1380 return true;
1381 };
1382
1383 // all of E's non-static data members shall be [...] well-formed
1384 // when named as e.name in the context of the structured binding,
1385 // E shall not have an anonymous union member, ...
1386 unsigned I = 0;
1387 for (auto *FD : RD->fields()) {
1388 if (FD->isUnnamedBitfield())
1389 continue;
1390
1391 // All the non-static data members are required to be nameable, so they
1392 // must all have names.
1393 if (!FD->getDeclName()) {
1394 if (RD->isLambda()) {
1395 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1396 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1397 return true;
1398 }
1399
1400 if (FD->isAnonymousStructOrUnion()) {
1401 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1402 << DecompType << FD->getType()->isUnionType();
1403 S.Diag(FD->getLocation(), diag::note_declared_at);
1404 return true;
1405 }
1406
1407 // FIXME: Are there any other ways we could have an anonymous member?
1408 }
1409
1410 // We have a real field to bind.
1411 if (I >= Bindings.size())
1412 return DiagnoseBadNumberOfBindings();
1413 auto *B = Bindings[I++];
1414 SourceLocation Loc = B->getLocation();
1415
1416 // The field must be accessible in the context of the structured binding.
1417 // We already checked that the base class is accessible.
1418 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1419 // const_cast here.
1420 S.CheckStructuredBindingMemberAccess(
1421 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1422 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1423 BasePair.getAccess(), FD->getAccess())));
1424
1425 // Initialize the binding to Src.FD.
1426 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1427 if (E.isInvalid())
1428 return true;
1429 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1430 VK_LValue, &BasePath);
1431 if (E.isInvalid())
1432 return true;
1433 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1434 CXXScopeSpec(), FD,
1435 DeclAccessPair::make(FD, FD->getAccess()),
1436 DeclarationNameInfo(FD->getDeclName(), Loc));
1437 if (E.isInvalid())
1438 return true;
1439
1440 // If the type of the member is T, the referenced type is cv T, where cv is
1441 // the cv-qualification of the decomposition expression.
1442 //
1443 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1444 // 'const' to the type of the field.
1445 Qualifiers Q = DecompType.getQualifiers();
1446 if (FD->isMutable())
1447 Q.removeConst();
1448 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1449 }
1450
1451 if (I != Bindings.size())
1452 return DiagnoseBadNumberOfBindings();
1453
1454 return false;
1455}
1456
1457void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1458 QualType DecompType = DD->getType();
1459
1460 // If the type of the decomposition is dependent, then so is the type of
1461 // each binding.
1462 if (DecompType->isDependentType()) {
1463 for (auto *B : DD->bindings())
1464 B->setType(Context.DependentTy);
1465 return;
1466 }
1467
1468 DecompType = DecompType.getNonReferenceType();
1469 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1470
1471 // C++1z [dcl.decomp]/2:
1472 // If E is an array type [...]
1473 // As an extension, we also support decomposition of built-in complex and
1474 // vector types.
1475 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1476 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1477 DD->setInvalidDecl();
1478 return;
1479 }
1480 if (auto *VT = DecompType->getAs<VectorType>()) {
1481 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1482 DD->setInvalidDecl();
1483 return;
1484 }
1485 if (auto *CT = DecompType->getAs<ComplexType>()) {
1486 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1487 DD->setInvalidDecl();
1488 return;
1489 }
1490
1491 // C++1z [dcl.decomp]/3:
1492 // if the expression std::tuple_size<E>::value is a well-formed integral
1493 // constant expression, [...]
1494 llvm::APSInt TupleSize(32);
1495 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1496 case IsTupleLike::Error:
1497 DD->setInvalidDecl();
1498 return;
1499
1500 case IsTupleLike::TupleLike:
1501 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1502 DD->setInvalidDecl();
1503 return;
1504
1505 case IsTupleLike::NotTupleLike:
1506 break;
1507 }
1508
1509 // C++1z [dcl.dcl]/8:
1510 // [E shall be of array or non-union class type]
1511 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1512 if (!RD || RD->isUnion()) {
1513 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1514 << DD << !RD << DecompType;
1515 DD->setInvalidDecl();
1516 return;
1517 }
1518
1519 // C++1z [dcl.decomp]/4:
1520 // all of E's non-static data members shall be [...] direct members of
1521 // E or of the same unambiguous public base class of E, ...
1522 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1523 DD->setInvalidDecl();
1524}
1525
1526/// Merge the exception specifications of two variable declarations.
1527///
1528/// This is called when there's a redeclaration of a VarDecl. The function
1529/// checks if the redeclaration might have an exception specification and
1530/// validates compatibility and merges the specs if necessary.
1531void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1532 // Shortcut if exceptions are disabled.
1533 if (!getLangOpts().CXXExceptions)
1534 return;
1535
1536 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1537, __PRETTY_FUNCTION__))
1537 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1537, __PRETTY_FUNCTION__))
;
1538
1539 QualType NewType = New->getType();
1540 QualType OldType = Old->getType();
1541
1542 // We're only interested in pointers and references to functions, as well
1543 // as pointers to member functions.
1544 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1545 NewType = R->getPointeeType();
1546 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1547 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1548 NewType = P->getPointeeType();
1549 OldType = OldType->castAs<PointerType>()->getPointeeType();
1550 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1551 NewType = M->getPointeeType();
1552 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1553 }
1554
1555 if (!NewType->isFunctionProtoType())
1556 return;
1557
1558 // There's lots of special cases for functions. For function pointers, system
1559 // libraries are hopefully not as broken so that we don't need these
1560 // workarounds.
1561 if (CheckEquivalentExceptionSpec(
1562 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1563 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1564 New->setInvalidDecl();
1565 }
1566}
1567
1568/// CheckCXXDefaultArguments - Verify that the default arguments for a
1569/// function declaration are well-formed according to C++
1570/// [dcl.fct.default].
1571void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1572 unsigned NumParams = FD->getNumParams();
1573 unsigned ParamIdx = 0;
1574
1575 // This checking doesn't make sense for explicit specializations; their
1576 // default arguments are determined by the declaration we're specializing,
1577 // not by FD.
1578 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1579 return;
1580 if (auto *FTD = FD->getDescribedFunctionTemplate())
1581 if (FTD->isMemberSpecialization())
1582 return;
1583
1584 // Find first parameter with a default argument
1585 for (; ParamIdx < NumParams; ++ParamIdx) {
1586 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1587 if (Param->hasDefaultArg())
1588 break;
1589 }
1590
1591 // C++20 [dcl.fct.default]p4:
1592 // In a given function declaration, each parameter subsequent to a parameter
1593 // with a default argument shall have a default argument supplied in this or
1594 // a previous declaration, unless the parameter was expanded from a
1595 // parameter pack, or shall be a function parameter pack.
1596 for (; ParamIdx < NumParams; ++ParamIdx) {
1597 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1598 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1599 !(CurrentInstantiationScope &&
1600 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1601 if (Param->isInvalidDecl())
1602 /* We already complained about this parameter. */;
1603 else if (Param->getIdentifier())
1604 Diag(Param->getLocation(),
1605 diag::err_param_default_argument_missing_name)
1606 << Param->getIdentifier();
1607 else
1608 Diag(Param->getLocation(),
1609 diag::err_param_default_argument_missing);
1610 }
1611 }
1612}
1613
1614/// Check that the given type is a literal type. Issue a diagnostic if not,
1615/// if Kind is Diagnose.
1616/// \return \c true if a problem has been found (and optionally diagnosed).
1617template <typename... Ts>
1618static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1619 SourceLocation Loc, QualType T, unsigned DiagID,
1620 Ts &&...DiagArgs) {
1621 if (T->isDependentType())
1622 return false;
1623
1624 switch (Kind) {
1625 case Sema::CheckConstexprKind::Diagnose:
1626 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1627 std::forward<Ts>(DiagArgs)...);
1628
1629 case Sema::CheckConstexprKind::CheckValid:
1630 return !T->isLiteralType(SemaRef.Context);
1631 }
1632
1633 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1633)
;
1634}
1635
1636/// Determine whether a destructor cannot be constexpr due to
1637static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1638 const CXXDestructorDecl *DD,
1639 Sema::CheckConstexprKind Kind) {
1640 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1641 const CXXRecordDecl *RD =
1642 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1643 if (!RD || RD->hasConstexprDestructor())
1644 return true;
1645
1646 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1647 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1648 << static_cast<int>(DD->getConstexprKind()) << !FD
1649 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1650 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1651 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1652 }
1653 return false;
1654 };
1655
1656 const CXXRecordDecl *RD = DD->getParent();
1657 for (const CXXBaseSpecifier &B : RD->bases())
1658 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1659 return false;
1660 for (const FieldDecl *FD : RD->fields())
1661 if (!Check(FD->getLocation(), FD->getType(), FD))
1662 return false;
1663 return true;
1664}
1665
1666/// Check whether a function's parameter types are all literal types. If so,
1667/// return true. If not, produce a suitable diagnostic and return false.
1668static bool CheckConstexprParameterTypes(Sema &SemaRef,
1669 const FunctionDecl *FD,
1670 Sema::CheckConstexprKind Kind) {
1671 unsigned ArgIndex = 0;
1672 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1673 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1674 e = FT->param_type_end();
1675 i != e; ++i, ++ArgIndex) {
1676 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1677 SourceLocation ParamLoc = PD->getLocation();
1678 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1679 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1680 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1681 FD->isConsteval()))
1682 return false;
1683 }
1684 return true;
1685}
1686
1687/// Check whether a function's return type is a literal type. If so, return
1688/// true. If not, produce a suitable diagnostic and return false.
1689static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1690 Sema::CheckConstexprKind Kind) {
1691 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1692 diag::err_constexpr_non_literal_return,
1693 FD->isConsteval()))
1694 return false;
1695 return true;
1696}
1697
1698/// Get diagnostic %select index for tag kind for
1699/// record diagnostic message.
1700/// WARNING: Indexes apply to particular diagnostics only!
1701///
1702/// \returns diagnostic %select index.
1703static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1704 switch (Tag) {
1705 case TTK_Struct: return 0;
1706 case TTK_Interface: return 1;
1707 case TTK_Class: return 2;
1708 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1708)
;
1709 }
1710}
1711
1712static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1713 Stmt *Body,
1714 Sema::CheckConstexprKind Kind);
1715
1716// Check whether a function declaration satisfies the requirements of a
1717// constexpr function definition or a constexpr constructor definition. If so,
1718// return true. If not, produce appropriate diagnostics (unless asked not to by
1719// Kind) and return false.
1720//
1721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1722bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1723 CheckConstexprKind Kind) {
1724 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1725 if (MD && MD->isInstance()) {
1726 // C++11 [dcl.constexpr]p4:
1727 // The definition of a constexpr constructor shall satisfy the following
1728 // constraints:
1729 // - the class shall not have any virtual base classes;
1730 //
1731 // FIXME: This only applies to constructors and destructors, not arbitrary
1732 // member functions.
1733 const CXXRecordDecl *RD = MD->getParent();
1734 if (RD->getNumVBases()) {
1735 if (Kind == CheckConstexprKind::CheckValid)
1736 return false;
1737
1738 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1739 << isa<CXXConstructorDecl>(NewFD)
1740 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1741 for (const auto &I : RD->vbases())
1742 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1743 << I.getSourceRange();
1744 return false;
1745 }
1746 }
1747
1748 if (!isa<CXXConstructorDecl>(NewFD)) {
1749 // C++11 [dcl.constexpr]p3:
1750 // The definition of a constexpr function shall satisfy the following
1751 // constraints:
1752 // - it shall not be virtual; (removed in C++20)
1753 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1754 if (Method && Method->isVirtual()) {
1755 if (getLangOpts().CPlusPlus20) {
1756 if (Kind == CheckConstexprKind::Diagnose)
1757 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1758 } else {
1759 if (Kind == CheckConstexprKind::CheckValid)
1760 return false;
1761
1762 Method = Method->getCanonicalDecl();
1763 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1764
1765 // If it's not obvious why this function is virtual, find an overridden
1766 // function which uses the 'virtual' keyword.
1767 const CXXMethodDecl *WrittenVirtual = Method;
1768 while (!WrittenVirtual->isVirtualAsWritten())
1769 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1770 if (WrittenVirtual != Method)
1771 Diag(WrittenVirtual->getLocation(),
1772 diag::note_overridden_virtual_function);
1773 return false;
1774 }
1775 }
1776
1777 // - its return type shall be a literal type;
1778 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1779 return false;
1780 }
1781
1782 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1783 // A destructor can be constexpr only if the defaulted destructor could be;
1784 // we don't need to check the members and bases if we already know they all
1785 // have constexpr destructors.
1786 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1787 if (Kind == CheckConstexprKind::CheckValid)
1788 return false;
1789 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1790 return false;
1791 }
1792 }
1793
1794 // - each of its parameter types shall be a literal type;
1795 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1796 return false;
1797
1798 Stmt *Body = NewFD->getBody();
1799 assert(Body &&((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
1800 "CheckConstexprFunctionDefinition called on function with no body")((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
;
1801 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1802}
1803
1804/// Check the given declaration statement is legal within a constexpr function
1805/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1806///
1807/// \return true if the body is OK (maybe only as an extension), false if we
1808/// have diagnosed a problem.
1809static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1810 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1811 Sema::CheckConstexprKind Kind) {
1812 // C++11 [dcl.constexpr]p3 and p4:
1813 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1814 // contain only
1815 for (const auto *DclIt : DS->decls()) {
1816 switch (DclIt->getKind()) {
1817 case Decl::StaticAssert:
1818 case Decl::Using:
1819 case Decl::UsingShadow:
1820 case Decl::UsingDirective:
1821 case Decl::UnresolvedUsingTypename:
1822 case Decl::UnresolvedUsingValue:
1823 // - static_assert-declarations
1824 // - using-declarations,
1825 // - using-directives,
1826 continue;
1827
1828 case Decl::Typedef:
1829 case Decl::TypeAlias: {
1830 // - typedef declarations and alias-declarations that do not define
1831 // classes or enumerations,
1832 const auto *TN = cast<TypedefNameDecl>(DclIt);
1833 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1834 // Don't allow variably-modified types in constexpr functions.
1835 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1836 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1837 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1838 << TL.getSourceRange() << TL.getType()
1839 << isa<CXXConstructorDecl>(Dcl);
1840 }
1841 return false;
1842 }
1843 continue;
1844 }
1845
1846 case Decl::Enum:
1847 case Decl::CXXRecord:
1848 // C++1y allows types to be defined, not just declared.
1849 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1850 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851 SemaRef.Diag(DS->getBeginLoc(),
1852 SemaRef.getLangOpts().CPlusPlus14
1853 ? diag::warn_cxx11_compat_constexpr_type_definition
1854 : diag::ext_constexpr_type_definition)
1855 << isa<CXXConstructorDecl>(Dcl);
1856 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1857 return false;
1858 }
1859 }
1860 continue;
1861
1862 case Decl::EnumConstant:
1863 case Decl::IndirectField:
1864 case Decl::ParmVar:
1865 // These can only appear with other declarations which are banned in
1866 // C++11 and permitted in C++1y, so ignore them.
1867 continue;
1868
1869 case Decl::Var:
1870 case Decl::Decomposition: {
1871 // C++1y [dcl.constexpr]p3 allows anything except:
1872 // a definition of a variable of non-literal type or of static or
1873 // thread storage duration or [before C++2a] for which no
1874 // initialization is performed.
1875 const auto *VD = cast<VarDecl>(DclIt);
1876 if (VD->isThisDeclarationADefinition()) {
1877 if (VD->isStaticLocal()) {
1878 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879 SemaRef.Diag(VD->getLocation(),
1880 diag::err_constexpr_local_var_static)
1881 << isa<CXXConstructorDecl>(Dcl)
1882 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1883 }
1884 return false;
1885 }
1886 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1887 diag::err_constexpr_local_var_non_literal_type,
1888 isa<CXXConstructorDecl>(Dcl)))
1889 return false;
1890 if (!VD->getType()->isDependentType() &&
1891 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1892 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1893 SemaRef.Diag(
1894 VD->getLocation(),
1895 SemaRef.getLangOpts().CPlusPlus20
1896 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1897 : diag::ext_constexpr_local_var_no_init)
1898 << isa<CXXConstructorDecl>(Dcl);
1899 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1900 return false;
1901 }
1902 continue;
1903 }
1904 }
1905 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1906 SemaRef.Diag(VD->getLocation(),
1907 SemaRef.getLangOpts().CPlusPlus14
1908 ? diag::warn_cxx11_compat_constexpr_local_var
1909 : diag::ext_constexpr_local_var)
1910 << isa<CXXConstructorDecl>(Dcl);
1911 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1912 return false;
1913 }
1914 continue;
1915 }
1916
1917 case Decl::NamespaceAlias:
1918 case Decl::Function:
1919 // These are disallowed in C++11 and permitted in C++1y. Allow them
1920 // everywhere as an extension.
1921 if (!Cxx1yLoc.isValid())
1922 Cxx1yLoc = DS->getBeginLoc();
1923 continue;
1924
1925 default:
1926 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1927 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1928 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1929 }
1930 return false;
1931 }
1932 }
1933
1934 return true;
1935}
1936
1937/// Check that the given field is initialized within a constexpr constructor.
1938///
1939/// \param Dcl The constexpr constructor being checked.
1940/// \param Field The field being checked. This may be a member of an anonymous
1941/// struct or union nested within the class being checked.
1942/// \param Inits All declarations, including anonymous struct/union members and
1943/// indirect members, for which any initialization was provided.
1944/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1945/// multiple notes for different members to the same error.
1946/// \param Kind Whether we're diagnosing a constructor as written or determining
1947/// whether the formal requirements are satisfied.
1948/// \return \c false if we're checking for validity and the constructor does
1949/// not satisfy the requirements on a constexpr constructor.
1950static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1951 const FunctionDecl *Dcl,
1952 FieldDecl *Field,
1953 llvm::SmallSet<Decl*, 16> &Inits,
1954 bool &Diagnosed,
1955 Sema::CheckConstexprKind Kind) {
1956 // In C++20 onwards, there's nothing to check for validity.
1957 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1958 SemaRef.getLangOpts().CPlusPlus20)
1959 return true;
1960
1961 if (Field->isInvalidDecl())
1962 return true;
1963
1964 if (Field->isUnnamedBitfield())
1965 return true;
1966
1967 // Anonymous unions with no variant members and empty anonymous structs do not
1968 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1969 // indirect fields don't need initializing.
1970 if (Field->isAnonymousStructOrUnion() &&
1971 (Field->getType()->isUnionType()
1972 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1973 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1974 return true;
1975
1976 if (!Inits.count(Field)) {
1977 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1978 if (!Diagnosed) {
1979 SemaRef.Diag(Dcl->getLocation(),
1980 SemaRef.getLangOpts().CPlusPlus20
1981 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1982 : diag::ext_constexpr_ctor_missing_init);
1983 Diagnosed = true;
1984 }
1985 SemaRef.Diag(Field->getLocation(),
1986 diag::note_constexpr_ctor_missing_init);
1987 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1988 return false;
1989 }
1990 } else if (Field->isAnonymousStructOrUnion()) {
1991 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1992 for (auto *I : RD->fields())
1993 // If an anonymous union contains an anonymous struct of which any member
1994 // is initialized, all members must be initialized.
1995 if (!RD->isUnion() || Inits.count(I))
1996 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1997 Kind))
1998 return false;
1999 }
2000 return true;
2001}
2002
2003/// Check the provided statement is allowed in a constexpr function
2004/// definition.
2005static bool
2006CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2007 SmallVectorImpl<SourceLocation> &ReturnStmts,
2008 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2009 Sema::CheckConstexprKind Kind) {
2010 // - its function-body shall be [...] a compound-statement that contains only
2011 switch (S->getStmtClass()) {
2012 case Stmt::NullStmtClass:
2013 // - null statements,
2014 return true;
2015
2016 case Stmt::DeclStmtClass:
2017 // - static_assert-declarations
2018 // - using-declarations,
2019 // - using-directives,
2020 // - typedef declarations and alias-declarations that do not define
2021 // classes or enumerations,
2022 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2023 return false;
2024 return true;
2025
2026 case Stmt::ReturnStmtClass:
2027 // - and exactly one return statement;
2028 if (isa<CXXConstructorDecl>(Dcl)) {
2029 // C++1y allows return statements in constexpr constructors.
2030 if (!Cxx1yLoc.isValid())
2031 Cxx1yLoc = S->getBeginLoc();
2032 return true;
2033 }
2034
2035 ReturnStmts.push_back(S->getBeginLoc());
2036 return true;
2037
2038 case Stmt::CompoundStmtClass: {
2039 // C++1y allows compound-statements.
2040 if (!Cxx1yLoc.isValid())
2041 Cxx1yLoc = S->getBeginLoc();
2042
2043 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2044 for (auto *BodyIt : CompStmt->body()) {
2045 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2046 Cxx1yLoc, Cxx2aLoc, Kind))
2047 return false;
2048 }
2049 return true;
2050 }
2051
2052 case Stmt::AttributedStmtClass:
2053 if (!Cxx1yLoc.isValid())
2054 Cxx1yLoc = S->getBeginLoc();
2055 return true;
2056
2057 case Stmt::IfStmtClass: {
2058 // C++1y allows if-statements.
2059 if (!Cxx1yLoc.isValid())
2060 Cxx1yLoc = S->getBeginLoc();
2061
2062 IfStmt *If = cast<IfStmt>(S);
2063 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2064 Cxx1yLoc, Cxx2aLoc, Kind))
2065 return false;
2066 if (If->getElse() &&
2067 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2068 Cxx1yLoc, Cxx2aLoc, Kind))
2069 return false;
2070 return true;
2071 }
2072
2073 case Stmt::WhileStmtClass:
2074 case Stmt::DoStmtClass:
2075 case Stmt::ForStmtClass:
2076 case Stmt::CXXForRangeStmtClass:
2077 case Stmt::ContinueStmtClass:
2078 // C++1y allows all of these. We don't allow them as extensions in C++11,
2079 // because they don't make sense without variable mutation.
2080 if (!SemaRef.getLangOpts().CPlusPlus14)
2081 break;
2082 if (!Cxx1yLoc.isValid())
2083 Cxx1yLoc = S->getBeginLoc();
2084 for (Stmt *SubStmt : S->children())
2085 if (SubStmt &&
2086 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2087 Cxx1yLoc, Cxx2aLoc, Kind))
2088 return false;
2089 return true;
2090
2091 case Stmt::SwitchStmtClass:
2092 case Stmt::CaseStmtClass:
2093 case Stmt::DefaultStmtClass:
2094 case Stmt::BreakStmtClass:
2095 // C++1y allows switch-statements, and since they don't need variable
2096 // mutation, we can reasonably allow them in C++11 as an extension.
2097 if (!Cxx1yLoc.isValid())
2098 Cxx1yLoc = S->getBeginLoc();
2099 for (Stmt *SubStmt : S->children())
2100 if (SubStmt &&
2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2102 Cxx1yLoc, Cxx2aLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::GCCAsmStmtClass:
2107 case Stmt::MSAsmStmtClass:
2108 // C++2a allows inline assembly statements.
2109 case Stmt::CXXTryStmtClass:
2110 if (Cxx2aLoc.isInvalid())
2111 Cxx2aLoc = S->getBeginLoc();
2112 for (Stmt *SubStmt : S->children()) {
2113 if (SubStmt &&
2114 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2115 Cxx1yLoc, Cxx2aLoc, Kind))
2116 return false;
2117 }
2118 return true;
2119
2120 case Stmt::CXXCatchStmtClass:
2121 // Do not bother checking the language mode (already covered by the
2122 // try block check).
2123 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2124 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2125 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2126 return false;
2127 return true;
2128
2129 default:
2130 if (!isa<Expr>(S))
2131 break;
2132
2133 // C++1y allows expression-statements.
2134 if (!Cxx1yLoc.isValid())
2135 Cxx1yLoc = S->getBeginLoc();
2136 return true;
2137 }
2138
2139 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2140 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2141 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2142 }
2143 return false;
2144}
2145
2146/// Check the body for the given constexpr function declaration only contains
2147/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2148///
2149/// \return true if the body is OK, false if we have found or diagnosed a
2150/// problem.
2151static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2152 Stmt *Body,
2153 Sema::CheckConstexprKind Kind) {
2154 SmallVector<SourceLocation, 4> ReturnStmts;
2155
2156 if (isa<CXXTryStmt>(Body)) {
2157 // C++11 [dcl.constexpr]p3:
2158 // The definition of a constexpr function shall satisfy the following
2159 // constraints: [...]
2160 // - its function-body shall be = delete, = default, or a
2161 // compound-statement
2162 //
2163 // C++11 [dcl.constexpr]p4:
2164 // In the definition of a constexpr constructor, [...]
2165 // - its function-body shall not be a function-try-block;
2166 //
2167 // This restriction is lifted in C++2a, as long as inner statements also
2168 // apply the general constexpr rules.
2169 switch (Kind) {
2170 case Sema::CheckConstexprKind::CheckValid:
2171 if (!SemaRef.getLangOpts().CPlusPlus20)
2172 return false;
2173 break;
2174
2175 case Sema::CheckConstexprKind::Diagnose:
2176 SemaRef.Diag(Body->getBeginLoc(),
2177 !SemaRef.getLangOpts().CPlusPlus20
2178 ? diag::ext_constexpr_function_try_block_cxx20
2179 : diag::warn_cxx17_compat_constexpr_function_try_block)
2180 << isa<CXXConstructorDecl>(Dcl);
2181 break;
2182 }
2183 }
2184
2185 // - its function-body shall be [...] a compound-statement that contains only
2186 // [... list of cases ...]
2187 //
2188 // Note that walking the children here is enough to properly check for
2189 // CompoundStmt and CXXTryStmt body.
2190 SourceLocation Cxx1yLoc, Cxx2aLoc;
2191 for (Stmt *SubStmt : Body->children()) {
2192 if (SubStmt &&
2193 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2194 Cxx1yLoc, Cxx2aLoc, Kind))
2195 return false;
2196 }
2197
2198 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2199 // If this is only valid as an extension, report that we don't satisfy the
2200 // constraints of the current language.
2201 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2202 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2203 return false;
2204 } else if (Cxx2aLoc.isValid()) {
2205 SemaRef.Diag(Cxx2aLoc,
2206 SemaRef.getLangOpts().CPlusPlus20
2207 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2208 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2209 << isa<CXXConstructorDecl>(Dcl);
2210 } else if (Cxx1yLoc.isValid()) {
2211 SemaRef.Diag(Cxx1yLoc,
2212 SemaRef.getLangOpts().CPlusPlus14
2213 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2214 : diag::ext_constexpr_body_invalid_stmt)
2215 << isa<CXXConstructorDecl>(Dcl);
2216 }
2217
2218 if (const CXXConstructorDecl *Constructor
2219 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2220 const CXXRecordDecl *RD = Constructor->getParent();
2221 // DR1359:
2222 // - every non-variant non-static data member and base class sub-object
2223 // shall be initialized;
2224 // DR1460:
2225 // - if the class is a union having variant members, exactly one of them
2226 // shall be initialized;
2227 if (RD->isUnion()) {
2228 if (Constructor->getNumCtorInitializers() == 0 &&
2229 RD->hasVariantMembers()) {
2230 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2231 SemaRef.Diag(
2232 Dcl->getLocation(),
2233 SemaRef.getLangOpts().CPlusPlus20
2234 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2235 : diag::ext_constexpr_union_ctor_no_init);
2236 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2237 return false;
2238 }
2239 }
2240 } else if (!Constructor->isDependentContext() &&
2241 !Constructor->isDelegatingConstructor()) {
2242 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2242, __PRETTY_FUNCTION__))
;
2243
2244 // Skip detailed checking if we have enough initializers, and we would
2245 // allow at most one initializer per member.
2246 bool AnyAnonStructUnionMembers = false;
2247 unsigned Fields = 0;
2248 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2249 E = RD->field_end(); I != E; ++I, ++Fields) {
2250 if (I->isAnonymousStructOrUnion()) {
2251 AnyAnonStructUnionMembers = true;
2252 break;
2253 }
2254 }
2255 // DR1460:
2256 // - if the class is a union-like class, but is not a union, for each of
2257 // its anonymous union members having variant members, exactly one of
2258 // them shall be initialized;
2259 if (AnyAnonStructUnionMembers ||
2260 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2261 // Check initialization of non-static data members. Base classes are
2262 // always initialized so do not need to be checked. Dependent bases
2263 // might not have initializers in the member initializer list.
2264 llvm::SmallSet<Decl*, 16> Inits;
2265 for (const auto *I: Constructor->inits()) {
2266 if (FieldDecl *FD = I->getMember())
2267 Inits.insert(FD);
2268 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2269 Inits.insert(ID->chain_begin(), ID->chain_end());
2270 }
2271
2272 bool Diagnosed = false;
2273 for (auto *I : RD->fields())
2274 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2275 Kind))
2276 return false;
2277 }
2278 }
2279 } else {
2280 if (ReturnStmts.empty()) {
2281 // C++1y doesn't require constexpr functions to contain a 'return'
2282 // statement. We still do, unless the return type might be void, because
2283 // otherwise if there's no return statement, the function cannot
2284 // be used in a core constant expression.
2285 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2286 (Dcl->getReturnType()->isVoidType() ||
2287 Dcl->getReturnType()->isDependentType());
2288 switch (Kind) {
2289 case Sema::CheckConstexprKind::Diagnose:
2290 SemaRef.Diag(Dcl->getLocation(),
2291 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2292 : diag::err_constexpr_body_no_return)
2293 << Dcl->isConsteval();
2294 if (!OK)
2295 return false;
2296 break;
2297
2298 case Sema::CheckConstexprKind::CheckValid:
2299 // The formal requirements don't include this rule in C++14, even
2300 // though the "must be able to produce a constant expression" rules
2301 // still imply it in some cases.
2302 if (!SemaRef.getLangOpts().CPlusPlus14)
2303 return false;
2304 break;
2305 }
2306 } else if (ReturnStmts.size() > 1) {
2307 switch (Kind) {
2308 case Sema::CheckConstexprKind::Diagnose:
2309 SemaRef.Diag(
2310 ReturnStmts.back(),
2311 SemaRef.getLangOpts().CPlusPlus14
2312 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2313 : diag::ext_constexpr_body_multiple_return);
2314 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2315 SemaRef.Diag(ReturnStmts[I],
2316 diag::note_constexpr_body_previous_return);
2317 break;
2318
2319 case Sema::CheckConstexprKind::CheckValid:
2320 if (!SemaRef.getLangOpts().CPlusPlus14)
2321 return false;
2322 break;
2323 }
2324 }
2325 }
2326
2327 // C++11 [dcl.constexpr]p5:
2328 // if no function argument values exist such that the function invocation
2329 // substitution would produce a constant expression, the program is
2330 // ill-formed; no diagnostic required.
2331 // C++11 [dcl.constexpr]p3:
2332 // - every constructor call and implicit conversion used in initializing the
2333 // return value shall be one of those allowed in a constant expression.
2334 // C++11 [dcl.constexpr]p4:
2335 // - every constructor involved in initializing non-static data members and
2336 // base class sub-objects shall be a constexpr constructor.
2337 //
2338 // Note that this rule is distinct from the "requirements for a constexpr
2339 // function", so is not checked in CheckValid mode.
2340 SmallVector<PartialDiagnosticAt, 8> Diags;
2341 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2342 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2343 SemaRef.Diag(Dcl->getLocation(),
2344 diag::ext_constexpr_function_never_constant_expr)
2345 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2346 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2347 SemaRef.Diag(Diags[I].first, Diags[I].second);
2348 // Don't return false here: we allow this for compatibility in
2349 // system headers.
2350 }
2351
2352 return true;
2353}
2354
2355/// Get the class that is directly named by the current context. This is the
2356/// class for which an unqualified-id in this scope could name a constructor
2357/// or destructor.
2358///
2359/// If the scope specifier denotes a class, this will be that class.
2360/// If the scope specifier is empty, this will be the class whose
2361/// member-specification we are currently within. Otherwise, there
2362/// is no such class.
2363CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2364 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2364, __PRETTY_FUNCTION__))
;
2365
2366 if (SS && SS->isInvalid())
2367 return nullptr;
2368
2369 if (SS && SS->isNotEmpty()) {
2370 DeclContext *DC = computeDeclContext(*SS, true);
2371 return dyn_cast_or_null<CXXRecordDecl>(DC);
2372 }
2373
2374 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2375}
2376
2377/// isCurrentClassName - Determine whether the identifier II is the
2378/// name of the class type currently being defined. In the case of
2379/// nested classes, this will only return true if II is the name of
2380/// the innermost class.
2381bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2382 const CXXScopeSpec *SS) {
2383 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2384 return CurDecl && &II == CurDecl->getIdentifier();
2385}
2386
2387/// Determine whether the identifier II is a typo for the name of
2388/// the class type currently being defined. If so, update it to the identifier
2389/// that should have been used.
2390bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2391 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2391, __PRETTY_FUNCTION__))
;
2392
2393 if (!getLangOpts().SpellChecking)
2394 return false;
2395
2396 CXXRecordDecl *CurDecl;
2397 if (SS && SS->isSet() && !SS->isInvalid()) {
2398 DeclContext *DC = computeDeclContext(*SS, true);
2399 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2400 } else
2401 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2402
2403 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2404 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2405 < II->getLength()) {
2406 II = CurDecl->getIdentifier();
2407 return true;
2408 }
2409
2410 return false;
2411}
2412
2413/// Determine whether the given class is a base class of the given
2414/// class, including looking at dependent bases.
2415static bool findCircularInheritance(const CXXRecordDecl *Class,
2416 const CXXRecordDecl *Current) {
2417 SmallVector<const CXXRecordDecl*, 8> Queue;
2418
2419 Class = Class->getCanonicalDecl();
2420 while (true) {
2421 for (const auto &I : Current->bases()) {
2422 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2423 if (!Base)
2424 continue;
2425
2426 Base = Base->getDefinition();
2427 if (!Base)
2428 continue;
2429
2430 if (Base->getCanonicalDecl() == Class)
2431 return true;
2432
2433 Queue.push_back(Base);
2434 }
2435
2436 if (Queue.empty())
2437 return false;
2438
2439 Current = Queue.pop_back_val();
2440 }
2441
2442 return false;
2443}
2444
2445/// Check the validity of a C++ base class specifier.
2446///
2447/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2448/// and returns NULL otherwise.
2449CXXBaseSpecifier *
2450Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2451 SourceRange SpecifierRange,
2452 bool Virtual, AccessSpecifier Access,
2453 TypeSourceInfo *TInfo,
2454 SourceLocation EllipsisLoc) {
2455 QualType BaseType = TInfo->getType();
2456 if (BaseType->containsErrors()) {
2457 // Already emitted a diagnostic when parsing the error type.
2458 return nullptr;
2459 }
2460 // C++ [class.union]p1:
2461 // A union shall not have base classes.
2462 if (Class->isUnion()) {
2463 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2464 << SpecifierRange;
2465 return nullptr;
2466 }
2467
2468 if (EllipsisLoc.isValid() &&
2469 !TInfo->getType()->containsUnexpandedParameterPack()) {
2470 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2471 << TInfo->getTypeLoc().getSourceRange();
2472 EllipsisLoc = SourceLocation();
2473 }
2474
2475 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2476
2477 if (BaseType->isDependentType()) {
2478 // Make sure that we don't have circular inheritance among our dependent
2479 // bases. For non-dependent bases, the check for completeness below handles
2480 // this.
2481 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2482 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2483 ((BaseDecl = BaseDecl->getDefinition()) &&
2484 findCircularInheritance(Class, BaseDecl))) {
2485 Diag(BaseLoc, diag::err_circular_inheritance)
2486 << BaseType << Context.getTypeDeclType(Class);
2487
2488 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2489 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2490 << BaseType;
2491
2492 return nullptr;
2493 }
2494 }
2495
2496 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2497 Class->getTagKind() == TTK_Class,
2498 Access, TInfo, EllipsisLoc);
2499 }
2500
2501 // Base specifiers must be record types.
2502 if (!BaseType->isRecordType()) {
2503 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2504 return nullptr;
2505 }
2506
2507 // C++ [class.union]p1:
2508 // A union shall not be used as a base class.
2509 if (BaseType->isUnionType()) {
2510 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2511 return nullptr;
2512 }
2513
2514 // For the MS ABI, propagate DLL attributes to base class templates.
2515 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2516 if (Attr *ClassAttr = getDLLAttr(Class)) {
2517 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2518 BaseType->getAsCXXRecordDecl())) {
2519 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2520 BaseLoc);
2521 }
2522 }
2523 }
2524
2525 // C++ [class.derived]p2:
2526 // The class-name in a base-specifier shall not be an incompletely
2527 // defined class.
2528 if (RequireCompleteType(BaseLoc, BaseType,
2529 diag::err_incomplete_base_class, SpecifierRange)) {
2530 Class->setInvalidDecl();
2531 return nullptr;
2532 }
2533
2534 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2535 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2536 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2536, __PRETTY_FUNCTION__))
;
2537 BaseDecl = BaseDecl->getDefinition();
2538 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2538, __PRETTY_FUNCTION__))
;
2539 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2540 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2540, __PRETTY_FUNCTION__))
;
2541
2542 // Microsoft docs say:
2543 // "If a base-class has a code_seg attribute, derived classes must have the
2544 // same attribute."
2545 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2546 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2547 if ((DerivedCSA || BaseCSA) &&
2548 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2549 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2550 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2551 << CXXBaseDecl;
2552 return nullptr;
2553 }
2554
2555 // A class which contains a flexible array member is not suitable for use as a
2556 // base class:
2557 // - If the layout determines that a base comes before another base,
2558 // the flexible array member would index into the subsequent base.
2559 // - If the layout determines that base comes before the derived class,
2560 // the flexible array member would index into the derived class.
2561 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2562 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2563 << CXXBaseDecl->getDeclName();
2564 return nullptr;
2565 }
2566
2567 // C++ [class]p3:
2568 // If a class is marked final and it appears as a base-type-specifier in
2569 // base-clause, the program is ill-formed.
2570 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2571 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2572 << CXXBaseDecl->getDeclName()
2573 << FA->isSpelledAsSealed();
2574 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2575 << CXXBaseDecl->getDeclName() << FA->getRange();
2576 return nullptr;
2577 }
2578
2579 if (BaseDecl->isInvalidDecl())
2580 Class->setInvalidDecl();
2581
2582 // Create the base specifier.
2583 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2584 Class->getTagKind() == TTK_Class,
2585 Access, TInfo, EllipsisLoc);
2586}
2587
2588/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2589/// one entry in the base class list of a class specifier, for
2590/// example:
2591/// class foo : public bar, virtual private baz {
2592/// 'public bar' and 'virtual private baz' are each base-specifiers.
2593BaseResult
2594Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2595 ParsedAttributes &Attributes,
2596 bool Virtual, AccessSpecifier Access,
2597 ParsedType basetype, SourceLocation BaseLoc,
2598 SourceLocation EllipsisLoc) {
2599 if (!classdecl)
2600 return true;
2601
2602 AdjustDeclIfTemplate(classdecl);
2603 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2604 if (!Class)
2605 return true;
2606
2607 // We haven't yet attached the base specifiers.
2608 Class->setIsParsingBaseSpecifiers();
2609
2610 // We do not support any C++11 attributes on base-specifiers yet.
2611 // Diagnose any attributes we see.
2612 for (const ParsedAttr &AL : Attributes) {
2613 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2614 continue;
2615 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2616 ? (unsigned)diag::warn_unknown_attribute_ignored
2617 : (unsigned)diag::err_base_specifier_attribute)
2618 << AL << AL.getRange();
2619 }
2620
2621 TypeSourceInfo *TInfo = nullptr;
2622 GetTypeFromParser(basetype, &TInfo);
2623
2624 if (EllipsisLoc.isInvalid() &&
2625 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2626 UPPC_BaseType))
2627 return true;
2628
2629 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2630 Virtual, Access, TInfo,
2631 EllipsisLoc))
2632 return BaseSpec;
2633 else
2634 Class->setInvalidDecl();
2635
2636 return true;
2637}
2638
2639/// Use small set to collect indirect bases. As this is only used
2640/// locally, there's no need to abstract the small size parameter.
2641typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2642
2643/// Recursively add the bases of Type. Don't add Type itself.
2644static void
2645NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2646 const QualType &Type)
2647{
2648 // Even though the incoming type is a base, it might not be
2649 // a class -- it could be a template parm, for instance.
2650 if (auto Rec = Type->getAs<RecordType>()) {
2651 auto Decl = Rec->getAsCXXRecordDecl();
2652
2653 // Iterate over its bases.
2654 for (const auto &BaseSpec : Decl->bases()) {
2655 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2656 .getUnqualifiedType();
2657 if (Set.insert(Base).second)
2658 // If we've not already seen it, recurse.
2659 NoteIndirectBases(Context, Set, Base);
2660 }
2661 }
2662}
2663
2664/// Performs the actual work of attaching the given base class
2665/// specifiers to a C++ class.
2666bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2667 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2668 if (Bases.empty())
2669 return false;
2670
2671 // Used to keep track of which base types we have already seen, so
2672 // that we can properly diagnose redundant direct base types. Note
2673 // that the key is always the unqualified canonical type of the base
2674 // class.
2675 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2676
2677 // Used to track indirect bases so we can see if a direct base is
2678 // ambiguous.
2679 IndirectBaseSet IndirectBaseTypes;
2680
2681 // Copy non-redundant base specifiers into permanent storage.
2682 unsigned NumGoodBases = 0;
2683 bool Invalid = false;
2684 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2685 QualType NewBaseType
2686 = Context.getCanonicalType(Bases[idx]->getType());
2687 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2688
2689 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2690 if (KnownBase) {
2691 // C++ [class.mi]p3:
2692 // A class shall not be specified as a direct base class of a
2693 // derived class more than once.
2694 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2695 << KnownBase->getType() << Bases[idx]->getSourceRange();
2696
2697 // Delete the duplicate base class specifier; we're going to
2698 // overwrite its pointer later.
2699 Context.Deallocate(Bases[idx]);
2700
2701 Invalid = true;
2702 } else {
2703 // Okay, add this new base class.
2704 KnownBase = Bases[idx];
2705 Bases[NumGoodBases++] = Bases[idx];
2706
2707 // Note this base's direct & indirect bases, if there could be ambiguity.
2708 if (Bases.size() > 1)
2709 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2710
2711 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2712 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2713 if (Class->isInterface() &&
2714 (!RD->isInterfaceLike() ||
2715 KnownBase->getAccessSpecifier() != AS_public)) {
2716 // The Microsoft extension __interface does not permit bases that
2717 // are not themselves public interfaces.
2718 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2719 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2720 << RD->getSourceRange();
2721 Invalid = true;
2722 }
2723 if (RD->hasAttr<WeakAttr>())
2724 Class->addAttr(WeakAttr::CreateImplicit(Context));
2725 }
2726 }
2727 }
2728
2729 // Attach the remaining base class specifiers to the derived class.
2730 Class->setBases(Bases.data(), NumGoodBases);
2731
2732 // Check that the only base classes that are duplicate are virtual.
2733 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2734 // Check whether this direct base is inaccessible due to ambiguity.
2735 QualType BaseType = Bases[idx]->getType();
2736
2737 // Skip all dependent types in templates being used as base specifiers.
2738 // Checks below assume that the base specifier is a CXXRecord.
2739 if (BaseType->isDependentType())
2740 continue;
2741
2742 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2743 .getUnqualifiedType();
2744
2745 if (IndirectBaseTypes.count(CanonicalBase)) {
2746 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2747 /*DetectVirtual=*/true);
2748 bool found
2749 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2750 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2750, __PRETTY_FUNCTION__))
;
2751 (void)found;
2752
2753 if (Paths.isAmbiguous(CanonicalBase))
2754 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2755 << BaseType << getAmbiguousPathsDisplayString(Paths)
2756 << Bases[idx]->getSourceRange();
2757 else
2758 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2758, __PRETTY_FUNCTION__))
;
2759 }
2760
2761 // Delete the base class specifier, since its data has been copied
2762 // into the CXXRecordDecl.
2763 Context.Deallocate(Bases[idx]);
2764 }
2765
2766 return Invalid;
2767}
2768
2769/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2770/// class, after checking whether there are any duplicate base
2771/// classes.
2772void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2773 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2774 if (!ClassDecl || Bases.empty())
2775 return;
2776
2777 AdjustDeclIfTemplate(ClassDecl);
2778 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2779}
2780
2781/// Determine whether the type \p Derived is a C++ class that is
2782/// derived from the type \p Base.
2783bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2784 if (!getLangOpts().CPlusPlus)
2785 return false;
2786
2787 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2788 if (!DerivedRD)
2789 return false;
2790
2791 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2792 if (!BaseRD)
2793 return false;
2794
2795 // If either the base or the derived type is invalid, don't try to
2796 // check whether one is derived from the other.
2797 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2798 return false;
2799
2800 // FIXME: In a modules build, do we need the entire path to be visible for us
2801 // to be able to use the inheritance relationship?
2802 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2803 return false;
2804
2805 return DerivedRD->isDerivedFrom(BaseRD);
2806}
2807
2808/// Determine whether the type \p Derived is a C++ class that is
2809/// derived from the type \p Base.
2810bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2811 CXXBasePaths &Paths) {
2812 if (!getLangOpts().CPlusPlus)
2813 return false;
2814
2815 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2816 if (!DerivedRD)
2817 return false;
2818
2819 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2820 if (!BaseRD)
2821 return false;
2822
2823 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2824 return false;
2825
2826 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2827}
2828
2829static void BuildBasePathArray(const CXXBasePath &Path,
2830 CXXCastPath &BasePathArray) {
2831 // We first go backward and check if we have a virtual base.
2832 // FIXME: It would be better if CXXBasePath had the base specifier for
2833 // the nearest virtual base.
2834 unsigned Start = 0;
2835 for (unsigned I = Path.size(); I != 0; --I) {
2836 if (Path[I - 1].Base->isVirtual()) {
2837 Start = I - 1;
2838 break;
2839 }
2840 }
2841
2842 // Now add all bases.
2843 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2844 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2845}
2846
2847
2848void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2849 CXXCastPath &BasePathArray) {
2850 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2850, __PRETTY_FUNCTION__))
;
2851 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2851, __PRETTY_FUNCTION__))
;
2852 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2853}
2854/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2855/// conversion (where Derived and Base are class types) is
2856/// well-formed, meaning that the conversion is unambiguous (and
2857/// that all of the base classes are accessible). Returns true
2858/// and emits a diagnostic if the code is ill-formed, returns false
2859/// otherwise. Loc is the location where this routine should point to
2860/// if there is an error, and Range is the source range to highlight
2861/// if there is an error.
2862///
2863/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2864/// diagnostic for the respective type of error will be suppressed, but the
2865/// check for ill-formed code will still be performed.
2866bool
2867Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2868 unsigned InaccessibleBaseID,
2869 unsigned AmbiguousBaseConvID,
2870 SourceLocation Loc, SourceRange Range,
2871 DeclarationName Name,
2872 CXXCastPath *BasePath,
2873 bool IgnoreAccess) {
2874 // First, determine whether the path from Derived to Base is
2875 // ambiguous. This is slightly more expensive than checking whether
2876 // the Derived to Base conversion exists, because here we need to
2877 // explore multiple paths to determine if there is an ambiguity.
2878 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2879 /*DetectVirtual=*/false);
2880 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2881 if (!DerivationOkay)
2882 return true;
2883
2884 const CXXBasePath *Path = nullptr;
2885 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2886 Path = &Paths.front();
2887
2888 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2889 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2890 // user to access such bases.
2891 if (!Path && getLangOpts().MSVCCompat) {
2892 for (const CXXBasePath &PossiblePath : Paths) {
2893 if (PossiblePath.size() == 1) {
2894 Path = &PossiblePath;
2895 if (AmbiguousBaseConvID)
2896 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2897 << Base << Derived << Range;
2898 break;
2899 }
2900 }
2901 }
2902
2903 if (Path) {
2904 if (!IgnoreAccess) {
2905 // Check that the base class can be accessed.
2906 switch (
2907 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2908 case AR_inaccessible:
2909 return true;
2910 case AR_accessible:
2911 case AR_dependent:
2912 case AR_delayed:
2913 break;
2914 }
2915 }
2916
2917 // Build a base path if necessary.
2918 if (BasePath)
2919 ::BuildBasePathArray(*Path, *BasePath);
2920 return false;
2921 }
2922
2923 if (AmbiguousBaseConvID) {
2924 // We know that the derived-to-base conversion is ambiguous, and
2925 // we're going to produce a diagnostic. Perform the derived-to-base
2926 // search just one more time to compute all of the possible paths so
2927 // that we can print them out. This is more expensive than any of
2928 // the previous derived-to-base checks we've done, but at this point
2929 // performance isn't as much of an issue.
2930 Paths.clear();
2931 Paths.setRecordingPaths(true);
2932 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2933 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2933, __PRETTY_FUNCTION__))
;
2934 (void)StillOkay;
2935
2936 // Build up a textual representation of the ambiguous paths, e.g.,
2937 // D -> B -> A, that will be used to illustrate the ambiguous
2938 // conversions in the diagnostic. We only print one of the paths
2939 // to each base class subobject.
2940 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2941
2942 Diag(Loc, AmbiguousBaseConvID)
2943 << Derived << Base << PathDisplayStr << Range << Name;
2944 }
2945 return true;
2946}
2947
2948bool
2949Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2950 SourceLocation Loc, SourceRange Range,
2951 CXXCastPath *BasePath,
2952 bool IgnoreAccess) {
2953 return CheckDerivedToBaseConversion(
2954 Derived, Base, diag::err_upcast_to_inaccessible_base,
2955 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2956 BasePath, IgnoreAccess);
2957}
2958
2959
2960/// Builds a string representing ambiguous paths from a
2961/// specific derived class to different subobjects of the same base
2962/// class.
2963///
2964/// This function builds a string that can be used in error messages
2965/// to show the different paths that one can take through the
2966/// inheritance hierarchy to go from the derived class to different
2967/// subobjects of a base class. The result looks something like this:
2968/// @code
2969/// struct D -> struct B -> struct A
2970/// struct D -> struct C -> struct A
2971/// @endcode
2972std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2973 std::string PathDisplayStr;
2974 std::set<unsigned> DisplayedPaths;
2975 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2976 Path != Paths.end(); ++Path) {
2977 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2978 // We haven't displayed a path to this particular base
2979 // class subobject yet.
2980 PathDisplayStr += "\n ";
2981 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2982 for (CXXBasePath::const_iterator Element = Path->begin();
2983 Element != Path->end(); ++Element)
2984 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2985 }
2986 }
2987
2988 return PathDisplayStr;
2989}
2990
2991//===----------------------------------------------------------------------===//
2992// C++ class member Handling
2993//===----------------------------------------------------------------------===//
2994
2995/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2996bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2997 SourceLocation ColonLoc,
2998 const ParsedAttributesView &Attrs) {
2999 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2999, __PRETTY_FUNCTION__))
;
3000 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3001 ASLoc, ColonLoc);
3002 CurContext->addHiddenDecl(ASDecl);
3003 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3004}
3005
3006/// CheckOverrideControl - Check C++11 override control semantics.
3007void Sema::CheckOverrideControl(NamedDecl *D) {
3008 if (D->isInvalidDecl())
3009 return;
3010
3011 // We only care about "override" and "final" declarations.
3012 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3013 return;
3014
3015 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3016
3017 // We can't check dependent instance methods.
3018 if (MD && MD->isInstance() &&
3019 (MD->getParent()->hasAnyDependentBases() ||
3020 MD->getType()->isDependentType()))
3021 return;
3022
3023 if (MD && !MD->isVirtual()) {
3024 // If we have a non-virtual method, check if if hides a virtual method.
3025 // (In that case, it's most likely the method has the wrong type.)
3026 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3027 FindHiddenVirtualMethods(MD, OverloadedMethods);
3028
3029 if (!OverloadedMethods.empty()) {
3030 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3031 Diag(OA->getLocation(),
3032 diag::override_keyword_hides_virtual_member_function)
3033 << "override" << (OverloadedMethods.size() > 1);
3034 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3035 Diag(FA->getLocation(),
3036 diag::override_keyword_hides_virtual_member_function)
3037 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3038 << (OverloadedMethods.size() > 1);
3039 }
3040 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3041 MD->setInvalidDecl();
3042 return;
3043 }
3044 // Fall through into the general case diagnostic.
3045 // FIXME: We might want to attempt typo correction here.
3046 }
3047
3048 if (!MD || !MD->isVirtual()) {
3049 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3050 Diag(OA->getLocation(),
3051 diag::override_keyword_only_allowed_on_virtual_member_functions)
3052 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3053 D->dropAttr<OverrideAttr>();
3054 }
3055 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3056 Diag(FA->getLocation(),
3057 diag::override_keyword_only_allowed_on_virtual_member_functions)
3058 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3059 << FixItHint::CreateRemoval(FA->getLocation());
3060 D->dropAttr<FinalAttr>();
3061 }
3062 return;
3063 }
3064
3065 // C++11 [class.virtual]p5:
3066 // If a function is marked with the virt-specifier override and
3067 // does not override a member function of a base class, the program is
3068 // ill-formed.
3069 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3070 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3071 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3072 << MD->getDeclName();
3073}
3074
3075void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3076 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3077 return;
3078 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3079 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3080 return;
3081
3082 SourceLocation Loc = MD->getLocation();
3083 SourceLocation SpellingLoc = Loc;
3084 if (getSourceManager().isMacroArgExpansion(Loc))
3085 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3086 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3087 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3088 return;
3089
3090 if (MD->size_overridden_methods() > 0) {
3091 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3092 unsigned DiagID =
3093 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3094 ? DiagInconsistent
3095 : DiagSuggest;
3096 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3097 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3098 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3099 };
3100 if (isa<CXXDestructorDecl>(MD))
3101 EmitDiag(
3102 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3103 diag::warn_suggest_destructor_marked_not_override_overriding);
3104 else
3105 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3106 diag::warn_suggest_function_marked_not_override_overriding);
3107 }
3108}
3109
3110/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3111/// function overrides a virtual member function marked 'final', according to
3112/// C++11 [class.virtual]p4.
3113bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3114 const CXXMethodDecl *Old) {
3115 FinalAttr *FA = Old->getAttr<FinalAttr>();
3116 if (!FA)
3117 return false;
3118
3119 Diag(New->getLocation(), diag::err_final_function_overridden)
3120 << New->getDeclName()
3121 << FA->isSpelledAsSealed();
3122 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3123 return true;
3124}
3125
3126static bool InitializationHasSideEffects(const FieldDecl &FD) {
3127 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3128 // FIXME: Destruction of ObjC lifetime types has side-effects.
3129 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3130 return !RD->isCompleteDefinition() ||
3131 !RD->hasTrivialDefaultConstructor() ||
3132 !RD->hasTrivialDestructor();
3133 return false;
3134}
3135
3136static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3137 ParsedAttributesView::const_iterator Itr =
3138 llvm::find_if(list, [](const ParsedAttr &AL) {
3139 return AL.isDeclspecPropertyAttribute();
3140 });
3141 if (Itr != list.end())
3142 return &*Itr;
3143 return nullptr;
3144}
3145
3146// Check if there is a field shadowing.
3147void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3148 DeclarationName FieldName,
3149 const CXXRecordDecl *RD,
3150 bool DeclIsField) {
3151 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3152 return;
3153
3154 // To record a shadowed field in a base
3155 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3156 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3157 CXXBasePath &Path) {
3158 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3159 // Record an ambiguous path directly
3160 if (Bases.find(Base) != Bases.end())
3161 return true;
3162 for (const auto Field : Base->lookup(FieldName)) {
3163 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3164 Field->getAccess() != AS_private) {
3165 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3165, __PRETTY_FUNCTION__))
;
3166 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3166, __PRETTY_FUNCTION__))
;
3167 Bases[Base] = Field;
3168 return true;
3169 }
3170 }
3171 return false;
3172 };
3173
3174 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3175 /*DetectVirtual=*/true);
3176 if (!RD->lookupInBases(FieldShadowed, Paths))
3177 return;
3178
3179 for (const auto &P : Paths) {
3180 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3181 auto It = Bases.find(Base);
3182 // Skip duplicated bases
3183 if (It == Bases.end())
3184 continue;
3185 auto BaseField = It->second;
3186 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3186, __PRETTY_FUNCTION__))
;
3187 if (AS_none !=
3188 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3189 Diag(Loc, diag::warn_shadow_field)
3190 << FieldName << RD << Base << DeclIsField;
3191 Diag(BaseField->getLocation(), diag::note_shadow_field);
3192 Bases.erase(It);
3193 }
3194 }
3195}
3196
3197/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3198/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3199/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3200/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3201/// present (but parsing it has been deferred).
3202NamedDecl *
3203Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3204 MultiTemplateParamsArg TemplateParameterLists,
3205 Expr *BW, const VirtSpecifiers &VS,
3206 InClassInitStyle InitStyle) {
3207 const DeclSpec &DS = D.getDeclSpec();
3208 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3209 DeclarationName Name = NameInfo.getName();
3210 SourceLocation Loc = NameInfo.getLoc();
3211
3212 // For anonymous bitfields, the location should point to the type.
3213 if (Loc.isInvalid())
3214 Loc = D.getBeginLoc();
3215
3216 Expr *BitWidth = static_cast<Expr*>(BW);
3217
3218 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3218, __PRETTY_FUNCTION__))
;
3219 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3219, __PRETTY_FUNCTION__))
;
3220
3221 bool isFunc = D.isDeclarationOfFunction();
3222 const ParsedAttr *MSPropertyAttr =
3223 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3224
3225 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3226 // The Microsoft extension __interface only permits public member functions
3227 // and prohibits constructors, destructors, operators, non-public member
3228 // functions, static methods and data members.
3229 unsigned InvalidDecl;
3230 bool ShowDeclName = true;
3231 if (!isFunc &&
3232 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3233 InvalidDecl = 0;
3234 else if (!isFunc)
3235 InvalidDecl = 1;
3236 else if (AS != AS_public)
3237 InvalidDecl = 2;
3238 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3239 InvalidDecl = 3;
3240 else switch (Name.getNameKind()) {
3241 case DeclarationName::CXXConstructorName:
3242 InvalidDecl = 4;
3243 ShowDeclName = false;
3244 break;
3245
3246 case DeclarationName::CXXDestructorName:
3247 InvalidDecl = 5;
3248 ShowDeclName = false;
3249 break;
3250
3251 case DeclarationName::CXXOperatorName:
3252 case DeclarationName::CXXConversionFunctionName:
3253 InvalidDecl = 6;
3254 break;
3255
3256 default:
3257 InvalidDecl = 0;
3258 break;
3259 }
3260
3261 if (InvalidDecl) {
3262 if (ShowDeclName)
3263 Diag(Loc, diag::err_invalid_member_in_interface)
3264 << (InvalidDecl-1) << Name;
3265 else
3266 Diag(Loc, diag::err_invalid_member_in_interface)
3267 << (InvalidDecl-1) << "";
3268 return nullptr;
3269 }
3270 }
3271
3272 // C++ 9.2p6: A member shall not be declared to have automatic storage
3273 // duration (auto, register) or with the extern storage-class-specifier.
3274 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3275 // data members and cannot be applied to names declared const or static,
3276 // and cannot be applied to reference members.
3277 switch (DS.getStorageClassSpec()) {
3278 case DeclSpec::SCS_unspecified:
3279 case DeclSpec::SCS_typedef:
3280 case DeclSpec::SCS_static:
3281 break;
3282 case DeclSpec::SCS_mutable:
3283 if (isFunc) {
3284 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3285
3286 // FIXME: It would be nicer if the keyword was ignored only for this
3287 // declarator. Otherwise we could get follow-up errors.
3288 D.getMutableDeclSpec().ClearStorageClassSpecs();
3289 }
3290 break;
3291 default:
3292 Diag(DS.getStorageClassSpecLoc(),
3293 diag::err_storageclass_invalid_for_member);
3294 D.getMutableDeclSpec().ClearStorageClassSpecs();
3295 break;
3296 }
3297
3298 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3299 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3300 !isFunc);
3301
3302 if (DS.hasConstexprSpecifier() && isInstField) {
3303 SemaDiagnosticBuilder B =
3304 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3305 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3306 if (InitStyle == ICIS_NoInit) {
3307 B << 0 << 0;
3308 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3309 B << FixItHint::CreateRemoval(ConstexprLoc);
3310 else {
3311 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3312 D.getMutableDeclSpec().ClearConstexprSpec();
3313 const char *PrevSpec;
3314 unsigned DiagID;
3315 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3316 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3317 (void)Failed;
3318 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3318, __PRETTY_FUNCTION__))
;
3319 }
3320 } else {
3321 B << 1;
3322 const char *PrevSpec;
3323 unsigned DiagID;
3324 if (D.getMutableDeclSpec().SetStorageClassSpec(
3325 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3326 Context.getPrintingPolicy())) {
3327 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3328, __PRETTY_FUNCTION__))
3328 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3328, __PRETTY_FUNCTION__))
;
3329 B << 1;
3330 } else {
3331 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3332 isInstField = false;
3333 }
3334 }
3335 }
3336
3337 NamedDecl *Member;
3338 if (isInstField) {
3339 CXXScopeSpec &SS = D.getCXXScopeSpec();
3340
3341 // Data members must have identifiers for names.
3342 if (!Name.isIdentifier()) {
3343 Diag(Loc, diag::err_bad_variable_name)
3344 << Name;
3345 return nullptr;
3346 }
3347
3348 IdentifierInfo *II = Name.getAsIdentifierInfo();
3349
3350 // Member field could not be with "template" keyword.
3351 // So TemplateParameterLists should be empty in this case.
3352 if (TemplateParameterLists.size()) {
3353 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3354 if (TemplateParams->size()) {
3355 // There is no such thing as a member field template.
3356 Diag(D.getIdentifierLoc(), diag::err_template_member)
3357 << II
3358 << SourceRange(TemplateParams->getTemplateLoc(),
3359 TemplateParams->getRAngleLoc());
3360 } else {
3361 // There is an extraneous 'template<>' for this member.
3362 Diag(TemplateParams->getTemplateLoc(),
3363 diag::err_template_member_noparams)
3364 << II
3365 << SourceRange(TemplateParams->getTemplateLoc(),
3366 TemplateParams->getRAngleLoc());
3367 }
3368 return nullptr;
3369 }
3370
3371 if (SS.isSet() && !SS.isInvalid()) {
3372 // The user provided a superfluous scope specifier inside a class
3373 // definition:
3374 //
3375 // class X {
3376 // int X::member;
3377 // };
3378 if (DeclContext *DC = computeDeclContext(SS, false))
3379 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3380 D.getName().getKind() ==
3381 UnqualifiedIdKind::IK_TemplateId);
3382 else
3383 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3384 << Name << SS.getRange();
3385
3386 SS.clear();
3387 }
3388
3389 if (MSPropertyAttr) {
3390 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3391 BitWidth, InitStyle, AS, *MSPropertyAttr);
3392 if (!Member)
3393 return nullptr;
3394 isInstField = false;
3395 } else {
3396 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3397 BitWidth, InitStyle, AS);
3398 if (!Member)
3399 return nullptr;
3400 }
3401
3402 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3403 } else {
3404 Member = HandleDeclarator(S, D, TemplateParameterLists);
3405 if (!Member)
3406 return nullptr;
3407
3408 // Non-instance-fields can't have a bitfield.
3409 if (BitWidth) {
3410 if (Member->isInvalidDecl()) {
3411 // don't emit another diagnostic.
3412 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3413 // C++ 9.6p3: A bit-field shall not be a static member.
3414 // "static member 'A' cannot be a bit-field"
3415 Diag(Loc, diag::err_static_not_bitfield)
3416 << Name << BitWidth->getSourceRange();
3417 } else if (isa<TypedefDecl>(Member)) {
3418 // "typedef member 'x' cannot be a bit-field"
3419 Diag(Loc, diag::err_typedef_not_bitfield)
3420 << Name << BitWidth->getSourceRange();
3421 } else {
3422 // A function typedef ("typedef int f(); f a;").
3423 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3424 Diag(Loc, diag::err_not_integral_type_bitfield)
3425 << Name << cast<ValueDecl>(Member)->getType()
3426 << BitWidth->getSourceRange();
3427 }
3428
3429 BitWidth = nullptr;
3430 Member->setInvalidDecl();
3431 }
3432
3433 NamedDecl *NonTemplateMember = Member;
3434 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3435 NonTemplateMember = FunTmpl->getTemplatedDecl();
3436 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3437 NonTemplateMember = VarTmpl->getTemplatedDecl();
3438
3439 Member->setAccess(AS);
3440
3441 // If we have declared a member function template or static data member
3442 // template, set the access of the templated declaration as well.
3443 if (NonTemplateMember != Member)
3444 NonTemplateMember->setAccess(AS);
3445
3446 // C++ [temp.deduct.guide]p3:
3447 // A deduction guide [...] for a member class template [shall be
3448 // declared] with the same access [as the template].
3449 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3450 auto *TD = DG->getDeducedTemplate();
3451 // Access specifiers are only meaningful if both the template and the
3452 // deduction guide are from the same scope.
3453 if (AS != TD->getAccess() &&
3454 TD->getDeclContext()->getRedeclContext()->Equals(
3455 DG->getDeclContext()->getRedeclContext())) {
3456 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3457 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3458 << TD->getAccess();
3459 const AccessSpecDecl *LastAccessSpec = nullptr;
3460 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3461 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3462 LastAccessSpec = AccessSpec;
3463 }
3464 assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier"
) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3464, __PRETTY_FUNCTION__))
;
3465 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3466 << AS;
3467 }
3468 }
3469 }
3470
3471 if (VS.isOverrideSpecified())
3472 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3473 AttributeCommonInfo::AS_Keyword));
3474 if (VS.isFinalSpecified())
3475 Member->addAttr(FinalAttr::Create(
3476 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3477 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3478
3479 if (VS.getLastLocation().isValid()) {
3480 // Update the end location of a method that has a virt-specifiers.
3481 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3482 MD->setRangeEnd(VS.getLastLocation());
3483 }
3484
3485 CheckOverrideControl(Member);
3486
3487 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3487, __PRETTY_FUNCTION__))
;
3488
3489 if (isInstField) {
3490 FieldDecl *FD = cast<FieldDecl>(Member);
3491 FieldCollector->Add(FD);
3492
3493 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3494 // Remember all explicit private FieldDecls that have a name, no side
3495 // effects and are not part of a dependent type declaration.
3496 if (!FD->isImplicit() && FD->getDeclName() &&
3497 FD->getAccess() == AS_private &&
3498 !FD->hasAttr<UnusedAttr>() &&
3499 !FD->getParent()->isDependentContext() &&
3500 !InitializationHasSideEffects(*FD))
3501 UnusedPrivateFields.insert(FD);
3502 }
3503 }
3504
3505 return Member;
3506}
3507
3508namespace {
3509 class UninitializedFieldVisitor
3510 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3511 Sema &S;
3512 // List of Decls to generate a warning on. Also remove Decls that become
3513 // initialized.
3514 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3515 // List of base classes of the record. Classes are removed after their
3516 // initializers.
3517 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3518 // Vector of decls to be removed from the Decl set prior to visiting the
3519 // nodes. These Decls may have been initialized in the prior initializer.
3520 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3521 // If non-null, add a note to the warning pointing back to the constructor.
3522 const CXXConstructorDecl *Constructor;
3523 // Variables to hold state when processing an initializer list. When
3524 // InitList is true, special case initialization of FieldDecls matching
3525 // InitListFieldDecl.
3526 bool InitList;
3527 FieldDecl *InitListFieldDecl;
3528 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3529
3530 public:
3531 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3532 UninitializedFieldVisitor(Sema &S,
3533 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3534 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3535 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3536 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3537
3538 // Returns true if the use of ME is not an uninitialized use.
3539 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3540 bool CheckReferenceOnly) {
3541 llvm::SmallVector<FieldDecl*, 4> Fields;
3542 bool ReferenceField = false;
3543 while (ME) {
3544 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3545 if (!FD)
3546 return false;
3547 Fields.push_back(FD);
3548 if (FD->getType()->isReferenceType())
3549 ReferenceField = true;
3550 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3551 }
3552
3553 // Binding a reference to an uninitialized field is not an
3554 // uninitialized use.
3555 if (CheckReferenceOnly && !ReferenceField)
3556 return true;
3557
3558 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3559 // Discard the first field since it is the field decl that is being
3560 // initialized.
3561 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3562 UsedFieldIndex.push_back((*I)->getFieldIndex());
3563 }
3564
3565 for (auto UsedIter = UsedFieldIndex.begin(),
3566 UsedEnd = UsedFieldIndex.end(),
3567 OrigIter = InitFieldIndex.begin(),
3568 OrigEnd = InitFieldIndex.end();
3569 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3570 if (*UsedIter < *OrigIter)
3571 return true;
3572 if (*UsedIter > *OrigIter)
3573 break;
3574 }
3575
3576 return false;
3577 }
3578
3579 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3580 bool AddressOf) {
3581 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3582 return;
3583
3584 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3585 // or union.
3586 MemberExpr *FieldME = ME;
3587
3588 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3589
3590 Expr *Base = ME;
3591 while (MemberExpr *SubME =
3592 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3593
3594 if (isa<VarDecl>(SubME->getMemberDecl()))
3595 return;
3596
3597 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3598 if (!FD->isAnonymousStructOrUnion())
3599 FieldME = SubME;
3600
3601 if (!FieldME->getType().isPODType(S.Context))
3602 AllPODFields = false;
3603
3604 Base = SubME->getBase();
3605 }
3606
3607 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3608 Visit(Base);
3609 return;
3610 }
3611
3612 if (AddressOf && AllPODFields)
3613 return;
3614
3615 ValueDecl* FoundVD = FieldME->getMemberDecl();
3616
3617 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3618 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3619 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3620 }
3621
3622 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3623 QualType T = BaseCast->getType();
3624 if (T->isPointerType() &&
3625 BaseClasses.count(T->getPointeeType())) {
3626 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3627 << T->getPointeeType() << FoundVD;
3628 }
3629 }
3630 }
3631
3632 if (!Decls.count(FoundVD))
3633 return;
3634
3635 const bool IsReference = FoundVD->getType()->isReferenceType();
3636
3637 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3638 // Special checking for initializer lists.
3639 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3640 return;
3641 }
3642 } else {
3643 // Prevent double warnings on use of unbounded references.
3644 if (CheckReferenceOnly && !IsReference)
3645 return;
3646 }
3647
3648 unsigned diag = IsReference
3649 ? diag::warn_reference_field_is_uninit
3650 : diag::warn_field_is_uninit;
3651 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3652 if (Constructor)
3653 S.Diag(Constructor->getLocation(),
3654 diag::note_uninit_in_this_constructor)
3655 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3656
3657 }
3658
3659 void HandleValue(Expr *E, bool AddressOf) {
3660 E = E->IgnoreParens();
3661
3662 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3663 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3664 AddressOf /*AddressOf*/);
3665 return;
3666 }
3667
3668 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3669 Visit(CO->getCond());
3670 HandleValue(CO->getTrueExpr(), AddressOf);
3671 HandleValue(CO->getFalseExpr(), AddressOf);
3672 return;
3673 }
3674
3675 if (BinaryConditionalOperator *BCO =
3676 dyn_cast<BinaryConditionalOperator>(E)) {
3677 Visit(BCO->getCond());
3678 HandleValue(BCO->getFalseExpr(), AddressOf);
3679 return;
3680 }
3681
3682 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3683 HandleValue(OVE->getSourceExpr(), AddressOf);
3684 return;
3685 }
3686
3687 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3688 switch (BO->getOpcode()) {
3689 default:
3690 break;
3691 case(BO_PtrMemD):
3692 case(BO_PtrMemI):
3693 HandleValue(BO->getLHS(), AddressOf);
3694 Visit(BO->getRHS());
3695 return;
3696 case(BO_Comma):
3697 Visit(BO->getLHS());
3698 HandleValue(BO->getRHS(), AddressOf);
3699 return;
3700 }
3701 }
3702
3703 Visit(E);
3704 }
3705
3706 void CheckInitListExpr(InitListExpr *ILE) {
3707 InitFieldIndex.push_back(0);
3708 for (auto Child : ILE->children()) {
3709 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3710 CheckInitListExpr(SubList);
3711 } else {
3712 Visit(Child);
3713 }
3714 ++InitFieldIndex.back();
3715 }
3716 InitFieldIndex.pop_back();
3717 }
3718
3719 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3720 FieldDecl *Field, const Type *BaseClass) {
3721 // Remove Decls that may have been initialized in the previous
3722 // initializer.
3723 for (ValueDecl* VD : DeclsToRemove)
3724 Decls.erase(VD);
3725 DeclsToRemove.clear();
3726
3727 Constructor = FieldConstructor;
3728 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3729
3730 if (ILE && Field) {
3731 InitList = true;
3732 InitListFieldDecl = Field;
3733 InitFieldIndex.clear();
3734 CheckInitListExpr(ILE);
3735 } else {
3736 InitList = false;
3737 Visit(E);
3738 }
3739
3740 if (Field)
3741 Decls.erase(Field);
3742 if (BaseClass)
3743 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3744 }
3745
3746 void VisitMemberExpr(MemberExpr *ME) {
3747 // All uses of unbounded reference fields will warn.
3748 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3749 }
3750
3751 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3752 if (E->getCastKind() == CK_LValueToRValue) {
3753 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3754 return;
3755 }
3756
3757 Inherited::VisitImplicitCastExpr(E);
3758 }
3759
3760 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3761 if (E->getConstructor()->isCopyConstructor()) {
3762 Expr *ArgExpr = E->getArg(0);
3763 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3764 if (ILE->getNumInits() == 1)
3765 ArgExpr = ILE->getInit(0);
3766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3767 if (ICE->getCastKind() == CK_NoOp)
3768 ArgExpr = ICE->getSubExpr();
3769 HandleValue(ArgExpr, false /*AddressOf*/);
3770 return;
3771 }
3772 Inherited::VisitCXXConstructExpr(E);
3773 }
3774
3775 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3776 Expr *Callee = E->getCallee();
3777 if (isa<MemberExpr>(Callee)) {
3778 HandleValue(Callee, false /*AddressOf*/);
3779 for (auto Arg : E->arguments())
3780 Visit(Arg);
3781 return;
3782 }
3783
3784 Inherited::VisitCXXMemberCallExpr(E);
3785 }
3786
3787 void VisitCallExpr(CallExpr *E) {
3788 // Treat std::move as a use.
3789 if (E->isCallToStdMove()) {
3790 HandleValue(E->getArg(0), /*AddressOf=*/false);
3791 return;
3792 }
3793
3794 Inherited::VisitCallExpr(E);
3795 }
3796
3797 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3798 Expr *Callee = E->getCallee();
3799
3800 if (isa<UnresolvedLookupExpr>(Callee))
3801 return Inherited::VisitCXXOperatorCallExpr(E);
3802
3803 Visit(Callee);
3804 for (auto Arg : E->arguments())
3805 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3806 }
3807
3808 void VisitBinaryOperator(BinaryOperator *E) {
3809 // If a field assignment is detected, remove the field from the
3810 // uninitiailized field set.
3811 if (E->getOpcode() == BO_Assign)
3812 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3813 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3814 if (!FD->getType()->isReferenceType())
3815 DeclsToRemove.push_back(FD);
3816
3817 if (E->isCompoundAssignmentOp()) {
3818 HandleValue(E->getLHS(), false /*AddressOf*/);
3819 Visit(E->getRHS());
3820 return;
3821 }
3822
3823 Inherited::VisitBinaryOperator(E);
3824 }
3825
3826 void VisitUnaryOperator(UnaryOperator *E) {
3827 if (E->isIncrementDecrementOp()) {
3828 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3829 return;
3830 }
3831 if (E->getOpcode() == UO_AddrOf) {
3832 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3833 HandleValue(ME->getBase(), true /*AddressOf*/);
3834 return;
3835 }
3836 }
3837
3838 Inherited::VisitUnaryOperator(E);
3839 }
3840 };
3841
3842 // Diagnose value-uses of fields to initialize themselves, e.g.
3843 // foo(foo)
3844 // where foo is not also a parameter to the constructor.
3845 // Also diagnose across field uninitialized use such as
3846 // x(y), y(x)
3847 // TODO: implement -Wuninitialized and fold this into that framework.
3848 static void DiagnoseUninitializedFields(
3849 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3850
3851 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3852 Constructor->getLocation())) {
3853 return;
3854 }
3855
3856 if (Constructor->isInvalidDecl())
3857 return;
3858
3859 const CXXRecordDecl *RD = Constructor->getParent();
3860
3861 if (RD->isDependentContext())
3862 return;
3863
3864 // Holds fields that are uninitialized.
3865 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3866
3867 // At the beginning, all fields are uninitialized.
3868 for (auto *I : RD->decls()) {
3869 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3870 UninitializedFields.insert(FD);
3871 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3872 UninitializedFields.insert(IFD->getAnonField());
3873 }
3874 }
3875
3876 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3877 for (auto I : RD->bases())
3878 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3879
3880 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3881 return;
3882
3883 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3884 UninitializedFields,
3885 UninitializedBaseClasses);
3886
3887 for (const auto *FieldInit : Constructor->inits()) {
3888 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3889 break;
3890
3891 Expr *InitExpr = FieldInit->getInit();
3892 if (!InitExpr)
3893 continue;
3894
3895 if (CXXDefaultInitExpr *Default =
3896 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3897 InitExpr = Default->getExpr();
3898 if (!InitExpr)
3899 continue;
3900 // In class initializers will point to the constructor.
3901 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3902 FieldInit->getAnyMember(),
3903 FieldInit->getBaseClass());
3904 } else {
3905 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3906 FieldInit->getAnyMember(),
3907 FieldInit->getBaseClass());
3908 }
3909 }
3910 }
3911} // namespace
3912
3913/// Enter a new C++ default initializer scope. After calling this, the
3914/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3915/// parsing or instantiating the initializer failed.
3916void Sema::ActOnStartCXXInClassMemberInitializer() {
3917 // Create a synthetic function scope to represent the call to the constructor
3918 // that notionally surrounds a use of this initializer.
3919 PushFunctionScope();
3920}
3921
3922void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3923 if (!D.isFunctionDeclarator())
3924 return;
3925 auto &FTI = D.getFunctionTypeInfo();
3926 if (!FTI.Params)
3927 return;
3928 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3929 FTI.NumParams)) {
3930 auto *ParamDecl = cast<NamedDecl>(Param.Param);
3931 if (ParamDecl->getDeclName())
3932 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3933 }
3934}
3935
3936ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3937 return ActOnRequiresClause(ConstraintExpr);
3938}
3939
3940ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3941 if (ConstraintExpr.isInvalid())
3942 return ExprError();
3943
3944 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3945 if (ConstraintExpr.isInvalid())
3946 return ExprError();
3947
3948 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3949 UPPC_RequiresClause))
3950 return ExprError();
3951
3952 return ConstraintExpr;
3953}
3954
3955/// This is invoked after parsing an in-class initializer for a
3956/// non-static C++ class member, and after instantiating an in-class initializer
3957/// in a class template. Such actions are deferred until the class is complete.
3958void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3959 SourceLocation InitLoc,
3960 Expr *InitExpr) {
3961 // Pop the notional constructor scope we created earlier.
3962 PopFunctionScopeInfo(nullptr, D);
3963
3964 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3965 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3966, __PRETTY_FUNCTION__))
3966 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3966, __PRETTY_FUNCTION__))
;
3967
3968 if (!InitExpr) {
3969 D->setInvalidDecl();
3970 if (FD)
3971 FD->removeInClassInitializer();
3972 return;
3973 }
3974
3975 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3976 FD->setInvalidDecl();
3977 FD->removeInClassInitializer();
3978 return;
3979 }
3980
3981 ExprResult Init = InitExpr;
3982 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3983 InitializedEntity Entity =
3984 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3985 InitializationKind Kind =
3986 FD->getInClassInitStyle() == ICIS_ListInit
3987 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3988 InitExpr->getBeginLoc(),
3989 InitExpr->getEndLoc())
3990 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3991 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3992 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3993 if (Init.isInvalid()) {
3994 FD->setInvalidDecl();
3995 return;
3996 }
3997 }
3998
3999 // C++11 [class.base.init]p7:
4000 // The initialization of each base and member constitutes a
4001 // full-expression.
4002 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4003 if (Init.isInvalid()) {
4004 FD->setInvalidDecl();
4005 return;
4006 }
4007
4008 InitExpr = Init.get();
4009
4010 FD->setInClassInitializer(InitExpr);
4011}
4012
4013/// Find the direct and/or virtual base specifiers that
4014/// correspond to the given base type, for use in base initialization
4015/// within a constructor.
4016static bool FindBaseInitializer(Sema &SemaRef,
4017 CXXRecordDecl *ClassDecl,
4018 QualType BaseType,
4019 const CXXBaseSpecifier *&DirectBaseSpec,
4020 const CXXBaseSpecifier *&VirtualBaseSpec) {
4021 // First, check for a direct base class.
4022 DirectBaseSpec = nullptr;
4023 for (const auto &Base : ClassDecl->bases()) {
4024 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4025 // We found a direct base of this type. That's what we're
4026 // initializing.
4027 DirectBaseSpec = &Base;
4028 break;
4029 }
4030 }
4031
4032 // Check for a virtual base class.
4033 // FIXME: We might be able to short-circuit this if we know in advance that
4034 // there are no virtual bases.
4035 VirtualBaseSpec = nullptr;
4036 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4037 // We haven't found a base yet; search the class hierarchy for a
4038 // virtual base class.
4039 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4040 /*DetectVirtual=*/false);
4041 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4042 SemaRef.Context.getTypeDeclType(ClassDecl),
4043 BaseType, Paths)) {
4044 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4045 Path != Paths.end(); ++Path) {
4046 if (Path->back().Base->isVirtual()) {
4047 VirtualBaseSpec = Path->back().Base;
4048 break;
4049 }
4050 }
4051 }
4052 }
4053
4054 return DirectBaseSpec || VirtualBaseSpec;
4055}
4056
4057/// Handle a C++ member initializer using braced-init-list syntax.
4058MemInitResult
4059Sema::ActOnMemInitializer(Decl *ConstructorD,
4060 Scope *S,
4061 CXXScopeSpec &SS,
4062 IdentifierInfo *MemberOrBase,
4063 ParsedType TemplateTypeTy,
4064 const DeclSpec &DS,
4065 SourceLocation IdLoc,
4066 Expr *InitList,
4067 SourceLocation EllipsisLoc) {
4068 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4069 DS, IdLoc, InitList,
4070 EllipsisLoc);
4071}
4072
4073/// Handle a C++ member initializer using parentheses syntax.
4074MemInitResult
4075Sema::ActOnMemInitializer(Decl *ConstructorD,
4076 Scope *S,
4077 CXXScopeSpec &SS,
4078 IdentifierInfo *MemberOrBase,
4079 ParsedType TemplateTypeTy,
4080 const DeclSpec &DS,
4081 SourceLocation IdLoc,
4082 SourceLocation LParenLoc,
4083 ArrayRef<Expr *> Args,
4084 SourceLocation RParenLoc,
4085 SourceLocation EllipsisLoc) {
4086 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4087 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4088 DS, IdLoc, List, EllipsisLoc);
4089}
4090
4091namespace {
4092
4093// Callback to only accept typo corrections that can be a valid C++ member
4094// intializer: either a non-static field member or a base class.
4095class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4096public:
4097 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4098 : ClassDecl(ClassDecl) {}
4099
4100 bool ValidateCandidate(const TypoCorrection &candidate) override {
4101 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4102 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4103 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4104 return isa<TypeDecl>(ND);
4105 }
4106 return false;
4107 }
4108
4109 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4110 return std::make_unique<MemInitializerValidatorCCC>(*this);
4111 }
4112
4113private:
4114 CXXRecordDecl *ClassDecl;
4115};
4116
4117}
4118
4119ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4120 CXXScopeSpec &SS,
4121 ParsedType TemplateTypeTy,
4122 IdentifierInfo *MemberOrBase) {
4123 if (SS.getScopeRep() || TemplateTypeTy)
4124 return nullptr;
4125 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4126 if (Result.empty())
4127 return nullptr;
4128 ValueDecl *Member;
4129 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4130 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4131 return Member;
4132 return nullptr;
4133}
4134
4135/// Handle a C++ member initializer.
4136MemInitResult
4137Sema::BuildMemInitializer(Decl *ConstructorD,
4138 Scope *S,
4139 CXXScopeSpec &SS,
4140 IdentifierInfo *MemberOrBase,
4141 ParsedType TemplateTypeTy,
4142 const DeclSpec &DS,
4143 SourceLocation IdLoc,
4144 Expr *Init,
4145 SourceLocation EllipsisLoc) {
4146 ExprResult Res = CorrectDelayedTyposInExpr(Init);
4147 if (!Res.isUsable())
4148 return true;
4149 Init = Res.get();
4150
4151 if (!ConstructorD)
4152 return true;
4153
4154 AdjustDeclIfTemplate(ConstructorD);
4155
4156 CXXConstructorDecl *Constructor
4157 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4158 if (!Constructor) {
4159 // The user wrote a constructor initializer on a function that is
4160 // not a C++ constructor. Ignore the error for now, because we may
4161 // have more member initializers coming; we'll diagnose it just
4162 // once in ActOnMemInitializers.
4163 return true;
4164 }
4165
4166 CXXRecordDecl *ClassDecl = Constructor->getParent();
4167
4168 // C++ [class.base.init]p2:
4169 // Names in a mem-initializer-id are looked up in the scope of the
4170 // constructor's class and, if not found in that scope, are looked
4171 // up in the scope containing the constructor's definition.
4172 // [Note: if the constructor's class contains a member with the
4173 // same name as a direct or virtual base class of the class, a
4174 // mem-initializer-id naming the member or base class and composed
4175 // of a single identifier refers to the class member. A
4176 // mem-initializer-id for the hidden base class may be specified
4177 // using a qualified name. ]
4178
4179 // Look for a member, first.
4180 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4181 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4182 if (EllipsisLoc.isValid())
4183 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4184 << MemberOrBase
4185 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4186
4187 return BuildMemberInitializer(Member, Init, IdLoc);
4188 }
4189 // It didn't name a member, so see if it names a class.
4190 QualType BaseType;
4191 TypeSourceInfo *TInfo = nullptr;
4192
4193 if (TemplateTypeTy) {
4194 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4195 if (BaseType.isNull())
4196 return true;
4197 } else if (DS.getTypeSpecType() == TST_decltype) {
4198 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4199 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4200 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4201 return true;
4202 } else {
4203 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4204 LookupParsedName(R, S, &SS);
4205
4206 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4207 if (!TyD) {
4208 if (R.isAmbiguous()) return true;
4209
4210 // We don't want access-control diagnostics here.
4211 R.suppressDiagnostics();
4212
4213 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4214 bool NotUnknownSpecialization = false;
4215 DeclContext *DC = computeDeclContext(SS, false);
4216 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4217 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4218
4219 if (!NotUnknownSpecialization) {
4220 // When the scope specifier can refer to a member of an unknown
4221 // specialization, we take it as a type name.
4222 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4223 SS.getWithLocInContext(Context),
4224 *MemberOrBase, IdLoc);
4225 if (BaseType.isNull())
4226 return true;
4227
4228 TInfo = Context.CreateTypeSourceInfo(BaseType);
4229 DependentNameTypeLoc TL =
4230 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4231 if (!TL.isNull()) {
4232 TL.setNameLoc(IdLoc);
4233 TL.setElaboratedKeywordLoc(SourceLocation());
4234 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4235 }
4236
4237 R.clear();
4238 R.setLookupName(MemberOrBase);
4239 }
4240 }
4241
4242 // If no results were found, try to correct typos.
4243 TypoCorrection Corr;
4244 MemInitializerValidatorCCC CCC(ClassDecl);
4245 if (R.empty() && BaseType.isNull() &&
4246 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4247 CCC, CTK_ErrorRecovery, ClassDecl))) {
4248 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4249 // We have found a non-static data member with a similar
4250 // name to what was typed; complain and initialize that
4251 // member.
4252 diagnoseTypo(Corr,
4253 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4254 << MemberOrBase << true);
4255 return BuildMemberInitializer(Member, Init, IdLoc);
4256 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4257 const CXXBaseSpecifier *DirectBaseSpec;
4258 const CXXBaseSpecifier *VirtualBaseSpec;
4259 if (FindBaseInitializer(*this, ClassDecl,
4260 Context.getTypeDeclType(Type),
4261 DirectBaseSpec, VirtualBaseSpec)) {
4262 // We have found a direct or virtual base class with a
4263 // similar name to what was typed; complain and initialize
4264 // that base class.
4265 diagnoseTypo(Corr,
4266 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4267 << MemberOrBase << false,
4268 PDiag() /*Suppress note, we provide our own.*/);
4269
4270 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4271 : VirtualBaseSpec;
4272 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4273 << BaseSpec->getType() << BaseSpec->getSourceRange();
4274
4275 TyD = Type;
4276 }
4277 }
4278 }
4279
4280 if (!TyD && BaseType.isNull()) {
4281 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4282 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4283 return true;
4284 }
4285 }
4286
4287 if (BaseType.isNull()) {
4288 BaseType = Context.getTypeDeclType(TyD);
4289 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4290 if (SS.isSet()) {
4291 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4292 BaseType);
4293 TInfo = Context.CreateTypeSourceInfo(BaseType);
4294 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4295 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4296 TL.setElaboratedKeywordLoc(SourceLocation());
4297 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4298 }
4299 }
4300 }
4301
4302 if (!TInfo)
4303 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4304
4305 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4306}
4307
4308MemInitResult
4309Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4310 SourceLocation IdLoc) {
4311 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4312 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4313 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4314, __PRETTY_FUNCTION__))
4314 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4314, __PRETTY_FUNCTION__))
;
4315
4316 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4317 return true;
4318
4319 if (Member->isInvalidDecl())
4320 return true;
4321
4322 MultiExprArg Args;
4323 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4324 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4325 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4326 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4327 } else {
4328 // Template instantiation doesn't reconstruct ParenListExprs for us.
4329 Args = Init;
4330 }
4331
4332 SourceRange InitRange = Init->getSourceRange();
4333
4334 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4335 // Can't check initialization for a member of dependent type or when
4336 // any of the arguments are type-dependent expressions.
4337 DiscardCleanupsInEvaluationContext();
4338 } else {
4339 bool InitList = false;
4340 if (isa<InitListExpr>(Init)) {
4341 InitList = true;
4342 Args = Init;
4343 }
4344
4345 // Initialize the member.
4346 InitializedEntity MemberEntity =
4347 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4348 : InitializedEntity::InitializeMember(IndirectMember,
4349 nullptr);
4350 InitializationKind Kind =
4351 InitList ? InitializationKind::CreateDirectList(
4352 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4353 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4354 InitRange.getEnd());
4355
4356 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4357 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4358 nullptr);
4359 if (MemberInit.isInvalid())
4360 return true;
4361
4362 // C++11 [class.base.init]p7:
4363 // The initialization of each base and member constitutes a
4364 // full-expression.
4365 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4366 /*DiscardedValue*/ false);
4367 if (MemberInit.isInvalid())
4368 return true;
4369
4370 Init = MemberInit.get();
4371 }
4372
4373 if (DirectMember) {
4374 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4375 InitRange.getBegin(), Init,
4376 InitRange.getEnd());
4377 } else {
4378 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4379 InitRange.getBegin(), Init,
4380 InitRange.getEnd());
4381 }
4382}
4383
4384MemInitResult
4385Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4386 CXXRecordDecl *ClassDecl) {
4387 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4388 if (!LangOpts.CPlusPlus11)
4389 return Diag(NameLoc, diag::err_delegating_ctor)
4390 << TInfo->getTypeLoc().getLocalSourceRange();
4391 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4392
4393 bool InitList = true;
4394 MultiExprArg Args = Init;
4395 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4396 InitList = false;
4397 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4398 }
4399
4400 SourceRange InitRange = Init->getSourceRange();
4401 // Initialize the object.
4402 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4403 QualType(ClassDecl->getTypeForDecl(), 0));
4404 InitializationKind Kind =
4405 InitList ? InitializationKind::CreateDirectList(
4406 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4407 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4408 InitRange.getEnd());
4409 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4410 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4411 Args, nullptr);
4412 if (DelegationInit.isInvalid())
4413 return true;
4414
4415 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4416, __PRETTY_FUNCTION__))
4416 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4416, __PRETTY_FUNCTION__))
;
4417
4418 // C++11 [class.base.init]p7:
4419 // The initialization of each base and member constitutes a
4420 // full-expression.
4421 DelegationInit = ActOnFinishFullExpr(
4422 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4423 if (DelegationInit.isInvalid())
4424 return true;
4425
4426 // If we are in a dependent context, template instantiation will
4427 // perform this type-checking again. Just save the arguments that we
4428 // received in a ParenListExpr.
4429 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4430 // of the information that we have about the base
4431 // initializer. However, deconstructing the ASTs is a dicey process,
4432 // and this approach is far more likely to get the corner cases right.
4433 if (CurContext->isDependentContext())
4434 DelegationInit = Init;
4435
4436 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4437 DelegationInit.getAs<Expr>(),
4438 InitRange.getEnd());
4439}
4440
4441MemInitResult
4442Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4443 Expr *Init, CXXRecordDecl *ClassDecl,
4444 SourceLocation EllipsisLoc) {
4445 SourceLocation BaseLoc
4446 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4447
4448 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4449 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4450 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4451
4452 // C++ [class.base.init]p2:
4453 // [...] Unless the mem-initializer-id names a nonstatic data
4454 // member of the constructor's class or a direct or virtual base
4455 // of that class, the mem-initializer is ill-formed. A
4456 // mem-initializer-list can initialize a base class using any
4457 // name that denotes that base class type.
4458 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4459
4460 SourceRange InitRange = Init->getSourceRange();
4461 if (EllipsisLoc.isValid()) {
4462 // This is a pack expansion.
4463 if (!BaseType->containsUnexpandedParameterPack()) {
4464 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4465 << SourceRange(BaseLoc, InitRange.getEnd());
4466
4467 EllipsisLoc = SourceLocation();
4468 }
4469 } else {
4470 // Check for any unexpanded parameter packs.
4471 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4472 return true;
4473
4474 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4475 return true;
4476 }
4477
4478 // Check for direct and virtual base classes.
4479 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4480 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4481 if (!Dependent) {
4482 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4483 BaseType))
4484 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4485
4486 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4487 VirtualBaseSpec);
4488
4489 // C++ [base.class.init]p2:
4490 // Unless the mem-initializer-id names a nonstatic data member of the
4491 // constructor's class or a direct or virtual base of that class, the
4492 // mem-initializer is ill-formed.
4493 if (!DirectBaseSpec && !VirtualBaseSpec) {
4494 // If the class has any dependent bases, then it's possible that
4495 // one of those types will resolve to the same type as
4496 // BaseType. Therefore, just treat this as a dependent base
4497 // class initialization. FIXME: Should we try to check the
4498 // initialization anyway? It seems odd.
4499 if (ClassDecl->hasAnyDependentBases())
4500 Dependent = true;
4501 else
4502 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4503 << BaseType << Context.getTypeDeclType(ClassDecl)
4504 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4505 }
4506 }
4507
4508 if (Dependent) {
4509 DiscardCleanupsInEvaluationContext();
4510
4511 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4512 /*IsVirtual=*/false,
4513 InitRange.getBegin(), Init,
4514 InitRange.getEnd(), EllipsisLoc);
4515 }
4516
4517 // C++ [base.class.init]p2:
4518 // If a mem-initializer-id is ambiguous because it designates both
4519 // a direct non-virtual base class and an inherited virtual base
4520 // class, the mem-initializer is ill-formed.
4521 if (DirectBaseSpec && VirtualBaseSpec)
4522 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4523 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4524
4525 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4526 if (!BaseSpec)
4527 BaseSpec = VirtualBaseSpec;
4528
4529 // Initialize the base.
4530 bool InitList = true;
4531 MultiExprArg Args = Init;
4532 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4533 InitList = false;
4534 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4535 }
4536
4537 InitializedEntity BaseEntity =
4538 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4539 InitializationKind Kind =
4540 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4541 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4542 InitRange.getEnd());
4543 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4544 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4545 if (BaseInit.isInvalid())
4546 return true;
4547
4548 // C++11 [class.base.init]p7:
4549 // The initialization of each base and member constitutes a
4550 // full-expression.
4551 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4552 /*DiscardedValue*/ false);
4553 if (BaseInit.isInvalid())
4554 return true;
4555
4556 // If we are in a dependent context, template instantiation will
4557 // perform this type-checking again. Just save the arguments that we
4558 // received in a ParenListExpr.
4559 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4560 // of the information that we have about the base
4561 // initializer. However, deconstructing the ASTs is a dicey process,
4562 // and this approach is far more likely to get the corner cases right.
4563 if (CurContext->isDependentContext())
4564 BaseInit = Init;
4565
4566 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4567 BaseSpec->isVirtual(),
4568 InitRange.getBegin(),
4569 BaseInit.getAs<Expr>(),
4570 InitRange.getEnd(), EllipsisLoc);
4571}
4572
4573// Create a static_cast\<T&&>(expr).
4574static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4575 if (T.isNull()) T = E->getType();
4576 QualType TargetType = SemaRef.BuildReferenceType(
4577 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4578 SourceLocation ExprLoc = E->getBeginLoc();
4579 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4580 TargetType, ExprLoc);
4581
4582 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4583 SourceRange(ExprLoc, ExprLoc),
4584 E->getSourceRange()).get();
4585}
4586
4587/// ImplicitInitializerKind - How an implicit base or member initializer should
4588/// initialize its base or member.
4589enum ImplicitInitializerKind {
4590 IIK_Default,
4591 IIK_Copy,
4592 IIK_Move,
4593 IIK_Inherit
4594};
4595
4596static bool
4597BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4598 ImplicitInitializerKind ImplicitInitKind,
4599 CXXBaseSpecifier *BaseSpec,
4600 bool IsInheritedVirtualBase,
4601 CXXCtorInitializer *&CXXBaseInit) {
4602 InitializedEntity InitEntity
4603 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4604 IsInheritedVirtualBase);
4605
4606 ExprResult BaseInit;
4607
4608 switch (ImplicitInitKind) {
4609 case IIK_Inherit:
4610 case IIK_Default: {
4611 InitializationKind InitKind
4612 = InitializationKind::CreateDefault(Constructor->getLocation());
4613 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4614 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4615 break;
4616 }
4617
4618 case IIK_Move:
4619 case IIK_Copy: {
4620 bool Moving = ImplicitInitKind == IIK_Move;
4621 ParmVarDecl *Param = Constructor->getParamDecl(0);
4622 QualType ParamType = Param->getType().getNonReferenceType();
4623
4624 Expr *CopyCtorArg =
4625 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4626 SourceLocation(), Param, false,
4627 Constructor->getLocation(), ParamType,
4628 VK_LValue, nullptr);
4629
4630 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4631
4632 // Cast to the base class to avoid ambiguities.
4633 QualType ArgTy =
4634 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4635 ParamType.getQualifiers());
4636
4637 if (Moving) {
4638 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4639 }
4640
4641 CXXCastPath BasePath;
4642 BasePath.push_back(BaseSpec);
4643 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4644 CK_UncheckedDerivedToBase,
4645 Moving ? VK_XValue : VK_LValue,
4646 &BasePath).get();
4647
4648 InitializationKind InitKind
4649 = InitializationKind::CreateDirect(Constructor->getLocation(),
4650 SourceLocation(), SourceLocation());
4651 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4652 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4653 break;
4654 }
4655 }
4656
4657 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4658 if (BaseInit.isInvalid())
4659 return true;
4660
4661 CXXBaseInit =
4662 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4663 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4664 SourceLocation()),
4665 BaseSpec->isVirtual(),
4666 SourceLocation(),
4667 BaseInit.getAs<Expr>(),
4668 SourceLocation(),
4669 SourceLocation());
4670
4671 return false;
4672}
4673
4674static bool RefersToRValueRef(Expr *MemRef) {
4675 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4676 return Referenced->getType()->isRValueReferenceType();
4677}
4678
4679static bool
4680BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4681 ImplicitInitializerKind ImplicitInitKind,
4682 FieldDecl *Field, IndirectFieldDecl *Indirect,
4683 CXXCtorInitializer *&CXXMemberInit) {
4684 if (Field->isInvalidDecl())
4685 return true;
4686
4687 SourceLocation Loc = Constructor->getLocation();
4688
4689 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4690 bool Moving = ImplicitInitKind == IIK_Move;
4691 ParmVarDecl *Param = Constructor->getParamDecl(0);
4692 QualType ParamType = Param->getType().getNonReferenceType();
4693
4694 // Suppress copying zero-width bitfields.
4695 if (Field->isZeroLengthBitField(SemaRef.Context))
4696 return false;
4697
4698 Expr *MemberExprBase =
4699 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4700 SourceLocation(), Param, false,
4701 Loc, ParamType, VK_LValue, nullptr);
4702
4703 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4704
4705 if (Moving) {
4706 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4707 }
4708
4709 // Build a reference to this field within the parameter.
4710 CXXScopeSpec SS;
4711 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4712 Sema::LookupMemberName);
4713 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4714 : cast<ValueDecl>(Field), AS_public);
4715 MemberLookup.resolveKind();
4716 ExprResult CtorArg
4717 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4718 ParamType, Loc,
4719 /*IsArrow=*/false,
4720 SS,
4721 /*TemplateKWLoc=*/SourceLocation(),
4722 /*FirstQualifierInScope=*/nullptr,
4723 MemberLookup,
4724 /*TemplateArgs=*/nullptr,
4725 /*S*/nullptr);
4726 if (CtorArg.isInvalid())
4727 return true;
4728
4729 // C++11 [class.copy]p15:
4730 // - if a member m has rvalue reference type T&&, it is direct-initialized
4731 // with static_cast<T&&>(x.m);
4732 if (RefersToRValueRef(CtorArg.get())) {
4733 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4734 }
4735
4736 InitializedEntity Entity =
4737 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4738 /*Implicit*/ true)
4739 : InitializedEntity::InitializeMember(Field, nullptr,
4740 /*Implicit*/ true);
4741
4742 // Direct-initialize to use the copy constructor.
4743 InitializationKind InitKind =
4744 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4745
4746 Expr *CtorArgE = CtorArg.getAs<Expr>();
4747 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4748 ExprResult MemberInit =
4749 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4750 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4751 if (MemberInit.isInvalid())
4752 return true;
4753
4754 if (Indirect)
4755 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4756 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4757 else
4758 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4759 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4760 return false;
4761 }
4762
4763 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4764, __PRETTY_FUNCTION__))
4764 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4764, __PRETTY_FUNCTION__))
;
4765
4766 QualType FieldBaseElementType =
4767 SemaRef.Context.getBaseElementType(Field->getType());
4768
4769 if (FieldBaseElementType->isRecordType()) {
4770 InitializedEntity InitEntity =
4771 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4772 /*Implicit*/ true)
4773 : InitializedEntity::InitializeMember(Field, nullptr,
4774 /*Implicit*/ true);
4775 InitializationKind InitKind =
4776 InitializationKind::CreateDefault(Loc);
4777
4778 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4779 ExprResult MemberInit =
4780 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4781
4782 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4783 if (MemberInit.isInvalid())
4784 return true;
4785
4786 if (Indirect)
4787 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4788 Indirect, Loc,
4789 Loc,
4790 MemberInit.get(),
4791 Loc);
4792 else
4793 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4794 Field, Loc, Loc,
4795 MemberInit.get(),
4796 Loc);
4797 return false;
4798 }
4799
4800 if (!Field->getParent()->isUnion()) {
4801 if (FieldBaseElementType->isReferenceType()) {
4802 SemaRef.Diag(Constructor->getLocation(),
4803 diag::err_uninitialized_member_in_ctor)
4804 << (int)Constructor->isImplicit()
4805 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4806 << 0 << Field->getDeclName();
4807 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4808 return true;
4809 }
4810
4811 if (FieldBaseElementType.isConstQualified()) {
4812 SemaRef.Diag(Constructor->getLocation(),
4813 diag::err_uninitialized_member_in_ctor)
4814 << (int)Constructor->isImplicit()
4815 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4816 << 1 << Field->getDeclName();
4817 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4818 return true;
4819 }
4820 }
4821
4822 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4823 // ARC and Weak:
4824 // Default-initialize Objective-C pointers to NULL.
4825 CXXMemberInit
4826 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4827 Loc, Loc,
4828 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4829 Loc);
4830 return false;
4831 }
4832
4833 // Nothing to initialize.
4834 CXXMemberInit = nullptr;
4835 return false;
4836}
4837
4838namespace {
4839struct BaseAndFieldInfo {
4840 Sema &S;
4841 CXXConstructorDecl *Ctor;
4842 bool AnyErrorsInInits;
4843 ImplicitInitializerKind IIK;
4844 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4845 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4846 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4847
4848 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4849 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4850 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4851 if (Ctor->getInheritedConstructor())
4852 IIK = IIK_Inherit;
4853 else if (Generated && Ctor->isCopyConstructor())
4854 IIK = IIK_Copy;
4855 else if (Generated && Ctor->isMoveConstructor())
4856 IIK = IIK_Move;
4857 else
4858 IIK = IIK_Default;
4859 }
4860
4861 bool isImplicitCopyOrMove() const {
4862 switch (IIK) {
4863 case IIK_Copy:
4864 case IIK_Move:
4865 return true;
4866
4867 case IIK_Default:
4868 case IIK_Inherit:
4869 return false;
4870 }
4871
4872 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4872)
;
4873 }
4874
4875 bool addFieldInitializer(CXXCtorInitializer *Init) {
4876 AllToInit.push_back(Init);
4877
4878 // Check whether this initializer makes the field "used".
4879 if (Init->getInit()->HasSideEffects(S.Context))
4880 S.UnusedPrivateFields.remove(Init->getAnyMember());
4881
4882 return false;
4883 }
4884
4885 bool isInactiveUnionMember(FieldDecl *Field) {
4886 RecordDecl *Record = Field->getParent();
4887 if (!Record->isUnion())
4888 return false;
4889
4890 if (FieldDecl *Active =
4891 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4892 return Active != Field->getCanonicalDecl();
4893
4894 // In an implicit copy or move constructor, ignore any in-class initializer.
4895 if (isImplicitCopyOrMove())
4896 return true;
4897
4898 // If there's no explicit initialization, the field is active only if it
4899 // has an in-class initializer...
4900 if (Field->hasInClassInitializer())
4901 return false;
4902 // ... or it's an anonymous struct or union whose class has an in-class
4903 // initializer.
4904 if (!Field->isAnonymousStructOrUnion())
4905 return true;
4906 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4907 return !FieldRD->hasInClassInitializer();
4908 }
4909
4910 /// Determine whether the given field is, or is within, a union member
4911 /// that is inactive (because there was an initializer given for a different
4912 /// member of the union, or because the union was not initialized at all).
4913 bool isWithinInactiveUnionMember(FieldDecl *Field,
4914 IndirectFieldDecl *Indirect) {
4915 if (!Indirect)
4916 return isInactiveUnionMember(Field);
4917
4918 for (auto *C : Indirect->chain()) {
4919 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4920 if (Field && isInactiveUnionMember(Field))
4921 return true;
4922 }
4923 return false;
4924 }
4925};
4926}
4927
4928/// Determine whether the given type is an incomplete or zero-lenfgth
4929/// array type.
4930static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4931 if (T->isIncompleteArrayType())
4932 return true;
4933
4934 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4935 if (!ArrayT->getSize())
4936 return true;
4937
4938 T = ArrayT->getElementType();
4939 }
4940
4941 return false;
4942}
4943
4944static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4945 FieldDecl *Field,
4946 IndirectFieldDecl *Indirect = nullptr) {
4947 if (Field->isInvalidDecl())
4948 return false;
4949
4950 // Overwhelmingly common case: we have a direct initializer for this field.
4951 if (CXXCtorInitializer *Init =
4952 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4953 return Info.addFieldInitializer(Init);
4954
4955 // C++11 [class.base.init]p8:
4956 // if the entity is a non-static data member that has a
4957 // brace-or-equal-initializer and either
4958 // -- the constructor's class is a union and no other variant member of that
4959 // union is designated by a mem-initializer-id or
4960 // -- the constructor's class is not a union, and, if the entity is a member
4961 // of an anonymous union, no other member of that union is designated by
4962 // a mem-initializer-id,
4963 // the entity is initialized as specified in [dcl.init].
4964 //
4965 // We also apply the same rules to handle anonymous structs within anonymous
4966 // unions.
4967 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4968 return false;
4969
4970 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4971 ExprResult DIE =
4972 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4973 if (DIE.isInvalid())
4974 return true;
4975
4976 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4977 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4978
4979 CXXCtorInitializer *Init;
4980 if (Indirect)
4981 Init = new (SemaRef.Context)
4982 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4983 SourceLocation(), DIE.get(), SourceLocation());
4984 else
4985 Init = new (SemaRef.Context)
4986 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4987 SourceLocation(), DIE.get(), SourceLocation());
4988 return Info.addFieldInitializer(Init);
4989 }
4990
4991 // Don't initialize incomplete or zero-length arrays.
4992 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4993 return false;
4994
4995 // Don't try to build an implicit initializer if there were semantic
4996 // errors in any of the initializers (and therefore we might be
4997 // missing some that the user actually wrote).
4998 if (Info.AnyErrorsInInits)
4999 return false;
5000
5001 CXXCtorInitializer *Init = nullptr;
5002 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5003 Indirect, Init))
5004 return true;
5005
5006 if (!Init)
5007 return false;
5008
5009 return Info.addFieldInitializer(Init);
5010}
5011
5012bool
5013Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5014 CXXCtorInitializer *Initializer) {
5015 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5015, __PRETTY_FUNCTION__))
;
5016 Constructor->setNumCtorInitializers(1);
5017 CXXCtorInitializer **initializer =
5018 new (Context) CXXCtorInitializer*[1];
5019 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5020 Constructor->setCtorInitializers(initializer);
5021
5022 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5023 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5024 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5025 }
5026
5027 DelegatingCtorDecls.push_back(Constructor);
5028
5029 DiagnoseUninitializedFields(*this, Constructor);
5030
5031 return false;
5032}
5033
5034bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5035 ArrayRef<CXXCtorInitializer *> Initializers) {
5036 if (Constructor->isDependentContext()) {
5037 // Just store the initializers as written, they will be checked during
5038 // instantiation.
5039 if (!Initializers.empty()) {
5040 Constructor->setNumCtorInitializers(Initializers.size());
5041 CXXCtorInitializer **baseOrMemberInitializers =
5042 new (Context) CXXCtorInitializer*[Initializers.size()];
5043 memcpy(baseOrMemberInitializers, Initializers.data(),
5044 Initializers.size() * sizeof(CXXCtorInitializer*));
5045 Constructor->setCtorInitializers(baseOrMemberInitializers);
5046 }
5047
5048 // Let template instantiation know whether we had errors.
5049 if (AnyErrors)
5050 Constructor->setInvalidDecl();
5051
5052 return false;
5053 }
5054
5055 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5056
5057 // We need to build the initializer AST according to order of construction
5058 // and not what user specified in the Initializers list.
5059 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5060 if (!ClassDecl)
5061 return true;
5062
5063 bool HadError = false;
5064
5065 for (unsigned i = 0; i < Initializers.size(); i++) {
5066 CXXCtorInitializer *Member = Initializers[i];
5067
5068 if (Member->isBaseInitializer())
5069 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5070 else {
5071 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5072
5073 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5074 for (auto *C : F->chain()) {
5075 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5076 if (FD && FD->getParent()->isUnion())
5077 Info.ActiveUnionMember.insert(std::make_pair(
5078 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5079 }
5080 } else if (FieldDecl *FD = Member->getMember()) {
5081 if (FD->getParent()->isUnion())
5082 Info.ActiveUnionMember.insert(std::make_pair(
5083 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5084 }
5085 }
5086 }
5087
5088 // Keep track of the direct virtual bases.
5089 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5090 for (auto &I : ClassDecl->bases()) {
5091 if (I.isVirtual())
5092 DirectVBases.insert(&I);
5093 }
5094
5095 // Push virtual bases before others.
5096 for (auto &VBase : ClassDecl->vbases()) {
5097 if (CXXCtorInitializer *Value
5098 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5099 // [class.base.init]p7, per DR257:
5100 // A mem-initializer where the mem-initializer-id names a virtual base
5101 // class is ignored during execution of a constructor of any class that
5102 // is not the most derived class.
5103 if (ClassDecl->isAbstract()) {
5104 // FIXME: Provide a fixit to remove the base specifier. This requires
5105 // tracking the location of the associated comma for a base specifier.
5106 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5107 << VBase.getType() << ClassDecl;
5108 DiagnoseAbstractType(ClassDecl);
5109 }
5110
5111 Info.AllToInit.push_back(Value);
5112 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5113 // [class.base.init]p8, per DR257:
5114 // If a given [...] base class is not named by a mem-initializer-id
5115 // [...] and the entity is not a virtual base class of an abstract
5116 // class, then [...] the entity is default-initialized.
5117 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5118 CXXCtorInitializer *CXXBaseInit;
5119 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5120 &VBase, IsInheritedVirtualBase,
5121 CXXBaseInit)) {
5122 HadError = true;
5123 continue;
5124 }
5125
5126 Info.AllToInit.push_back(CXXBaseInit);
5127 }
5128 }
5129
5130 // Non-virtual bases.
5131 for (auto &Base : ClassDecl->bases()) {
5132 // Virtuals are in the virtual base list and already constructed.
5133 if (Base.isVirtual())
5134 continue;
5135
5136 if (CXXCtorInitializer *Value
5137 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5138 Info.AllToInit.push_back(Value);
5139 } else if (!AnyErrors) {
5140 CXXCtorInitializer *CXXBaseInit;
5141 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5142 &Base, /*IsInheritedVirtualBase=*/false,
5143 CXXBaseInit)) {
5144 HadError = true;
5145 continue;
5146 }
5147
5148 Info.AllToInit.push_back(CXXBaseInit);
5149 }
5150 }
5151
5152 // Fields.
5153 for (auto *Mem : ClassDecl->decls()) {
5154 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5155 // C++ [class.bit]p2:
5156 // A declaration for a bit-field that omits the identifier declares an
5157 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5158 // initialized.
5159 if (F->isUnnamedBitfield())
5160 continue;
5161
5162 // If we're not generating the implicit copy/move constructor, then we'll
5163 // handle anonymous struct/union fields based on their individual
5164 // indirect fields.
5165 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5166 continue;
5167
5168 if (CollectFieldInitializer(*this, Info, F))
5169 HadError = true;
5170 continue;
5171 }
5172
5173 // Beyond this point, we only consider default initialization.
5174 if (Info.isImplicitCopyOrMove())
5175 continue;
5176
5177 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5178 if (F->getType()->isIncompleteArrayType()) {
5179 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5180, __PRETTY_FUNCTION__))
5180 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5180, __PRETTY_FUNCTION__))
;
5181 continue;
5182 }
5183
5184 // Initialize each field of an anonymous struct individually.
5185 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5186 HadError = true;
5187
5188 continue;
5189 }
5190 }
5191
5192 unsigned NumInitializers = Info.AllToInit.size();
5193 if (NumInitializers > 0) {
5194 Constructor->setNumCtorInitializers(NumInitializers);
5195 CXXCtorInitializer **baseOrMemberInitializers =
5196 new (Context) CXXCtorInitializer*[NumInitializers];
5197 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5198 NumInitializers * sizeof(CXXCtorInitializer*));
5199 Constructor->setCtorInitializers(baseOrMemberInitializers);
5200
5201 // Constructors implicitly reference the base and member
5202 // destructors.
5203 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5204 Constructor->getParent());
5205 }
5206
5207 return HadError;
5208}
5209
5210static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5211 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5212 const RecordDecl *RD = RT->getDecl();
5213 if (RD->isAnonymousStructOrUnion()) {
5214 for (auto *Field : RD->fields())
5215 PopulateKeysForFields(Field, IdealInits);
5216 return;
5217 }
5218 }
5219 IdealInits.push_back(Field->getCanonicalDecl());
5220}
5221
5222static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5223 return Context.getCanonicalType(BaseType).getTypePtr();
5224}
5225
5226static const void *GetKeyForMember(ASTContext &Context,
5227 CXXCtorInitializer *Member) {
5228 if (!Member->isAnyMemberInitializer())
5229 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5230
5231 return Member->getAnyMember()->getCanonicalDecl();
5232}
5233
5234static void DiagnoseBaseOrMemInitializerOrder(
5235 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5236 ArrayRef<CXXCtorInitializer *> Inits) {
5237 if (Constructor->getDeclContext()->isDependentContext())
5238 return;
5239
5240 // Don't check initializers order unless the warning is enabled at the
5241 // location of at least one initializer.
5242 bool ShouldCheckOrder = false;
5243 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5244 CXXCtorInitializer *Init = Inits[InitIndex];
5245 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5246 Init->getSourceLocation())) {
5247 ShouldCheckOrder = true;
5248 break;
5249 }
5250 }
5251 if (!ShouldCheckOrder)
5252 return;
5253
5254 // Build the list of bases and members in the order that they'll
5255 // actually be initialized. The explicit initializers should be in
5256 // this same order but may be missing things.
5257 SmallVector<const void*, 32> IdealInitKeys;
5258
5259 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5260
5261 // 1. Virtual bases.
5262 for (const auto &VBase : ClassDecl->vbases())
5263 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5264
5265 // 2. Non-virtual bases.
5266 for (const auto &Base : ClassDecl->bases()) {
5267 if (Base.isVirtual())
5268 continue;
5269 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5270 }
5271
5272 // 3. Direct fields.
5273 for (auto *Field : ClassDecl->fields()) {
5274 if (Field->isUnnamedBitfield())
5275 continue;
5276
5277 PopulateKeysForFields(Field, IdealInitKeys);
5278 }
5279
5280 unsigned NumIdealInits = IdealInitKeys.size();
5281 unsigned IdealIndex = 0;
5282
5283 CXXCtorInitializer *PrevInit = nullptr;
5284 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5285 CXXCtorInitializer *Init = Inits[InitIndex];
5286 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5287
5288 // Scan forward to try to find this initializer in the idealized
5289 // initializers list.
5290 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5291 if (InitKey == IdealInitKeys[IdealIndex])
5292 break;
5293
5294 // If we didn't find this initializer, it must be because we
5295 // scanned past it on a previous iteration. That can only
5296 // happen if we're out of order; emit a warning.
5297 if (IdealIndex == NumIdealInits && PrevInit) {
5298 Sema::SemaDiagnosticBuilder D =
5299 SemaRef.Diag(PrevInit->getSourceLocation(),
5300 diag::warn_initializer_out_of_order);
5301
5302 if (PrevInit->isAnyMemberInitializer())
5303 D << 0 << PrevInit->getAnyMember()->getDeclName();
5304 else
5305 D << 1 << PrevInit->getTypeSourceInfo()->getType();
5306
5307 if (Init->isAnyMemberInitializer())
5308 D << 0 << Init->getAnyMember()->getDeclName();
5309 else
5310 D << 1 << Init->getTypeSourceInfo()->getType();
5311
5312 // Move back to the initializer's location in the ideal list.
5313 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5314 if (InitKey == IdealInitKeys[IdealIndex])
5315 break;
5316
5317 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5318, __PRETTY_FUNCTION__))
5318 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5318, __PRETTY_FUNCTION__))
;
5319 }
5320
5321 PrevInit = Init;
5322 }
5323}
5324
5325namespace {
5326bool CheckRedundantInit(Sema &S,
5327 CXXCtorInitializer *Init,
5328 CXXCtorInitializer *&PrevInit) {
5329 if (!PrevInit) {
5330 PrevInit = Init;
5331 return false;
5332 }
5333
5334 if (FieldDecl *Field = Init->getAnyMember())
5335 S.Diag(Init->getSourceLocation(),
5336 diag::err_multiple_mem_initialization)
5337 << Field->getDeclName()
5338 << Init->getSourceRange();
5339 else {
5340 const Type *BaseClass = Init->getBaseClass();
5341 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5341, __PRETTY_FUNCTION__))
;
5342 S.Diag(Init->getSourceLocation(),
5343 diag::err_multiple_base_initialization)
5344 << QualType(BaseClass, 0)
5345 << Init->getSourceRange();
5346 }
5347 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5348 << 0 << PrevInit->getSourceRange();
5349
5350 return true;
5351}
5352
5353typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5354typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5355
5356bool CheckRedundantUnionInit(Sema &S,
5357 CXXCtorInitializer *Init,
5358 RedundantUnionMap &Unions) {
5359 FieldDecl *Field = Init->getAnyMember();
5360 RecordDecl *Parent = Field->getParent();
5361 NamedDecl *Child = Field;
5362
5363 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5364 if (Parent->isUnion()) {
5365 UnionEntry &En = Unions[Parent];
5366 if (En.first && En.first != Child) {
5367 S.Diag(Init->getSourceLocation(),
5368 diag::err_multiple_mem_union_initialization)
5369 << Field->getDeclName()
5370 << Init->getSourceRange();
5371 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5372 << 0 << En.second->getSourceRange();
5373 return true;
5374 }
5375 if (!En.first) {
5376 En.first = Child;
5377 En.second = Init;
5378 }
5379 if (!Parent->isAnonymousStructOrUnion())
5380 return false;
5381 }
5382
5383 Child = Parent;
5384 Parent = cast<RecordDecl>(Parent->getDeclContext());
5385 }
5386
5387 return false;
5388}
5389}
5390
5391/// ActOnMemInitializers - Handle the member initializers for a constructor.
5392void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5393 SourceLocation ColonLoc,
5394 ArrayRef<CXXCtorInitializer*> MemInits,
5395 bool AnyErrors) {
5396 if (!ConstructorDecl)
5397 return;
5398
5399 AdjustDeclIfTemplate(ConstructorDecl);
5400
5401 CXXConstructorDecl *Constructor
5402 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5403
5404 if (!Constructor) {
5405 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5406 return;
5407 }
5408
5409 // Mapping for the duplicate initializers check.
5410 // For member initializers, this is keyed with a FieldDecl*.
5411 // For base initializers, this is keyed with a Type*.
5412 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5413
5414 // Mapping for the inconsistent anonymous-union initializers check.
5415 RedundantUnionMap MemberUnions;
5416
5417 bool HadError = false;
5418 for (unsigned i = 0; i < MemInits.size(); i++) {
5419 CXXCtorInitializer *Init = MemInits[i];
5420
5421 // Set the source order index.
5422 Init->setSourceOrder(i);
5423
5424 if (Init->isAnyMemberInitializer()) {
5425 const void *Key = GetKeyForMember(Context, Init);
5426 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5427 CheckRedundantUnionInit(*this, Init, MemberUnions))
5428 HadError = true;
5429 } else if (Init->isBaseInitializer()) {
5430 const void *Key = GetKeyForMember(Context, Init);
5431 if (CheckRedundantInit(*this, Init, Members[Key]))
5432 HadError = true;
5433 } else {
5434 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5434, __PRETTY_FUNCTION__))
;
5435 // This must be the only initializer
5436 if (MemInits.size() != 1) {
5437 Diag(Init->getSourceLocation(),
5438 diag::err_delegating_initializer_alone)
5439 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5440 // We will treat this as being the only initializer.
5441 }
5442 SetDelegatingInitializer(Constructor, MemInits[i]);
5443 // Return immediately as the initializer is set.
5444 return;
5445 }
5446 }
5447
5448 if (HadError)
5449 return;
5450
5451 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5452
5453 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5454
5455 DiagnoseUninitializedFields(*this, Constructor);
5456}
5457
5458void
5459Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5460 CXXRecordDecl *ClassDecl) {
5461 // Ignore dependent contexts. Also ignore unions, since their members never
5462 // have destructors implicitly called.
5463 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
18
Assuming the condition is false
19
Calling 'TagDecl::isUnion'
22
Returning from 'TagDecl::isUnion'
23
Taking false branch
5464 return;
5465
5466 // FIXME: all the access-control diagnostics are positioned on the
5467 // field/base declaration. That's probably good; that said, the
5468 // user might reasonably want to know why the destructor is being
5469 // emitted, and we currently don't say.
5470
5471 // Non-static data members.
5472 for (auto *Field : ClassDecl->fields()) {
5473 if (Field->isInvalidDecl())
5474 continue;
5475
5476 // Don't destroy incomplete or zero-length arrays.
5477 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5478 continue;
5479
5480 QualType FieldType = Context.getBaseElementType(Field->getType());
5481
5482 const RecordType* RT = FieldType->getAs<RecordType>();
5483 if (!RT)
5484 continue;
5485
5486 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5487 if (FieldClassDecl->isInvalidDecl())
5488 continue;
5489 if (FieldClassDecl->hasIrrelevantDestructor())
5490 continue;
5491 // The destructor for an implicit anonymous union member is never invoked.
5492 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5493 continue;
5494
5495 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5496 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5496, __PRETTY_FUNCTION__))
;
5497 CheckDestructorAccess(Field->getLocation(), Dtor,
5498 PDiag(diag::err_access_dtor_field)
5499 << Field->getDeclName()
5500 << FieldType);
5501
5502 MarkFunctionReferenced(Location, Dtor);
5503 DiagnoseUseOfDecl(Dtor, Location);
5504 }
5505
5506 // We only potentially invoke the destructors of potentially constructed
5507 // subobjects.
5508 bool VisitVirtualBases = !ClassDecl->isAbstract();
24
Assuming the condition is false
5509
5510 // If the destructor exists and has already been marked used in the MS ABI,
5511 // then virtual base destructors have already been checked and marked used.
5512 // Skip checking them again to avoid duplicate diagnostics.
5513 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
25
Taking true branch
5514 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5515 if (Dtor && Dtor->isUsed())
26
Assuming 'Dtor' is null
5516 VisitVirtualBases = false;
5517 }
5518
5519 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5520
5521 // Bases.
5522 for (const auto &Base : ClassDecl->bases()) {
27
Assuming '__begin1' is not equal to '__end1'
5523 // Bases are always records in a well-formed non-dependent class.
5524 const RecordType *RT = Base.getType()->getAs<RecordType>();
28
Assuming the object is not a 'RecordType'
29
'RT' initialized to a null pointer value
5525
5526 // Remember direct virtual bases.
5527 if (Base.isVirtual()) {
30
Assuming the condition is false
31
Taking false branch
5528 if (!VisitVirtualBases)
5529 continue;
5530 DirectVirtualBases.insert(RT);
5531 }
5532
5533 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
32
Called C++ object pointer is null
5534 // If our base class is invalid, we probably can't get its dtor anyway.
5535 if (BaseClassDecl->isInvalidDecl())
5536 continue;
5537 if (BaseClassDecl->hasIrrelevantDestructor())
5538 continue;
5539
5540 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5541 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5541, __PRETTY_FUNCTION__))
;
5542
5543 // FIXME: caret should be on the start of the class name
5544 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5545 PDiag(diag::err_access_dtor_base)
5546 << Base.getType() << Base.getSourceRange(),
5547 Context.getTypeDeclType(ClassDecl));
5548
5549 MarkFunctionReferenced(Location, Dtor);
5550 DiagnoseUseOfDecl(Dtor, Location);
5551 }
5552
5553 if (VisitVirtualBases)
5554 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5555 &DirectVirtualBases);
5556}
5557
5558void Sema::MarkVirtualBaseDestructorsReferenced(
5559 SourceLocation Location, CXXRecordDecl *ClassDecl,
5560 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5561 // Virtual bases.
5562 for (const auto &VBase : ClassDecl->vbases()) {
5563 // Bases are always records in a well-formed non-dependent class.
5564 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5565
5566 // Ignore already visited direct virtual bases.
5567 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5568 continue;
5569
5570 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5571 // If our base class is invalid, we probably can't get its dtor anyway.
5572 if (BaseClassDecl->isInvalidDecl())
5573 continue;
5574 if (BaseClassDecl->hasIrrelevantDestructor())
5575 continue;
5576
5577 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5578 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5578, __PRETTY_FUNCTION__))
;
5579 if (CheckDestructorAccess(
5580 ClassDecl->getLocation(), Dtor,
5581 PDiag(diag::err_access_dtor_vbase)
5582 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5583 Context.getTypeDeclType(ClassDecl)) ==
5584 AR_accessible) {
5585 CheckDerivedToBaseConversion(
5586 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5587 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5588 SourceRange(), DeclarationName(), nullptr);
5589 }
5590
5591 MarkFunctionReferenced(Location, Dtor);
5592 DiagnoseUseOfDecl(Dtor, Location);
5593 }
5594}
5595
5596void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5597 if (!CDtorDecl)
5598 return;
5599
5600 if (CXXConstructorDecl *Constructor
5601 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5602 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5603 DiagnoseUninitializedFields(*this, Constructor);
5604 }
5605}
5606
5607bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5608 if (!getLangOpts().CPlusPlus)
5609 return false;
5610
5611 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5612 if (!RD)
5613 return false;
5614
5615 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5616 // class template specialization here, but doing so breaks a lot of code.
5617
5618 // We can't answer whether something is abstract until it has a
5619 // definition. If it's currently being defined, we'll walk back
5620 // over all the declarations when we have a full definition.
5621 const CXXRecordDecl *Def = RD->getDefinition();
5622 if (!Def || Def->isBeingDefined())
5623 return false;
5624
5625 return RD->isAbstract();
5626}
5627
5628bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5629 TypeDiagnoser &Diagnoser) {
5630 if (!isAbstractType(Loc, T))
5631 return false;
5632
5633 T = Context.getBaseElementType(T);
5634 Diagnoser.diagnose(*this, Loc, T);
5635 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5636 return true;
5637}
5638
5639void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5640 // Check if we've already emitted the list of pure virtual functions
5641 // for this class.
5642 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5643 return;
5644
5645 // If the diagnostic is suppressed, don't emit the notes. We're only
5646 // going to emit them once, so try to attach them to a diagnostic we're
5647 // actually going to show.
5648 if (Diags.isLastDiagnosticIgnored())
5649 return;
5650
5651 CXXFinalOverriderMap FinalOverriders;
5652 RD->getFinalOverriders(FinalOverriders);
5653
5654 // Keep a set of seen pure methods so we won't diagnose the same method
5655 // more than once.
5656 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5657
5658 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5659 MEnd = FinalOverriders.end();
5660 M != MEnd;
5661 ++M) {
5662 for (OverridingMethods::iterator SO = M->second.begin(),
5663 SOEnd = M->second.end();
5664 SO != SOEnd; ++SO) {
5665 // C++ [class.abstract]p4:
5666 // A class is abstract if it contains or inherits at least one
5667 // pure virtual function for which the final overrider is pure
5668 // virtual.
5669
5670 //
5671 if (SO->second.size() != 1)
5672 continue;
5673
5674 if (!SO->second.front().Method->isPure())
5675 continue;
5676
5677 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5678 continue;
5679
5680 Diag(SO->second.front().Method->getLocation(),
5681 diag::note_pure_virtual_function)
5682 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5683 }
5684 }
5685
5686 if (!PureVirtualClassDiagSet)
5687 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5688 PureVirtualClassDiagSet->insert(RD);
5689}
5690
5691namespace {
5692struct AbstractUsageInfo {
5693 Sema &S;
5694 CXXRecordDecl *Record;
5695 CanQualType AbstractType;
5696 bool Invalid;
5697
5698 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5699 : S(S), Record(Record),
5700 AbstractType(S.Context.getCanonicalType(
5701 S.Context.getTypeDeclType(Record))),
5702 Invalid(false) {}
5703
5704 void DiagnoseAbstractType() {
5705 if (Invalid) return;
5706 S.DiagnoseAbstractType(Record);
5707 Invalid = true;
5708 }
5709
5710 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5711};
5712
5713struct CheckAbstractUsage {
5714 AbstractUsageInfo &Info;
5715 const NamedDecl *Ctx;
5716
5717 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5718 : Info(Info), Ctx(Ctx) {}
5719
5720 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5721 switch (TL.getTypeLocClass()) {
5722#define ABSTRACT_TYPELOC(CLASS, PARENT)
5723#define TYPELOC(CLASS, PARENT) \
5724 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5725#include "clang/AST/TypeLocNodes.def"
5726 }
5727 }
5728
5729 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5730 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5731 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5732 if (!TL.getParam(I))
5733 continue;
5734
5735 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5736 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5737 }
5738 }
5739
5740 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5741 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5742 }
5743
5744 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5745 // Visit the type parameters from a permissive context.
5746 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5747 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5748 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5749 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5750 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5751 // TODO: other template argument types?
5752 }
5753 }
5754
5755 // Visit pointee types from a permissive context.
5756#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5757 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5758 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5759 }
5760 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5761 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5762 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5763 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5764 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5765
5766 /// Handle all the types we haven't given a more specific
5767 /// implementation for above.
5768 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5769 // Every other kind of type that we haven't called out already
5770 // that has an inner type is either (1) sugar or (2) contains that
5771 // inner type in some way as a subobject.
5772 if (TypeLoc Next = TL.getNextTypeLoc())
5773 return Visit(Next, Sel);
5774
5775 // If there's no inner type and we're in a permissive context,
5776 // don't diagnose.
5777 if (Sel == Sema::AbstractNone) return;
5778
5779 // Check whether the type matches the abstract type.
5780 QualType T = TL.getType();
5781 if (T->isArrayType()) {
5782 Sel = Sema::AbstractArrayType;
5783 T = Info.S.Context.getBaseElementType(T);
5784 }
5785 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5786 if (CT != Info.AbstractType) return;
5787
5788 // It matched; do some magic.
5789 if (Sel == Sema::AbstractArrayType) {
5790 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5791 << T << TL.getSourceRange();
5792 } else {
5793 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5794 << Sel << T << TL.getSourceRange();
5795 }
5796 Info.DiagnoseAbstractType();
5797 }
5798};
5799
5800void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5801 Sema::AbstractDiagSelID Sel) {
5802 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5803}
5804
5805}
5806
5807/// Check for invalid uses of an abstract type in a method declaration.
5808static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5809 CXXMethodDecl *MD) {
5810 // No need to do the check on definitions, which require that
5811 // the return/param types be complete.
5812 if (MD->doesThisDeclarationHaveABody())
5813 return;
5814
5815 // For safety's sake, just ignore it if we don't have type source
5816 // information. This should never happen for non-implicit methods,
5817 // but...
5818 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5819 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5820}
5821
5822/// Check for invalid uses of an abstract type within a class definition.
5823static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5824 CXXRecordDecl *RD) {
5825 for (auto *D : RD->decls()) {
5826 if (D->isImplicit()) continue;
5827
5828 // Methods and method templates.
5829 if (isa<CXXMethodDecl>(D)) {
5830 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5831 } else if (isa<FunctionTemplateDecl>(D)) {
5832 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5833 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5834
5835 // Fields and static variables.
5836 } else if (isa<FieldDecl>(D)) {
5837 FieldDecl *FD = cast<FieldDecl>(D);
5838 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5839 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5840 } else if (isa<VarDecl>(D)) {
5841 VarDecl *VD = cast<VarDecl>(D);
5842 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5843 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5844
5845 // Nested classes and class templates.
5846 } else if (isa<CXXRecordDecl>(D)) {
5847 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5848 } else if (isa<ClassTemplateDecl>(D)) {
5849 CheckAbstractClassUsage(Info,
5850 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5851 }
5852 }
5853}
5854
5855static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5856 Attr *ClassAttr = getDLLAttr(Class);
5857 if (!ClassAttr)
5858 return;
5859
5860 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5860, __PRETTY_FUNCTION__))
;
5861
5862 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5863
5864 if (TSK == TSK_ExplicitInstantiationDeclaration)
5865 // Don't go any further if this is just an explicit instantiation
5866 // declaration.
5867 return;
5868
5869 // Add a context note to explain how we got to any diagnostics produced below.
5870 struct MarkingClassDllexported {
5871 Sema &S;
5872 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5873 SourceLocation AttrLoc)
5874 : S(S) {
5875 Sema::CodeSynthesisContext Ctx;
5876 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5877 Ctx.PointOfInstantiation = AttrLoc;
5878 Ctx.Entity = Class;
5879 S.pushCodeSynthesisContext(Ctx);
5880 }
5881 ~MarkingClassDllexported() {
5882 S.popCodeSynthesisContext();
5883 }
5884 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5885
5886 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5887 S.MarkVTableUsed(Class->getLocation(), Class, true);
5888
5889 for (Decl *Member : Class->decls()) {
5890 // Defined static variables that are members of an exported base
5891 // class must be marked export too.
5892 auto *VD = dyn_cast<VarDecl>(Member);
5893 if (VD && Member->getAttr<DLLExportAttr>() &&
5894 VD->getStorageClass() == SC_Static &&
5895 TSK == TSK_ImplicitInstantiation)
5896 S.MarkVariableReferenced(VD->getLocation(), VD);
5897
5898 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5899 if (!MD)
5900 continue;
5901
5902 if (Member->getAttr<DLLExportAttr>()) {
5903 if (MD->isUserProvided()) {
5904 // Instantiate non-default class member functions ...
5905
5906 // .. except for certain kinds of template specializations.
5907 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5908 continue;
5909
5910 S.MarkFunctionReferenced(Class->getLocation(), MD);
5911
5912 // The function will be passed to the consumer when its definition is
5913 // encountered.
5914 } else if (MD->isExplicitlyDefaulted()) {
5915 // Synthesize and instantiate explicitly defaulted methods.
5916 S.MarkFunctionReferenced(Class->getLocation(), MD);
5917
5918 if (TSK != TSK_ExplicitInstantiationDefinition) {
5919 // Except for explicit instantiation defs, we will not see the
5920 // definition again later, so pass it to the consumer now.
5921 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5922 }
5923 } else if (!MD->isTrivial() ||
5924 MD->isCopyAssignmentOperator() ||
5925 MD->isMoveAssignmentOperator()) {
5926 // Synthesize and instantiate non-trivial implicit methods, and the copy
5927 // and move assignment operators. The latter are exported even if they
5928 // are trivial, because the address of an operator can be taken and
5929 // should compare equal across libraries.
5930 S.MarkFunctionReferenced(Class->getLocation(), MD);
5931
5932 // There is no later point when we will see the definition of this
5933 // function, so pass it to the consumer now.
5934 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5935 }
5936 }
5937 }
5938}
5939
5940static void checkForMultipleExportedDefaultConstructors(Sema &S,
5941 CXXRecordDecl *Class) {
5942 // Only the MS ABI has default constructor closures, so we don't need to do
5943 // this semantic checking anywhere else.
5944 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5945 return;
5946
5947 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5948 for (Decl *Member : Class->decls()) {
5949 // Look for exported default constructors.
5950 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5951 if (!CD || !CD->isDefaultConstructor())
5952 continue;
5953 auto *Attr = CD->getAttr<DLLExportAttr>();
5954 if (!Attr)
5955 continue;
5956
5957 // If the class is non-dependent, mark the default arguments as ODR-used so
5958 // that we can properly codegen the constructor closure.
5959 if (!Class->isDependentContext()) {
5960 for (ParmVarDecl *PD : CD->parameters()) {
5961 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5962 S.DiscardCleanupsInEvaluationContext();
5963 }
5964 }
5965
5966 if (LastExportedDefaultCtor) {
5967 S.Diag(LastExportedDefaultCtor->getLocation(),
5968 diag::err_attribute_dll_ambiguous_default_ctor)
5969 << Class;
5970 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5971 << CD->getDeclName();
5972 return;
5973 }
5974 LastExportedDefaultCtor = CD;
5975 }
5976}
5977
5978static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5979 CXXRecordDecl *Class) {
5980 bool ErrorReported = false;
5981 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5982 ClassTemplateDecl *TD) {
5983 if (ErrorReported)
5984 return;
5985 S.Diag(TD->getLocation(),
5986 diag::err_cuda_device_builtin_surftex_cls_template)
5987 << /*surface*/ 0 << TD;
5988 ErrorReported = true;
5989 };
5990
5991 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5992 if (!TD) {
5993 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5994 if (!SD) {
5995 S.Diag(Class->getLocation(),
5996 diag::err_cuda_device_builtin_surftex_ref_decl)
5997 << /*surface*/ 0 << Class;
5998 S.Diag(Class->getLocation(),
5999 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6000 << Class;
6001 return;
6002 }
6003 TD = SD->getSpecializedTemplate();
6004 }
6005
6006 TemplateParameterList *Params = TD->getTemplateParameters();
6007 unsigned N = Params->size();
6008
6009 if (N != 2) {
6010 reportIllegalClassTemplate(S, TD);
6011 S.Diag(TD->getLocation(),
6012 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6013 << TD << 2;
6014 }
6015 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6016 reportIllegalClassTemplate(S, TD);
6017 S.Diag(TD->getLocation(),
6018 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6019 << TD << /*1st*/ 0 << /*type*/ 0;
6020 }
6021 if (N > 1) {
6022 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6023 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6024 reportIllegalClassTemplate(S, TD);
6025 S.Diag(TD->getLocation(),
6026 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6027 << TD << /*2nd*/ 1 << /*integer*/ 1;
6028 }
6029 }
6030}
6031
6032static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6033 CXXRecordDecl *Class) {
6034 bool ErrorReported = false;
6035 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6036 ClassTemplateDecl *TD) {
6037 if (ErrorReported)
6038 return;
6039 S.Diag(TD->getLocation(),
6040 diag::err_cuda_device_builtin_surftex_cls_template)
6041 << /*texture*/ 1 << TD;
6042 ErrorReported = true;
6043 };
6044
6045 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6046 if (!TD) {
6047 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6048 if (!SD) {
6049 S.Diag(Class->getLocation(),
6050 diag::err_cuda_device_builtin_surftex_ref_decl)
6051 << /*texture*/ 1 << Class;
6052 S.Diag(Class->getLocation(),
6053 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6054 << Class;
6055 return;
6056 }
6057 TD = SD->getSpecializedTemplate();
6058 }
6059
6060 TemplateParameterList *Params = TD->getTemplateParameters();
6061 unsigned N = Params->size();
6062
6063 if (N != 3) {
6064 reportIllegalClassTemplate(S, TD);
6065 S.Diag(TD->getLocation(),
6066 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6067 << TD << 3;
6068 }
6069 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6070 reportIllegalClassTemplate(S, TD);
6071 S.Diag(TD->getLocation(),
6072 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6073 << TD << /*1st*/ 0 << /*type*/ 0;
6074 }
6075 if (N > 1) {
6076 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6