Bug Summary

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