Bug Summary

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