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