Bug Summary

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