Bug Summary

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