Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 654, column 34
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaDeclCXX.cpp
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/AttributeCommonInfo.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/Specifiers.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
41#include "clang/Sema/Template.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/StringExtras.h"
46#include <map>
47#include <set>
48
49using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// CheckDefaultArgumentVisitor
53//===----------------------------------------------------------------------===//
54
55namespace {
56/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57/// the default argument of a parameter to determine whether it
58/// contains any ill-formed subexpressions. For example, this will
59/// diagnose the use of local variables or parameters within the
60/// default argument expression.
61class CheckDefaultArgumentVisitor
62 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63 Sema &S;
64 const Expr *DefaultArg;
65
66public:
67 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68 : S(S), DefaultArg(DefaultArg) {}
69
70 bool VisitExpr(const Expr *Node);
71 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73 bool VisitLambdaExpr(const LambdaExpr *Lambda);
74 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75};
76
77/// VisitExpr - Visit all of the children of this expression.
78bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79 bool IsInvalid = false;
80 for (const Stmt *SubStmt : Node->children())
81 IsInvalid |= Visit(SubStmt);
82 return IsInvalid;
83}
84
85/// VisitDeclRefExpr - Visit a reference to a declaration, to
86/// determine whether this declaration can be used in the default
87/// argument expression.
88bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89 const NamedDecl *Decl = DRE->getDecl();
90 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91 // C++ [dcl.fct.default]p9:
92 // [...] parameters of a function shall not be used in default
93 // argument expressions, even if they are not evaluated. [...]
94 //
95 // C++17 [dcl.fct.default]p9 (by CWG 2082):
96 // [...] A parameter shall not appear as a potentially-evaluated
97 // expression in a default argument. [...]
98 //
99 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100 return S.Diag(DRE->getBeginLoc(),
101 diag::err_param_default_argument_references_param)
102 << Param->getDeclName() << DefaultArg->getSourceRange();
103 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104 // C++ [dcl.fct.default]p7:
105 // Local variables shall not be used in default argument
106 // expressions.
107 //
108 // C++17 [dcl.fct.default]p7 (by CWG 2082):
109 // A local variable shall not appear as a potentially-evaluated
110 // expression in a default argument.
111 //
112 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113 // Note: A local variable cannot be odr-used (6.3) in a default argument.
114 //
115 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116 return S.Diag(DRE->getBeginLoc(),
117 diag::err_param_default_argument_references_local)
118 << VDecl->getDeclName() << DefaultArg->getSourceRange();
119 }
120
121 return false;
122}
123
124/// VisitCXXThisExpr - Visit a C++ "this" expression.
125bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126 // C++ [dcl.fct.default]p8:
127 // The keyword this shall not be used in a default argument of a
128 // member function.
129 return S.Diag(ThisE->getBeginLoc(),
130 diag::err_param_default_argument_references_this)
131 << ThisE->getSourceRange();
132}
133
134bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135 const PseudoObjectExpr *POE) {
136 bool Invalid = false;
137 for (const Expr *E : POE->semantics()) {
138 // Look through bindings.
139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140 E = OVE->getSourceExpr();
141 assert(E && "pseudo-object binding without source expression?")(static_cast <bool> (E && "pseudo-object binding without source expression?"
) ? void (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 141, __extension__ __PRETTY_FUNCTION__
))
;
142 }
143
144 Invalid |= Visit(E);
145 }
146 return Invalid;
147}
148
149bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150 // C++11 [expr.lambda.prim]p13:
151 // A lambda-expression appearing in a default argument shall not
152 // implicitly or explicitly capture any entity.
153 if (Lambda->capture_begin() == Lambda->capture_end())
154 return false;
155
156 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157}
158} // namespace
159
160void
161Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162 const CXXMethodDecl *Method) {
163 // If we have an MSAny spec already, don't bother.
164 if (!Method || ComputedEST == EST_MSAny)
165 return;
166
167 const FunctionProtoType *Proto
168 = Method->getType()->getAs<FunctionProtoType>();
169 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170 if (!Proto)
171 return;
172
173 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174
175 // If we have a throw-all spec at this point, ignore the function.
176 if (ComputedEST == EST_None)
177 return;
178
179 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180 EST = EST_BasicNoexcept;
181
182 switch (EST) {
183 case EST_Unparsed:
184 case EST_Uninstantiated:
185 case EST_Unevaluated:
186 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "clang/lib/Sema/SemaDeclCXX.cpp", 186)
;
187
188 // If this function can throw any exceptions, make a note of that.
189 case EST_MSAny:
190 case EST_None:
191 // FIXME: Whichever we see last of MSAny and None determines our result.
192 // We should make a consistent, order-independent choice here.
193 ClearExceptions();
194 ComputedEST = EST;
195 return;
196 case EST_NoexceptFalse:
197 ClearExceptions();
198 ComputedEST = EST_None;
199 return;
200 // FIXME: If the call to this decl is using any of its default arguments, we
201 // need to search them for potentially-throwing calls.
202 // If this function has a basic noexcept, it doesn't affect the outcome.
203 case EST_BasicNoexcept:
204 case EST_NoexceptTrue:
205 case EST_NoThrow:
206 return;
207 // If we're still at noexcept(true) and there's a throw() callee,
208 // change to that specification.
209 case EST_DynamicNone:
210 if (ComputedEST == EST_BasicNoexcept)
211 ComputedEST = EST_DynamicNone;
212 return;
213 case EST_DependentNoexcept:
214 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "clang/lib/Sema/SemaDeclCXX.cpp", 215)
215 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "clang/lib/Sema/SemaDeclCXX.cpp", 215)
;
216 case EST_Dynamic:
217 break;
218 }
219 assert(EST == EST_Dynamic && "EST case not considered earlier.")(static_cast <bool> (EST == EST_Dynamic && "EST case not considered earlier."
) ? void (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 219, __extension__ __PRETTY_FUNCTION__
))
;
220 assert(ComputedEST != EST_None &&(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 221, __extension__ __PRETTY_FUNCTION__
))
221 "Shouldn't collect exceptions when throw-all is guaranteed.")(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 221, __extension__ __PRETTY_FUNCTION__
))
;
222 ComputedEST = EST_Dynamic;
223 // Record the exceptions in this function's exception specification.
224 for (const auto &E : Proto->exceptions())
225 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226 Exceptions.push_back(E);
227}
228
229void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230 if (!S || ComputedEST == EST_MSAny)
231 return;
232
233 // FIXME:
234 //
235 // C++0x [except.spec]p14:
236 // [An] implicit exception-specification specifies the type-id T if and
237 // only if T is allowed by the exception-specification of a function directly
238 // invoked by f's implicit definition; f shall allow all exceptions if any
239 // function it directly invokes allows all exceptions, and f shall allow no
240 // exceptions if every function it directly invokes allows no exceptions.
241 //
242 // Note in particular that if an implicit exception-specification is generated
243 // for a function containing a throw-expression, that specification can still
244 // be noexcept(true).
245 //
246 // Note also that 'directly invoked' is not defined in the standard, and there
247 // is no indication that we should only consider potentially-evaluated calls.
248 //
249 // Ultimately we should implement the intent of the standard: the exception
250 // specification should be the set of exceptions which can be thrown by the
251 // implicit definition. For now, we assume that any non-nothrow expression can
252 // throw any exception.
253
254 if (Self->canThrow(S))
255 ComputedEST = EST_None;
256}
257
258ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259 SourceLocation EqualLoc) {
260 if (RequireCompleteType(Param->getLocation(), Param->getType(),
261 diag::err_typecheck_decl_incomplete_type))
262 return true;
263
264 // C++ [dcl.fct.default]p5
265 // A default argument expression is implicitly converted (clause
266 // 4) to the parameter type. The default argument expression has
267 // the same semantic constraints as the initializer expression in
268 // a declaration of a variable of the parameter type, using the
269 // copy-initialization semantics (8.5).
270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271 Param);
272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273 EqualLoc);
274 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276 if (Result.isInvalid())
277 return true;
278 Arg = Result.getAs<Expr>();
279
280 CheckCompletedExpr(Arg, EqualLoc);
281 Arg = MaybeCreateExprWithCleanups(Arg);
282
283 return Arg;
284}
285
286void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287 SourceLocation EqualLoc) {
288 // Add the default argument to the parameter
289 Param->setDefaultArg(Arg);
290
291 // We have already instantiated this parameter; provide each of the
292 // instantiations with the uninstantiated default argument.
293 UnparsedDefaultArgInstantiationsMap::iterator InstPos
294 = UnparsedDefaultArgInstantiations.find(Param);
295 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298
299 // We're done tracking this parameter's instantiations.
300 UnparsedDefaultArgInstantiations.erase(InstPos);
301 }
302}
303
304/// ActOnParamDefaultArgument - Check whether the default argument
305/// provided for a function parameter is well-formed. If so, attach it
306/// to the parameter declaration.
307void
308Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309 Expr *DefaultArg) {
310 if (!param || !DefaultArg)
311 return;
312
313 ParmVarDecl *Param = cast<ParmVarDecl>(param);
314 UnparsedDefaultArgLocs.erase(Param);
315
316 auto Fail = [&] {
317 Param->setInvalidDecl();
318 Param->setDefaultArg(new (Context) OpaqueValueExpr(
319 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320 };
321
322 // Default arguments are only permitted in C++
323 if (!getLangOpts().CPlusPlus) {
324 Diag(EqualLoc, diag::err_param_default_argument)
325 << DefaultArg->getSourceRange();
326 return Fail();
327 }
328
329 // Check for unexpanded parameter packs.
330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331 return Fail();
332 }
333
334 // C++11 [dcl.fct.default]p3
335 // A default argument expression [...] shall not be specified for a
336 // parameter pack.
337 if (Param->isParameterPack()) {
338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339 << DefaultArg->getSourceRange();
340 // Recover by discarding the default argument.
341 Param->setDefaultArg(nullptr);
342 return;
343 }
344
345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346 if (Result.isInvalid())
347 return Fail();
348
349 DefaultArg = Result.getAs<Expr>();
350
351 // Check that the default argument is well-formed
352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353 if (DefaultArgChecker.Visit(DefaultArg))
354 return Fail();
355
356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357}
358
359/// ActOnParamUnparsedDefaultArgument - We've seen a default
360/// argument for a function parameter, but we can't parse it yet
361/// because we're inside a class definition. Note that this default
362/// argument will be parsed later.
363void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364 SourceLocation EqualLoc,
365 SourceLocation ArgLoc) {
366 if (!param)
367 return;
368
369 ParmVarDecl *Param = cast<ParmVarDecl>(param);
370 Param->setUnparsedDefaultArg();
371 UnparsedDefaultArgLocs[Param] = ArgLoc;
372}
373
374/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375/// the default argument for the parameter param failed.
376void Sema::ActOnParamDefaultArgumentError(Decl *param,
377 SourceLocation EqualLoc) {
378 if (!param)
379 return;
380
381 ParmVarDecl *Param = cast<ParmVarDecl>(param);
382 Param->setInvalidDecl();
383 UnparsedDefaultArgLocs.erase(Param);
384 Param->setDefaultArg(new (Context) OpaqueValueExpr(
385 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386}
387
388/// CheckExtraCXXDefaultArguments - Check for any extra default
389/// arguments in the declarator, which is not a function declaration
390/// or definition and therefore is not permitted to have default
391/// arguments. This routine should be invoked for every declarator
392/// that is not a function declaration or definition.
393void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394 // C++ [dcl.fct.default]p3
395 // A default argument expression shall be specified only in the
396 // parameter-declaration-clause of a function declaration or in a
397 // template-parameter (14.1). It shall not be specified for a
398 // parameter pack. If it is specified in a
399 // parameter-declaration-clause, it shall not occur within a
400 // declarator or abstract-declarator of a parameter-declaration.
401 bool MightBeFunction = D.isFunctionDeclarationContext();
402 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403 DeclaratorChunk &chunk = D.getTypeObject(i);
404 if (chunk.Kind == DeclaratorChunk::Function) {
405 if (MightBeFunction) {
406 // This is a function declaration. It can have default arguments, but
407 // keep looking in case its return type is a function type with default
408 // arguments.
409 MightBeFunction = false;
410 continue;
411 }
412 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413 ++argIdx) {
414 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415 if (Param->hasUnparsedDefaultArg()) {
416 std::unique_ptr<CachedTokens> Toks =
417 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418 SourceRange SR;
419 if (Toks->size() > 1)
420 SR = SourceRange((*Toks)[1].getLocation(),
421 Toks->back().getLocation());
422 else
423 SR = UnparsedDefaultArgLocs[Param];
424 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425 << SR;
426 } else if (Param->getDefaultArg()) {
427 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428 << Param->getDefaultArg()->getSourceRange();
429 Param->setDefaultArg(nullptr);
430 }
431 }
432 } else if (chunk.Kind != DeclaratorChunk::Paren) {
433 MightBeFunction = false;
434 }
435 }
436}
437
438static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441 });
442}
443
444/// MergeCXXFunctionDecl - Merge two declarations of the same C++
445/// function, once we already know that they have the same
446/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447/// error, false otherwise.
448bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449 Scope *S) {
450 bool Invalid = false;
451
452 // The declaration context corresponding to the scope is the semantic
453 // parent, unless this is a local function declaration, in which case
454 // it is that surrounding function.
455 DeclContext *ScopeDC = New->isLocalExternDecl()
1
Assuming the condition is false
2
'?' condition is false
456 ? New->getLexicalDeclContext()
457 : New->getDeclContext();
458
459 // Find the previous declaration for the purpose of default arguments.
460 FunctionDecl *PrevForDefaultArgs = Old;
461 for (/**/; PrevForDefaultArgs;
3
Assuming pointer value is null
4
Loop condition is false. Execution continues on line 509
462 // Don't bother looking back past the latest decl if this is a local
463 // extern declaration; nothing else could work.
464 PrevForDefaultArgs = New->isLocalExternDecl()
465 ? nullptr
466 : PrevForDefaultArgs->getPreviousDecl()) {
467 // Ignore hidden declarations.
468 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469 continue;
470
471 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472 !New->isCXXClassMember()) {
473 // Ignore default arguments of old decl if they are not in
474 // the same scope and this is not an out-of-line definition of
475 // a member function.
476 continue;
477 }
478
479 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480 // If only one of these is a local function declaration, then they are
481 // declared in different scopes, even though isDeclInScope may think
482 // they're in the same scope. (If both are local, the scope check is
483 // sufficient, and if neither is local, then they are in the same scope.)
484 continue;
485 }
486
487 // We found the right previous declaration.
488 break;
489 }
490
491 // C++ [dcl.fct.default]p4:
492 // For non-template functions, default arguments can be added in
493 // later declarations of a function in the same
494 // scope. Declarations in different scopes have completely
495 // distinct sets of default arguments. That is, declarations in
496 // inner scopes do not acquire default arguments from
497 // declarations in outer scopes, and vice versa. In a given
498 // function declaration, all parameters subsequent to a
499 // parameter with a default argument shall have default
500 // arguments supplied in this or previous declarations. A
501 // default argument shall not be redefined by a later
502 // declaration (not even to the same value).
503 //
504 // C++ [dcl.fct.default]p6:
505 // Except for member functions of class templates, the default arguments
506 // in a member function definition that appears outside of the class
507 // definition are added to the set of default arguments provided by the
508 // member function declaration in the class definition.
509 for (unsigned p = 0, NumParams = PrevForDefaultArgs
4.1
'PrevForDefaultArgs' is null
5
'?' condition is false
510 ? PrevForDefaultArgs->getNumParams() 511 : 0; 512 p < NumParams; ++p) { 513 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 514 ParmVarDecl *NewParam = New->getParamDecl(p); 515 516 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 517 bool NewParamHasDfl = NewParam->hasDefaultArg(); 518 519 if (OldParamHasDfl && NewParamHasDfl) { 520 unsigned DiagDefaultParamID = 521 diag::err_param_default_argument_redefinition; 522 523 // MSVC accepts that default parameters be redefined for member functions 524 // of template class. The new default parameter's value is ignored. 525 Invalid = true; 526 if (getLangOpts().MicrosoftExt) { 527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 528 if (MD && MD->getParent()->getDescribedClassTemplate()) { 529 // Merge the old default argument into the new parameter. 530 NewParam->setHasInheritedDefaultArg(); 531 if (OldParam->hasUninstantiatedDefaultArg()) 532 NewParam->setUninstantiatedDefaultArg( 533 OldParam->getUninstantiatedDefaultArg()); 534 else 535 NewParam->setDefaultArg(OldParam->getInit()); 536 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 537 Invalid = false; 538 } 539 } 540 541 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 542 // hint here. Alternatively, we could walk the type-source information 543 // for NewParam to find the last source location in the type... but it 544 // isn't worth the effort right now. This is the kind of test case that 545 // is hard to get right: 546 // int f(int); 547 // void g(int (*fp)(int) = f); 548 // void g(int (*fp)(int) = &f); 549 Diag(NewParam->getLocation(), DiagDefaultParamID) 550 << NewParam->getDefaultArgRange(); 551 552 // Look for the function declaration where the default argument was 553 // actually written, which may be a declaration prior to Old. 554 for (auto Older = PrevForDefaultArgs; 555 OldParam->hasInheritedDefaultArg(); /**/) { 556 Older = Older->getPreviousDecl(); 557 OldParam = Older->getParamDecl(p); 558 } 559 560 Diag(OldParam->getLocation(), diag::note_previous_definition) 561 << OldParam->getDefaultArgRange(); 562 } else if (OldParamHasDfl) { 563 // Merge the old default argument into the new parameter unless the new 564 // function is a friend declaration in a template class. In the latter 565 // case the default arguments will be inherited when the friend 566 // declaration will be instantiated. 567 if (New->getFriendObjectKind() == Decl::FOK_None || 568 !New->getLexicalDeclContext()->isDependentContext()) { 569 // It's important to use getInit() here; getDefaultArg() 570 // strips off any top-level ExprWithCleanups. 571 NewParam->setHasInheritedDefaultArg(); 572 if (OldParam->hasUnparsedDefaultArg()) 573 NewParam->setUnparsedDefaultArg(); 574 else if (OldParam->hasUninstantiatedDefaultArg()) 575 NewParam->setUninstantiatedDefaultArg( 576 OldParam->getUninstantiatedDefaultArg()); 577 else 578 NewParam->setDefaultArg(OldParam->getInit()); 579 } 580 } else if (NewParamHasDfl) { 581 if (New->getDescribedFunctionTemplate()) { 582 // Paragraph 4, quoted above, only applies to non-template functions. 583 Diag(NewParam->getLocation(), 584 diag::err_param_default_argument_template_redecl) 585 << NewParam->getDefaultArgRange(); 586 Diag(PrevForDefaultArgs->getLocation(), 587 diag::note_template_prev_declaration) 588 << false; 589 } else if (New->getTemplateSpecializationKind() 590 != TSK_ImplicitInstantiation && 591 New->getTemplateSpecializationKind() != TSK_Undeclared) { 592 // C++ [temp.expr.spec]p21: 593 // Default function arguments shall not be specified in a declaration 594 // or a definition for one of the following explicit specializations: 595 // - the explicit specialization of a function template; 596 // - the explicit specialization of a member function template; 597 // - the explicit specialization of a member function of a class 598 // template where the class template specialization to which the 599 // member function specialization belongs is implicitly 600 // instantiated. 601 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 602 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 603 << New->getDeclName() 604 << NewParam->getDefaultArgRange(); 605 } else if (New->getDeclContext()->isDependentContext()) { 606 // C++ [dcl.fct.default]p6 (DR217): 607 // Default arguments for a member function of a class template shall 608 // be specified on the initial declaration of the member function 609 // within the class template. 610 // 611 // Reading the tea leaves a bit in DR217 and its reference to DR205 612 // leads me to the conclusion that one cannot add default function 613 // arguments for an out-of-line definition of a member function of a 614 // dependent type. 615 int WhichKind = 2; 616 if (CXXRecordDecl *Record 617 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 618 if (Record->getDescribedClassTemplate()) 619 WhichKind = 0; 620 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 621 WhichKind = 1; 622 else 623 WhichKind = 2; 624 } 625 626 Diag(NewParam->getLocation(), 627 diag::err_param_default_argument_member_template_redecl) 628 << WhichKind 629 << NewParam->getDefaultArgRange(); 630 } 631 } 632 } 633 634 // DR1344: If a default argument is added outside a class definition and that 635 // default argument makes the function a special member function, the program 636 // is ill-formed. This can only happen for constructors. 637 if (isa<CXXConstructorDecl>(New) &&
6
Assuming 'New' is not a 'CXXConstructorDecl'
638 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 639 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 640 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 641 if (NewSM != OldSM) { 642 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 643 assert(NewParam->hasDefaultArg())(static_cast <bool> (NewParam->hasDefaultArg()) ? void
(0) : __assert_fail ("NewParam->hasDefaultArg()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 643, __extension__ __PRETTY_FUNCTION__))
; 644 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 645 << NewParam->getDefaultArgRange() << NewSM; 646 Diag(Old->getLocation(), diag::note_previous_declaration); 647 } 648 } 649 650 const FunctionDecl *Def; 651 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 652 // template has a constexpr specifier then all its declarations shall 653 // contain the constexpr specifier. 654 if (New->getConstexprKind() != Old->getConstexprKind()) {
7
Called C++ object pointer is null
655 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 656 << New << static_cast<int>(New->getConstexprKind()) 657 << static_cast<int>(Old->getConstexprKind()); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 661 Old->isDefined(Def) && 662 // If a friend function is inlined but does not have 'inline' 663 // specifier, it is a definition. Do not report attribute conflict 664 // in this case, redefinition will be diagnosed later. 665 (New->isInlineSpecified() || 666 New->getFriendObjectKind() == Decl::FOK_None)) { 667 // C++11 [dcl.fcn.spec]p4: 668 // If the definition of a function appears in a translation unit before its 669 // first declaration as inline, the program is ill-formed. 670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 671 Diag(Def->getLocation(), diag::note_previous_definition); 672 Invalid = true; 673 } 674 675 // C++17 [temp.deduct.guide]p3: 676 // Two deduction guide declarations in the same translation unit 677 // for the same class template shall not have equivalent 678 // parameter-declaration-clauses. 679 if (isa<CXXDeductionGuideDecl>(New) && 680 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 681 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 } 684 685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 686 // argument expression, that declaration shall be a definition and shall be 687 // the only declaration of the function or function template in the 688 // translation unit. 689 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 690 functionDeclHasDefaultArgument(Old)) { 691 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 692 Diag(Old->getLocation(), diag::note_previous_declaration); 693 Invalid = true; 694 } 695 696 // C++11 [temp.friend]p4 (DR329): 697 // When a function is defined in a friend function declaration in a class 698 // template, the function is instantiated when the function is odr-used. 699 // The same restrictions on multiple declarations and definitions that 700 // apply to non-template function declarations and definitions also apply 701 // to these implicit definitions. 702 const FunctionDecl *OldDefinition = nullptr; 703 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 704 Old->isDefined(OldDefinition, true)) 705 CheckForFunctionRedefinition(New, OldDefinition); 706 707 return Invalid; 708} 709 710NamedDecl * 711Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 712 MultiTemplateParamsArg TemplateParamLists) { 713 assert(D.isDecompositionDeclarator())(static_cast <bool> (D.isDecompositionDeclarator()) ? void
(0) : __assert_fail ("D.isDecompositionDeclarator()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 713, __extension__ __PRETTY_FUNCTION__))
; 714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 715 716 // The syntax only allows a decomposition declarator as a simple-declaration, 717 // a for-range-declaration, or a condition in Clang, but we parse it in more 718 // cases than that. 719 if (!D.mayHaveDecompositionDeclarator()) { 720 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 721 << Decomp.getSourceRange(); 722 return nullptr; 723 } 724 725 if (!TemplateParamLists.empty()) { 726 // FIXME: There's no rule against this, but there are also no rules that 727 // would actually make it usable, so we reject it for now. 728 Diag(TemplateParamLists.front()->getTemplateLoc(), 729 diag::err_decomp_decl_template); 730 return nullptr; 731 } 732 733 Diag(Decomp.getLSquareLoc(), 734 !getLangOpts().CPlusPlus17 735 ? diag::ext_decomp_decl 736 : D.getContext() == DeclaratorContext::Condition 737 ? diag::ext_decomp_decl_cond 738 : diag::warn_cxx14_compat_decomp_decl) 739 << Decomp.getSourceRange(); 740 741 // The semantic context is always just the current context. 742 DeclContext *const DC = CurContext; 743 744 // C++17 [dcl.dcl]/8: 745 // The decl-specifier-seq shall contain only the type-specifier auto 746 // and cv-qualifiers. 747 // C++2a [dcl.dcl]/8: 748 // If decl-specifier-seq contains any decl-specifier other than static, 749 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 750 auto &DS = D.getDeclSpec(); 751 { 752 SmallVector<StringRef, 8> BadSpecifiers; 753 SmallVector<SourceLocation, 8> BadSpecifierLocs; 754 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 755 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 756 if (auto SCS = DS.getStorageClassSpec()) { 757 if (SCS == DeclSpec::SCS_static) { 758 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 759 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 760 } else { 761 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 762 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 763 } 764 } 765 if (auto TSCS = DS.getThreadStorageClassSpec()) { 766 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 767 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 768 } 769 if (DS.hasConstexprSpecifier()) { 770 BadSpecifiers.push_back( 771 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 772 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 773 } 774 if (DS.isInlineSpecified()) { 775 BadSpecifiers.push_back("inline"); 776 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 777 } 778 if (!BadSpecifiers.empty()) { 779 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 780 Err << (int)BadSpecifiers.size() 781 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 782 // Don't add FixItHints to remove the specifiers; we do still respect 783 // them when building the underlying variable. 784 for (auto Loc : BadSpecifierLocs) 785 Err << SourceRange(Loc, Loc); 786 } else if (!CPlusPlus20Specifiers.empty()) { 787 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 788 getLangOpts().CPlusPlus20 789 ? diag::warn_cxx17_compat_decomp_decl_spec 790 : diag::ext_decomp_decl_spec); 791 Warn << (int)CPlusPlus20Specifiers.size() 792 << llvm::join(CPlusPlus20Specifiers.begin(), 793 CPlusPlus20Specifiers.end(), " "); 794 for (auto Loc : CPlusPlus20SpecifierLocs) 795 Warn << SourceRange(Loc, Loc); 796 } 797 // We can't recover from it being declared as a typedef. 798 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 799 return nullptr; 800 } 801 802 // C++2a [dcl.struct.bind]p1: 803 // A cv that includes volatile is deprecated 804 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 805 getLangOpts().CPlusPlus20) 806 Diag(DS.getVolatileSpecLoc(), 807 diag::warn_deprecated_volatile_structured_binding); 808 809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 810 QualType R = TInfo->getType(); 811 812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 813 UPPC_DeclarationType)) 814 D.setInvalidType(); 815 816 // The syntax only allows a single ref-qualifier prior to the decomposition 817 // declarator. No other declarator chunks are permitted. Also check the type 818 // specifier here. 819 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 820 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 821 (D.getNumTypeObjects() == 1 && 822 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 823 Diag(Decomp.getLSquareLoc(), 824 (D.hasGroupingParens() || 825 (D.getNumTypeObjects() && 826 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 827 ? diag::err_decomp_decl_parens 828 : diag::err_decomp_decl_type) 829 << R; 830 831 // In most cases, there's no actual problem with an explicitly-specified 832 // type, but a function type won't work here, and ActOnVariableDeclarator 833 // shouldn't be called for such a type. 834 if (R->isFunctionType()) 835 D.setInvalidType(); 836 } 837 838 // Build the BindingDecls. 839 SmallVector<BindingDecl*, 8> Bindings; 840 841 // Build the BindingDecls. 842 for (auto &B : D.getDecompositionDeclarator().bindings()) { 843 // Check for name conflicts. 844 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 846 ForVisibleRedeclaration); 847 LookupName(Previous, S, 848 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 849 850 // It's not permitted to shadow a template parameter name. 851 if (Previous.isSingleResult() && 852 Previous.getFoundDecl()->isTemplateParameter()) { 853 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 854 Previous.getFoundDecl()); 855 Previous.clear(); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 860 // Find the shadowed declaration before filtering for scope. 861 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 862 ? getShadowedDeclaration(BD, Previous) 863 : nullptr; 864 865 bool ConsiderLinkage = DC->isFunctionOrMethod() && 866 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 867 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 868 /*AllowInlineNamespace*/false); 869 870 if (!Previous.empty()) { 871 auto *Old = Previous.getRepresentativeDecl(); 872 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 873 Diag(Old->getLocation(), diag::note_previous_definition); 874 } else if (ShadowedDecl && !D.isRedeclaration()) { 875 CheckShadow(BD, ShadowedDecl, Previous); 876 } 877 PushOnScopeChains(BD, S, true); 878 Bindings.push_back(BD); 879 ParsingInitForAutoVars.insert(BD); 880 } 881 882 // There are no prior lookup results for the variable itself, because it 883 // is unnamed. 884 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 885 Decomp.getLSquareLoc()); 886 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 887 ForVisibleRedeclaration); 888 889 // Build the variable that holds the non-decomposed object. 890 bool AddToScope = true; 891 NamedDecl *New = 892 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 893 MultiTemplateParamsArg(), AddToScope, Bindings); 894 if (AddToScope) { 895 S->AddDecl(New); 896 CurContext->addHiddenDecl(New); 897 } 898 899 if (isInOpenMPDeclareTargetContext()) 900 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 901 902 return New; 903} 904 905static bool checkSimpleDecomposition( 906 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 907 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 908 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 909 if ((int64_t)Bindings.size() != NumElems) { 910 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 911 << DecompType << (unsigned)Bindings.size() 912 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U)) 913 << toString(NumElems, 10) << (NumElems < Bindings.size()); 914 return true; 915 } 916 917 unsigned I = 0; 918 for (auto *B : Bindings) { 919 SourceLocation Loc = B->getLocation(); 920 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 921 if (E.isInvalid()) 922 return true; 923 E = GetInit(Loc, E.get(), I++); 924 if (E.isInvalid()) 925 return true; 926 B->setBinding(ElemType, E.get()); 927 } 928 929 return false; 930} 931 932static bool checkArrayLikeDecomposition(Sema &S, 933 ArrayRef<BindingDecl *> Bindings, 934 ValueDecl *Src, QualType DecompType, 935 const llvm::APSInt &NumElems, 936 QualType ElemType) { 937 return checkSimpleDecomposition( 938 S, Bindings, Src, DecompType, NumElems, ElemType, 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 ExprResult E = S.ActOnIntegerConstant(Loc, I); 941 if (E.isInvalid()) 942 return ExprError(); 943 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 944 }); 945} 946 947static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 948 ValueDecl *Src, QualType DecompType, 949 const ConstantArrayType *CAT) { 950 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 951 llvm::APSInt(CAT->getSize()), 952 CAT->getElementType()); 953} 954 955static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 956 ValueDecl *Src, QualType DecompType, 957 const VectorType *VT) { 958 return checkArrayLikeDecomposition( 959 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 960 S.Context.getQualifiedType(VT->getElementType(), 961 DecompType.getQualifiers())); 962} 963 964static bool checkComplexDecomposition(Sema &S, 965 ArrayRef<BindingDecl *> Bindings, 966 ValueDecl *Src, QualType DecompType, 967 const ComplexType *CT) { 968 return checkSimpleDecomposition( 969 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 970 S.Context.getQualifiedType(CT->getElementType(), 971 DecompType.getQualifiers()), 972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 973 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 974 }); 975} 976 977static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 978 TemplateArgumentListInfo &Args, 979 const TemplateParameterList *Params) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 unsigned I = 0; 984 for (auto &Arg : Args.arguments()) { 985 if (!First) 986 OS << ", "; 987 Arg.getArgument().print(PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument( 989 PrintingPolicy, Params, I)); 990 First = false; 991 I++; 992 } 993 return std::string(OS.str()); 994} 995 996static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 997 SourceLocation Loc, StringRef Trait, 998 TemplateArgumentListInfo &Args, 999 unsigned DiagID) { 1000 auto DiagnoseMissing = [&] { 1001 if (DiagID) 1002 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1003 Args, /*Params*/ nullptr); 1004 return true; 1005 }; 1006 1007 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1008 NamespaceDecl *Std = S.getStdNamespace(); 1009 if (!Std) 1010 return DiagnoseMissing(); 1011 1012 // Look up the trait itself, within namespace std. We can diagnose various 1013 // problems with this lookup even if we've been asked to not diagnose a 1014 // missing specialization, because this can only fail if the user has been 1015 // declaring their own names in namespace std or we don't support the 1016 // standard library implementation in use. 1017 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1018 Loc, Sema::LookupOrdinaryName); 1019 if (!S.LookupQualifiedName(Result, Std)) 1020 return DiagnoseMissing(); 1021 if (Result.isAmbiguous()) 1022 return true; 1023 1024 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1025 if (!TraitTD) { 1026 Result.suppressDiagnostics(); 1027 NamedDecl *Found = *Result.begin(); 1028 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1029 S.Diag(Found->getLocation(), diag::note_declared_at); 1030 return true; 1031 } 1032 1033 // Build the template-id. 1034 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1035 if (TraitTy.isNull()) 1036 return true; 1037 if (!S.isCompleteType(Loc, TraitTy)) { 1038 if (DiagID) 1039 S.RequireCompleteType( 1040 Loc, TraitTy, DiagID, 1041 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1042 TraitTD->getTemplateParameters())); 1043 return true; 1044 } 1045 1046 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1047 assert(RD && "specialization of class template is not a class?")(static_cast <bool> (RD && "specialization of class template is not a class?"
) ? void (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1047, __extension__ __PRETTY_FUNCTION__
))
; 1048 1049 // Look up the member of the trait type. 1050 S.LookupQualifiedName(TraitMemberLookup, RD); 1051 return TraitMemberLookup.isAmbiguous(); 1052} 1053 1054static TemplateArgumentLoc 1055getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1056 uint64_t I) { 1057 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1058 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1059} 1060 1061static TemplateArgumentLoc 1062getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1063 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1064} 1065 1066namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1067 1068static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1069 llvm::APSInt &Size) { 1070 EnterExpressionEvaluationContext ContextRAII( 1071 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1072 1073 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1074 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1075 1076 // Form template argument list for tuple_size<T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1079 1080 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1081 // it's not tuple-like. 1082 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1083 R.empty()) 1084 return IsTupleLike::NotTupleLike; 1085 1086 // If we get this far, we've committed to the tuple interpretation, but 1087 // we can still fail if there actually isn't a usable ::value. 1088 1089 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1090 LookupResult &R; 1091 TemplateArgumentListInfo &Args; 1092 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1093 : R(R), Args(Args) {} 1094 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1095 SourceLocation Loc) override { 1096 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1097 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1098 /*Params*/ nullptr); 1099 } 1100 } Diagnoser(R, Args); 1101 1102 ExprResult E = 1103 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1104 if (E.isInvalid()) 1105 return IsTupleLike::Error; 1106 1107 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1108 if (E.isInvalid()) 1109 return IsTupleLike::Error; 1110 1111 return IsTupleLike::TupleLike; 1112} 1113 1114/// \return std::tuple_element<I, T>::type. 1115static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1116 unsigned I, QualType T) { 1117 // Form template argument list for tuple_element<I, T>. 1118 TemplateArgumentListInfo Args(Loc, Loc); 1119 Args.addArgument( 1120 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1121 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1122 1123 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1124 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1125 if (lookupStdTypeTraitMember( 1126 S, R, Loc, "tuple_element", Args, 1127 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1128 return QualType(); 1129 1130 auto *TD = R.getAsSingle<TypeDecl>(); 1131 if (!TD) { 1132 R.suppressDiagnostics(); 1133 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1134 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1135 /*Params*/ nullptr); 1136 if (!R.empty()) 1137 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1138 return QualType(); 1139 } 1140 1141 return S.Context.getTypeDeclType(TD); 1142} 1143 1144namespace { 1145struct InitializingBinding { 1146 Sema &S; 1147 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1148 Sema::CodeSynthesisContext Ctx; 1149 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1150 Ctx.PointOfInstantiation = BD->getLocation(); 1151 Ctx.Entity = BD; 1152 S.pushCodeSynthesisContext(Ctx); 1153 } 1154 ~InitializingBinding() { 1155 S.popCodeSynthesisContext(); 1156 } 1157}; 1158} 1159 1160static bool checkTupleLikeDecomposition(Sema &S, 1161 ArrayRef<BindingDecl *> Bindings, 1162 VarDecl *Src, QualType DecompType, 1163 const llvm::APSInt &TupleSize) { 1164 if ((int64_t)Bindings.size() != TupleSize) { 1165 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1166 << DecompType << (unsigned)Bindings.size() 1167 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U)) 1168 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1169 return true; 1170 } 1171 1172 if (Bindings.empty()) 1173 return false; 1174 1175 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1176 1177 // [dcl.decomp]p3: 1178 // The unqualified-id get is looked up in the scope of E by class member 1179 // access lookup ... 1180 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1181 bool UseMemberGet = false; 1182 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1183 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1184 S.LookupQualifiedName(MemberGet, RD); 1185 if (MemberGet.isAmbiguous()) 1186 return true; 1187 // ... and if that finds at least one declaration that is a function 1188 // template whose first template parameter is a non-type parameter ... 1189 for (NamedDecl *D : MemberGet) { 1190 if (FunctionTemplateDecl *FTD = 1191 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1192 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1193 if (TPL->size() != 0 && 1194 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1195 // ... the initializer is e.get<i>(). 1196 UseMemberGet = true; 1197 break; 1198 } 1199 } 1200 } 1201 } 1202 1203 unsigned I = 0; 1204 for (auto *B : Bindings) { 1205 InitializingBinding InitContext(S, B); 1206 SourceLocation Loc = B->getLocation(); 1207 1208 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1209 if (E.isInvalid()) 1210 return true; 1211 1212 // e is an lvalue if the type of the entity is an lvalue reference and 1213 // an xvalue otherwise 1214 if (!Src->getType()->isLValueReferenceType()) 1215 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1216 E.get(), nullptr, VK_XValue, 1217 FPOptionsOverride()); 1218 1219 TemplateArgumentListInfo Args(Loc, Loc); 1220 Args.addArgument( 1221 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1222 1223 if (UseMemberGet) { 1224 // if [lookup of member get] finds at least one declaration, the 1225 // initializer is e.get<i-1>(). 1226 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1227 CXXScopeSpec(), SourceLocation(), nullptr, 1228 MemberGet, &Args, nullptr); 1229 if (E.isInvalid()) 1230 return true; 1231 1232 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1233 } else { 1234 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1235 // in the associated namespaces. 1236 Expr *Get = UnresolvedLookupExpr::Create( 1237 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1238 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1239 UnresolvedSetIterator(), UnresolvedSetIterator()); 1240 1241 Expr *Arg = E.get(); 1242 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1243 } 1244 if (E.isInvalid()) 1245 return true; 1246 Expr *Init = E.get(); 1247 1248 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1249 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1250 if (T.isNull()) 1251 return true; 1252 1253 // each vi is a variable of type "reference to T" initialized with the 1254 // initializer, where the reference is an lvalue reference if the 1255 // initializer is an lvalue and an rvalue reference otherwise 1256 QualType RefType = 1257 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1258 if (RefType.isNull()) 1259 return true; 1260 auto *RefVD = VarDecl::Create( 1261 S.Context, Src->getDeclContext(), Loc, Loc, 1262 B->getDeclName().getAsIdentifierInfo(), RefType, 1263 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1264 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1265 RefVD->setTSCSpec(Src->getTSCSpec()); 1266 RefVD->setImplicit(); 1267 if (Src->isInlineSpecified()) 1268 RefVD->setInlineSpecified(); 1269 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1270 1271 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1272 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1273 InitializationSequence Seq(S, Entity, Kind, Init); 1274 E = Seq.Perform(S, Entity, Kind, Init); 1275 if (E.isInvalid()) 1276 return true; 1277 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1278 if (E.isInvalid()) 1279 return true; 1280 RefVD->setInit(E.get()); 1281 S.CheckCompleteVariableDeclaration(RefVD); 1282 1283 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1284 DeclarationNameInfo(B->getDeclName(), Loc), 1285 RefVD); 1286 if (E.isInvalid()) 1287 return true; 1288 1289 B->setBinding(T, E.get()); 1290 I++; 1291 } 1292 1293 return false; 1294} 1295 1296/// Find the base class to decompose in a built-in decomposition of a class type. 1297/// This base class search is, unfortunately, not quite like any other that we 1298/// perform anywhere else in C++. 1299static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1300 const CXXRecordDecl *RD, 1301 CXXCastPath &BasePath) { 1302 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1303 CXXBasePath &Path) { 1304 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1305 }; 1306 1307 const CXXRecordDecl *ClassWithFields = nullptr; 1308 AccessSpecifier AS = AS_public; 1309 if (RD->hasDirectFields()) 1310 // [dcl.decomp]p4: 1311 // Otherwise, all of E's non-static data members shall be public direct 1312 // members of E ... 1313 ClassWithFields = RD; 1314 else { 1315 // ... or of ... 1316 CXXBasePaths Paths; 1317 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1318 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1319 // If no classes have fields, just decompose RD itself. (This will work 1320 // if and only if zero bindings were provided.) 1321 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1322 } 1323 1324 CXXBasePath *BestPath = nullptr; 1325 for (auto &P : Paths) { 1326 if (!BestPath) 1327 BestPath = &P; 1328 else if (!S.Context.hasSameType(P.back().Base->getType(), 1329 BestPath->back().Base->getType())) { 1330 // ... the same ... 1331 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1332 << false << RD << BestPath->back().Base->getType() 1333 << P.back().Base->getType(); 1334 return DeclAccessPair(); 1335 } else if (P.Access < BestPath->Access) { 1336 BestPath = &P; 1337 } 1338 } 1339 1340 // ... unambiguous ... 1341 QualType BaseType = BestPath->back().Base->getType(); 1342 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1343 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1344 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1345 return DeclAccessPair(); 1346 } 1347 1348 // ... [accessible, implied by other rules] base class of E. 1349 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1350 *BestPath, diag::err_decomp_decl_inaccessible_base); 1351 AS = BestPath->Access; 1352 1353 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1354 S.BuildBasePathArray(Paths, BasePath); 1355 } 1356 1357 // The above search did not check whether the selected class itself has base 1358 // classes with fields, so check that now. 1359 CXXBasePaths Paths; 1360 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1361 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1362 << (ClassWithFields == RD) << RD << ClassWithFields 1363 << Paths.front().back().Base->getType(); 1364 return DeclAccessPair(); 1365 } 1366 1367 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1368} 1369 1370static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1371 ValueDecl *Src, QualType DecompType, 1372 const CXXRecordDecl *OrigRD) { 1373 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1374 diag::err_incomplete_type)) 1375 return true; 1376 1377 CXXCastPath BasePath; 1378 DeclAccessPair BasePair = 1379 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1380 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1381 if (!RD) 1382 return true; 1383 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1384 DecompType.getQualifiers()); 1385 1386 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1387 unsigned NumFields = llvm::count_if( 1388 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1389 assert(Bindings.size() != NumFields)(static_cast <bool> (Bindings.size() != NumFields) ? void
(0) : __assert_fail ("Bindings.size() != NumFields", "clang/lib/Sema/SemaDeclCXX.cpp"
, 1389, __extension__ __PRETTY_FUNCTION__))
; 1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1392 << (NumFields < Bindings.size()); 1393 return true; 1394 }; 1395 1396 // all of E's non-static data members shall be [...] well-formed 1397 // when named as e.name in the context of the structured binding, 1398 // E shall not have an anonymous union member, ... 1399 unsigned I = 0; 1400 for (auto *FD : RD->fields()) { 1401 if (FD->isUnnamedBitfield()) 1402 continue; 1403 1404 // All the non-static data members are required to be nameable, so they 1405 // must all have names. 1406 if (!FD->getDeclName()) { 1407 if (RD->isLambda()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1409 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1410 return true; 1411 } 1412 1413 if (FD->isAnonymousStructOrUnion()) { 1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1415 << DecompType << FD->getType()->isUnionType(); 1416 S.Diag(FD->getLocation(), diag::note_declared_at); 1417 return true; 1418 } 1419 1420 // FIXME: Are there any other ways we could have an anonymous member? 1421 } 1422 1423 // We have a real field to bind. 1424 if (I >= Bindings.size()) 1425 return DiagnoseBadNumberOfBindings(); 1426 auto *B = Bindings[I++]; 1427 SourceLocation Loc = B->getLocation(); 1428 1429 // The field must be accessible in the context of the structured binding. 1430 // We already checked that the base class is accessible. 1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1432 // const_cast here. 1433 S.CheckStructuredBindingMemberAccess( 1434 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1436 BasePair.getAccess(), FD->getAccess()))); 1437 1438 // Initialize the binding to Src.FD. 1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1440 if (E.isInvalid()) 1441 return true; 1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1443 VK_LValue, &BasePath); 1444 if (E.isInvalid()) 1445 return true; 1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1447 CXXScopeSpec(), FD, 1448 DeclAccessPair::make(FD, FD->getAccess()), 1449 DeclarationNameInfo(FD->getDeclName(), Loc)); 1450 if (E.isInvalid()) 1451 return true; 1452 1453 // If the type of the member is T, the referenced type is cv T, where cv is 1454 // the cv-qualification of the decomposition expression. 1455 // 1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1457 // 'const' to the type of the field. 1458 Qualifiers Q = DecompType.getQualifiers(); 1459 if (FD->isMutable()) 1460 Q.removeConst(); 1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1462 } 1463 1464 if (I != Bindings.size()) 1465 return DiagnoseBadNumberOfBindings(); 1466 1467 return false; 1468} 1469 1470void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1471 QualType DecompType = DD->getType(); 1472 1473 // If the type of the decomposition is dependent, then so is the type of 1474 // each binding. 1475 if (DecompType->isDependentType()) { 1476 for (auto *B : DD->bindings()) 1477 B->setType(Context.DependentTy); 1478 return; 1479 } 1480 1481 DecompType = DecompType.getNonReferenceType(); 1482 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1483 1484 // C++1z [dcl.decomp]/2: 1485 // If E is an array type [...] 1486 // As an extension, we also support decomposition of built-in complex and 1487 // vector types. 1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 if (auto *VT = DecompType->getAs<VectorType>()) { 1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1495 DD->setInvalidDecl(); 1496 return; 1497 } 1498 if (auto *CT = DecompType->getAs<ComplexType>()) { 1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1500 DD->setInvalidDecl(); 1501 return; 1502 } 1503 1504 // C++1z [dcl.decomp]/3: 1505 // if the expression std::tuple_size<E>::value is a well-formed integral 1506 // constant expression, [...] 1507 llvm::APSInt TupleSize(32); 1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1509 case IsTupleLike::Error: 1510 DD->setInvalidDecl(); 1511 return; 1512 1513 case IsTupleLike::TupleLike: 1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1515 DD->setInvalidDecl(); 1516 return; 1517 1518 case IsTupleLike::NotTupleLike: 1519 break; 1520 } 1521 1522 // C++1z [dcl.dcl]/8: 1523 // [E shall be of array or non-union class type] 1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1525 if (!RD || RD->isUnion()) { 1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1527 << DD << !RD << DecompType; 1528 DD->setInvalidDecl(); 1529 return; 1530 } 1531 1532 // C++1z [dcl.decomp]/4: 1533 // all of E's non-static data members shall be [...] direct members of 1534 // E or of the same unambiguous public base class of E, ... 1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1536 DD->setInvalidDecl(); 1537} 1538 1539/// Merge the exception specifications of two variable declarations. 1540/// 1541/// This is called when there's a redeclaration of a VarDecl. The function 1542/// checks if the redeclaration might have an exception specification and 1543/// validates compatibility and merges the specs if necessary. 1544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1545 // Shortcut if exceptions are disabled. 1546 if (!getLangOpts().CXXExceptions) 1547 return; 1548 1549 assert(Context.hasSameType(New->getType(), Old->getType()) &&(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1550, __extension__ __PRETTY_FUNCTION__
))
1550 "Should only be called if types are otherwise the same.")(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1550, __extension__ __PRETTY_FUNCTION__
))
; 1551 1552 QualType NewType = New->getType(); 1553 QualType OldType = Old->getType(); 1554 1555 // We're only interested in pointers and references to functions, as well 1556 // as pointers to member functions. 1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1558 NewType = R->getPointeeType(); 1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1561 NewType = P->getPointeeType(); 1562 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1564 NewType = M->getPointeeType(); 1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1566 } 1567 1568 if (!NewType->isFunctionProtoType()) 1569 return; 1570 1571 // There's lots of special cases for functions. For function pointers, system 1572 // libraries are hopefully not as broken so that we don't need these 1573 // workarounds. 1574 if (CheckEquivalentExceptionSpec( 1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1577 New->setInvalidDecl(); 1578 } 1579} 1580 1581/// CheckCXXDefaultArguments - Verify that the default arguments for a 1582/// function declaration are well-formed according to C++ 1583/// [dcl.fct.default]. 1584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1585 unsigned NumParams = FD->getNumParams(); 1586 unsigned ParamIdx = 0; 1587 1588 // This checking doesn't make sense for explicit specializations; their 1589 // default arguments are determined by the declaration we're specializing, 1590 // not by FD. 1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1592 return; 1593 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1594 if (FTD->isMemberSpecialization()) 1595 return; 1596 1597 // Find first parameter with a default argument 1598 for (; ParamIdx < NumParams; ++ParamIdx) { 1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1600 if (Param->hasDefaultArg()) 1601 break; 1602 } 1603 1604 // C++20 [dcl.fct.default]p4: 1605 // In a given function declaration, each parameter subsequent to a parameter 1606 // with a default argument shall have a default argument supplied in this or 1607 // a previous declaration, unless the parameter was expanded from a 1608 // parameter pack, or shall be a function parameter pack. 1609 for (; ParamIdx < NumParams; ++ParamIdx) { 1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1612 !(CurrentInstantiationScope && 1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1614 if (Param->isInvalidDecl()) 1615 /* We already complained about this parameter. */; 1616 else if (Param->getIdentifier()) 1617 Diag(Param->getLocation(), 1618 diag::err_param_default_argument_missing_name) 1619 << Param->getIdentifier(); 1620 else 1621 Diag(Param->getLocation(), 1622 diag::err_param_default_argument_missing); 1623 } 1624 } 1625} 1626 1627/// Check that the given type is a literal type. Issue a diagnostic if not, 1628/// if Kind is Diagnose. 1629/// \return \c true if a problem has been found (and optionally diagnosed). 1630template <typename... Ts> 1631static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1632 SourceLocation Loc, QualType T, unsigned DiagID, 1633 Ts &&...DiagArgs) { 1634 if (T->isDependentType()) 1635 return false; 1636 1637 switch (Kind) { 1638 case Sema::CheckConstexprKind::Diagnose: 1639 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1640 std::forward<Ts>(DiagArgs)...); 1641 1642 case Sema::CheckConstexprKind::CheckValid: 1643 return !T->isLiteralType(SemaRef.Context); 1644 } 1645 1646 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1646)
; 1647} 1648 1649/// Determine whether a destructor cannot be constexpr due to 1650static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1651 const CXXDestructorDecl *DD, 1652 Sema::CheckConstexprKind Kind) { 1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1654 const CXXRecordDecl *RD = 1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1656 if (!RD || RD->hasConstexprDestructor()) 1657 return true; 1658 1659 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1661 << static_cast<int>(DD->getConstexprKind()) << !FD 1662 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1665 } 1666 return false; 1667 }; 1668 1669 const CXXRecordDecl *RD = DD->getParent(); 1670 for (const CXXBaseSpecifier &B : RD->bases()) 1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1672 return false; 1673 for (const FieldDecl *FD : RD->fields()) 1674 if (!Check(FD->getLocation(), FD->getType(), FD)) 1675 return false; 1676 return true; 1677} 1678 1679/// Check whether a function's parameter types are all literal types. If so, 1680/// return true. If not, produce a suitable diagnostic and return false. 1681static bool CheckConstexprParameterTypes(Sema &SemaRef, 1682 const FunctionDecl *FD, 1683 Sema::CheckConstexprKind Kind) { 1684 unsigned ArgIndex = 0; 1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1687 e = FT->param_type_end(); 1688 i != e; ++i, ++ArgIndex) { 1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1690 SourceLocation ParamLoc = PD->getLocation(); 1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1692 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1694 FD->isConsteval())) 1695 return false; 1696 } 1697 return true; 1698} 1699 1700/// Check whether a function's return type is a literal type. If so, return 1701/// true. If not, produce a suitable diagnostic and return false. 1702static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1703 Sema::CheckConstexprKind Kind) { 1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1705 diag::err_constexpr_non_literal_return, 1706 FD->isConsteval())) 1707 return false; 1708 return true; 1709} 1710 1711/// Get diagnostic %select index for tag kind for 1712/// record diagnostic message. 1713/// WARNING: Indexes apply to particular diagnostics only! 1714/// 1715/// \returns diagnostic %select index. 1716static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1717 switch (Tag) { 1718 case TTK_Struct: return 0; 1719 case TTK_Interface: return 1; 1720 case TTK_Class: return 2; 1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1721)
; 1722 } 1723} 1724 1725static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1726 Stmt *Body, 1727 Sema::CheckConstexprKind Kind); 1728 1729// Check whether a function declaration satisfies the requirements of a 1730// constexpr function definition or a constexpr constructor definition. If so, 1731// return true. If not, produce appropriate diagnostics (unless asked not to by 1732// Kind) and return false. 1733// 1734// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1735bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1736 CheckConstexprKind Kind) { 1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1738 if (MD && MD->isInstance()) { 1739 // C++11 [dcl.constexpr]p4: 1740 // The definition of a constexpr constructor shall satisfy the following 1741 // constraints: 1742 // - the class shall not have any virtual base classes; 1743 // 1744 // FIXME: This only applies to constructors and destructors, not arbitrary 1745 // member functions. 1746 const CXXRecordDecl *RD = MD->getParent(); 1747 if (RD->getNumVBases()) { 1748 if (Kind == CheckConstexprKind::CheckValid) 1749 return false; 1750 1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1752 << isa<CXXConstructorDecl>(NewFD) 1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1754 for (const auto &I : RD->vbases()) 1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1756 << I.getSourceRange(); 1757 return false; 1758 } 1759 } 1760 1761 if (!isa<CXXConstructorDecl>(NewFD)) { 1762 // C++11 [dcl.constexpr]p3: 1763 // The definition of a constexpr function shall satisfy the following 1764 // constraints: 1765 // - it shall not be virtual; (removed in C++20) 1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1767 if (Method && Method->isVirtual()) { 1768 if (getLangOpts().CPlusPlus20) { 1769 if (Kind == CheckConstexprKind::Diagnose) 1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1771 } else { 1772 if (Kind == CheckConstexprKind::CheckValid) 1773 return false; 1774 1775 Method = Method->getCanonicalDecl(); 1776 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1777 1778 // If it's not obvious why this function is virtual, find an overridden 1779 // function which uses the 'virtual' keyword. 1780 const CXXMethodDecl *WrittenVirtual = Method; 1781 while (!WrittenVirtual->isVirtualAsWritten()) 1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1783 if (WrittenVirtual != Method) 1784 Diag(WrittenVirtual->getLocation(), 1785 diag::note_overridden_virtual_function); 1786 return false; 1787 } 1788 } 1789 1790 // - its return type shall be a literal type; 1791 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1792 return false; 1793 } 1794 1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1796 // A destructor can be constexpr only if the defaulted destructor could be; 1797 // we don't need to check the members and bases if we already know they all 1798 // have constexpr destructors. 1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1800 if (Kind == CheckConstexprKind::CheckValid) 1801 return false; 1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1803 return false; 1804 } 1805 } 1806 1807 // - each of its parameter types shall be a literal type; 1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1809 return false; 1810 1811 Stmt *Body = NewFD->getBody(); 1812 assert(Body &&(static_cast <bool> (Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? void (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1813, __extension__ __PRETTY_FUNCTION__
))
1813 "CheckConstexprFunctionDefinition called on function with no body")(static_cast <bool> (Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? void (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1813, __extension__ __PRETTY_FUNCTION__
))
; 1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1815} 1816 1817/// Check the given declaration statement is legal within a constexpr function 1818/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1819/// 1820/// \return true if the body is OK (maybe only as an extension), false if we 1821/// have diagnosed a problem. 1822static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1823 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1824 Sema::CheckConstexprKind Kind) { 1825 // C++11 [dcl.constexpr]p3 and p4: 1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1827 // contain only 1828 for (const auto *DclIt : DS->decls()) { 1829 switch (DclIt->getKind()) { 1830 case Decl::StaticAssert: 1831 case Decl::Using: 1832 case Decl::UsingShadow: 1833 case Decl::UsingDirective: 1834 case Decl::UnresolvedUsingTypename: 1835 case Decl::UnresolvedUsingValue: 1836 case Decl::UsingEnum: 1837 // - static_assert-declarations 1838 // - using-declarations, 1839 // - using-directives, 1840 // - using-enum-declaration 1841 continue; 1842 1843 case Decl::Typedef: 1844 case Decl::TypeAlias: { 1845 // - typedef declarations and alias-declarations that do not define 1846 // classes or enumerations, 1847 const auto *TN = cast<TypedefNameDecl>(DclIt); 1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1849 // Don't allow variably-modified types in constexpr functions. 1850 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1853 << TL.getSourceRange() << TL.getType() 1854 << isa<CXXConstructorDecl>(Dcl); 1855 } 1856 return false; 1857 } 1858 continue; 1859 } 1860 1861 case Decl::Enum: 1862 case Decl::CXXRecord: 1863 // C++1y allows types to be defined, not just declared. 1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1865 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1866 SemaRef.Diag(DS->getBeginLoc(), 1867 SemaRef.getLangOpts().CPlusPlus14 1868 ? diag::warn_cxx11_compat_constexpr_type_definition 1869 : diag::ext_constexpr_type_definition) 1870 << isa<CXXConstructorDecl>(Dcl); 1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1872 return false; 1873 } 1874 } 1875 continue; 1876 1877 case Decl::EnumConstant: 1878 case Decl::IndirectField: 1879 case Decl::ParmVar: 1880 // These can only appear with other declarations which are banned in 1881 // C++11 and permitted in C++1y, so ignore them. 1882 continue; 1883 1884 case Decl::Var: 1885 case Decl::Decomposition: { 1886 // C++1y [dcl.constexpr]p3 allows anything except: 1887 // a definition of a variable of non-literal type or of static or 1888 // thread storage duration or [before C++2a] for which no 1889 // initialization is performed. 1890 const auto *VD = cast<VarDecl>(DclIt); 1891 if (VD->isThisDeclarationADefinition()) { 1892 if (VD->isStaticLocal()) { 1893 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1894 SemaRef.Diag(VD->getLocation(), 1895 SemaRef.getLangOpts().CPlusPlus2b 1896 ? diag::warn_cxx20_compat_constexpr_var 1897 : diag::ext_constexpr_static_var) 1898 << isa<CXXConstructorDecl>(Dcl) 1899 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1900 } else if (!SemaRef.getLangOpts().CPlusPlus2b) { 1901 return false; 1902 } 1903 } 1904 if (SemaRef.LangOpts.CPlusPlus2b) { 1905 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1906 diag::warn_cxx20_compat_constexpr_var, 1907 isa<CXXConstructorDecl>(Dcl), 1908 /*variable of non-literal type*/ 2); 1909 } else if (CheckLiteralType( 1910 SemaRef, Kind, VD->getLocation(), VD->getType(), 1911 diag::err_constexpr_local_var_non_literal_type, 1912 isa<CXXConstructorDecl>(Dcl))) { 1913 return false; 1914 } 1915 if (!VD->getType()->isDependentType() && 1916 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1917 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1918 SemaRef.Diag( 1919 VD->getLocation(), 1920 SemaRef.getLangOpts().CPlusPlus20 1921 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1922 : diag::ext_constexpr_local_var_no_init) 1923 << isa<CXXConstructorDecl>(Dcl); 1924 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1925 return false; 1926 } 1927 continue; 1928 } 1929 } 1930 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1931 SemaRef.Diag(VD->getLocation(), 1932 SemaRef.getLangOpts().CPlusPlus14 1933 ? diag::warn_cxx11_compat_constexpr_local_var 1934 : diag::ext_constexpr_local_var) 1935 << isa<CXXConstructorDecl>(Dcl); 1936 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1937 return false; 1938 } 1939 continue; 1940 } 1941 1942 case Decl::NamespaceAlias: 1943 case Decl::Function: 1944 // These are disallowed in C++11 and permitted in C++1y. Allow them 1945 // everywhere as an extension. 1946 if (!Cxx1yLoc.isValid()) 1947 Cxx1yLoc = DS->getBeginLoc(); 1948 continue; 1949 1950 default: 1951 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1952 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1953 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1954 } 1955 return false; 1956 } 1957 } 1958 1959 return true; 1960} 1961 1962/// Check that the given field is initialized within a constexpr constructor. 1963/// 1964/// \param Dcl The constexpr constructor being checked. 1965/// \param Field The field being checked. This may be a member of an anonymous 1966/// struct or union nested within the class being checked. 1967/// \param Inits All declarations, including anonymous struct/union members and 1968/// indirect members, for which any initialization was provided. 1969/// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1970/// multiple notes for different members to the same error. 1971/// \param Kind Whether we're diagnosing a constructor as written or determining 1972/// whether the formal requirements are satisfied. 1973/// \return \c false if we're checking for validity and the constructor does 1974/// not satisfy the requirements on a constexpr constructor. 1975static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1976 const FunctionDecl *Dcl, 1977 FieldDecl *Field, 1978 llvm::SmallSet<Decl*, 16> &Inits, 1979 bool &Diagnosed, 1980 Sema::CheckConstexprKind Kind) { 1981 // In C++20 onwards, there's nothing to check for validity. 1982 if (Kind == Sema::CheckConstexprKind::CheckValid && 1983 SemaRef.getLangOpts().CPlusPlus20) 1984 return true; 1985 1986 if (Field->isInvalidDecl()) 1987 return true; 1988 1989 if (Field->isUnnamedBitfield()) 1990 return true; 1991 1992 // Anonymous unions with no variant members and empty anonymous structs do not 1993 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1994 // indirect fields don't need initializing. 1995 if (Field->isAnonymousStructOrUnion() && 1996 (Field->getType()->isUnionType() 1997 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1998 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1999 return true; 2000 2001 if (!Inits.count(Field)) { 2002 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2003 if (!Diagnosed) { 2004 SemaRef.Diag(Dcl->getLocation(), 2005 SemaRef.getLangOpts().CPlusPlus20 2006 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 2007 : diag::ext_constexpr_ctor_missing_init); 2008 Diagnosed = true; 2009 } 2010 SemaRef.Diag(Field->getLocation(), 2011 diag::note_constexpr_ctor_missing_init); 2012 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2013 return false; 2014 } 2015 } else if (Field->isAnonymousStructOrUnion()) { 2016 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2017 for (auto *I : RD->fields()) 2018 // If an anonymous union contains an anonymous struct of which any member 2019 // is initialized, all members must be initialized. 2020 if (!RD->isUnion() || Inits.count(I)) 2021 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2022 Kind)) 2023 return false; 2024 } 2025 return true; 2026} 2027 2028/// Check the provided statement is allowed in a constexpr function 2029/// definition. 2030static bool 2031CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2032 SmallVectorImpl<SourceLocation> &ReturnStmts, 2033 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2034 SourceLocation &Cxx2bLoc, 2035 Sema::CheckConstexprKind Kind) { 2036 // - its function-body shall be [...] a compound-statement that contains only 2037 switch (S->getStmtClass()) { 2038 case Stmt::NullStmtClass: 2039 // - null statements, 2040 return true; 2041 2042 case Stmt::DeclStmtClass: 2043 // - static_assert-declarations 2044 // - using-declarations, 2045 // - using-directives, 2046 // - typedef declarations and alias-declarations that do not define 2047 // classes or enumerations, 2048 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2049 return false; 2050 return true; 2051 2052 case Stmt::ReturnStmtClass: 2053 // - and exactly one return statement; 2054 if (isa<CXXConstructorDecl>(Dcl)) { 2055 // C++1y allows return statements in constexpr constructors. 2056 if (!Cxx1yLoc.isValid()) 2057 Cxx1yLoc = S->getBeginLoc(); 2058 return true; 2059 } 2060 2061 ReturnStmts.push_back(S->getBeginLoc()); 2062 return true; 2063 2064 case Stmt::AttributedStmtClass: 2065 // Attributes on a statement don't affect its formal kind and hence don't 2066 // affect its validity in a constexpr function. 2067 return CheckConstexprFunctionStmt( 2068 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts, 2069 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind); 2070 2071 case Stmt::CompoundStmtClass: { 2072 // C++1y allows compound-statements. 2073 if (!Cxx1yLoc.isValid()) 2074 Cxx1yLoc = S->getBeginLoc(); 2075 2076 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2077 for (auto *BodyIt : CompStmt->body()) { 2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2080 return false; 2081 } 2082 return true; 2083 } 2084 2085 case Stmt::IfStmtClass: { 2086 // C++1y allows if-statements. 2087 if (!Cxx1yLoc.isValid()) 2088 Cxx1yLoc = S->getBeginLoc(); 2089 2090 IfStmt *If = cast<IfStmt>(S); 2091 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2092 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2093 return false; 2094 if (If->getElse() && 2095 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2096 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2097 return false; 2098 return true; 2099 } 2100 2101 case Stmt::WhileStmtClass: 2102 case Stmt::DoStmtClass: 2103 case Stmt::ForStmtClass: 2104 case Stmt::CXXForRangeStmtClass: 2105 case Stmt::ContinueStmtClass: 2106 // C++1y allows all of these. We don't allow them as extensions in C++11, 2107 // because they don't make sense without variable mutation. 2108 if (!SemaRef.getLangOpts().CPlusPlus14) 2109 break; 2110 if (!Cxx1yLoc.isValid()) 2111 Cxx1yLoc = S->getBeginLoc(); 2112 for (Stmt *SubStmt : S->children()) { 2113 if (SubStmt && 2114 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2115 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2116 return false; 2117 } 2118 return true; 2119 2120 case Stmt::SwitchStmtClass: 2121 case Stmt::CaseStmtClass: 2122 case Stmt::DefaultStmtClass: 2123 case Stmt::BreakStmtClass: 2124 // C++1y allows switch-statements, and since they don't need variable 2125 // mutation, we can reasonably allow them in C++11 as an extension. 2126 if (!Cxx1yLoc.isValid()) 2127 Cxx1yLoc = S->getBeginLoc(); 2128 for (Stmt *SubStmt : S->children()) { 2129 if (SubStmt && 2130 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2131 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2132 return false; 2133 } 2134 return true; 2135 2136 case Stmt::LabelStmtClass: 2137 case Stmt::GotoStmtClass: 2138 if (Cxx2bLoc.isInvalid()) 2139 Cxx2bLoc = S->getBeginLoc(); 2140 for (Stmt *SubStmt : S->children()) { 2141 if (SubStmt && 2142 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2143 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2144 return false; 2145 } 2146 return true; 2147 2148 case Stmt::GCCAsmStmtClass: 2149 case Stmt::MSAsmStmtClass: 2150 // C++2a allows inline assembly statements. 2151 case Stmt::CXXTryStmtClass: 2152 if (Cxx2aLoc.isInvalid()) 2153 Cxx2aLoc = S->getBeginLoc(); 2154 for (Stmt *SubStmt : S->children()) { 2155 if (SubStmt && 2156 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2157 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2158 return false; 2159 } 2160 return true; 2161 2162 case Stmt::CXXCatchStmtClass: 2163 // Do not bother checking the language mode (already covered by the 2164 // try block check). 2165 if (!CheckConstexprFunctionStmt( 2166 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts, 2167 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2168 return false; 2169 return true; 2170 2171 default: 2172 if (!isa<Expr>(S)) 2173 break; 2174 2175 // C++1y allows expression-statements. 2176 if (!Cxx1yLoc.isValid()) 2177 Cxx1yLoc = S->getBeginLoc(); 2178 return true; 2179 } 2180 2181 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2182 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2183 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2184 } 2185 return false; 2186} 2187 2188/// Check the body for the given constexpr function declaration only contains 2189/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2190/// 2191/// \return true if the body is OK, false if we have found or diagnosed a 2192/// problem. 2193static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2194 Stmt *Body, 2195 Sema::CheckConstexprKind Kind) { 2196 SmallVector<SourceLocation, 4> ReturnStmts; 2197 2198 if (isa<CXXTryStmt>(Body)) { 2199 // C++11 [dcl.constexpr]p3: 2200 // The definition of a constexpr function shall satisfy the following 2201 // constraints: [...] 2202 // - its function-body shall be = delete, = default, or a 2203 // compound-statement 2204 // 2205 // C++11 [dcl.constexpr]p4: 2206 // In the definition of a constexpr constructor, [...] 2207 // - its function-body shall not be a function-try-block; 2208 // 2209 // This restriction is lifted in C++2a, as long as inner statements also 2210 // apply the general constexpr rules. 2211 switch (Kind) { 2212 case Sema::CheckConstexprKind::CheckValid: 2213 if (!SemaRef.getLangOpts().CPlusPlus20) 2214 return false; 2215 break; 2216 2217 case Sema::CheckConstexprKind::Diagnose: 2218 SemaRef.Diag(Body->getBeginLoc(), 2219 !SemaRef.getLangOpts().CPlusPlus20 2220 ? diag::ext_constexpr_function_try_block_cxx20 2221 : diag::warn_cxx17_compat_constexpr_function_try_block) 2222 << isa<CXXConstructorDecl>(Dcl); 2223 break; 2224 } 2225 } 2226 2227 // - its function-body shall be [...] a compound-statement that contains only 2228 // [... list of cases ...] 2229 // 2230 // Note that walking the children here is enough to properly check for 2231 // CompoundStmt and CXXTryStmt body. 2232 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc; 2233 for (Stmt *SubStmt : Body->children()) { 2234 if (SubStmt && 2235 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2236 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2237 return false; 2238 } 2239 2240 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2241 // If this is only valid as an extension, report that we don't satisfy the 2242 // constraints of the current language. 2243 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) || 2244 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2245 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2246 return false; 2247 } else if (Cxx2bLoc.isValid()) { 2248 SemaRef.Diag(Cxx2bLoc, 2249 SemaRef.getLangOpts().CPlusPlus2b 2250 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt 2251 : diag::ext_constexpr_body_invalid_stmt_cxx2b) 2252 << isa<CXXConstructorDecl>(Dcl); 2253 } else if (Cxx2aLoc.isValid()) { 2254 SemaRef.Diag(Cxx2aLoc, 2255 SemaRef.getLangOpts().CPlusPlus20 2256 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2257 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2258 << isa<CXXConstructorDecl>(Dcl); 2259 } else if (Cxx1yLoc.isValid()) { 2260 SemaRef.Diag(Cxx1yLoc, 2261 SemaRef.getLangOpts().CPlusPlus14 2262 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2263 : diag::ext_constexpr_body_invalid_stmt) 2264 << isa<CXXConstructorDecl>(Dcl); 2265 } 2266 2267 if (const CXXConstructorDecl *Constructor 2268 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2269 const CXXRecordDecl *RD = Constructor->getParent(); 2270 // DR1359: 2271 // - every non-variant non-static data member and base class sub-object 2272 // shall be initialized; 2273 // DR1460: 2274 // - if the class is a union having variant members, exactly one of them 2275 // shall be initialized; 2276 if (RD->isUnion()) { 2277 if (Constructor->getNumCtorInitializers() == 0 && 2278 RD->hasVariantMembers()) { 2279 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2280 SemaRef.Diag( 2281 Dcl->getLocation(), 2282 SemaRef.getLangOpts().CPlusPlus20 2283 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2284 : diag::ext_constexpr_union_ctor_no_init); 2285 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2286 return false; 2287 } 2288 } 2289 } else if (!Constructor->isDependentContext() && 2290 !Constructor->isDelegatingConstructor()) { 2291 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", 2291, __extension__ __PRETTY_FUNCTION__
))
; 2292 2293 // Skip detailed checking if we have enough initializers, and we would 2294 // allow at most one initializer per member. 2295 bool AnyAnonStructUnionMembers = false; 2296 unsigned Fields = 0; 2297 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2298 E = RD->field_end(); I != E; ++I, ++Fields) { 2299 if (I->isAnonymousStructOrUnion()) { 2300 AnyAnonStructUnionMembers = true; 2301 break; 2302 } 2303 } 2304 // DR1460: 2305 // - if the class is a union-like class, but is not a union, for each of 2306 // its anonymous union members having variant members, exactly one of 2307 // them shall be initialized; 2308 if (AnyAnonStructUnionMembers || 2309 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2310 // Check initialization of non-static data members. Base classes are 2311 // always initialized so do not need to be checked. Dependent bases 2312 // might not have initializers in the member initializer list. 2313 llvm::SmallSet<Decl*, 16> Inits; 2314 for (const auto *I: Constructor->inits()) { 2315 if (FieldDecl *FD = I->getMember()) 2316 Inits.insert(FD); 2317 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2318 Inits.insert(ID->chain_begin(), ID->chain_end()); 2319 } 2320 2321 bool Diagnosed = false; 2322 for (auto *I : RD->fields()) 2323 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2324 Kind)) 2325 return false; 2326 } 2327 } 2328 } else { 2329 if (ReturnStmts.empty()) { 2330 // C++1y doesn't require constexpr functions to contain a 'return' 2331 // statement. We still do, unless the return type might be void, because 2332 // otherwise if there's no return statement, the function cannot 2333 // be used in a core constant expression. 2334 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2335 (Dcl->getReturnType()->isVoidType() || 2336 Dcl->getReturnType()->isDependentType()); 2337 switch (Kind) { 2338 case Sema::CheckConstexprKind::Diagnose: 2339 SemaRef.Diag(Dcl->getLocation(), 2340 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2341 : diag::err_constexpr_body_no_return) 2342 << Dcl->isConsteval(); 2343 if (!OK) 2344 return false; 2345 break; 2346 2347 case Sema::CheckConstexprKind::CheckValid: 2348 // The formal requirements don't include this rule in C++14, even 2349 // though the "must be able to produce a constant expression" rules 2350 // still imply it in some cases. 2351 if (!SemaRef.getLangOpts().CPlusPlus14) 2352 return false; 2353 break; 2354 } 2355 } else if (ReturnStmts.size() > 1) { 2356 switch (Kind) { 2357 case Sema::CheckConstexprKind::Diagnose: 2358 SemaRef.Diag( 2359 ReturnStmts.back(), 2360 SemaRef.getLangOpts().CPlusPlus14 2361 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2362 : diag::ext_constexpr_body_multiple_return); 2363 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2364 SemaRef.Diag(ReturnStmts[I], 2365 diag::note_constexpr_body_previous_return); 2366 break; 2367 2368 case Sema::CheckConstexprKind::CheckValid: 2369 if (!SemaRef.getLangOpts().CPlusPlus14) 2370 return false; 2371 break; 2372 } 2373 } 2374 } 2375 2376 // C++11 [dcl.constexpr]p5: 2377 // if no function argument values exist such that the function invocation 2378 // substitution would produce a constant expression, the program is 2379 // ill-formed; no diagnostic required. 2380 // C++11 [dcl.constexpr]p3: 2381 // - every constructor call and implicit conversion used in initializing the 2382 // return value shall be one of those allowed in a constant expression. 2383 // C++11 [dcl.constexpr]p4: 2384 // - every constructor involved in initializing non-static data members and 2385 // base class sub-objects shall be a constexpr constructor. 2386 // 2387 // Note that this rule is distinct from the "requirements for a constexpr 2388 // function", so is not checked in CheckValid mode. 2389 SmallVector<PartialDiagnosticAt, 8> Diags; 2390 if (Kind == Sema::CheckConstexprKind::Diagnose && 2391 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2392 SemaRef.Diag(Dcl->getLocation(), 2393 diag::ext_constexpr_function_never_constant_expr) 2394 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2395 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2396 SemaRef.Diag(Diags[I].first, Diags[I].second); 2397 // Don't return false here: we allow this for compatibility in 2398 // system headers. 2399 } 2400 2401 return true; 2402} 2403 2404/// Get the class that is directly named by the current context. This is the 2405/// class for which an unqualified-id in this scope could name a constructor 2406/// or destructor. 2407/// 2408/// If the scope specifier denotes a class, this will be that class. 2409/// If the scope specifier is empty, this will be the class whose 2410/// member-specification we are currently within. Otherwise, there 2411/// is no such class. 2412CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2413 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", 2413, __extension__ __PRETTY_FUNCTION__
))
; 2414 2415 if (SS && SS->isInvalid()) 2416 return nullptr; 2417 2418 if (SS && SS->isNotEmpty()) { 2419 DeclContext *DC = computeDeclContext(*SS, true); 2420 return dyn_cast_or_null<CXXRecordDecl>(DC); 2421 } 2422 2423 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2424} 2425 2426/// isCurrentClassName - Determine whether the identifier II is the 2427/// name of the class type currently being defined. In the case of 2428/// nested classes, this will only return true if II is the name of 2429/// the innermost class. 2430bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2431 const CXXScopeSpec *SS) { 2432 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2433 return CurDecl && &II == CurDecl->getIdentifier(); 2434} 2435 2436/// Determine whether the identifier II is a typo for the name of 2437/// the class type currently being defined. If so, update it to the identifier 2438/// that should have been used. 2439bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2440 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", 2440, __extension__ __PRETTY_FUNCTION__
))
; 2441 2442 if (!getLangOpts().SpellChecking) 2443 return false; 2444 2445 CXXRecordDecl *CurDecl; 2446 if (SS && SS->isSet() && !SS->isInvalid()) { 2447 DeclContext *DC = computeDeclContext(*SS, true); 2448 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2449 } else 2450 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2451 2452 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2453 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2454 < II->getLength()) { 2455 II = CurDecl->getIdentifier(); 2456 return true; 2457 } 2458 2459 return false; 2460} 2461 2462/// Determine whether the given class is a base class of the given 2463/// class, including looking at dependent bases. 2464static bool findCircularInheritance(const CXXRecordDecl *Class, 2465 const CXXRecordDecl *Current) { 2466 SmallVector<const CXXRecordDecl*, 8> Queue; 2467 2468 Class = Class->getCanonicalDecl(); 2469 while (true) { 2470 for (const auto &I : Current->bases()) { 2471 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2472 if (!Base) 2473 continue; 2474 2475 Base = Base->getDefinition(); 2476 if (!Base) 2477 continue; 2478 2479 if (Base->getCanonicalDecl() == Class) 2480 return true; 2481 2482 Queue.push_back(Base); 2483 } 2484 2485 if (Queue.empty()) 2486 return false; 2487 2488 Current = Queue.pop_back_val(); 2489 } 2490 2491 return false; 2492} 2493 2494/// Check the validity of a C++ base class specifier. 2495/// 2496/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2497/// and returns NULL otherwise. 2498CXXBaseSpecifier * 2499Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2500 SourceRange SpecifierRange, 2501 bool Virtual, AccessSpecifier Access, 2502 TypeSourceInfo *TInfo, 2503 SourceLocation EllipsisLoc) { 2504 QualType BaseType = TInfo->getType(); 2505 if (BaseType->containsErrors()) { 2506 // Already emitted a diagnostic when parsing the error type. 2507 return nullptr; 2508 } 2509 // C++ [class.union]p1: 2510 // A union shall not have base classes. 2511 if (Class->isUnion()) { 2512 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2513 << SpecifierRange; 2514 return nullptr; 2515 } 2516 2517 if (EllipsisLoc.isValid() && 2518 !TInfo->getType()->containsUnexpandedParameterPack()) { 2519 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2520 << TInfo->getTypeLoc().getSourceRange(); 2521 EllipsisLoc = SourceLocation(); 2522 } 2523 2524 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2525 2526 if (BaseType->isDependentType()) { 2527 // Make sure that we don't have circular inheritance among our dependent 2528 // bases. For non-dependent bases, the check for completeness below handles 2529 // this. 2530 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2531 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2532 ((BaseDecl = BaseDecl->getDefinition()) && 2533 findCircularInheritance(Class, BaseDecl))) { 2534 Diag(BaseLoc, diag::err_circular_inheritance) 2535 << BaseType << Context.getTypeDeclType(Class); 2536 2537 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2538 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2539 << BaseType; 2540 2541 return nullptr; 2542 } 2543 } 2544 2545 // Make sure that we don't make an ill-formed AST where the type of the 2546 // Class is non-dependent and its attached base class specifier is an 2547 // dependent type, which violates invariants in many clang code paths (e.g. 2548 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2549 // explicitly mark the Class decl invalid. The diagnostic was already 2550 // emitted. 2551 if (!Class->getTypeForDecl()->isDependentType()) 2552 Class->setInvalidDecl(); 2553 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2554 Class->getTagKind() == TTK_Class, 2555 Access, TInfo, EllipsisLoc); 2556 } 2557 2558 // Base specifiers must be record types. 2559 if (!BaseType->isRecordType()) { 2560 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2561 return nullptr; 2562 } 2563 2564 // C++ [class.union]p1: 2565 // A union shall not be used as a base class. 2566 if (BaseType->isUnionType()) { 2567 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2568 return nullptr; 2569 } 2570 2571 // For the MS ABI, propagate DLL attributes to base class templates. 2572 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2573 if (Attr *ClassAttr = getDLLAttr(Class)) { 2574 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2575 BaseType->getAsCXXRecordDecl())) { 2576 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2577 BaseLoc); 2578 } 2579 } 2580 } 2581 2582 // C++ [class.derived]p2: 2583 // The class-name in a base-specifier shall not be an incompletely 2584 // defined class. 2585 if (RequireCompleteType(BaseLoc, BaseType, 2586 diag::err_incomplete_base_class, SpecifierRange)) { 2587 Class->setInvalidDecl(); 2588 return nullptr; 2589 } 2590 2591 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2592 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2593 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", 2593, __extension__ __PRETTY_FUNCTION__
))
; 2594 BaseDecl = BaseDecl->getDefinition(); 2595 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", 2595, __extension__ __PRETTY_FUNCTION__
))
; 2596 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2597 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", 2597, __extension__ __PRETTY_FUNCTION__
))
; 2598 2599 // Microsoft docs say: 2600 // "If a base-class has a code_seg attribute, derived classes must have the 2601 // same attribute." 2602 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2603 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2604 if ((DerivedCSA || BaseCSA) && 2605 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2606 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2607 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2608 << CXXBaseDecl; 2609 return nullptr; 2610 } 2611 2612 // A class which contains a flexible array member is not suitable for use as a 2613 // base class: 2614 // - If the layout determines that a base comes before another base, 2615 // the flexible array member would index into the subsequent base. 2616 // - If the layout determines that base comes before the derived class, 2617 // the flexible array member would index into the derived class. 2618 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2619 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2620 << CXXBaseDecl->getDeclName(); 2621 return nullptr; 2622 } 2623 2624 // C++ [class]p3: 2625 // If a class is marked final and it appears as a base-type-specifier in 2626 // base-clause, the program is ill-formed. 2627 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2628 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2629 << CXXBaseDecl->getDeclName() 2630 << FA->isSpelledAsSealed(); 2631 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2632 << CXXBaseDecl->getDeclName() << FA->getRange(); 2633 return nullptr; 2634 } 2635 2636 if (BaseDecl->isInvalidDecl()) 2637 Class->setInvalidDecl(); 2638 2639 // Create the base specifier. 2640 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2641 Class->getTagKind() == TTK_Class, 2642 Access, TInfo, EllipsisLoc); 2643} 2644 2645/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2646/// one entry in the base class list of a class specifier, for 2647/// example: 2648/// class foo : public bar, virtual private baz { 2649/// 'public bar' and 'virtual private baz' are each base-specifiers. 2650BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2651 const ParsedAttributesView &Attributes, 2652 bool Virtual, AccessSpecifier Access, 2653 ParsedType basetype, SourceLocation BaseLoc, 2654 SourceLocation EllipsisLoc) { 2655 if (!classdecl) 2656 return true; 2657 2658 AdjustDeclIfTemplate(classdecl); 2659 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2660 if (!Class) 2661 return true; 2662 2663 // We haven't yet attached the base specifiers. 2664 Class->setIsParsingBaseSpecifiers(); 2665 2666 // We do not support any C++11 attributes on base-specifiers yet. 2667 // Diagnose any attributes we see. 2668 for (const ParsedAttr &AL : Attributes) { 2669 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2670 continue; 2671 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2672 ? (unsigned)diag::warn_unknown_attribute_ignored 2673 : (unsigned)diag::err_base_specifier_attribute) 2674 << AL << AL.getRange(); 2675 } 2676 2677 TypeSourceInfo *TInfo = nullptr; 2678 GetTypeFromParser(basetype, &TInfo); 2679 2680 if (EllipsisLoc.isInvalid() && 2681 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2682 UPPC_BaseType)) 2683 return true; 2684 2685 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2686 Virtual, Access, TInfo, 2687 EllipsisLoc)) 2688 return BaseSpec; 2689 else 2690 Class->setInvalidDecl(); 2691 2692 return true; 2693} 2694 2695/// Use small set to collect indirect bases. As this is only used 2696/// locally, there's no need to abstract the small size parameter. 2697typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2698 2699/// Recursively add the bases of Type. Don't add Type itself. 2700static void 2701NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2702 const QualType &Type) 2703{ 2704 // Even though the incoming type is a base, it might not be 2705 // a class -- it could be a template parm, for instance. 2706 if (auto Rec = Type->getAs<RecordType>()) { 2707 auto Decl = Rec->getAsCXXRecordDecl(); 2708 2709 // Iterate over its bases. 2710 for (const auto &BaseSpec : Decl->bases()) { 2711 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2712 .getUnqualifiedType(); 2713 if (Set.insert(Base).second) 2714 // If we've not already seen it, recurse. 2715 NoteIndirectBases(Context, Set, Base); 2716 } 2717 } 2718} 2719 2720/// Performs the actual work of attaching the given base class 2721/// specifiers to a C++ class. 2722bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2723 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2724 if (Bases.empty()) 2725 return false; 2726 2727 // Used to keep track of which base types we have already seen, so 2728 // that we can properly diagnose redundant direct base types. Note 2729 // that the key is always the unqualified canonical type of the base 2730 // class. 2731 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2732 2733 // Used to track indirect bases so we can see if a direct base is 2734 // ambiguous. 2735 IndirectBaseSet IndirectBaseTypes; 2736 2737 // Copy non-redundant base specifiers into permanent storage. 2738 unsigned NumGoodBases = 0; 2739 bool Invalid = false; 2740 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2741 QualType NewBaseType 2742 = Context.getCanonicalType(Bases[idx]->getType()); 2743 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2744 2745 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2746 if (KnownBase) { 2747 // C++ [class.mi]p3: 2748 // A class shall not be specified as a direct base class of a 2749 // derived class more than once. 2750 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2751 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2752 2753 // Delete the duplicate base class specifier; we're going to 2754 // overwrite its pointer later. 2755 Context.Deallocate(Bases[idx]); 2756 2757 Invalid = true; 2758 } else { 2759 // Okay, add this new base class. 2760 KnownBase = Bases[idx]; 2761 Bases[NumGoodBases++] = Bases[idx]; 2762 2763 if (NewBaseType->isDependentType()) 2764 continue; 2765 // Note this base's direct & indirect bases, if there could be ambiguity. 2766 if (Bases.size() > 1) 2767 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2768 2769 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2770 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2771 if (Class->isInterface() && 2772 (!RD->isInterfaceLike() || 2773 KnownBase->getAccessSpecifier() != AS_public)) { 2774 // The Microsoft extension __interface does not permit bases that 2775 // are not themselves public interfaces. 2776 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2777 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2778 << RD->getSourceRange(); 2779 Invalid = true; 2780 } 2781 if (RD->hasAttr<WeakAttr>()) 2782 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2783 } 2784 } 2785 } 2786 2787 // Attach the remaining base class specifiers to the derived class. 2788 Class->setBases(Bases.data(), NumGoodBases); 2789 2790 // Check that the only base classes that are duplicate are virtual. 2791 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2792 // Check whether this direct base is inaccessible due to ambiguity. 2793 QualType BaseType = Bases[idx]->getType(); 2794 2795 // Skip all dependent types in templates being used as base specifiers. 2796 // Checks below assume that the base specifier is a CXXRecord. 2797 if (BaseType->isDependentType()) 2798 continue; 2799 2800 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2801 .getUnqualifiedType(); 2802 2803 if (IndirectBaseTypes.count(CanonicalBase)) { 2804 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2805 /*DetectVirtual=*/true); 2806 bool found 2807 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2808 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "clang/lib/Sema/SemaDeclCXX.cpp", 2808, __extension__
__PRETTY_FUNCTION__))
; 2809 (void)found; 2810 2811 if (Paths.isAmbiguous(CanonicalBase)) 2812 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2813 << BaseType << getAmbiguousPathsDisplayString(Paths) 2814 << Bases[idx]->getSourceRange(); 2815 else 2816 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 2816, __extension__ __PRETTY_FUNCTION__))
; 2817 } 2818 2819 // Delete the base class specifier, since its data has been copied 2820 // into the CXXRecordDecl. 2821 Context.Deallocate(Bases[idx]); 2822 } 2823 2824 return Invalid; 2825} 2826 2827/// ActOnBaseSpecifiers - Attach the given base specifiers to the 2828/// class, after checking whether there are any duplicate base 2829/// classes. 2830void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2831 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2832 if (!ClassDecl || Bases.empty()) 2833 return; 2834 2835 AdjustDeclIfTemplate(ClassDecl); 2836 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2837} 2838 2839/// Determine whether the type \p Derived is a C++ class that is 2840/// derived from the type \p Base. 2841bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2842 if (!getLangOpts().CPlusPlus) 2843 return false; 2844 2845 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2846 if (!DerivedRD) 2847 return false; 2848 2849 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2850 if (!BaseRD) 2851 return false; 2852 2853 // If either the base or the derived type is invalid, don't try to 2854 // check whether one is derived from the other. 2855 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2856 return false; 2857 2858 // FIXME: In a modules build, do we need the entire path to be visible for us 2859 // to be able to use the inheritance relationship? 2860 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2861 return false; 2862 2863 return DerivedRD->isDerivedFrom(BaseRD); 2864} 2865 2866/// Determine whether the type \p Derived is a C++ class that is 2867/// derived from the type \p Base. 2868bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2869 CXXBasePaths &Paths) { 2870 if (!getLangOpts().CPlusPlus) 2871 return false; 2872 2873 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2874 if (!DerivedRD) 2875 return false; 2876 2877 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2878 if (!BaseRD) 2879 return false; 2880 2881 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2882 return false; 2883 2884 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2885} 2886 2887static void BuildBasePathArray(const CXXBasePath &Path, 2888 CXXCastPath &BasePathArray) { 2889 // We first go backward and check if we have a virtual base. 2890 // FIXME: It would be better if CXXBasePath had the base specifier for 2891 // the nearest virtual base. 2892 unsigned Start = 0; 2893 for (unsigned I = Path.size(); I != 0; --I) { 2894 if (Path[I - 1].Base->isVirtual()) { 2895 Start = I - 1; 2896 break; 2897 } 2898 } 2899 2900 // Now add all bases. 2901 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2902 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2903} 2904 2905 2906void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2907 CXXCastPath &BasePathArray) { 2908 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", 2908, __extension__ __PRETTY_FUNCTION__
))
; 2909 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", 2909, __extension__ __PRETTY_FUNCTION__
))
; 2910 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2911} 2912/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2913/// conversion (where Derived and Base are class types) is 2914/// well-formed, meaning that the conversion is unambiguous (and 2915/// that all of the base classes are accessible). Returns true 2916/// and emits a diagnostic if the code is ill-formed, returns false 2917/// otherwise. Loc is the location where this routine should point to 2918/// if there is an error, and Range is the source range to highlight 2919/// if there is an error. 2920/// 2921/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2922/// diagnostic for the respective type of error will be suppressed, but the 2923/// check for ill-formed code will still be performed. 2924bool 2925Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2926 unsigned InaccessibleBaseID, 2927 unsigned AmbiguousBaseConvID, 2928 SourceLocation Loc, SourceRange Range, 2929 DeclarationName Name, 2930 CXXCastPath *BasePath, 2931 bool IgnoreAccess) { 2932 // First, determine whether the path from Derived to Base is 2933 // ambiguous. This is slightly more expensive than checking whether 2934 // the Derived to Base conversion exists, because here we need to 2935 // explore multiple paths to determine if there is an ambiguity. 2936 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2937 /*DetectVirtual=*/false); 2938 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2939 if (!DerivationOkay) 2940 return true; 2941 2942 const CXXBasePath *Path = nullptr; 2943 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2944 Path = &Paths.front(); 2945 2946 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2947 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2948 // user to access such bases. 2949 if (!Path && getLangOpts().MSVCCompat) { 2950 for (const CXXBasePath &PossiblePath : Paths) { 2951 if (PossiblePath.size() == 1) { 2952 Path = &PossiblePath; 2953 if (AmbiguousBaseConvID) 2954 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2955 << Base << Derived << Range; 2956 break; 2957 } 2958 } 2959 } 2960 2961 if (Path) { 2962 if (!IgnoreAccess) { 2963 // Check that the base class can be accessed. 2964 switch ( 2965 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2966 case AR_inaccessible: 2967 return true; 2968 case AR_accessible: 2969 case AR_dependent: 2970 case AR_delayed: 2971 break; 2972 } 2973 } 2974 2975 // Build a base path if necessary. 2976 if (BasePath) 2977 ::BuildBasePathArray(*Path, *BasePath); 2978 return false; 2979 } 2980 2981 if (AmbiguousBaseConvID) { 2982 // We know that the derived-to-base conversion is ambiguous, and 2983 // we're going to produce a diagnostic. Perform the derived-to-base 2984 // search just one more time to compute all of the possible paths so 2985 // that we can print them out. This is more expensive than any of 2986 // the previous derived-to-base checks we've done, but at this point 2987 // performance isn't as much of an issue. 2988 Paths.clear(); 2989 Paths.setRecordingPaths(true); 2990 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2991 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", 2991, __extension__ __PRETTY_FUNCTION__
))
; 2992 (void)StillOkay; 2993 2994 // Build up a textual representation of the ambiguous paths, e.g., 2995 // D -> B -> A, that will be used to illustrate the ambiguous 2996 // conversions in the diagnostic. We only print one of the paths 2997 // to each base class subobject. 2998 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2999 3000 Diag(Loc, AmbiguousBaseConvID) 3001 << Derived << Base << PathDisplayStr << Range << Name; 3002 } 3003 return true; 3004} 3005 3006bool 3007Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3008 SourceLocation Loc, SourceRange Range, 3009 CXXCastPath *BasePath, 3010 bool IgnoreAccess) { 3011 return CheckDerivedToBaseConversion( 3012 Derived, Base, diag::err_upcast_to_inaccessible_base, 3013 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 3014 BasePath, IgnoreAccess); 3015} 3016 3017 3018/// Builds a string representing ambiguous paths from a 3019/// specific derived class to different subobjects of the same base 3020/// class. 3021/// 3022/// This function builds a string that can be used in error messages 3023/// to show the different paths that one can take through the 3024/// inheritance hierarchy to go from the derived class to different 3025/// subobjects of a base class. The result looks something like this: 3026/// @code 3027/// struct D -> struct B -> struct A 3028/// struct D -> struct C -> struct A 3029/// @endcode 3030std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 3031 std::string PathDisplayStr; 3032 std::set<unsigned> DisplayedPaths; 3033 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3034 Path != Paths.end(); ++Path) { 3035 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3036 // We haven't displayed a path to this particular base 3037 // class subobject yet. 3038 PathDisplayStr += "\n "; 3039 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3040 for (CXXBasePath::const_iterator Element = Path->begin(); 3041 Element != Path->end(); ++Element) 3042 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3043 } 3044 } 3045 3046 return PathDisplayStr; 3047} 3048 3049//===----------------------------------------------------------------------===// 3050// C++ class member Handling 3051//===----------------------------------------------------------------------===// 3052 3053/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3054bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3055 SourceLocation ColonLoc, 3056 const ParsedAttributesView &Attrs) { 3057 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", 3057, __extension__ __PRETTY_FUNCTION__
))
; 3058 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3059 ASLoc, ColonLoc); 3060 CurContext->addHiddenDecl(ASDecl); 3061 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3062} 3063 3064/// CheckOverrideControl - Check C++11 override control semantics. 3065void Sema::CheckOverrideControl(NamedDecl *D) { 3066 if (D->isInvalidDecl()) 3067 return; 3068 3069 // We only care about "override" and "final" declarations. 3070 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3071 return; 3072 3073 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3074 3075 // We can't check dependent instance methods. 3076 if (MD && MD->isInstance() && 3077 (MD->getParent()->hasAnyDependentBases() || 3078 MD->getType()->isDependentType())) 3079 return; 3080 3081 if (MD && !MD->isVirtual()) { 3082 // If we have a non-virtual method, check if if hides a virtual method. 3083 // (In that case, it's most likely the method has the wrong type.) 3084 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3085 FindHiddenVirtualMethods(MD, OverloadedMethods); 3086 3087 if (!OverloadedMethods.empty()) { 3088 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3089 Diag(OA->getLocation(), 3090 diag::override_keyword_hides_virtual_member_function) 3091 << "override" << (OverloadedMethods.size() > 1); 3092 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3093 Diag(FA->getLocation(), 3094 diag::override_keyword_hides_virtual_member_function) 3095 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3096 << (OverloadedMethods.size() > 1); 3097 } 3098 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3099 MD->setInvalidDecl(); 3100 return; 3101 } 3102 // Fall through into the general case diagnostic. 3103 // FIXME: We might want to attempt typo correction here. 3104 } 3105 3106 if (!MD || !MD->isVirtual()) { 3107 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3108 Diag(OA->getLocation(), 3109 diag::override_keyword_only_allowed_on_virtual_member_functions) 3110 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3111 D->dropAttr<OverrideAttr>(); 3112 } 3113 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3114 Diag(FA->getLocation(), 3115 diag::override_keyword_only_allowed_on_virtual_member_functions) 3116 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3117 << FixItHint::CreateRemoval(FA->getLocation()); 3118 D->dropAttr<FinalAttr>(); 3119 } 3120 return; 3121 } 3122 3123 // C++11 [class.virtual]p5: 3124 // If a function is marked with the virt-specifier override and 3125 // does not override a member function of a base class, the program is 3126 // ill-formed. 3127 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3128 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3129 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3130 << MD->getDeclName(); 3131} 3132 3133void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3134 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3135 return; 3136 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3137 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3138 return; 3139 3140 SourceLocation Loc = MD->getLocation(); 3141 SourceLocation SpellingLoc = Loc; 3142 if (getSourceManager().isMacroArgExpansion(Loc)) 3143 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3144 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3145 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3146 return; 3147 3148 if (MD->size_overridden_methods() > 0) { 3149 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3150 unsigned DiagID = 3151 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3152 ? DiagInconsistent 3153 : DiagSuggest; 3154 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3155 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3156 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3157 }; 3158 if (isa<CXXDestructorDecl>(MD)) 3159 EmitDiag( 3160 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3161 diag::warn_suggest_destructor_marked_not_override_overriding); 3162 else 3163 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3164 diag::warn_suggest_function_marked_not_override_overriding); 3165 } 3166} 3167 3168/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3169/// function overrides a virtual member function marked 'final', according to 3170/// C++11 [class.virtual]p4. 3171bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3172 const CXXMethodDecl *Old) { 3173 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3174 if (!FA) 3175 return false; 3176 3177 Diag(New->getLocation(), diag::err_final_function_overridden) 3178 << New->getDeclName() 3179 << FA->isSpelledAsSealed(); 3180 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3181 return true; 3182} 3183 3184static bool InitializationHasSideEffects(const FieldDecl &FD) { 3185 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3186 // FIXME: Destruction of ObjC lifetime types has side-effects. 3187 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3188 return !RD->isCompleteDefinition() || 3189 !RD->hasTrivialDefaultConstructor() || 3190 !RD->hasTrivialDestructor(); 3191 return false; 3192} 3193 3194static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3195 ParsedAttributesView::const_iterator Itr = 3196 llvm::find_if(list, [](const ParsedAttr &AL) { 3197 return AL.isDeclspecPropertyAttribute(); 3198 }); 3199 if (Itr != list.end()) 3200 return &*Itr; 3201 return nullptr; 3202} 3203 3204// Check if there is a field shadowing. 3205void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3206 DeclarationName FieldName, 3207 const CXXRecordDecl *RD, 3208 bool DeclIsField) { 3209 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3210 return; 3211 3212 // To record a shadowed field in a base 3213 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3214 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3215 CXXBasePath &Path) { 3216 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3217 // Record an ambiguous path directly 3218 if (Bases.find(Base) != Bases.end()) 3219 return true; 3220 for (const auto Field : Base->lookup(FieldName)) { 3221 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3222 Field->getAccess() != AS_private) { 3223 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", 3223, __extension__ __PRETTY_FUNCTION__
))
; 3224 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", 3224, __extension__ __PRETTY_FUNCTION__
))
; 3225 Bases[Base] = Field; 3226 return true; 3227 } 3228 } 3229 return false; 3230 }; 3231 3232 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3233 /*DetectVirtual=*/true); 3234 if (!RD->lookupInBases(FieldShadowed, Paths)) 3235 return; 3236 3237 for (const auto &P : Paths) { 3238 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3239 auto It = Bases.find(Base); 3240 // Skip duplicated bases 3241 if (It == Bases.end()) 3242 continue; 3243 auto BaseField = It->second; 3244 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", 3244, __extension__ __PRETTY_FUNCTION__
))
; 3245 if (AS_none != 3246 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3247 Diag(Loc, diag::warn_shadow_field) 3248 << FieldName << RD << Base << DeclIsField; 3249 Diag(BaseField->getLocation(), diag::note_shadow_field); 3250 Bases.erase(It); 3251 } 3252 } 3253} 3254 3255/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3256/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3257/// bitfield width if there is one, 'InitExpr' specifies the initializer if 3258/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3259/// present (but parsing it has been deferred). 3260NamedDecl * 3261Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3262 MultiTemplateParamsArg TemplateParameterLists, 3263 Expr *BW, const VirtSpecifiers &VS, 3264 InClassInitStyle InitStyle) { 3265 const DeclSpec &DS = D.getDeclSpec(); 3266 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3267 DeclarationName Name = NameInfo.getName(); 3268 SourceLocation Loc = NameInfo.getLoc(); 3269 3270 // For anonymous bitfields, the location should point to the type. 3271 if (Loc.isInvalid()) 3272 Loc = D.getBeginLoc(); 3273 3274 Expr *BitWidth = static_cast<Expr*>(BW); 3275 3276 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 3276, __extension__ __PRETTY_FUNCTION__
))
; 3277 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 3277, __extension__ __PRETTY_FUNCTION__))
; 3278 3279 bool isFunc = D.isDeclarationOfFunction(); 3280 const ParsedAttr *MSPropertyAttr = 3281 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3282 3283 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3284 // The Microsoft extension __interface only permits public member functions 3285 // and prohibits constructors, destructors, operators, non-public member 3286 // functions, static methods and data members. 3287 unsigned InvalidDecl; 3288 bool ShowDeclName = true; 3289 if (!isFunc && 3290 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3291 InvalidDecl = 0; 3292 else if (!isFunc) 3293 InvalidDecl = 1; 3294 else if (AS != AS_public) 3295 InvalidDecl = 2; 3296 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3297 InvalidDecl = 3; 3298 else switch (Name.getNameKind()) { 3299 case DeclarationName::CXXConstructorName: 3300 InvalidDecl = 4; 3301 ShowDeclName = false; 3302 break; 3303 3304 case DeclarationName::CXXDestructorName: 3305 InvalidDecl = 5; 3306 ShowDeclName = false; 3307 break; 3308 3309 case DeclarationName::CXXOperatorName: 3310 case DeclarationName::CXXConversionFunctionName: 3311 InvalidDecl = 6; 3312 break; 3313 3314 default: 3315 InvalidDecl = 0; 3316 break; 3317 } 3318 3319 if (InvalidDecl) { 3320 if (ShowDeclName) 3321 Diag(Loc, diag::err_invalid_member_in_interface) 3322 << (InvalidDecl-1) << Name; 3323 else 3324 Diag(Loc, diag::err_invalid_member_in_interface) 3325 << (InvalidDecl-1) << ""; 3326 return nullptr; 3327 } 3328 } 3329 3330 // C++ 9.2p6: A member shall not be declared to have automatic storage 3331 // duration (auto, register) or with the extern storage-class-specifier. 3332 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3333 // data members and cannot be applied to names declared const or static, 3334 // and cannot be applied to reference members. 3335 switch (DS.getStorageClassSpec()) { 3336 case DeclSpec::SCS_unspecified: 3337 case DeclSpec::SCS_typedef: 3338 case DeclSpec::SCS_static: 3339 break; 3340 case DeclSpec::SCS_mutable: 3341 if (isFunc) { 3342 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3343 3344 // FIXME: It would be nicer if the keyword was ignored only for this 3345 // declarator. Otherwise we could get follow-up errors. 3346 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3347 } 3348 break; 3349 default: 3350 Diag(DS.getStorageClassSpecLoc(), 3351 diag::err_storageclass_invalid_for_member); 3352 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3353 break; 3354 } 3355 3356 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3357 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3358 !isFunc); 3359 3360 if (DS.hasConstexprSpecifier() && isInstField) { 3361 SemaDiagnosticBuilder B = 3362 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3363 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3364 if (InitStyle == ICIS_NoInit) { 3365 B << 0 << 0; 3366 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3367 B << FixItHint::CreateRemoval(ConstexprLoc); 3368 else { 3369 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3370 D.getMutableDeclSpec().ClearConstexprSpec(); 3371 const char *PrevSpec; 3372 unsigned DiagID; 3373 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3374 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3375 (void)Failed; 3376 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", 3376, __extension__ __PRETTY_FUNCTION__
))
; 3377 } 3378 } else { 3379 B << 1; 3380 const char *PrevSpec; 3381 unsigned DiagID; 3382 if (D.getMutableDeclSpec().SetStorageClassSpec( 3383 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3384 Context.getPrintingPolicy())) { 3385 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", 3386, __extension__ __PRETTY_FUNCTION__
))
3386 "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", 3386, __extension__ __PRETTY_FUNCTION__
))
; 3387 B << 1; 3388 } else { 3389 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3390 isInstField = false; 3391 } 3392 } 3393 } 3394 3395 NamedDecl *Member; 3396 if (isInstField) { 3397 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3398 3399 // Data members must have identifiers for names. 3400 if (!Name.isIdentifier()) { 3401 Diag(Loc, diag::err_bad_variable_name) 3402 << Name; 3403 return nullptr; 3404 } 3405 3406 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3407 3408 // Member field could not be with "template" keyword. 3409 // So TemplateParameterLists should be empty in this case. 3410 if (TemplateParameterLists.size()) { 3411 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3412 if (TemplateParams->size()) { 3413 // There is no such thing as a member field template. 3414 Diag(D.getIdentifierLoc(), diag::err_template_member) 3415 << II 3416 << SourceRange(TemplateParams->getTemplateLoc(), 3417 TemplateParams->getRAngleLoc()); 3418 } else { 3419 // There is an extraneous 'template<>' for this member. 3420 Diag(TemplateParams->getTemplateLoc(), 3421 diag::err_template_member_noparams) 3422 << II 3423 << SourceRange(TemplateParams->getTemplateLoc(), 3424 TemplateParams->getRAngleLoc()); 3425 } 3426 return nullptr; 3427 } 3428 3429 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 3430 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments) 3431 << II 3432 << SourceRange(D.getName().TemplateId->LAngleLoc, 3433 D.getName().TemplateId->RAngleLoc) 3434 << D.getName().TemplateId->LAngleLoc; 3435 D.SetIdentifier(II, Loc); 3436 } 3437 3438 if (SS.isSet() && !SS.isInvalid()) { 3439 // The user provided a superfluous scope specifier inside a class 3440 // definition: 3441 // 3442 // class X { 3443 // int X::member; 3444 // }; 3445 if (DeclContext *DC = computeDeclContext(SS, false)) 3446 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3447 D.getName().getKind() == 3448 UnqualifiedIdKind::IK_TemplateId); 3449 else 3450 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3451 << Name << SS.getRange(); 3452 3453 SS.clear(); 3454 } 3455 3456 if (MSPropertyAttr) { 3457 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3458 BitWidth, InitStyle, AS, *MSPropertyAttr); 3459 if (!Member) 3460 return nullptr; 3461 isInstField = false; 3462 } else { 3463 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3464 BitWidth, InitStyle, AS); 3465 if (!Member) 3466 return nullptr; 3467 } 3468 3469 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3470 } else { 3471 Member = HandleDeclarator(S, D, TemplateParameterLists); 3472 if (!Member) 3473 return nullptr; 3474 3475 // Non-instance-fields can't have a bitfield. 3476 if (BitWidth) { 3477 if (Member->isInvalidDecl()) { 3478 // don't emit another diagnostic. 3479 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3480 // C++ 9.6p3: A bit-field shall not be a static member. 3481 // "static member 'A' cannot be a bit-field" 3482 Diag(Loc, diag::err_static_not_bitfield) 3483 << Name << BitWidth->getSourceRange(); 3484 } else if (isa<TypedefDecl>(Member)) { 3485 // "typedef member 'x' cannot be a bit-field" 3486 Diag(Loc, diag::err_typedef_not_bitfield) 3487 << Name << BitWidth->getSourceRange(); 3488 } else { 3489 // A function typedef ("typedef int f(); f a;"). 3490 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3491 Diag(Loc, diag::err_not_integral_type_bitfield) 3492 << Name << cast<ValueDecl>(Member)->getType() 3493 << BitWidth->getSourceRange(); 3494 } 3495 3496 BitWidth = nullptr; 3497 Member->setInvalidDecl(); 3498 } 3499 3500 NamedDecl *NonTemplateMember = Member; 3501 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3502 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3503 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3504 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3505 3506 Member->setAccess(AS); 3507 3508 // If we have declared a member function template or static data member 3509 // template, set the access of the templated declaration as well. 3510 if (NonTemplateMember != Member) 3511 NonTemplateMember->setAccess(AS); 3512 3513 // C++ [temp.deduct.guide]p3: 3514 // A deduction guide [...] for a member class template [shall be 3515 // declared] with the same access [as the template]. 3516 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3517 auto *TD = DG->getDeducedTemplate(); 3518 // Access specifiers are only meaningful if both the template and the 3519 // deduction guide are from the same scope. 3520 if (AS != TD->getAccess() && 3521 TD->getDeclContext()->getRedeclContext()->Equals( 3522 DG->getDeclContext()->getRedeclContext())) { 3523 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3524 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3525 << TD->getAccess(); 3526 const AccessSpecDecl *LastAccessSpec = nullptr; 3527 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3528 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3529 LastAccessSpec = AccessSpec; 3530 } 3531 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", 3531, __extension__ __PRETTY_FUNCTION__
))
; 3532 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3533 << AS; 3534 } 3535 } 3536 } 3537 3538 if (VS.isOverrideSpecified()) 3539 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3540 AttributeCommonInfo::AS_Keyword)); 3541 if (VS.isFinalSpecified()) 3542 Member->addAttr(FinalAttr::Create( 3543 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3544 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3545 3546 if (VS.getLastLocation().isValid()) { 3547 // Update the end location of a method that has a virt-specifiers. 3548 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3549 MD->setRangeEnd(VS.getLastLocation()); 3550 } 3551 3552 CheckOverrideControl(Member); 3553 3554 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", 3554, __extension__ __PRETTY_FUNCTION__
))
; 3555 3556 if (isInstField) { 3557 FieldDecl *FD = cast<FieldDecl>(Member); 3558 FieldCollector->Add(FD); 3559 3560 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3561 // Remember all explicit private FieldDecls that have a name, no side 3562 // effects and are not part of a dependent type declaration. 3563 if (!FD->isImplicit() && FD->getDeclName() && 3564 FD->getAccess() == AS_private && 3565 !FD->hasAttr<UnusedAttr>() && 3566 !FD->getParent()->isDependentContext() && 3567 !InitializationHasSideEffects(*FD)) 3568 UnusedPrivateFields.insert(FD); 3569 } 3570 } 3571 3572 return Member; 3573} 3574 3575namespace { 3576 class UninitializedFieldVisitor 3577 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3578 Sema &S; 3579 // List of Decls to generate a warning on. Also remove Decls that become 3580 // initialized. 3581 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3582 // List of base classes of the record. Classes are removed after their 3583 // initializers. 3584 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3585 // Vector of decls to be removed from the Decl set prior to visiting the 3586 // nodes. These Decls may have been initialized in the prior initializer. 3587 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3588 // If non-null, add a note to the warning pointing back to the constructor. 3589 const CXXConstructorDecl *Constructor; 3590 // Variables to hold state when processing an initializer list. When 3591 // InitList is true, special case initialization of FieldDecls matching 3592 // InitListFieldDecl. 3593 bool InitList; 3594 FieldDecl *InitListFieldDecl; 3595 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3596 3597 public: 3598 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3599 UninitializedFieldVisitor(Sema &S, 3600 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3601 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3602 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3603 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3604 3605 // Returns true if the use of ME is not an uninitialized use. 3606 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3607 bool CheckReferenceOnly) { 3608 llvm::SmallVector<FieldDecl*, 4> Fields; 3609 bool ReferenceField = false; 3610 while (ME) { 3611 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3612 if (!FD) 3613 return false; 3614 Fields.push_back(FD); 3615 if (FD->getType()->isReferenceType()) 3616 ReferenceField = true; 3617 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3618 } 3619 3620 // Binding a reference to an uninitialized field is not an 3621 // uninitialized use. 3622 if (CheckReferenceOnly && !ReferenceField) 3623 return true; 3624 3625 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3626 // Discard the first field since it is the field decl that is being 3627 // initialized. 3628 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) 3629 UsedFieldIndex.push_back(FD->getFieldIndex()); 3630 3631 for (auto UsedIter = UsedFieldIndex.begin(), 3632 UsedEnd = UsedFieldIndex.end(), 3633 OrigIter = InitFieldIndex.begin(), 3634 OrigEnd = InitFieldIndex.end(); 3635 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3636 if (*UsedIter < *OrigIter) 3637 return true; 3638 if (*UsedIter > *OrigIter) 3639 break; 3640 } 3641 3642 return false; 3643 } 3644 3645 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3646 bool AddressOf) { 3647 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3648 return; 3649 3650 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3651 // or union. 3652 MemberExpr *FieldME = ME; 3653 3654 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3655 3656 Expr *Base = ME; 3657 while (MemberExpr *SubME = 3658 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3659 3660 if (isa<VarDecl>(SubME->getMemberDecl())) 3661 return; 3662 3663 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3664 if (!FD->isAnonymousStructOrUnion()) 3665 FieldME = SubME; 3666 3667 if (!FieldME->getType().isPODType(S.Context)) 3668 AllPODFields = false; 3669 3670 Base = SubME->getBase(); 3671 } 3672 3673 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3674 Visit(Base); 3675 return; 3676 } 3677 3678 if (AddressOf && AllPODFields) 3679 return; 3680 3681 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3682 3683 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3684 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3685 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3686 } 3687 3688 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3689 QualType T = BaseCast->getType(); 3690 if (T->isPointerType() && 3691 BaseClasses.count(T->getPointeeType())) { 3692 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3693 << T->getPointeeType() << FoundVD; 3694 } 3695 } 3696 } 3697 3698 if (!Decls.count(FoundVD)) 3699 return; 3700 3701 const bool IsReference = FoundVD->getType()->isReferenceType(); 3702 3703 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3704 // Special checking for initializer lists. 3705 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3706 return; 3707 } 3708 } else { 3709 // Prevent double warnings on use of unbounded references. 3710 if (CheckReferenceOnly && !IsReference) 3711 return; 3712 } 3713 3714 unsigned diag = IsReference 3715 ? diag::warn_reference_field_is_uninit 3716 : diag::warn_field_is_uninit; 3717 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3718 if (Constructor) 3719 S.Diag(Constructor->getLocation(), 3720 diag::note_uninit_in_this_constructor) 3721 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3722 3723 } 3724 3725 void HandleValue(Expr *E, bool AddressOf) { 3726 E = E->IgnoreParens(); 3727 3728 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3729 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3730 AddressOf /*AddressOf*/); 3731 return; 3732 } 3733 3734 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3735 Visit(CO->getCond()); 3736 HandleValue(CO->getTrueExpr(), AddressOf); 3737 HandleValue(CO->getFalseExpr(), AddressOf); 3738 return; 3739 } 3740 3741 if (BinaryConditionalOperator *BCO = 3742 dyn_cast<BinaryConditionalOperator>(E)) { 3743 Visit(BCO->getCond()); 3744 HandleValue(BCO->getFalseExpr(), AddressOf); 3745 return; 3746 } 3747 3748 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3749 HandleValue(OVE->getSourceExpr(), AddressOf); 3750 return; 3751 } 3752 3753 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3754 switch (BO->getOpcode()) { 3755 default: 3756 break; 3757 case(BO_PtrMemD): 3758 case(BO_PtrMemI): 3759 HandleValue(BO->getLHS(), AddressOf); 3760 Visit(BO->getRHS()); 3761 return; 3762 case(BO_Comma): 3763 Visit(BO->getLHS()); 3764 HandleValue(BO->getRHS(), AddressOf); 3765 return; 3766 } 3767 } 3768 3769 Visit(E); 3770 } 3771 3772 void CheckInitListExpr(InitListExpr *ILE) { 3773 InitFieldIndex.push_back(0); 3774 for (auto Child : ILE->children()) { 3775 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3776 CheckInitListExpr(SubList); 3777 } else { 3778 Visit(Child); 3779 } 3780 ++InitFieldIndex.back(); 3781 } 3782 InitFieldIndex.pop_back(); 3783 } 3784 3785 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3786 FieldDecl *Field, const Type *BaseClass) { 3787 // Remove Decls that may have been initialized in the previous 3788 // initializer. 3789 for (ValueDecl* VD : DeclsToRemove) 3790 Decls.erase(VD); 3791 DeclsToRemove.clear(); 3792 3793 Constructor = FieldConstructor; 3794 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3795 3796 if (ILE && Field) { 3797 InitList = true; 3798 InitListFieldDecl = Field; 3799 InitFieldIndex.clear(); 3800 CheckInitListExpr(ILE); 3801 } else { 3802 InitList = false; 3803 Visit(E); 3804 } 3805 3806 if (Field) 3807 Decls.erase(Field); 3808 if (BaseClass) 3809 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3810 } 3811 3812 void VisitMemberExpr(MemberExpr *ME) { 3813 // All uses of unbounded reference fields will warn. 3814 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3815 } 3816 3817 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3818 if (E->getCastKind() == CK_LValueToRValue) { 3819 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3820 return; 3821 } 3822 3823 Inherited::VisitImplicitCastExpr(E); 3824 } 3825 3826 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3827 if (E->getConstructor()->isCopyConstructor()) { 3828 Expr *ArgExpr = E->getArg(0); 3829 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3830 if (ILE->getNumInits() == 1) 3831 ArgExpr = ILE->getInit(0); 3832 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3833 if (ICE->getCastKind() == CK_NoOp) 3834 ArgExpr = ICE->getSubExpr(); 3835 HandleValue(ArgExpr, false /*AddressOf*/); 3836 return; 3837 } 3838 Inherited::VisitCXXConstructExpr(E); 3839 } 3840 3841 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3842 Expr *Callee = E->getCallee(); 3843 if (isa<MemberExpr>(Callee)) { 3844 HandleValue(Callee, false /*AddressOf*/); 3845 for (auto Arg : E->arguments()) 3846 Visit(Arg); 3847 return; 3848 } 3849 3850 Inherited::VisitCXXMemberCallExpr(E); 3851 } 3852 3853 void VisitCallExpr(CallExpr *E) { 3854 // Treat std::move as a use. 3855 if (E->isCallToStdMove()) { 3856 HandleValue(E->getArg(0), /*AddressOf=*/false); 3857 return; 3858 } 3859 3860 Inherited::VisitCallExpr(E); 3861 } 3862 3863 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3864 Expr *Callee = E->getCallee(); 3865 3866 if (isa<UnresolvedLookupExpr>(Callee)) 3867 return Inherited::VisitCXXOperatorCallExpr(E); 3868 3869 Visit(Callee); 3870 for (auto Arg : E->arguments()) 3871 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3872 } 3873 3874 void VisitBinaryOperator(BinaryOperator *E) { 3875 // If a field assignment is detected, remove the field from the 3876 // uninitiailized field set. 3877 if (E->getOpcode() == BO_Assign) 3878 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3879 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3880 if (!FD->getType()->isReferenceType()) 3881 DeclsToRemove.push_back(FD); 3882 3883 if (E->isCompoundAssignmentOp()) { 3884 HandleValue(E->getLHS(), false /*AddressOf*/); 3885 Visit(E->getRHS()); 3886 return; 3887 } 3888 3889 Inherited::VisitBinaryOperator(E); 3890 } 3891 3892 void VisitUnaryOperator(UnaryOperator *E) { 3893 if (E->isIncrementDecrementOp()) { 3894 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3895 return; 3896 } 3897 if (E->getOpcode() == UO_AddrOf) { 3898 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3899 HandleValue(ME->getBase(), true /*AddressOf*/); 3900 return; 3901 } 3902 } 3903 3904 Inherited::VisitUnaryOperator(E); 3905 } 3906 }; 3907 3908 // Diagnose value-uses of fields to initialize themselves, e.g. 3909 // foo(foo) 3910 // where foo is not also a parameter to the constructor. 3911 // Also diagnose across field uninitialized use such as 3912 // x(y), y(x) 3913 // TODO: implement -Wuninitialized and fold this into that framework. 3914 static void DiagnoseUninitializedFields( 3915 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3916 3917 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3918 Constructor->getLocation())) { 3919 return; 3920 } 3921 3922 if (Constructor->isInvalidDecl()) 3923 return; 3924 3925 const CXXRecordDecl *RD = Constructor->getParent(); 3926 3927 if (RD->isDependentContext()) 3928 return; 3929 3930 // Holds fields that are uninitialized. 3931 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3932 3933 // At the beginning, all fields are uninitialized. 3934 for (auto *I : RD->decls()) { 3935 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3936 UninitializedFields.insert(FD); 3937 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3938 UninitializedFields.insert(IFD->getAnonField()); 3939 } 3940 } 3941 3942 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3943 for (auto I : RD->bases()) 3944 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3945 3946 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3947 return; 3948 3949 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3950 UninitializedFields, 3951 UninitializedBaseClasses); 3952 3953 for (const auto *FieldInit : Constructor->inits()) { 3954 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3955 break; 3956 3957 Expr *InitExpr = FieldInit->getInit(); 3958 if (!InitExpr) 3959 continue; 3960 3961 if (CXXDefaultInitExpr *Default = 3962 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3963 InitExpr = Default->getExpr(); 3964 if (!InitExpr) 3965 continue; 3966 // In class initializers will point to the constructor. 3967 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3968 FieldInit->getAnyMember(), 3969 FieldInit->getBaseClass()); 3970 } else { 3971 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3972 FieldInit->getAnyMember(), 3973 FieldInit->getBaseClass()); 3974 } 3975 } 3976 } 3977} // namespace 3978 3979/// Enter a new C++ default initializer scope. After calling this, the 3980/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3981/// parsing or instantiating the initializer failed. 3982void Sema::ActOnStartCXXInClassMemberInitializer() { 3983 // Create a synthetic function scope to represent the call to the constructor 3984 // that notionally surrounds a use of this initializer. 3985 PushFunctionScope(); 3986} 3987 3988void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3989 if (!D.isFunctionDeclarator()) 3990 return; 3991 auto &FTI = D.getFunctionTypeInfo(); 3992 if (!FTI.Params) 3993 return; 3994 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3995 FTI.NumParams)) { 3996 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3997 if (ParamDecl->getDeclName()) 3998 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3999 } 4000} 4001 4002ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 4003 return ActOnRequiresClause(ConstraintExpr); 4004} 4005 4006ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 4007 if (ConstraintExpr.isInvalid()) 4008 return ExprError(); 4009 4010 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 4011 if (ConstraintExpr.isInvalid()) 4012 return ExprError(); 4013 4014 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 4015 UPPC_RequiresClause)) 4016 return ExprError(); 4017 4018 return ConstraintExpr; 4019} 4020 4021/// This is invoked after parsing an in-class initializer for a 4022/// non-static C++ class member, and after instantiating an in-class initializer 4023/// in a class template. Such actions are deferred until the class is complete. 4024void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 4025 SourceLocation InitLoc, 4026 Expr *InitExpr) { 4027 // Pop the notional constructor scope we created earlier. 4028 PopFunctionScopeInfo(nullptr, D); 4029 4030 FieldDecl *FD = dyn_cast<FieldDecl>(D); 4031 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", 4032, __extension__ __PRETTY_FUNCTION__
))
4032 "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", 4032, __extension__ __PRETTY_FUNCTION__
))
; 4033 4034 if (!InitExpr) { 4035 D->setInvalidDecl(); 4036 if (FD) 4037 FD->removeInClassInitializer(); 4038 return; 4039 } 4040 4041 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4042 FD->setInvalidDecl(); 4043 FD->removeInClassInitializer(); 4044 return; 4045 } 4046 4047 ExprResult Init = InitExpr; 4048 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4049 InitializedEntity Entity = 4050 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4051 InitializationKind Kind = 4052 FD->getInClassInitStyle() == ICIS_ListInit 4053 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4054 InitExpr->getBeginLoc(), 4055 InitExpr->getEndLoc()) 4056 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4057 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4058 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4059 if (Init.isInvalid()) { 4060 FD->setInvalidDecl(); 4061 return; 4062 } 4063 } 4064 4065 // C++11 [class.base.init]p7: 4066 // The initialization of each base and member constitutes a 4067 // full-expression. 4068 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4069 if (Init.isInvalid()) { 4070 FD->setInvalidDecl(); 4071 return; 4072 } 4073 4074 InitExpr = Init.get(); 4075 4076 FD->setInClassInitializer(InitExpr); 4077} 4078 4079/// Find the direct and/or virtual base specifiers that 4080/// correspond to the given base type, for use in base initialization 4081/// within a constructor. 4082static bool FindBaseInitializer(Sema &SemaRef, 4083 CXXRecordDecl *ClassDecl, 4084 QualType BaseType, 4085 const CXXBaseSpecifier *&DirectBaseSpec, 4086 const CXXBaseSpecifier *&VirtualBaseSpec) { 4087 // First, check for a direct base class. 4088 DirectBaseSpec = nullptr; 4089 for (const auto &Base : ClassDecl->bases()) { 4090 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4091 // We found a direct base of this type. That's what we're 4092 // initializing. 4093 DirectBaseSpec = &Base; 4094 break; 4095 } 4096 } 4097 4098 // Check for a virtual base class. 4099 // FIXME: We might be able to short-circuit this if we know in advance that 4100 // there are no virtual bases. 4101 VirtualBaseSpec = nullptr; 4102 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4103 // We haven't found a base yet; search the class hierarchy for a 4104 // virtual base class. 4105 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4106 /*DetectVirtual=*/false); 4107 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4108 SemaRef.Context.getTypeDeclType(ClassDecl), 4109 BaseType, Paths)) { 4110 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4111 Path != Paths.end(); ++Path) { 4112 if (Path->back().Base->isVirtual()) { 4113 VirtualBaseSpec = Path->back().Base; 4114 break; 4115 } 4116 } 4117 } 4118 } 4119 4120 return DirectBaseSpec || VirtualBaseSpec; 4121} 4122 4123/// Handle a C++ member initializer using braced-init-list syntax. 4124MemInitResult 4125Sema::ActOnMemInitializer(Decl *ConstructorD, 4126 Scope *S, 4127 CXXScopeSpec &SS, 4128 IdentifierInfo *MemberOrBase, 4129 ParsedType TemplateTypeTy, 4130 const DeclSpec &DS, 4131 SourceLocation IdLoc, 4132 Expr *InitList, 4133 SourceLocation EllipsisLoc) { 4134 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4135 DS, IdLoc, InitList, 4136 EllipsisLoc); 4137} 4138 4139/// Handle a C++ member initializer using parentheses syntax. 4140MemInitResult 4141Sema::ActOnMemInitializer(Decl *ConstructorD, 4142 Scope *S, 4143 CXXScopeSpec &SS, 4144 IdentifierInfo *MemberOrBase, 4145 ParsedType TemplateTypeTy, 4146 const DeclSpec &DS, 4147 SourceLocation IdLoc, 4148 SourceLocation LParenLoc, 4149 ArrayRef<Expr *> Args, 4150 SourceLocation RParenLoc, 4151 SourceLocation EllipsisLoc) { 4152 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4153 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4154 DS, IdLoc, List, EllipsisLoc); 4155} 4156 4157namespace { 4158 4159// Callback to only accept typo corrections that can be a valid C++ member 4160// initializer: either a non-static field member or a base class. 4161class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4162public: 4163 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4164 : ClassDecl(ClassDecl) {} 4165 4166 bool ValidateCandidate(const TypoCorrection &candidate) override { 4167 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4168 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4169 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4170 return isa<TypeDecl>(ND); 4171 } 4172 return false; 4173 } 4174 4175 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4176 return std::make_unique<MemInitializerValidatorCCC>(*this); 4177 } 4178 4179private: 4180 CXXRecordDecl *ClassDecl; 4181}; 4182 4183} 4184 4185ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4186 CXXScopeSpec &SS, 4187 ParsedType TemplateTypeTy, 4188 IdentifierInfo *MemberOrBase) { 4189 if (SS.getScopeRep() || TemplateTypeTy) 4190 return nullptr; 4191 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4192 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4193 return cast<ValueDecl>(D); 4194 return nullptr; 4195} 4196 4197/// Handle a C++ member initializer. 4198MemInitResult 4199Sema::BuildMemInitializer(Decl *ConstructorD, 4200 Scope *S, 4201 CXXScopeSpec &SS, 4202 IdentifierInfo *MemberOrBase, 4203 ParsedType TemplateTypeTy, 4204 const DeclSpec &DS, 4205 SourceLocation IdLoc, 4206 Expr *Init, 4207 SourceLocation EllipsisLoc) { 4208 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4209 /*RecoverUncorrectedTypos=*/true); 4210 if (!Res.isUsable()) 4211 return true; 4212 Init = Res.get(); 4213 4214 if (!ConstructorD) 4215 return true; 4216 4217 AdjustDeclIfTemplate(ConstructorD); 4218 4219 CXXConstructorDecl *Constructor 4220 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4221 if (!Constructor) { 4222 // The user wrote a constructor initializer on a function that is 4223 // not a C++ constructor. Ignore the error for now, because we may 4224 // have more member initializers coming; we'll diagnose it just 4225 // once in ActOnMemInitializers. 4226 return true; 4227 } 4228 4229 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4230 4231 // C++ [class.base.init]p2: 4232 // Names in a mem-initializer-id are looked up in the scope of the 4233 // constructor's class and, if not found in that scope, are looked 4234 // up in the scope containing the constructor's definition. 4235 // [Note: if the constructor's class contains a member with the 4236 // same name as a direct or virtual base class of the class, a 4237 // mem-initializer-id naming the member or base class and composed 4238 // of a single identifier refers to the class member. A 4239 // mem-initializer-id for the hidden base class may be specified 4240 // using a qualified name. ] 4241 4242 // Look for a member, first. 4243 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4244 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4245 if (EllipsisLoc.isValid()) 4246 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4247 << MemberOrBase 4248 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4249 4250 return BuildMemberInitializer(Member, Init, IdLoc); 4251 } 4252 // It didn't name a member, so see if it names a class. 4253 QualType BaseType; 4254 TypeSourceInfo *TInfo = nullptr; 4255 4256 if (TemplateTypeTy) { 4257 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4258 if (BaseType.isNull()) 4259 return true; 4260 } else if (DS.getTypeSpecType() == TST_decltype) { 4261 BaseType = BuildDecltypeType(DS.getRepAsExpr()); 4262 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4263 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4264 return true; 4265 } else { 4266 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4267 LookupParsedName(R, S, &SS); 4268 4269 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4270 if (!TyD) { 4271 if (R.isAmbiguous()) return true; 4272 4273 // We don't want access-control diagnostics here. 4274 R.suppressDiagnostics(); 4275 4276 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4277 bool NotUnknownSpecialization = false; 4278 DeclContext *DC = computeDeclContext(SS, false); 4279 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4280 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4281 4282 if (!NotUnknownSpecialization) { 4283 // When the scope specifier can refer to a member of an unknown 4284 // specialization, we take it as a type name. 4285 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4286 SS.getWithLocInContext(Context), 4287 *MemberOrBase, IdLoc); 4288 if (BaseType.isNull()) 4289 return true; 4290 4291 TInfo = Context.CreateTypeSourceInfo(BaseType); 4292 DependentNameTypeLoc TL = 4293 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4294 if (!TL.isNull()) { 4295 TL.setNameLoc(IdLoc); 4296 TL.setElaboratedKeywordLoc(SourceLocation()); 4297 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4298 } 4299 4300 R.clear(); 4301 R.setLookupName(MemberOrBase); 4302 } 4303 } 4304 4305 // If no results were found, try to correct typos. 4306 TypoCorrection Corr; 4307 MemInitializerValidatorCCC CCC(ClassDecl); 4308 if (R.empty() && BaseType.isNull() && 4309 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4310 CCC, CTK_ErrorRecovery, ClassDecl))) { 4311 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4312 // We have found a non-static data member with a similar 4313 // name to what was typed; complain and initialize that 4314 // member. 4315 diagnoseTypo(Corr, 4316 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4317 << MemberOrBase << true); 4318 return BuildMemberInitializer(Member, Init, IdLoc); 4319 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4320 const CXXBaseSpecifier *DirectBaseSpec; 4321 const CXXBaseSpecifier *VirtualBaseSpec; 4322 if (FindBaseInitializer(*this, ClassDecl, 4323 Context.getTypeDeclType(Type), 4324 DirectBaseSpec, VirtualBaseSpec)) { 4325 // We have found a direct or virtual base class with a 4326 // similar name to what was typed; complain and initialize 4327 // that base class. 4328 diagnoseTypo(Corr, 4329 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4330 << MemberOrBase << false, 4331 PDiag() /*Suppress note, we provide our own.*/); 4332 4333 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4334 : VirtualBaseSpec; 4335 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4336 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4337 4338 TyD = Type; 4339 } 4340 } 4341 } 4342 4343 if (!TyD && BaseType.isNull()) { 4344 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4345 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4346 return true; 4347 } 4348 } 4349 4350 if (BaseType.isNull()) { 4351 BaseType = Context.getTypeDeclType(TyD); 4352 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4353 if (SS.isSet()) { 4354 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4355 BaseType); 4356 TInfo = Context.CreateTypeSourceInfo(BaseType); 4357 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4358 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4359 TL.setElaboratedKeywordLoc(SourceLocation()); 4360 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4361 } 4362 } 4363 } 4364 4365 if (!TInfo) 4366 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4367 4368 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4369} 4370 4371MemInitResult 4372Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4373 SourceLocation IdLoc) { 4374 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4375 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4376 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", 4377, __extension__ __PRETTY_FUNCTION__
))
4377 "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", 4377, __extension__ __PRETTY_FUNCTION__
))
; 4378 4379 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4380 return true; 4381 4382 if (Member->isInvalidDecl()) 4383 return true; 4384 4385 MultiExprArg Args; 4386 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4387 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4388 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4389 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4390 } else { 4391 // Template instantiation doesn't reconstruct ParenListExprs for us. 4392 Args = Init; 4393 } 4394 4395 SourceRange InitRange = Init->getSourceRange(); 4396 4397 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4398 // Can't check initialization for a member of dependent type or when 4399 // any of the arguments are type-dependent expressions. 4400 DiscardCleanupsInEvaluationContext(); 4401 } else { 4402 bool InitList = false; 4403 if (isa<InitListExpr>(Init)) { 4404 InitList = true; 4405 Args = Init; 4406 } 4407 4408 // Initialize the member. 4409 InitializedEntity MemberEntity = 4410 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4411 : InitializedEntity::InitializeMember(IndirectMember, 4412 nullptr); 4413 InitializationKind Kind = 4414 InitList ? InitializationKind::CreateDirectList( 4415 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4416 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4417 InitRange.getEnd()); 4418 4419 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4420 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4421 nullptr); 4422 if (!MemberInit.isInvalid()) { 4423 // C++11 [class.base.init]p7: 4424 // The initialization of each base and member constitutes a 4425 // full-expression. 4426 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4427 /*DiscardedValue*/ false); 4428 } 4429 4430 if (MemberInit.isInvalid()) { 4431 // Args were sensible expressions but we couldn't initialize the member 4432 // from them. Preserve them in a RecoveryExpr instead. 4433 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4434 Member->getType()) 4435 .get(); 4436 if (!Init) 4437 return true; 4438 } else { 4439 Init = MemberInit.get(); 4440 } 4441 } 4442 4443 if (DirectMember) { 4444 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4445 InitRange.getBegin(), Init, 4446 InitRange.getEnd()); 4447 } else { 4448 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4449 InitRange.getBegin(), Init, 4450 InitRange.getEnd()); 4451 } 4452} 4453 4454MemInitResult 4455Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4456 CXXRecordDecl *ClassDecl) { 4457 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4458 if (!LangOpts.CPlusPlus11) 4459 return Diag(NameLoc, diag::err_delegating_ctor) 4460 << TInfo->getTypeLoc().getLocalSourceRange(); 4461 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4462 4463 bool InitList = true; 4464 MultiExprArg Args = Init; 4465 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4466 InitList = false; 4467 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4468 } 4469 4470 SourceRange InitRange = Init->getSourceRange(); 4471 // Initialize the object. 4472 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4473 QualType(ClassDecl->getTypeForDecl(), 0)); 4474 InitializationKind Kind = 4475 InitList ? InitializationKind::CreateDirectList( 4476 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4477 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4478 InitRange.getEnd()); 4479 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4480 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4481 Args, nullptr); 4482 if (!DelegationInit.isInvalid()) { 4483 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", 4485, __extension__ __PRETTY_FUNCTION__
))
4484 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", 4485, __extension__ __PRETTY_FUNCTION__
))
4485 "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", 4485, __extension__ __PRETTY_FUNCTION__
))
; 4486 4487 // C++11 [class.base.init]p7: 4488 // The initialization of each base and member constitutes a 4489 // full-expression. 4490 DelegationInit = ActOnFinishFullExpr( 4491 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4492 } 4493 4494 if (DelegationInit.isInvalid()) { 4495 DelegationInit = 4496 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4497 QualType(ClassDecl->getTypeForDecl(), 0)); 4498 if (DelegationInit.isInvalid()) 4499 return true; 4500 } else { 4501 // If we are in a dependent context, template instantiation will 4502 // perform this type-checking again. Just save the arguments that we 4503 // received in a ParenListExpr. 4504 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4505 // of the information that we have about the base 4506 // initializer. However, deconstructing the ASTs is a dicey process, 4507 // and this approach is far more likely to get the corner cases right. 4508 if (CurContext->isDependentContext()) 4509 DelegationInit = Init; 4510 } 4511 4512 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4513 DelegationInit.getAs<Expr>(), 4514 InitRange.getEnd()); 4515} 4516 4517MemInitResult 4518Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4519 Expr *Init, CXXRecordDecl *ClassDecl, 4520 SourceLocation EllipsisLoc) { 4521 SourceLocation BaseLoc 4522 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4523 4524 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4525 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4526 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4527 4528 // C++ [class.base.init]p2: 4529 // [...] Unless the mem-initializer-id names a nonstatic data 4530 // member of the constructor's class or a direct or virtual base 4531 // of that class, the mem-initializer is ill-formed. A 4532 // mem-initializer-list can initialize a base class using any 4533 // name that denotes that base class type. 4534 4535 // We can store the initializers in "as-written" form and delay analysis until 4536 // instantiation if the constructor is dependent. But not for dependent 4537 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4538 bool Dependent = CurContext->isDependentContext() && 4539 (BaseType->isDependentType() || Init->isTypeDependent()); 4540 4541 SourceRange InitRange = Init->getSourceRange(); 4542 if (EllipsisLoc.isValid()) { 4543 // This is a pack expansion. 4544 if (!BaseType->containsUnexpandedParameterPack()) { 4545 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4546 << SourceRange(BaseLoc, InitRange.getEnd()); 4547 4548 EllipsisLoc = SourceLocation(); 4549 } 4550 } else { 4551 // Check for any unexpanded parameter packs. 4552 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4553 return true; 4554 4555 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4556 return true; 4557 } 4558 4559 // Check for direct and virtual base classes. 4560 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4561 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4562 if (!Dependent) { 4563 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4564 BaseType)) 4565 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4566 4567 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4568 VirtualBaseSpec); 4569 4570 // C++ [base.class.init]p2: 4571 // Unless the mem-initializer-id names a nonstatic data member of the 4572 // constructor's class or a direct or virtual base of that class, the 4573 // mem-initializer is ill-formed. 4574 if (!DirectBaseSpec && !VirtualBaseSpec) { 4575 // If the class has any dependent bases, then it's possible that 4576 // one of those types will resolve to the same type as 4577 // BaseType. Therefore, just treat this as a dependent base 4578 // class initialization. FIXME: Should we try to check the 4579 // initialization anyway? It seems odd. 4580 if (ClassDecl->hasAnyDependentBases()) 4581 Dependent = true; 4582 else 4583 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4584 << BaseType << Context.getTypeDeclType(ClassDecl) 4585 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4586 } 4587 } 4588 4589 if (Dependent) { 4590 DiscardCleanupsInEvaluationContext(); 4591 4592 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4593 /*IsVirtual=*/false, 4594 InitRange.getBegin(), Init, 4595 InitRange.getEnd(), EllipsisLoc); 4596 } 4597 4598 // C++ [base.class.init]p2: 4599 // If a mem-initializer-id is ambiguous because it designates both 4600 // a direct non-virtual base class and an inherited virtual base 4601 // class, the mem-initializer is ill-formed. 4602 if (DirectBaseSpec && VirtualBaseSpec) 4603 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4604 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4605 4606 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4607 if (!BaseSpec) 4608 BaseSpec = VirtualBaseSpec; 4609 4610 // Initialize the base. 4611 bool InitList = true; 4612 MultiExprArg Args = Init; 4613 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4614 InitList = false; 4615 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4616 } 4617 4618 InitializedEntity BaseEntity = 4619 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4620 InitializationKind Kind = 4621 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4622 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4623 InitRange.getEnd()); 4624 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4625 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4626 if (!BaseInit.isInvalid()) { 4627 // C++11 [class.base.init]p7: 4628 // The initialization of each base and member constitutes a 4629 // full-expression. 4630 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4631 /*DiscardedValue*/ false); 4632 } 4633 4634 if (BaseInit.isInvalid()) { 4635 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4636 Args, BaseType); 4637 if (BaseInit.isInvalid()) 4638 return true; 4639 } else { 4640 // If we are in a dependent context, template instantiation will 4641 // perform this type-checking again. Just save the arguments that we 4642 // received in a ParenListExpr. 4643 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4644 // of the information that we have about the base 4645 // initializer. However, deconstructing the ASTs is a dicey process, 4646 // and this approach is far more likely to get the corner cases right. 4647 if (CurContext->isDependentContext()) 4648 BaseInit = Init; 4649 } 4650 4651 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4652 BaseSpec->isVirtual(), 4653 InitRange.getBegin(), 4654 BaseInit.getAs<Expr>(), 4655 InitRange.getEnd(), EllipsisLoc); 4656} 4657 4658// Create a static_cast\<T&&>(expr). 4659static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4660 if (T.isNull()) T = E->getType(); 4661 QualType TargetType = SemaRef.BuildReferenceType( 4662 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4663 SourceLocation ExprLoc = E->getBeginLoc(); 4664 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4665 TargetType, ExprLoc); 4666 4667 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4668 SourceRange(ExprLoc, ExprLoc), 4669 E->getSourceRange()).get(); 4670} 4671 4672/// ImplicitInitializerKind - How an implicit base or member initializer should 4673/// initialize its base or member. 4674enum ImplicitInitializerKind { 4675 IIK_Default, 4676 IIK_Copy, 4677 IIK_Move, 4678 IIK_Inherit 4679}; 4680 4681static bool 4682BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4683 ImplicitInitializerKind ImplicitInitKind, 4684 CXXBaseSpecifier *BaseSpec, 4685 bool IsInheritedVirtualBase, 4686 CXXCtorInitializer *&CXXBaseInit) { 4687 InitializedEntity InitEntity 4688 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4689 IsInheritedVirtualBase); 4690 4691 ExprResult BaseInit; 4692 4693 switch (ImplicitInitKind) { 4694 case IIK_Inherit: 4695 case IIK_Default: { 4696 InitializationKind InitKind 4697 = InitializationKind::CreateDefault(Constructor->getLocation()); 4698 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4699 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4700 break; 4701 } 4702 4703 case IIK_Move: 4704 case IIK_Copy: { 4705 bool Moving = ImplicitInitKind == IIK_Move; 4706 ParmVarDecl *Param = Constructor->getParamDecl(0); 4707 QualType ParamType = Param->getType().getNonReferenceType(); 4708 4709 Expr *CopyCtorArg = 4710 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4711 SourceLocation(), Param, false, 4712 Constructor->getLocation(), ParamType, 4713 VK_LValue, nullptr); 4714 4715 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4716 4717 // Cast to the base class to avoid ambiguities. 4718 QualType ArgTy = 4719 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4720 ParamType.getQualifiers()); 4721 4722 if (Moving) { 4723 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4724 } 4725 4726 CXXCastPath BasePath; 4727 BasePath.push_back(BaseSpec); 4728 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4729 CK_UncheckedDerivedToBase, 4730 Moving ? VK_XValue : VK_LValue, 4731 &BasePath).get(); 4732 4733 InitializationKind InitKind 4734 = InitializationKind::CreateDirect(Constructor->getLocation(), 4735 SourceLocation(), SourceLocation()); 4736 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4737 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4738 break; 4739 } 4740 } 4741 4742 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4743 if (BaseInit.isInvalid()) 4744 return true; 4745 4746 CXXBaseInit = 4747 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4748 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4749 SourceLocation()), 4750 BaseSpec->isVirtual(), 4751 SourceLocation(), 4752 BaseInit.getAs<Expr>(), 4753 SourceLocation(), 4754 SourceLocation()); 4755 4756 return false; 4757} 4758 4759static bool RefersToRValueRef(Expr *MemRef) { 4760 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4761 return Referenced->getType()->isRValueReferenceType(); 4762} 4763 4764static bool 4765BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4766 ImplicitInitializerKind ImplicitInitKind, 4767 FieldDecl *Field, IndirectFieldDecl *Indirect, 4768 CXXCtorInitializer *&CXXMemberInit) { 4769 if (Field->isInvalidDecl()) 4770 return true; 4771 4772 SourceLocation Loc = Constructor->getLocation(); 4773 4774 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4775 bool Moving = ImplicitInitKind == IIK_Move; 4776 ParmVarDecl *Param = Constructor->getParamDecl(0); 4777 QualType ParamType = Param->getType().getNonReferenceType(); 4778 4779 // Suppress copying zero-width bitfields. 4780 if (Field->isZeroLengthBitField(SemaRef.Context)) 4781 return false; 4782 4783 Expr *MemberExprBase = 4784 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4785 SourceLocation(), Param, false, 4786 Loc, ParamType, VK_LValue, nullptr); 4787 4788 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4789 4790 if (Moving) { 4791 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4792 } 4793 4794 // Build a reference to this field within the parameter. 4795 CXXScopeSpec SS; 4796 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4797 Sema::LookupMemberName); 4798 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4799 : cast<ValueDecl>(Field), AS_public); 4800 MemberLookup.resolveKind(); 4801 ExprResult CtorArg 4802 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4803 ParamType, Loc, 4804 /*IsArrow=*/false, 4805 SS, 4806 /*TemplateKWLoc=*/SourceLocation(), 4807 /*FirstQualifierInScope=*/nullptr, 4808 MemberLookup, 4809 /*TemplateArgs=*/nullptr, 4810 /*S*/nullptr); 4811 if (CtorArg.isInvalid()) 4812 return true; 4813 4814 // C++11 [class.copy]p15: 4815 // - if a member m has rvalue reference type T&&, it is direct-initialized 4816 // with static_cast<T&&>(x.m); 4817 if (RefersToRValueRef(CtorArg.get())) { 4818 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4819 } 4820 4821 InitializedEntity Entity = 4822 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4823 /*Implicit*/ true) 4824 : InitializedEntity::InitializeMember(Field, nullptr, 4825 /*Implicit*/ true); 4826 4827 // Direct-initialize to use the copy constructor. 4828 InitializationKind InitKind = 4829 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4830 4831 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4832 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4833 ExprResult MemberInit = 4834 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4835 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4836 if (MemberInit.isInvalid()) 4837 return true; 4838 4839 if (Indirect) 4840 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4841 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4842 else 4843 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4844 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4845 return false; 4846 } 4847 4848 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", 4849, __extension__ __PRETTY_FUNCTION__
))
4849 "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", 4849, __extension__ __PRETTY_FUNCTION__
))
; 4850 4851 QualType FieldBaseElementType = 4852 SemaRef.Context.getBaseElementType(Field->getType()); 4853 4854 if (FieldBaseElementType->isRecordType()) { 4855 InitializedEntity InitEntity = 4856 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4857 /*Implicit*/ true) 4858 : InitializedEntity::InitializeMember(Field, nullptr, 4859 /*Implicit*/ true); 4860 InitializationKind InitKind = 4861 InitializationKind::CreateDefault(Loc); 4862 4863 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4864 ExprResult MemberInit = 4865 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4866 4867 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4868 if (MemberInit.isInvalid()) 4869 return true; 4870 4871 if (Indirect) 4872 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4873 Indirect, Loc, 4874 Loc, 4875 MemberInit.get(), 4876 Loc); 4877 else 4878 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4879 Field, Loc, Loc, 4880 MemberInit.get(), 4881 Loc); 4882 return false; 4883 } 4884 4885 if (!Field->getParent()->isUnion()) { 4886 if (FieldBaseElementType->isReferenceType()) { 4887 SemaRef.Diag(Constructor->getLocation(), 4888 diag::err_uninitialized_member_in_ctor) 4889 << (int)Constructor->isImplicit() 4890 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4891 << 0 << Field->getDeclName(); 4892 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4893 return true; 4894 } 4895 4896 if (FieldBaseElementType.isConstQualified()) { 4897 SemaRef.Diag(Constructor->getLocation(), 4898 diag::err_uninitialized_member_in_ctor) 4899 << (int)Constructor->isImplicit() 4900 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4901 << 1 << Field->getDeclName(); 4902 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4903 return true; 4904 } 4905 } 4906 4907 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4908 // ARC and Weak: 4909 // Default-initialize Objective-C pointers to NULL. 4910 CXXMemberInit 4911 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4912 Loc, Loc, 4913 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4914 Loc); 4915 return false; 4916 } 4917 4918 // Nothing to initialize. 4919 CXXMemberInit = nullptr; 4920 return false; 4921} 4922 4923namespace { 4924struct BaseAndFieldInfo { 4925 Sema &S; 4926 CXXConstructorDecl *Ctor; 4927 bool AnyErrorsInInits; 4928 ImplicitInitializerKind IIK; 4929 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4930 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4931 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4932 4933 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4934 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4935 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4936 if (Ctor->getInheritedConstructor()) 4937 IIK = IIK_Inherit; 4938 else if (Generated && Ctor->isCopyConstructor()) 4939 IIK = IIK_Copy; 4940 else if (Generated && Ctor->isMoveConstructor()) 4941 IIK = IIK_Move; 4942 else 4943 IIK = IIK_Default; 4944 } 4945 4946 bool isImplicitCopyOrMove() const { 4947 switch (IIK) { 4948 case IIK_Copy: 4949 case IIK_Move: 4950 return true; 4951 4952 case IIK_Default: 4953 case IIK_Inherit: 4954 return false; 4955 } 4956 4957 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 4957)
; 4958 } 4959 4960 bool addFieldInitializer(CXXCtorInitializer *Init) { 4961 AllToInit.push_back(Init); 4962 4963 // Check whether this initializer makes the field "used". 4964 if (Init->getInit()->HasSideEffects(S.Context)) 4965 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4966 4967 return false; 4968 } 4969 4970 bool isInactiveUnionMember(FieldDecl *Field) { 4971 RecordDecl *Record = Field->getParent(); 4972 if (!Record->isUnion()) 4973 return false; 4974 4975 if (FieldDecl *Active = 4976 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4977 return Active != Field->getCanonicalDecl(); 4978 4979 // In an implicit copy or move constructor, ignore any in-class initializer. 4980 if (isImplicitCopyOrMove()) 4981 return true; 4982 4983 // If there's no explicit initialization, the field is active only if it 4984 // has an in-class initializer... 4985 if (Field->hasInClassInitializer()) 4986 return false; 4987 // ... or it's an anonymous struct or union whose class has an in-class 4988 // initializer. 4989 if (!Field->isAnonymousStructOrUnion()) 4990 return true; 4991 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4992 return !FieldRD->hasInClassInitializer(); 4993 } 4994 4995 /// Determine whether the given field is, or is within, a union member 4996 /// that is inactive (because there was an initializer given for a different 4997 /// member of the union, or because the union was not initialized at all). 4998 bool isWithinInactiveUnionMember(FieldDecl *Field, 4999 IndirectFieldDecl *Indirect) { 5000 if (!Indirect) 5001 return isInactiveUnionMember(Field); 5002 5003 for (auto *C : Indirect->chain()) { 5004 FieldDecl *Field = dyn_cast<FieldDecl>(C); 5005 if (Field && isInactiveUnionMember(Field)) 5006 return true; 5007 } 5008 return false; 5009 } 5010}; 5011} 5012 5013/// Determine whether the given type is an incomplete or zero-lenfgth 5014/// array type. 5015static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 5016 if (T->isIncompleteArrayType()) 5017 return true; 5018 5019 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 5020 if (!ArrayT->getSize()) 5021 return true; 5022 5023 T = ArrayT->getElementType(); 5024 } 5025 5026 return false; 5027} 5028 5029static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 5030 FieldDecl *Field, 5031 IndirectFieldDecl *Indirect = nullptr) { 5032 if (Field->isInvalidDecl()) 5033 return false; 5034 5035 // Overwhelmingly common case: we have a direct initializer for this field. 5036 if (CXXCtorInitializer *Init = 5037 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 5038 return Info.addFieldInitializer(Init); 5039 5040 // C++11 [class.base.init]p8: 5041 // if the entity is a non-static data member that has a 5042 // brace-or-equal-initializer and either 5043 // -- the constructor's class is a union and no other variant member of that 5044 // union is designated by a mem-initializer-id or 5045 // -- the constructor's class is not a union, and, if the entity is a member 5046 // of an anonymous union, no other member of that union is designated by 5047 // a mem-initializer-id, 5048 // the entity is initialized as specified in [dcl.init]. 5049 // 5050 // We also apply the same rules to handle anonymous structs within anonymous 5051 // unions. 5052 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5053 return false; 5054 5055 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5056 ExprResult DIE = 5057 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5058 if (DIE.isInvalid()) 5059 return true; 5060 5061 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5062 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5063 5064 CXXCtorInitializer *Init; 5065 if (Indirect) 5066 Init = new (SemaRef.Context) 5067 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5068 SourceLocation(), DIE.get(), SourceLocation()); 5069 else 5070 Init = new (SemaRef.Context) 5071 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5072 SourceLocation(), DIE.get(), SourceLocation()); 5073 return Info.addFieldInitializer(Init); 5074 } 5075 5076 // Don't initialize incomplete or zero-length arrays. 5077 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5078 return false; 5079 5080 // Don't try to build an implicit initializer if there were semantic 5081 // errors in any of the initializers (and therefore we might be 5082 // missing some that the user actually wrote). 5083 if (Info.AnyErrorsInInits) 5084 return false; 5085 5086 CXXCtorInitializer *Init = nullptr; 5087 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5088 Indirect, Init)) 5089 return true; 5090 5091 if (!Init) 5092 return false; 5093 5094 return Info.addFieldInitializer(Init); 5095} 5096 5097bool 5098Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5099 CXXCtorInitializer *Initializer) { 5100 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5100, __extension__ __PRETTY_FUNCTION__
))
; 5101 Constructor->setNumCtorInitializers(1); 5102 CXXCtorInitializer **initializer = 5103 new (Context) CXXCtorInitializer*[1]; 5104 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5105 Constructor->setCtorInitializers(initializer); 5106 5107 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5108 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5109 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5110 } 5111 5112 DelegatingCtorDecls.push_back(Constructor); 5113 5114 DiagnoseUninitializedFields(*this, Constructor); 5115 5116 return false; 5117} 5118 5119bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5120 ArrayRef<CXXCtorInitializer *> Initializers) { 5121 if (Constructor->isDependentContext()) { 5122 // Just store the initializers as written, they will be checked during 5123 // instantiation. 5124 if (!Initializers.empty()) { 5125 Constructor->setNumCtorInitializers(Initializers.size()); 5126 CXXCtorInitializer **baseOrMemberInitializers = 5127 new (Context) CXXCtorInitializer*[Initializers.size()]; 5128 memcpy(baseOrMemberInitializers, Initializers.data(), 5129 Initializers.size() * sizeof(CXXCtorInitializer*)); 5130 Constructor->setCtorInitializers(baseOrMemberInitializers); 5131 } 5132 5133 // Let template instantiation know whether we had errors. 5134 if (AnyErrors) 5135 Constructor->setInvalidDecl(); 5136 5137 return false; 5138 } 5139 5140 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5141 5142 // We need to build the initializer AST according to order of construction 5143 // and not what user specified in the Initializers list. 5144 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5145 if (!ClassDecl) 5146 return true; 5147 5148 bool HadError = false; 5149 5150 for (unsigned i = 0; i < Initializers.size(); i++) { 5151 CXXCtorInitializer *Member = Initializers[i]; 5152 5153 if (Member->isBaseInitializer()) 5154 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5155 else { 5156 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5157 5158 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5159 for (auto *C : F->chain()) { 5160 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5161 if (FD && FD->getParent()->isUnion()) 5162 Info.ActiveUnionMember.insert(std::make_pair( 5163 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5164 } 5165 } else if (FieldDecl *FD = Member->getMember()) { 5166 if (FD->getParent()->isUnion()) 5167 Info.ActiveUnionMember.insert(std::make_pair( 5168 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5169 } 5170 } 5171 } 5172 5173 // Keep track of the direct virtual bases. 5174 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5175 for (auto &I : ClassDecl->bases()) { 5176 if (I.isVirtual()) 5177 DirectVBases.insert(&I); 5178 } 5179 5180 // Push virtual bases before others. 5181 for (auto &VBase : ClassDecl->vbases()) { 5182 if (CXXCtorInitializer *Value 5183 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5184 // [class.base.init]p7, per DR257: 5185 // A mem-initializer where the mem-initializer-id names a virtual base 5186 // class is ignored during execution of a constructor of any class that 5187 // is not the most derived class. 5188 if (ClassDecl->isAbstract()) { 5189 // FIXME: Provide a fixit to remove the base specifier. This requires 5190 // tracking the location of the associated comma for a base specifier. 5191 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5192 << VBase.getType() << ClassDecl; 5193 DiagnoseAbstractType(ClassDecl); 5194 } 5195 5196 Info.AllToInit.push_back(Value); 5197 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5198 // [class.base.init]p8, per DR257: 5199 // If a given [...] base class is not named by a mem-initializer-id 5200 // [...] and the entity is not a virtual base class of an abstract 5201 // class, then [...] the entity is default-initialized. 5202 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5203 CXXCtorInitializer *CXXBaseInit; 5204 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5205 &VBase, IsInheritedVirtualBase, 5206 CXXBaseInit)) { 5207 HadError = true; 5208 continue; 5209 } 5210 5211 Info.AllToInit.push_back(CXXBaseInit); 5212 } 5213 } 5214 5215 // Non-virtual bases. 5216 for (auto &Base : ClassDecl->bases()) { 5217 // Virtuals are in the virtual base list and already constructed. 5218 if (Base.isVirtual()) 5219 continue; 5220 5221 if (CXXCtorInitializer *Value 5222 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5223 Info.AllToInit.push_back(Value); 5224 } else if (!AnyErrors) { 5225 CXXCtorInitializer *CXXBaseInit; 5226 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5227 &Base, /*IsInheritedVirtualBase=*/false, 5228 CXXBaseInit)) { 5229 HadError = true; 5230 continue; 5231 } 5232 5233 Info.AllToInit.push_back(CXXBaseInit); 5234 } 5235 } 5236 5237 // Fields. 5238 for (auto *Mem : ClassDecl->decls()) { 5239 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5240 // C++ [class.bit]p2: 5241 // A declaration for a bit-field that omits the identifier declares an 5242 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5243 // initialized. 5244 if (F->isUnnamedBitfield()) 5245 continue; 5246 5247 // If we're not generating the implicit copy/move constructor, then we'll 5248 // handle anonymous struct/union fields based on their individual 5249 // indirect fields. 5250 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5251 continue; 5252 5253 if (CollectFieldInitializer(*this, Info, F)) 5254 HadError = true; 5255 continue; 5256 } 5257 5258 // Beyond this point, we only consider default initialization. 5259 if (Info.isImplicitCopyOrMove()) 5260 continue; 5261 5262 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5263 if (F->getType()->isIncompleteArrayType()) { 5264 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", 5265, __extension__ __PRETTY_FUNCTION__
))
5265 "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", 5265, __extension__ __PRETTY_FUNCTION__
))
; 5266 continue; 5267 } 5268 5269 // Initialize each field of an anonymous struct individually. 5270 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5271 HadError = true; 5272 5273 continue; 5274 } 5275 } 5276 5277 unsigned NumInitializers = Info.AllToInit.size(); 5278 if (NumInitializers > 0) { 5279 Constructor->setNumCtorInitializers(NumInitializers); 5280 CXXCtorInitializer **baseOrMemberInitializers = 5281 new (Context) CXXCtorInitializer*[NumInitializers]; 5282 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5283 NumInitializers * sizeof(CXXCtorInitializer*)); 5284 Constructor->setCtorInitializers(baseOrMemberInitializers); 5285 5286 // Constructors implicitly reference the base and member 5287 // destructors. 5288 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5289 Constructor->getParent()); 5290 } 5291 5292 return HadError; 5293} 5294 5295static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5296 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5297 const RecordDecl *RD = RT->getDecl(); 5298 if (RD->isAnonymousStructOrUnion()) { 5299 for (auto *Field : RD->fields()) 5300 PopulateKeysForFields(Field, IdealInits); 5301 return; 5302 } 5303 } 5304 IdealInits.push_back(Field->getCanonicalDecl()); 5305} 5306 5307static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5308 return Context.getCanonicalType(BaseType).getTypePtr(); 5309} 5310 5311static const void *GetKeyForMember(ASTContext &Context, 5312 CXXCtorInitializer *Member) { 5313 if (!Member->isAnyMemberInitializer()) 5314 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5315 5316 return Member->getAnyMember()->getCanonicalDecl(); 5317} 5318 5319static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5320 const CXXCtorInitializer *Previous, 5321 const CXXCtorInitializer *Current) { 5322 if (Previous->isAnyMemberInitializer()) 5323 Diag << 0 << Previous->getAnyMember(); 5324 else 5325 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5326 5327 if (Current->isAnyMemberInitializer()) 5328 Diag << 0 << Current->getAnyMember(); 5329 else 5330 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5331} 5332 5333static void DiagnoseBaseOrMemInitializerOrder( 5334 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5335 ArrayRef<CXXCtorInitializer *> Inits) { 5336 if (Constructor->getDeclContext()->isDependentContext()) 5337 return; 5338 5339 // Don't check initializers order unless the warning is enabled at the 5340 // location of at least one initializer. 5341 bool ShouldCheckOrder = false; 5342 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5343 CXXCtorInitializer *Init = Inits[InitIndex]; 5344 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5345 Init->getSourceLocation())) { 5346 ShouldCheckOrder = true; 5347 break; 5348 } 5349 } 5350 if (!ShouldCheckOrder) 5351 return; 5352 5353 // Build the list of bases and members in the order that they'll 5354 // actually be initialized. The explicit initializers should be in 5355 // this same order but may be missing things. 5356 SmallVector<const void*, 32> IdealInitKeys; 5357 5358 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5359 5360 // 1. Virtual bases. 5361 for (const auto &VBase : ClassDecl->vbases()) 5362 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5363 5364 // 2. Non-virtual bases. 5365 for (const auto &Base : ClassDecl->bases()) { 5366 if (Base.isVirtual()) 5367 continue; 5368 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5369 } 5370 5371 // 3. Direct fields. 5372 for (auto *Field : ClassDecl->fields()) { 5373 if (Field->isUnnamedBitfield()) 5374 continue; 5375 5376 PopulateKeysForFields(Field, IdealInitKeys); 5377 } 5378 5379 unsigned NumIdealInits = IdealInitKeys.size(); 5380 unsigned IdealIndex = 0; 5381 5382 // Track initializers that are in an incorrect order for either a warning or 5383 // note if multiple ones occur. 5384 SmallVector<unsigned> WarnIndexes; 5385 // Correlates the index of an initializer in the init-list to the index of 5386 // the field/base in the class. 5387 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5388 5389 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5390 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5391 5392 // Scan forward to try to find this initializer in the idealized 5393 // initializers list. 5394 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5395 if (InitKey == IdealInitKeys[IdealIndex]) 5396 break; 5397 5398 // If we didn't find this initializer, it must be because we 5399 // scanned past it on a previous iteration. That can only 5400 // happen if we're out of order; emit a warning. 5401 if (IdealIndex == NumIdealInits && InitIndex) { 5402 WarnIndexes.push_back(InitIndex); 5403 5404 // Move back to the initializer's location in the ideal list. 5405 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5406 if (InitKey == IdealInitKeys[IdealIndex]) 5407 break; 5408 5409 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", 5410, __extension__ __PRETTY_FUNCTION__
))
5410 "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", 5410, __extension__ __PRETTY_FUNCTION__
))
; 5411 } 5412 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5413 } 5414 5415 if (WarnIndexes.empty()) 5416 return; 5417 5418 // Sort based on the ideal order, first in the pair. 5419 llvm::sort(CorrelatedInitOrder, 5420 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5421 5422 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5423 // emit the diagnostic before we can try adding notes. 5424 { 5425 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5426 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5427 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5428 : diag::warn_some_initializers_out_of_order); 5429 5430 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5431 if (CorrelatedInitOrder[I].second == I) 5432 continue; 5433 // Ideally we would be using InsertFromRange here, but clang doesn't 5434 // appear to handle InsertFromRange correctly when the source range is 5435 // modified by another fix-it. 5436 D << FixItHint::CreateReplacement( 5437 Inits[I]->getSourceRange(), 5438 Lexer::getSourceText( 5439 CharSourceRange::getTokenRange( 5440 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5441 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5442 } 5443 5444 // If there is only 1 item out of order, the warning expects the name and 5445 // type of each being added to it. 5446 if (WarnIndexes.size() == 1) { 5447 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5448 Inits[WarnIndexes.front()]); 5449 return; 5450 } 5451 } 5452 // More than 1 item to warn, create notes letting the user know which ones 5453 // are bad. 5454 for (unsigned WarnIndex : WarnIndexes) { 5455 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5456 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5457 diag::note_initializer_out_of_order); 5458 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5459 D << PrevInit->getSourceRange(); 5460 } 5461} 5462 5463namespace { 5464bool CheckRedundantInit(Sema &S, 5465 CXXCtorInitializer *Init, 5466 CXXCtorInitializer *&PrevInit) { 5467 if (!PrevInit) { 5468 PrevInit = Init; 5469 return false; 5470 } 5471 5472 if (FieldDecl *Field = Init->getAnyMember()) 5473 S.Diag(Init->getSourceLocation(), 5474 diag::err_multiple_mem_initialization) 5475 << Field->getDeclName() 5476 << Init->getSourceRange(); 5477 else { 5478 const Type *BaseClass = Init->getBaseClass(); 5479 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", 5479, __extension__ __PRETTY_FUNCTION__
))
; 5480 S.Diag(Init->getSourceLocation(), 5481 diag::err_multiple_base_initialization) 5482 << QualType(BaseClass, 0) 5483 << Init->getSourceRange(); 5484 } 5485 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5486 << 0 << PrevInit->getSourceRange(); 5487 5488 return true; 5489} 5490 5491typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5492typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5493 5494bool CheckRedundantUnionInit(Sema &S, 5495 CXXCtorInitializer *Init, 5496 RedundantUnionMap &Unions) { 5497 FieldDecl *Field = Init->getAnyMember(); 5498 RecordDecl *Parent = Field->getParent(); 5499 NamedDecl *Child = Field; 5500 5501 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5502 if (Parent->isUnion()) { 5503 UnionEntry &En = Unions[Parent]; 5504 if (En.first && En.first != Child) { 5505 S.Diag(Init->getSourceLocation(), 5506 diag::err_multiple_mem_union_initialization) 5507 << Field->getDeclName() 5508 << Init->getSourceRange(); 5509 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5510 << 0 << En.second->getSourceRange(); 5511 return true; 5512 } 5513 if (!En.first) { 5514 En.first = Child; 5515 En.second = Init; 5516 } 5517 if (!Parent->isAnonymousStructOrUnion()) 5518 return false; 5519 } 5520 5521 Child = Parent; 5522 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5523 } 5524 5525 return false; 5526} 5527} // namespace 5528 5529/// ActOnMemInitializers - Handle the member initializers for a constructor. 5530void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5531 SourceLocation ColonLoc, 5532 ArrayRef<CXXCtorInitializer*> MemInits, 5533 bool AnyErrors) { 5534 if (!ConstructorDecl) 5535 return; 5536 5537 AdjustDeclIfTemplate(ConstructorDecl); 5538 5539 CXXConstructorDecl *Constructor 5540 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5541 5542 if (!Constructor) { 5543 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5544 return; 5545 } 5546 5547 // Mapping for the duplicate initializers check. 5548 // For member initializers, this is keyed with a FieldDecl*. 5549 // For base initializers, this is keyed with a Type*. 5550 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5551 5552 // Mapping for the inconsistent anonymous-union initializers check. 5553 RedundantUnionMap MemberUnions; 5554 5555 bool HadError = false; 5556 for (unsigned i = 0; i < MemInits.size(); i++) { 5557 CXXCtorInitializer *Init = MemInits[i]; 5558 5559 // Set the source order index. 5560 Init->setSourceOrder(i); 5561 5562 if (Init->isAnyMemberInitializer()) { 5563 const void *Key = GetKeyForMember(Context, Init); 5564 if (CheckRedundantInit(*this, Init, Members[Key]) || 5565 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5566 HadError = true; 5567 } else if (Init->isBaseInitializer()) { 5568 const void *Key = GetKeyForMember(Context, Init); 5569 if (CheckRedundantInit(*this, Init, Members[Key])) 5570 HadError = true; 5571 } else { 5572 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5572, __extension__ __PRETTY_FUNCTION__
))
; 5573 // This must be the only initializer 5574 if (MemInits.size() != 1) { 5575 Diag(Init->getSourceLocation(), 5576 diag::err_delegating_initializer_alone) 5577 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5578 // We will treat this as being the only initializer. 5579 } 5580 SetDelegatingInitializer(Constructor, MemInits[i]); 5581 // Return immediately as the initializer is set. 5582 return; 5583 } 5584 } 5585 5586 if (HadError) 5587 return; 5588 5589 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5590 5591 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5592 5593 DiagnoseUninitializedFields(*this, Constructor); 5594} 5595 5596void 5597Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5598 CXXRecordDecl *ClassDecl) { 5599 // Ignore dependent contexts. Also ignore unions, since their members never 5600 // have destructors implicitly called. 5601 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5602 return; 5603 5604 // FIXME: all the access-control diagnostics are positioned on the 5605 // field/base declaration. That's probably good; that said, the 5606 // user might reasonably want to know why the destructor is being 5607 // emitted, and we currently don't say. 5608 5609 // Non-static data members. 5610 for (auto *Field : ClassDecl->fields()) { 5611 if (Field->isInvalidDecl()) 5612 continue; 5613 5614 // Don't destroy incomplete or zero-length arrays. 5615 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5616 continue; 5617 5618 QualType FieldType = Context.getBaseElementType(Field->getType()); 5619 5620 const RecordType* RT = FieldType->getAs<RecordType>(); 5621 if (!RT) 5622 continue; 5623 5624 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5625 if (FieldClassDecl->isInvalidDecl()) 5626 continue; 5627 if (FieldClassDecl->hasIrrelevantDestructor()) 5628 continue; 5629 // The destructor for an implicit anonymous union member is never invoked. 5630 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5631 continue; 5632 5633 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5634 assert(Dtor && "No dtor found for FieldClassDecl!")(static_cast <bool> (Dtor && "No dtor found for FieldClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5634, __extension__ __PRETTY_FUNCTION__
))
; 5635 CheckDestructorAccess(Field->getLocation(), Dtor, 5636 PDiag(diag::err_access_dtor_field) 5637 << Field->getDeclName() 5638 << FieldType); 5639 5640 MarkFunctionReferenced(Location, Dtor); 5641 DiagnoseUseOfDecl(Dtor, Location); 5642 } 5643 5644 // We only potentially invoke the destructors of potentially constructed 5645 // subobjects. 5646 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5647 5648 // If the destructor exists and has already been marked used in the MS ABI, 5649 // then virtual base destructors have already been checked and marked used. 5650 // Skip checking them again to avoid duplicate diagnostics. 5651 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5652 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5653 if (Dtor && Dtor->isUsed()) 5654 VisitVirtualBases = false; 5655 } 5656 5657 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5658 5659 // Bases. 5660 for (const auto &Base : ClassDecl->bases()) { 5661 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5662 if (!RT) 5663 continue; 5664 5665 // Remember direct virtual bases. 5666 if (Base.isVirtual()) { 5667 if (!VisitVirtualBases) 5668 continue; 5669 DirectVirtualBases.insert(RT); 5670 } 5671 5672 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5673 // If our base class is invalid, we probably can't get its dtor anyway. 5674 if (BaseClassDecl->isInvalidDecl()) 5675 continue; 5676 if (BaseClassDecl->hasIrrelevantDestructor()) 5677 continue; 5678 5679 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5680 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5680, __extension__ __PRETTY_FUNCTION__
))
; 5681 5682 // FIXME: caret should be on the start of the class name 5683 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5684 PDiag(diag::err_access_dtor_base) 5685 << Base.getType() << Base.getSourceRange(), 5686 Context.getTypeDeclType(ClassDecl)); 5687 5688 MarkFunctionReferenced(Location, Dtor); 5689 DiagnoseUseOfDecl(Dtor, Location); 5690 } 5691 5692 if (VisitVirtualBases) 5693 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5694 &DirectVirtualBases); 5695} 5696 5697void Sema::MarkVirtualBaseDestructorsReferenced( 5698 SourceLocation Location, CXXRecordDecl *ClassDecl, 5699 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5700 // Virtual bases. 5701 for (const auto &VBase : ClassDecl->vbases()) { 5702 // Bases are always records in a well-formed non-dependent class. 5703 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5704 5705 // Ignore already visited direct virtual bases. 5706 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5707 continue; 5708 5709 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5710 // If our base class is invalid, we probably can't get its dtor anyway. 5711 if (BaseClassDecl->isInvalidDecl()) 5712 continue; 5713 if (BaseClassDecl->hasIrrelevantDestructor()) 5714 continue; 5715 5716 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5717 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5717, __extension__ __PRETTY_FUNCTION__
))
; 5718 if (CheckDestructorAccess( 5719 ClassDecl->getLocation(), Dtor, 5720 PDiag(diag::err_access_dtor_vbase) 5721 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5722 Context.getTypeDeclType(ClassDecl)) == 5723 AR_accessible) { 5724 CheckDerivedToBaseConversion( 5725 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5726 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5727 SourceRange(), DeclarationName(), nullptr); 5728 } 5729 5730 MarkFunctionReferenced(Location, Dtor); 5731 DiagnoseUseOfDecl(Dtor, Location); 5732 } 5733} 5734 5735void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5736 if (!CDtorDecl) 5737 return; 5738 5739 if (CXXConstructorDecl *Constructor 5740 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5741 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5742 DiagnoseUninitializedFields(*this, Constructor); 5743 } 5744} 5745 5746bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5747 if (!getLangOpts().CPlusPlus) 5748 return false; 5749 5750 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5751 if (!RD) 5752 return false; 5753 5754 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5755 // class template specialization here, but doing so breaks a lot of code. 5756 5757 // We can't answer whether something is abstract until it has a 5758 // definition. If it's currently being defined, we'll walk back 5759 // over all the declarations when we have a full definition. 5760 const CXXRecordDecl *Def = RD->getDefinition(); 5761 if (!Def || Def->isBeingDefined()) 5762 return false; 5763 5764 return RD->isAbstract(); 5765} 5766 5767bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5768 TypeDiagnoser &Diagnoser) { 5769 if (!isAbstractType(Loc, T)) 5770 return false; 5771 5772 T = Context.getBaseElementType(T); 5773 Diagnoser.diagnose(*this, Loc, T); 5774 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5775 return true; 5776} 5777 5778void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5779 // Check if we've already emitted the list of pure virtual functions 5780 // for this class. 5781 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5782 return; 5783 5784 // If the diagnostic is suppressed, don't emit the notes. We're only 5785 // going to emit them once, so try to attach them to a diagnostic we're 5786 // actually going to show. 5787 if (Diags.isLastDiagnosticIgnored()) 5788 return; 5789 5790 CXXFinalOverriderMap FinalOverriders; 5791 RD->getFinalOverriders(FinalOverriders); 5792 5793 // Keep a set of seen pure methods so we won't diagnose the same method 5794 // more than once. 5795 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5796 5797 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5798 MEnd = FinalOverriders.end(); 5799 M != MEnd; 5800 ++M) { 5801 for (OverridingMethods::iterator SO = M->second.begin(), 5802 SOEnd = M->second.end(); 5803 SO != SOEnd; ++SO) { 5804 // C++ [class.abstract]p4: 5805 // A class is abstract if it contains or inherits at least one 5806 // pure virtual function for which the final overrider is pure 5807 // virtual. 5808 5809 // 5810 if (SO->second.size() != 1) 5811 continue; 5812 5813 if (!SO->second.front().Method->isPure()) 5814 continue; 5815 5816 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5817 continue; 5818 5819 Diag(SO->second.front().Method->getLocation(), 5820 diag::note_pure_virtual_function) 5821 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5822 } 5823 } 5824 5825 if (!PureVirtualClassDiagSet) 5826 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5827 PureVirtualClassDiagSet->insert(RD); 5828} 5829 5830namespace { 5831struct AbstractUsageInfo { 5832 Sema &S; 5833 CXXRecordDecl *Record; 5834 CanQualType AbstractType; 5835 bool Invalid; 5836 5837 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5838 : S(S), Record(Record), 5839 AbstractType(S.Context.getCanonicalType( 5840 S.Context.getTypeDeclType(Record))), 5841 Invalid(false) {} 5842 5843 void DiagnoseAbstractType() { 5844 if (Invalid) return; 5845 S.DiagnoseAbstractType(Record); 5846 Invalid = true; 5847 } 5848 5849 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5850}; 5851 5852struct CheckAbstractUsage { 5853 AbstractUsageInfo &Info; 5854 const NamedDecl *Ctx; 5855 5856 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5857 : Info(Info), Ctx(Ctx) {} 5858 5859 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5860 switch (TL.getTypeLocClass()) { 5861#define ABSTRACT_TYPELOC(CLASS, PARENT) 5862#define TYPELOC(CLASS, PARENT) \ 5863 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5864#include "clang/AST/TypeLocNodes.def" 5865 } 5866 } 5867 5868 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5869 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5870 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5871 if (!TL.getParam(I)) 5872 continue; 5873 5874 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5875 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5876 } 5877 } 5878 5879 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5880 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5881 } 5882 5883 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5884 // Visit the type parameters from a permissive context. 5885 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5886 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5887 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5888 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5889 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5890 // TODO: other template argument types? 5891 } 5892 } 5893 5894 // Visit pointee types from a permissive context. 5895#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5896 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5897 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5898 } 5899 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5900 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5901 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5902 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5903 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5904 5905 /// Handle all the types we haven't given a more specific 5906 /// implementation for above. 5907 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5908 // Every other kind of type that we haven't called out already 5909 // that has an inner type is either (1) sugar or (2) contains that 5910 // inner type in some way as a subobject. 5911 if (TypeLoc Next = TL.getNextTypeLoc()) 5912 return Visit(Next, Sel); 5913 5914 // If there's no inner type and we're in a permissive context, 5915 // don't diagnose. 5916 if (Sel == Sema::AbstractNone) return; 5917 5918 // Check whether the type matches the abstract type. 5919 QualType T = TL.getType(); 5920 if (T->isArrayType()) { 5921 Sel = Sema::AbstractArrayType; 5922 T = Info.S.Context.getBaseElementType(T); 5923 } 5924 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5925 if (CT != Info.AbstractType) return; 5926 5927 // It matched; do some magic. 5928 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5929 if (Sel == Sema::AbstractArrayType) { 5930 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5931 << T << TL.getSourceRange(); 5932 } else { 5933 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5934 << Sel << T << TL.getSourceRange(); 5935 } 5936 Info.DiagnoseAbstractType(); 5937 } 5938}; 5939 5940void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5941 Sema::AbstractDiagSelID Sel) { 5942 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5943} 5944 5945} 5946 5947/// Check for invalid uses of an abstract type in a function declaration. 5948static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5949 FunctionDecl *FD) { 5950 // No need to do the check on definitions, which require that 5951 // the return/param types be complete. 5952 if (FD->doesThisDeclarationHaveABody()) 5953 return; 5954 5955 // For safety's sake, just ignore it if we don't have type source 5956 // information. This should never happen for non-implicit methods, 5957 // but... 5958 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5959 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 5960} 5961 5962/// Check for invalid uses of an abstract type in a variable0 declaration. 5963static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5964 VarDecl *VD) { 5965 // No need to do the check on definitions, which require that 5966 // the type is complete. 5967 if (VD->isThisDeclarationADefinition()) 5968 return; 5969 5970 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 5971 Sema::AbstractVariableType); 5972} 5973 5974/// Check for invalid uses of an abstract type within a class definition. 5975static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5976 CXXRecordDecl *RD) { 5977 for (auto *D : RD->decls()) { 5978 if (D->isImplicit()) continue; 5979 5980 // Step through friends to the befriended declaration. 5981 if (auto *FD = dyn_cast<FriendDecl>(D)) { 5982 D = FD->getFriendDecl(); 5983 if (!D) continue; 5984 } 5985 5986 // Functions and function templates. 5987 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 5988 CheckAbstractClassUsage(Info, FD); 5989 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 5990 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 5991 5992 // Fields and static variables. 5993 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 5994 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5995 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5996 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 5997 CheckAbstractClassUsage(Info, VD); 5998 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 5999 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 6000 6001 // Nested classes and class templates. 6002 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6003 CheckAbstractClassUsage(Info, RD); 6004 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 6005 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 6006 } 6007 } 6008} 6009 6010static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 6011 Attr *ClassAttr = getDLLAttr(Class); 6012 if (!ClassAttr) 6013 return; 6014 6015 assert(ClassAttr->getKind() == attr::DLLExport)(static_cast <bool> (ClassAttr->getKind() == attr::DLLExport
) ? void (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "clang/lib/Sema/SemaDeclCXX.cpp", 6015, __extension__ __PRETTY_FUNCTION__
))
; 6016 6017 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6018 6019 if (TSK == TSK_ExplicitInstantiationDeclaration) 6020 // Don't go any further if this is just an explicit instantiation 6021 // declaration. 6022 return; 6023 6024 // Add a context note to explain how we got to any diagnostics produced below. 6025 struct MarkingClassDllexported { 6026 Sema &S; 6027 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 6028 SourceLocation AttrLoc) 6029 : S(S) { 6030 Sema::CodeSynthesisContext Ctx; 6031 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 6032 Ctx.PointOfInstantiation = AttrLoc; 6033 Ctx.Entity = Class; 6034 S.pushCodeSynthesisContext(Ctx); 6035 } 6036 ~MarkingClassDllexported() { 6037 S.popCodeSynthesisContext(); 6038 } 6039 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 6040 6041 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6042 S.MarkVTableUsed(Class->getLocation(), Class, true); 6043 6044 for (Decl *Member : Class->decls()) { 6045 // Skip members that were not marked exported. 6046 if (!Member->hasAttr<DLLExportAttr>()) 6047 continue; 6048 6049 // Defined static variables that are members of an exported base 6050 // class must be marked export too. 6051 auto *VD = dyn_cast<VarDecl>(Member); 6052 if (VD && VD->getStorageClass() == SC_Static && 6053 TSK == TSK_ImplicitInstantiation) 6054 S.MarkVariableReferenced(VD->getLocation(), VD); 6055 6056 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6057 if (!MD) 6058 continue; 6059 6060 if (MD->isUserProvided()) { 6061 // Instantiate non-default class member functions ... 6062 6063 // .. except for certain kinds of template specializations. 6064 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6065 continue; 6066 6067 // If this is an MS ABI dllexport default constructor, instantiate any 6068 // default arguments. 6069 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6070 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6071 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6072 S.InstantiateDefaultCtorDefaultArgs(CD); 6073 } 6074 } 6075 6076 S.MarkFunctionReferenced(Class->getLocation(), MD); 6077 6078 // The function will be passed to the consumer when its definition is 6079 // encountered. 6080 } else if (MD->isExplicitlyDefaulted()) { 6081 // Synthesize and instantiate explicitly defaulted methods. 6082 S.MarkFunctionReferenced(Class->getLocation(), MD); 6083 6084 if (TSK != TSK_ExplicitInstantiationDefinition) { 6085 // Except for explicit instantiation defs, we will not see the 6086 // definition again later, so pass it to the consumer now. 6087 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6088 } 6089 } else if (!MD->isTrivial() || 6090 MD->isCopyAssignmentOperator() || 6091 MD->isMoveAssignmentOperator()) { 6092 // Synthesize and instantiate non-trivial implicit methods, and the copy 6093 // and move assignment operators. The latter are exported even if they 6094 // are trivial, because the address of an operator can be taken and 6095 // should compare equal across libraries. 6096 S.MarkFunctionReferenced(Class->getLocation(), MD); 6097 6098 // There is no later point when we will see the definition of this 6099 // function, so pass it to the consumer now. 6100 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6101 } 6102 } 6103} 6104 6105static void checkForMultipleExportedDefaultConstructors(Sema &S, 6106 CXXRecordDecl *Class) { 6107 // Only the MS ABI has default constructor closures, so we don't need to do 6108 // this semantic checking anywhere else. 6109 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6110 return; 6111 6112 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6113 for (Decl *Member : Class->decls()) { 6114 // Look for exported default constructors. 6115 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6116 if (!CD || !CD->isDefaultConstructor()) 6117 continue; 6118 auto *Attr = CD->getAttr<DLLExportAttr>(); 6119 if (!Attr) 6120 continue; 6121 6122 // If the class is non-dependent, mark the default arguments as ODR-used so 6123 // that we can properly codegen the constructor closure. 6124 if (!Class->isDependentContext()) { 6125 for (ParmVarDecl *PD : CD->parameters()) { 6126 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6127 S.DiscardCleanupsInEvaluationContext(); 6128 } 6129 } 6130 6131 if (LastExportedDefaultCtor) { 6132 S.Diag(LastExportedDefaultCtor->getLocation(), 6133 diag::err_attribute_dll_ambiguous_default_ctor) 6134 << Class; 6135 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6136 << CD->getDeclName(); 6137 return; 6138 } 6139 LastExportedDefaultCtor = CD; 6140 } 6141} 6142 6143static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6144 CXXRecordDecl *Class) { 6145 bool ErrorReported = false; 6146 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6147 ClassTemplateDecl *TD) { 6148 if (ErrorReported) 6149 return; 6150 S.Diag(TD->getLocation(), 6151 diag::err_cuda_device_builtin_surftex_cls_template) 6152 << /*surface*/ 0 << TD; 6153 ErrorReported = true; 6154 }; 6155 6156 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6157 if (!TD) { 6158 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6159 if (!SD) { 6160 S.Diag(Class->getLocation(), 6161 diag::err_cuda_device_builtin_surftex_ref_decl) 6162 << /*surface*/ 0 << Class; 6163 S.Diag(Class->getLocation(), 6164 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6165 << Class; 6166 return; 6167 } 6168 TD = SD->getSpecializedTemplate(); 6169 } 6170 6171 TemplateParameterList *Params = TD->getTemplateParameters(); 6172 unsigned N = Params->size(); 6173 6174 if (N != 2) { 6175 reportIllegalClassTemplate(S, TD); 6176 S.Diag(TD->getLocation(), 6177 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6178 << TD << 2; 6179 } 6180 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6181 reportIllegalClassTemplate(S, TD); 6182 S.Diag(TD->getLocation(), 6183 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6184 << TD << /*1st*/ 0 << /*type*/ 0; 6185 } 6186 if (N > 1) { 6187 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6188 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6189 reportIllegalClassTemplate(S, TD); 6190 S.Diag(TD->getLocation(), 6191 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6192 << TD << /*2nd*/ 1 << /*integer*/ 1; 6193 } 6194 } 6195} 6196 6197static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6198 CXXRecordDecl *Class) { 6199 bool ErrorReported = false; 6200 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6201 ClassTemplateDecl *TD) { 6202 if (ErrorReported) 6203 return; 6204 S.Diag(TD->getLocation(), 6205 diag::err_cuda_device_builtin_surftex_cls_template) 6206 << /*texture*/ 1 << TD; 6207 ErrorReported = true; 6208 }; 6209 6210 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6211 if (!TD) { 6212 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6213 if (!SD) { 6214 S.Diag(Class->getLocation(), 6215 diag::err_cuda_device_builtin_surftex_ref_decl) 6216 << /*texture*/ 1 << Class; 6217 S.Diag(Class->getLocation(), 6218 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6219 << Class; 6220 return; 6221 } 6222 TD = SD->getSpecializedTemplate(); 6223 } 6224 6225 TemplateParameterList *Params = TD->getTemplateParameters(); 6226 unsigned N = Params->size(); 6227 6228 if (N != 3) { 6229 reportIllegalClassTemplate(S, TD); 6230 S.Diag(TD->getLocation(), 6231 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6232 << TD << 3; 6233 } 6234 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6235 reportIllegalClassTemplate(S, TD); 6236 S.Diag(TD->getLocation(), 6237 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6238 << TD << /*1st*/ 0 << /*type*/ 0; 6239 } 6240 if (N > 1) { 6241 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6242 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6243 reportIllegalClassTemplate(S, TD); 6244 S.Diag(TD->getLocation(), 6245 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6246 << TD << /*2nd*/ 1 << /*integer*/ 1; 6247 } 6248 } 6249 if (N > 2) { 6250 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6251 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6252 reportIllegalClassTemplate(S, TD); 6253 S.Diag(TD->getLocation(), 6254 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6255 << TD << /*3rd*/ 2 << /*integer*/ 1; 6256 } 6257 } 6258} 6259 6260void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6261 // Mark any compiler-generated routines with the implicit code_seg attribute. 6262 for (auto *Method : Class->methods()) { 6263 if (Method->isUserProvided()) 6264 continue; 6265 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6266 Method->addAttr(A); 6267 } 6268} 6269 6270/// Check class-level dllimport/dllexport attribute. 6271void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6272 Attr *ClassAttr = getDLLAttr(Class); 6273 6274 // MSVC inherits DLL attributes to partial class template specializations. 6275 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6276 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6277 if (Attr *TemplateAttr = 6278 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6279 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6280 A->setInherited(true); 6281 ClassAttr = A; 6282 } 6283 } 6284 } 6285 6286 if (!ClassAttr) 6287 return; 6288 6289 if (!Class->isExternallyVisible()) { 6290 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6291 << Class << ClassAttr; 6292 return; 6293 } 6294 6295 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6296 !ClassAttr->isInherited()) { 6297 // Diagnose dll attributes on members of class with dll attribute. 6298 for (Decl *Member : Class->decls()) { 6299 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6300 continue; 6301 InheritableAttr *MemberAttr = getDLLAttr(Member); 6302 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6303 continue; 6304 6305 Diag(MemberAttr->getLocation(), 6306 diag::err_attribute_dll_member_of_dll_class) 6307 << MemberAttr << ClassAttr; 6308 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6309 Member->setInvalidDecl(); 6310 } 6311 } 6312 6313 if (Class->getDescribedClassTemplate()) 6314 // Don't inherit dll attribute until the template is instantiated. 6315 return; 6316 6317 // The class is either imported or exported. 6318 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6319 6320 // Check if this was a dllimport attribute propagated from a derived class to 6321 // a base class template specialization. We don't apply these attributes to 6322 // static data members. 6323 const bool PropagatedImport = 6324 !ClassExported && 6325 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6326 6327 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6328 6329 // Ignore explicit dllexport on explicit class template instantiation 6330 // declarations, except in MinGW mode. 6331 if (ClassExported && !ClassAttr->isInherited() && 6332 TSK == TSK_ExplicitInstantiationDeclaration && 6333 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6334 Class->dropAttr<DLLExportAttr>(); 6335 return; 6336 } 6337 6338 // Force declaration of implicit members so they can inherit the attribute. 6339 ForceDeclarationOfImplicitMembers(Class); 6340 6341 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6342 // seem to be true in practice? 6343 6344 for (Decl *Member : Class->decls()) { 6345 VarDecl *VD = dyn_cast<VarDecl>(Member); 6346 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6347 6348 // Only methods and static fields inherit the attributes. 6349 if (!VD && !MD) 6350 continue; 6351 6352 if (MD) { 6353 // Don't process deleted methods. 6354 if (MD->isDeleted()) 6355 continue; 6356 6357 if (MD->isInlined()) { 6358 // MinGW does not import or export inline methods. But do it for 6359 // template instantiations. 6360 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6361 TSK != TSK_ExplicitInstantiationDeclaration && 6362 TSK != TSK_ExplicitInstantiationDefinition) 6363 continue; 6364 6365 // MSVC versions before 2015 don't export the move assignment operators 6366 // and move constructor, so don't attempt to import/export them if 6367 // we have a definition. 6368 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6369 if ((MD->isMoveAssignmentOperator() || 6370 (Ctor && Ctor->isMoveConstructor())) && 6371 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6372 continue; 6373 6374 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6375 // operator is exported anyway. 6376 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6377 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6378 continue; 6379 } 6380 } 6381 6382 // Don't apply dllimport attributes to static data members of class template 6383 // instantiations when the attribute is propagated from a derived class. 6384 if (VD && PropagatedImport) 6385 continue; 6386 6387 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6388 continue; 6389 6390 if (!getDLLAttr(Member)) { 6391 InheritableAttr *NewAttr = nullptr; 6392 6393 // Do not export/import inline function when -fno-dllexport-inlines is 6394 // passed. But add attribute for later local static var check. 6395 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6396 TSK != TSK_ExplicitInstantiationDeclaration && 6397 TSK != TSK_ExplicitInstantiationDefinition) { 6398 if (ClassExported) { 6399 NewAttr = ::new (getASTContext()) 6400 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6401 } else { 6402 NewAttr = ::new (getASTContext()) 6403 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6404 } 6405 } else { 6406 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6407 } 6408 6409 NewAttr->setInherited(true); 6410 Member->addAttr(NewAttr); 6411 6412 if (MD) { 6413 // Propagate DLLAttr to friend re-declarations of MD that have already 6414 // been constructed. 6415 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6416 FD = FD->getPreviousDecl()) { 6417 if (FD->getFriendObjectKind() == Decl::FOK_None) 6418 continue; 6419 assert(!getDLLAttr(FD) &&(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 6420, __extension__ __PRETTY_FUNCTION__
))
6420 "friend re-decl should not already have a DLLAttr")(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 6420, __extension__ __PRETTY_FUNCTION__
))
; 6421 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6422 NewAttr->setInherited(true); 6423 FD->addAttr(NewAttr); 6424 } 6425 } 6426 } 6427 } 6428 6429 if (ClassExported) 6430 DelayedDllExportClasses.push_back(Class); 6431} 6432 6433/// Perform propagation of DLL attributes from a derived class to a 6434/// templated base class for MS compatibility. 6435void Sema::propagateDLLAttrToBaseClassTemplate( 6436 CXXRecordDecl *Class, Attr *ClassAttr, 6437 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6438 if (getDLLAttr( 6439 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6440 // If the base class template has a DLL attribute, don't try to change it. 6441 return; 6442 } 6443 6444 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6445 if (!getDLLAttr(BaseTemplateSpec) && 6446 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6447 TSK == TSK_ImplicitInstantiation)) { 6448 // The template hasn't been instantiated yet (or it has, but only as an 6449 // explicit instantiation declaration or implicit instantiation, which means 6450 // we haven't codegenned any members yet), so propagate the attribute. 6451 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6452 NewAttr->setInherited(true); 6453 BaseTemplateSpec->addAttr(NewAttr); 6454 6455 // If this was an import, mark that we propagated it from a derived class to 6456 // a base class template specialization. 6457 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6458 ImportAttr->setPropagatedToBaseTemplate(); 6459 6460 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6461 // needs to be run again to work see the new attribute. Otherwise this will 6462 // get run whenever the template is instantiated. 6463 if (TSK != TSK_Undeclared) 6464 checkClassLevelDLLAttribute(BaseTemplateSpec); 6465 6466 return; 6467 } 6468 6469 if (getDLLAttr(BaseTemplateSpec)) { 6470 // The template has already been specialized or instantiated with an 6471 // attribute, explicitly or through propagation. We should not try to change 6472 // it. 6473 return; 6474 } 6475 6476 // The template was previously instantiated or explicitly specialized without 6477 // a dll attribute, It's too late for us to add an attribute, so warn that 6478 // this is unsupported. 6479 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6480 << BaseTemplateSpec->isExplicitSpecialization(); 6481 Diag(ClassAttr->getLocation(), diag::note_attribute); 6482 if (BaseTemplateSpec->isExplicitSpecialization()) { 6483 Diag(BaseTemplateSpec->getLocation(), 6484 diag::note_template_class_explicit_specialization_was_here) 6485 << BaseTemplateSpec; 6486 } else { 6487 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6488 diag::note_template_class_instantiation_was_here) 6489 << BaseTemplateSpec; 6490 } 6491} 6492 6493/// Determine the kind of defaulting that would be done for a given function. 6494/// 6495/// If the function is both a default constructor and a copy / move constructor 6496/// (due to having a default argument for the first parameter), this picks 6497/// CXXDefaultConstructor. 6498/// 6499/// FIXME: Check that case is properly handled by all callers. 6500Sema::DefaultedFunctionKind 6501Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6502 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6503 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6504 if (Ctor->isDefaultConstructor()) 6505 return Sema::CXXDefaultConstructor; 6506 6507 if (Ctor->isCopyConstructor()) 6508 return Sema::CXXCopyConstructor; 6509 6510 if (Ctor->isMoveConstructor()) 6511 return Sema::CXXMoveConstructor; 6512 } 6513 6514 if (MD->isCopyAssignmentOperator()) 6515 return Sema::CXXCopyAssignment; 6516 6517 if (MD->isMoveAssignmentOperator()) 6518 return Sema::CXXMoveAssignment; 6519 6520 if (isa<CXXDestructorDecl>(FD)) 6521 return Sema::CXXDestructor; 6522 } 6523 6524 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6525 case OO_EqualEqual: 6526 return DefaultedComparisonKind::Equal; 6527 6528 case OO_ExclaimEqual: 6529 return DefaultedComparisonKind::NotEqual; 6530 6531 case OO_Spaceship: 6532 // No point allowing this if <=> doesn't exist in the current language mode. 6533 if (!getLangOpts().CPlusPlus20) 6534 break; 6535 return DefaultedComparisonKind::ThreeWay; 6536 6537 case OO_Less: 6538 case OO_LessEqual: 6539 case OO_Greater: 6540 case OO_GreaterEqual: 6541 // No point allowing this if <=> doesn't exist in the current language mode. 6542 if (!getLangOpts().CPlusPlus20) 6543 break; 6544 return DefaultedComparisonKind::Relational; 6545 6546 default: 6547 break; 6548 } 6549 6550 // Not defaultable. 6551 return DefaultedFunctionKind(); 6552} 6553 6554static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6555 SourceLocation DefaultLoc) { 6556 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6557 if (DFK.isComparison()) 6558 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6559 6560 switch (DFK.asSpecialMember()) { 6561 case Sema::CXXDefaultConstructor: 6562 S.DefineImplicitDefaultConstructor(DefaultLoc, 6563 cast<CXXConstructorDecl>(FD)); 6564 break; 6565 case Sema::CXXCopyConstructor: 6566 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6567 break; 6568 case Sema::CXXCopyAssignment: 6569 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6570 break; 6571 case Sema::CXXDestructor: 6572 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6573 break; 6574 case Sema::CXXMoveConstructor: 6575 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6576 break; 6577 case Sema::CXXMoveAssignment: 6578 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6579 break; 6580 case Sema::CXXInvalid: 6581 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "clang/lib/Sema/SemaDeclCXX.cpp"
, 6581)
; 6582 } 6583} 6584 6585/// Determine whether a type is permitted to be passed or returned in 6586/// registers, per C++ [class.temporary]p3. 6587static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6588 TargetInfo::CallingConvKind CCK) { 6589 if (D->isDependentType() || D->isInvalidDecl()) 6590 return false; 6591 6592 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6593 // The PS4 platform ABI follows the behavior of Clang 3.2. 6594 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6595 return !D->hasNonTrivialDestructorForCall() && 6596 !D->hasNonTrivialCopyConstructorForCall(); 6597 6598 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6599 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6600 bool DtorIsTrivialForCall = false; 6601 6602 // If a class has at least one non-deleted, trivial copy constructor, it 6603 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6604 // 6605 // Note: This permits classes with non-trivial copy or move ctors to be 6606 // passed in registers, so long as they *also* have a trivial copy ctor, 6607 // which is non-conforming. 6608 if (D->needsImplicitCopyConstructor()) { 6609 if (!D->defaultedCopyConstructorIsDeleted()) { 6610 if (D->hasTrivialCopyConstructor()) 6611 CopyCtorIsTrivial = true; 6612 if (D->hasTrivialCopyConstructorForCall()) 6613 CopyCtorIsTrivialForCall = true; 6614 } 6615 } else { 6616 for (const CXXConstructorDecl *CD : D->ctors()) { 6617 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6618 if (CD->isTrivial()) 6619 CopyCtorIsTrivial = true; 6620 if (CD->isTrivialForCall()) 6621 CopyCtorIsTrivialForCall = true; 6622 } 6623 } 6624 } 6625 6626 if (D->needsImplicitDestructor()) { 6627 if (!D->defaultedDestructorIsDeleted() && 6628 D->hasTrivialDestructorForCall()) 6629 DtorIsTrivialForCall = true; 6630 } else if (const auto *DD = D->getDestructor()) { 6631 if (!DD->isDeleted() && DD->isTrivialForCall()) 6632 DtorIsTrivialForCall = true; 6633 } 6634 6635 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6636 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6637 return true; 6638 6639 // If a class has a destructor, we'd really like to pass it indirectly 6640 // because it allows us to elide copies. Unfortunately, MSVC makes that 6641 // impossible for small types, which it will pass in a single register or 6642 // stack slot. Most objects with dtors are large-ish, so handle that early. 6643 // We can't call out all large objects as being indirect because there are 6644 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6645 // how we pass large POD types. 6646 6647 // Note: This permits small classes with nontrivial destructors to be 6648 // passed in registers, which is non-conforming. 6649 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6650 uint64_t TypeSize = isAArch64 ? 128 : 64; 6651 6652 if (CopyCtorIsTrivial && 6653 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6654 return true; 6655 return false; 6656 } 6657 6658 // Per C++ [class.temporary]p3, the relevant condition is: 6659 // each copy constructor, move constructor, and destructor of X is 6660 // either trivial or deleted, and X has at least one non-deleted copy 6661 // or move constructor 6662 bool HasNonDeletedCopyOrMove = false; 6663 6664 if (D->needsImplicitCopyConstructor() && 6665 !D->defaultedCopyConstructorIsDeleted()) { 6666 if (!D->hasTrivialCopyConstructorForCall()) 6667 return false; 6668 HasNonDeletedCopyOrMove = true; 6669 } 6670 6671 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6672 !D->defaultedMoveConstructorIsDeleted()) { 6673 if (!D->hasTrivialMoveConstructorForCall()) 6674 return false; 6675 HasNonDeletedCopyOrMove = true; 6676 } 6677 6678 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6679 !D->hasTrivialDestructorForCall()) 6680 return false; 6681 6682 for (const CXXMethodDecl *MD : D->methods()) { 6683 if (MD->isDeleted()) 6684 continue; 6685 6686 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6687 if (CD && CD->isCopyOrMoveConstructor()) 6688 HasNonDeletedCopyOrMove = true; 6689 else if (!isa<CXXDestructorDecl>(MD)) 6690 continue; 6691 6692 if (!MD->isTrivialForCall()) 6693 return false; 6694 } 6695 6696 return HasNonDeletedCopyOrMove; 6697} 6698 6699/// Report an error regarding overriding, along with any relevant 6700/// overridden methods. 6701/// 6702/// \param DiagID the primary error to report. 6703/// \param MD the overriding method. 6704static bool 6705ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6706 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6707 bool IssuedDiagnostic = false; 6708 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6709 if (Report(O)) { 6710 if (!IssuedDiagnostic) { 6711 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6712 IssuedDiagnostic = true; 6713 } 6714 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6715 } 6716 } 6717 return IssuedDiagnostic; 6718} 6719 6720/// Perform semantic checks on a class definition that has been 6721/// completing, introducing implicitly-declared members, checking for 6722/// abstract types, etc. 6723/// 6724/// \param S The scope in which the class was parsed. Null if we didn't just 6725/// parse a class definition. 6726/// \param Record The completed class. 6727void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6728 if (!Record) 6729 return; 6730 6731 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6732 AbstractUsageInfo Info(*this, Record); 6733 CheckAbstractClassUsage(Info, Record); 6734 } 6735 6736 // If this is not an aggregate type and has no user-declared constructor, 6737 // complain about any non-static data members of reference or const scalar 6738 // type, since they will never get initializers. 6739 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6740 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6741 !Record->isLambda()) { 6742 bool Complained = false; 6743 for (const auto *F : Record->fields()) { 6744 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6745 continue; 6746 6747 if (F->getType()->isReferenceType() || 6748 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6749 if (!Complained) { 6750 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6751 << Record->getTagKind() << Record; 6752 Complained = true; 6753 } 6754 6755 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6756 << F->getType()->isReferenceType() 6757 << F->getDeclName(); 6758 } 6759 } 6760 } 6761 6762 if (Record->getIdentifier()) { 6763 // C++ [class.mem]p13: 6764 // If T is the name of a class, then each of the following shall have a 6765 // name different from T: 6766 // - every member of every anonymous union that is a member of class T. 6767 // 6768 // C++ [class.mem]p14: 6769 // In addition, if class T has a user-declared constructor (12.1), every 6770 // non-static data member of class T shall have a name different from T. 6771 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6772 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6773 ++I) { 6774 NamedDecl *D = (*I)->getUnderlyingDecl(); 6775 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6776 Record->hasUserDeclaredConstructor()) || 6777 isa<IndirectFieldDecl>(D)) { 6778 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6779 << D->getDeclName(); 6780 break; 6781 } 6782 } 6783 } 6784 6785 // Warn if the class has virtual methods but non-virtual public destructor. 6786 if (Record->isPolymorphic() && !Record->isDependentType()) { 6787 CXXDestructorDecl *dtor = Record->getDestructor(); 6788 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6789 !Record->hasAttr<FinalAttr>()) 6790 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6791 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6792 } 6793 6794 if (Record->isAbstract()) { 6795 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6796 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6797 << FA->isSpelledAsSealed(); 6798 DiagnoseAbstractType(Record); 6799 } 6800 } 6801 6802 // Warn if the class has a final destructor but is not itself marked final. 6803 if (!Record->hasAttr<FinalAttr>()) { 6804 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6805 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6806 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6807 << FA->isSpelledAsSealed() 6808 << FixItHint::CreateInsertion( 6809 getLocForEndOfToken(Record->getLocation()), 6810 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6811 Diag(Record->getLocation(), 6812 diag::note_final_dtor_non_final_class_silence) 6813 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6814 } 6815 } 6816 } 6817 6818 // See if trivial_abi has to be dropped. 6819 if (Record->hasAttr<TrivialABIAttr>()) 6820 checkIllFormedTrivialABIStruct(*Record); 6821 6822 // Set HasTrivialSpecialMemberForCall if the record has attribute 6823 // "trivial_abi". 6824 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6825 6826 if (HasTrivialABI) 6827 Record->setHasTrivialSpecialMemberForCall(); 6828 6829 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6830 // We check these last because they can depend on the properties of the 6831 // primary comparison functions (==, <=>). 6832 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6833 6834 // Perform checks that can't be done until we know all the properties of a 6835 // member function (whether it's defaulted, deleted, virtual, overriding, 6836 // ...). 6837 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6838 // A static function cannot override anything. 6839 if (MD->getStorageClass() == SC_Static) { 6840 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6841 [](const CXXMethodDecl *) { return true; })) 6842 return; 6843 } 6844 6845 // A deleted function cannot override a non-deleted function and vice 6846 // versa. 6847 if (ReportOverrides(*this, 6848 MD->isDeleted() ? diag::err_deleted_override 6849 : diag::err_non_deleted_override, 6850 MD, [&](const CXXMethodDecl *V) { 6851 return MD->isDeleted() != V->isDeleted(); 6852 })) { 6853 if (MD->isDefaulted() && MD->isDeleted()) 6854 // Explain why this defaulted function was deleted. 6855 DiagnoseDeletedDefaultedFunction(MD); 6856 return; 6857 } 6858 6859 // A consteval function cannot override a non-consteval function and vice 6860 // versa. 6861 if (ReportOverrides(*this, 6862 MD->isConsteval() ? diag::err_consteval_override 6863 : diag::err_non_consteval_override, 6864 MD, [&](const CXXMethodDecl *V) { 6865 return MD->isConsteval() != V->isConsteval(); 6866 })) { 6867 if (MD->isDefaulted() && MD->isDeleted()) 6868 // Explain why this defaulted function was deleted. 6869 DiagnoseDeletedDefaultedFunction(MD); 6870 return; 6871 } 6872 }; 6873 6874 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6875 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6876 return false; 6877 6878 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6879 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6880 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6881 DefaultedSecondaryComparisons.push_back(FD); 6882 return true; 6883 } 6884 6885 CheckExplicitlyDefaultedFunction(S, FD); 6886 return false; 6887 }; 6888 6889 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6890 // Check whether the explicitly-defaulted members are valid. 6891 bool Incomplete = CheckForDefaultedFunction(M); 6892 6893 // Skip the rest of the checks for a member of a dependent class. 6894 if (Record->isDependentType()) 6895 return; 6896 6897 // For an explicitly defaulted or deleted special member, we defer 6898 // determining triviality until the class is complete. That time is now! 6899 CXXSpecialMember CSM = getSpecialMember(M); 6900 if (!M->isImplicit() && !M->isUserProvided()) { 6901 if (CSM != CXXInvalid) { 6902 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6903 // Inform the class that we've finished declaring this member. 6904 Record->finishedDefaultedOrDeletedMember(M); 6905 M->setTrivialForCall( 6906 HasTrivialABI || 6907 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6908 Record->setTrivialForCallFlags(M); 6909 } 6910 } 6911 6912 // Set triviality for the purpose of calls if this is a user-provided 6913 // copy/move constructor or destructor. 6914 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6915 CSM == CXXDestructor) && M->isUserProvided()) { 6916 M->setTrivialForCall(HasTrivialABI); 6917 Record->setTrivialForCallFlags(M); 6918 } 6919 6920 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6921 M->hasAttr<DLLExportAttr>()) { 6922 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6923 M->isTrivial() && 6924 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6925 CSM == CXXDestructor)) 6926 M->dropAttr<DLLExportAttr>(); 6927 6928 if (M->hasAttr<DLLExportAttr>()) { 6929 // Define after any fields with in-class initializers have been parsed. 6930 DelayedDllExportMemberFunctions.push_back(M); 6931 } 6932 } 6933 6934 // Define defaulted constexpr virtual functions that override a base class 6935 // function right away. 6936 // FIXME: We can defer doing this until the vtable is marked as used. 6937 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6938 DefineDefaultedFunction(*this, M, M->getLocation()); 6939 6940 if (!Incomplete) 6941 CheckCompletedMemberFunction(M); 6942 }; 6943 6944 // Check the destructor before any other member function. We need to 6945 // determine whether it's trivial in order to determine whether the claas 6946 // type is a literal type, which is a prerequisite for determining whether 6947 // other special member functions are valid and whether they're implicitly 6948 // 'constexpr'. 6949 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6950 CompleteMemberFunction(Dtor); 6951 6952 bool HasMethodWithOverrideControl = false, 6953 HasOverridingMethodWithoutOverrideControl = false; 6954 for (auto *D : Record->decls()) { 6955 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6956 // FIXME: We could do this check for dependent types with non-dependent 6957 // bases. 6958 if (!Record->isDependentType()) { 6959 // See if a method overloads virtual methods in a base 6960 // class without overriding any. 6961 if (!M->isStatic()) 6962 DiagnoseHiddenVirtualMethods(M); 6963 if (M->hasAttr<OverrideAttr>()) 6964 HasMethodWithOverrideControl = true; 6965 else if (M->size_overridden_methods() > 0) 6966 HasOverridingMethodWithoutOverrideControl = true; 6967 } 6968 6969 if (!isa<CXXDestructorDecl>(M)) 6970 CompleteMemberFunction(M); 6971 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6972 CheckForDefaultedFunction( 6973 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6974 } 6975 } 6976 6977 if (HasOverridingMethodWithoutOverrideControl) { 6978 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6979 for (auto *M : Record->methods()) 6980 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6981 } 6982 6983 // Check the defaulted secondary comparisons after any other member functions. 6984 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6985 CheckExplicitlyDefaultedFunction(S, FD); 6986 6987 // If this is a member function, we deferred checking it until now. 6988 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6989 CheckCompletedMemberFunction(MD); 6990 } 6991 6992 // ms_struct is a request to use the same ABI rules as MSVC. Check 6993 // whether this class uses any C++ features that are implemented 6994 // completely differently in MSVC, and if so, emit a diagnostic. 6995 // That diagnostic defaults to an error, but we allow projects to 6996 // map it down to a warning (or ignore it). It's a fairly common 6997 // practice among users of the ms_struct pragma to mass-annotate 6998 // headers, sweeping up a bunch of types that the project doesn't 6999 // really rely on MSVC-compatible layout for. We must therefore 7000 // support "ms_struct except for C++ stuff" as a secondary ABI. 7001 // Don't emit this diagnostic if the feature was enabled as a 7002 // language option (as opposed to via a pragma or attribute), as 7003 // the option -mms-bitfields otherwise essentially makes it impossible 7004 // to build C++ code, unless this diagnostic is turned off. 7005 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 7006 (Record->isPolymorphic() || Record->getNumBases())) { 7007 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 7008 } 7009 7010 checkClassLevelDLLAttribute(Record); 7011 checkClassLevelCodeSegAttribute(Record); 7012 7013 bool ClangABICompat4 = 7014 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 7015 TargetInfo::CallingConvKind CCK = 7016 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 7017 bool CanPass = canPassInRegisters(*this, Record, CCK); 7018 7019 // Do not change ArgPassingRestrictions if it has already been set to 7020 // APK_CanNeverPassInRegs. 7021 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 7022 Record->setArgPassingRestrictions(CanPass 7023 ? RecordDecl::APK_CanPassInRegs 7024 : RecordDecl::APK_CannotPassInRegs); 7025 7026 // If canPassInRegisters returns true despite the record having a non-trivial 7027 // destructor, the record is destructed in the callee. This happens only when 7028 // the record or one of its subobjects has a field annotated with trivial_abi 7029 // or a field qualified with ObjC __strong/__weak. 7030 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 7031 Record->setParamDestroyedInCallee(true); 7032 else if (Record->hasNonTrivialDestructor()) 7033 Record->setParamDestroyedInCallee(CanPass); 7034 7035 if (getLangOpts().ForceEmitVTables) { 7036 // If we want to emit all the vtables, we need to mark it as used. This 7037 // is especially required for cases like vtable assumption loads. 7038 MarkVTableUsed(Record->getInnerLocStart(), Record); 7039 } 7040 7041 if (getLangOpts().CUDA) { 7042 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7043 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7044 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7045 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7046 } 7047} 7048 7049/// Look up the special member function that would be called by a special 7050/// member function for a subobject of class type. 7051/// 7052/// \param Class The class type of the subobject. 7053/// \param CSM The kind of special member function. 7054/// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7055/// \param ConstRHS True if this is a copy operation with a const object 7056/// on its RHS, that is, if the argument to the outer special member 7057/// function is 'const' and this is not a field marked 'mutable'. 7058static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7059 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7060 unsigned FieldQuals, bool ConstRHS) { 7061 unsigned LHSQuals = 0; 7062 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7063 LHSQuals = FieldQuals; 7064 7065 unsigned RHSQuals = FieldQuals; 7066 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7067 RHSQuals = 0; 7068 else if (ConstRHS) 7069 RHSQuals |= Qualifiers::Const; 7070 7071 return S.LookupSpecialMember(Class, CSM, 7072 RHSQuals & Qualifiers::Const, 7073 RHSQuals & Qualifiers::Volatile, 7074 false, 7075 LHSQuals & Qualifiers::Const, 7076 LHSQuals & Qualifiers::Volatile); 7077} 7078 7079class Sema::InheritedConstructorInfo { 7080 Sema &S; 7081 SourceLocation UseLoc; 7082 7083 /// A mapping from the base classes through which the constructor was 7084 /// inherited to the using shadow declaration in that base class (or a null 7085 /// pointer if the constructor was declared in that base class). 7086 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7087 InheritedFromBases; 7088 7089public: 7090 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7091 ConstructorUsingShadowDecl *Shadow) 7092 : S(S), UseLoc(UseLoc) { 7093 bool DiagnosedMultipleConstructedBases = false; 7094 CXXRecordDecl *ConstructedBase = nullptr; 7095 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7096 7097 // Find the set of such base class subobjects and check that there's a 7098 // unique constructed subobject. 7099 for (auto *D : Shadow->redecls()) { 7100 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7101 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7102 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7103 7104 InheritedFromBases.insert( 7105 std::make_pair(DNominatedBase->getCanonicalDecl(), 7106 DShadow->getNominatedBaseClassShadowDecl())); 7107 if (DShadow->constructsVirtualBase()) 7108 InheritedFromBases.insert( 7109 std::make_pair(DConstructedBase->getCanonicalDecl(), 7110 DShadow->getConstructedBaseClassShadowDecl())); 7111 else 7112 assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase
) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7112, __extension__ __PRETTY_FUNCTION__
))
; 7113 7114 // [class.inhctor.init]p2: 7115 // If the constructor was inherited from multiple base class subobjects 7116 // of type B, the program is ill-formed. 7117 if (!ConstructedBase) { 7118 ConstructedBase = DConstructedBase; 7119 ConstructedBaseIntroducer = D->getIntroducer(); 7120 } else if (ConstructedBase != DConstructedBase && 7121 !Shadow->isInvalidDecl()) { 7122 if (!DiagnosedMultipleConstructedBases) { 7123 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7124 << Shadow->getTargetDecl(); 7125 S.Diag(ConstructedBaseIntroducer->getLocation(), 7126 diag::note_ambiguous_inherited_constructor_using) 7127 << ConstructedBase; 7128 DiagnosedMultipleConstructedBases = true; 7129 } 7130 S.Diag(D->getIntroducer()->getLocation(), 7131 diag::note_ambiguous_inherited_constructor_using) 7132 << DConstructedBase; 7133 } 7134 } 7135 7136 if (DiagnosedMultipleConstructedBases) 7137 Shadow->setInvalidDecl(); 7138 } 7139 7140 /// Find the constructor to use for inherited construction of a base class, 7141 /// and whether that base class constructor inherits the constructor from a 7142 /// virtual base class (in which case it won't actually invoke it). 7143 std::pair<CXXConstructorDecl *, bool> 7144 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7145 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7146 if (It == InheritedFromBases.end()) 7147 return std::make_pair(nullptr, false); 7148 7149 // This is an intermediary class. 7150 if (It->second) 7151 return std::make_pair( 7152 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7153 It->second->constructsVirtualBase()); 7154 7155 // This is the base class from which the constructor was inherited. 7156 return std::make_pair(Ctor, false); 7157 } 7158}; 7159 7160/// Is the special member function which would be selected to perform the 7161/// specified operation on the specified class type a constexpr constructor? 7162static bool 7163specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7164 Sema::CXXSpecialMember CSM, unsigned Quals, 7165 bool ConstRHS, 7166 CXXConstructorDecl *InheritedCtor = nullptr, 7167 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7168 // If we're inheriting a constructor, see if we need to call it for this base 7169 // class. 7170 if (InheritedCtor) { 7171 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7171, __extension__ __PRETTY_FUNCTION__
))
; 7172 auto BaseCtor = 7173 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7174 if (BaseCtor) 7175 return BaseCtor->isConstexpr(); 7176 } 7177 7178 if (CSM == Sema::CXXDefaultConstructor) 7179 return ClassDecl->hasConstexprDefaultConstructor(); 7180 if (CSM == Sema::CXXDestructor) 7181 return ClassDecl->hasConstexprDestructor(); 7182 7183 Sema::SpecialMemberOverloadResult SMOR = 7184 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7185 if (!SMOR.getMethod()) 7186 // A constructor we wouldn't select can't be "involved in initializing" 7187 // anything. 7188 return true; 7189 return SMOR.getMethod()->isConstexpr(); 7190} 7191 7192/// Determine whether the specified special member function would be constexpr 7193/// if it were implicitly defined. 7194static bool defaultedSpecialMemberIsConstexpr( 7195 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7196 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7197 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7198 if (!S.getLangOpts().CPlusPlus11) 7199 return false; 7200 7201 // C++11 [dcl.constexpr]p4: 7202 // In the definition of a constexpr constructor [...] 7203 bool Ctor = true; 7204 switch (CSM) { 7205 case Sema::CXXDefaultConstructor: 7206 if (Inherited) 7207 break; 7208 // Since default constructor lookup is essentially trivial (and cannot 7209 // involve, for instance, template instantiation), we compute whether a 7210 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7211 // 7212 // This is important for performance; we need to know whether the default 7213 // constructor is constexpr to determine whether the type is a literal type. 7214 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7215 7216 case Sema::CXXCopyConstructor: 7217 case Sema::CXXMoveConstructor: 7218 // For copy or move constructors, we need to perform overload resolution. 7219 break; 7220 7221 case Sema::CXXCopyAssignment: 7222 case Sema::CXXMoveAssignment: 7223 if (!S.getLangOpts().CPlusPlus14) 7224 return false; 7225 // In C++1y, we need to perform overload resolution. 7226 Ctor = false; 7227 break; 7228 7229 case Sema::CXXDestructor: 7230 return ClassDecl->defaultedDestructorIsConstexpr(); 7231 7232 case Sema::CXXInvalid: 7233 return false; 7234 } 7235 7236 // -- if the class is a non-empty union, or for each non-empty anonymous 7237 // union member of a non-union class, exactly one non-static data member 7238 // shall be initialized; [DR1359] 7239 // 7240 // If we squint, this is guaranteed, since exactly one non-static data member 7241 // will be initialized (if the constructor isn't deleted), we just don't know 7242 // which one. 7243 if (Ctor && ClassDecl->isUnion()) 7244 return CSM == Sema::CXXDefaultConstructor 7245 ? ClassDecl->hasInClassInitializer() || 7246 !ClassDecl->hasVariantMembers() 7247 : true; 7248 7249 // -- the class shall not have any virtual base classes; 7250 if (Ctor && ClassDecl->getNumVBases()) 7251 return false; 7252 7253 // C++1y [class.copy]p26: 7254 // -- [the class] is a literal type, and 7255 if (!Ctor && !ClassDecl->isLiteral()) 7256 return false; 7257 7258 // -- every constructor involved in initializing [...] base class 7259 // sub-objects shall be a constexpr constructor; 7260 // -- the assignment operator selected to copy/move each direct base 7261 // class is a constexpr function, and 7262 for (const auto &B : ClassDecl->bases()) { 7263 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7264 if (!BaseType) continue; 7265 7266 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7267 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7268 InheritedCtor, Inherited)) 7269 return false; 7270 } 7271 7272 // -- every constructor involved in initializing non-static data members 7273 // [...] shall be a constexpr constructor; 7274 // -- every non-static data member and base class sub-object shall be 7275 // initialized 7276 // -- for each non-static data member of X that is of class type (or array 7277 // thereof), the assignment operator selected to copy/move that member is 7278 // a constexpr function 7279 for (const auto *F : ClassDecl->fields()) { 7280 if (F->isInvalidDecl()) 7281 continue; 7282 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7283 continue; 7284 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7285 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7286 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7287 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7288 BaseType.getCVRQualifiers(), 7289 ConstArg && !F->isMutable())) 7290 return false; 7291 } else if (CSM == Sema::CXXDefaultConstructor) { 7292 return false; 7293 } 7294 } 7295 7296 // All OK, it's constexpr! 7297 return true; 7298} 7299 7300namespace { 7301/// RAII object to register a defaulted function as having its exception 7302/// specification computed. 7303struct ComputingExceptionSpec { 7304 Sema &S; 7305 7306 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7307 : S(S) { 7308 Sema::CodeSynthesisContext Ctx; 7309 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7310 Ctx.PointOfInstantiation = Loc; 7311 Ctx.Entity = FD; 7312 S.pushCodeSynthesisContext(Ctx); 7313 } 7314 ~ComputingExceptionSpec() { 7315 S.popCodeSynthesisContext(); 7316 } 7317}; 7318} 7319 7320static Sema::ImplicitExceptionSpecification 7321ComputeDefaultedSpecialMemberExceptionSpec( 7322 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7323 Sema::InheritedConstructorInfo *ICI); 7324 7325static Sema::ImplicitExceptionSpecification 7326ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7327 FunctionDecl *FD, 7328 Sema::DefaultedComparisonKind DCK); 7329 7330static Sema::ImplicitExceptionSpecification 7331computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7332 auto DFK = S.getDefaultedFunctionKind(FD); 7333 if (DFK.isSpecialMember()) 7334 return ComputeDefaultedSpecialMemberExceptionSpec( 7335 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7336 if (DFK.isComparison()) 7337 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7338 DFK.asComparison()); 7339 7340 auto *CD = cast<CXXConstructorDecl>(FD); 7341 assert(CD->getInheritedConstructor() &&(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7343, __extension__ __PRETTY_FUNCTION__
))
7342 "only defaulted functions and inherited constructors have implicit "(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7343, __extension__ __PRETTY_FUNCTION__
))
7343 "exception specs")(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7343, __extension__ __PRETTY_FUNCTION__
))
; 7344 Sema::InheritedConstructorInfo ICI( 7345 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7346 return ComputeDefaultedSpecialMemberExceptionSpec( 7347 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7348} 7349 7350static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7351 CXXMethodDecl *MD) { 7352 FunctionProtoType::ExtProtoInfo EPI; 7353 7354 // Build an exception specification pointing back at this member. 7355 EPI.ExceptionSpec.Type = EST_Unevaluated; 7356 EPI.ExceptionSpec.SourceDecl = MD; 7357 7358 // Set the calling convention to the default for C++ instance methods. 7359 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7360 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7361 /*IsCXXMethod=*/true)); 7362 return EPI; 7363} 7364 7365void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7366 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7367 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7368 return; 7369 7370 // Evaluate the exception specification. 7371 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7372 auto ESI = IES.getExceptionSpec(); 7373 7374 // Update the type of the special member to use it. 7375 UpdateExceptionSpec(FD, ESI); 7376} 7377 7378void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7379 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted")(static_cast <bool> (FD->isExplicitlyDefaulted() &&
"not explicitly-defaulted") ? void (0) : __assert_fail ("FD->isExplicitlyDefaulted() && \"not explicitly-defaulted\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7379, __extension__ __PRETTY_FUNCTION__
))
; 7380 7381 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7382 if (!DefKind) { 7383 assert(FD->getDeclContext()->isDependentContext())(static_cast <bool> (FD->getDeclContext()->isDependentContext
()) ? void (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7383, __extension__ __PRETTY_FUNCTION__
))
; 7384 return; 7385 } 7386 7387 if (DefKind.isComparison()) 7388 UnusedPrivateFields.clear(); 7389 7390 if (DefKind.isSpecialMember() 7391 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7392 DefKind.asSpecialMember()) 7393 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7394 FD->setInvalidDecl(); 7395} 7396 7397bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7398 CXXSpecialMember CSM) { 7399 CXXRecordDecl *RD = MD->getParent(); 7400 7401 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7402, __extension__ __PRETTY_FUNCTION__
))
7402 "not an explicitly-defaulted special member")(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7402, __extension__ __PRETTY_FUNCTION__
))
; 7403 7404 // Defer all checking for special members of a dependent type. 7405 if (RD->isDependentType()) 7406 return false; 7407 7408 // Whether this was the first-declared instance of the constructor. 7409 // This affects whether we implicitly add an exception spec and constexpr. 7410 bool First = MD == MD->getCanonicalDecl(); 7411 7412 bool HadError = false; 7413 7414 // C++11 [dcl.fct.def.default]p1: 7415 // A function that is explicitly defaulted shall 7416 // -- be a special member function [...] (checked elsewhere), 7417 // -- have the same type (except for ref-qualifiers, and except that a 7418 // copy operation can take a non-const reference) as an implicit 7419 // declaration, and 7420 // -- not have default arguments. 7421 // C++2a changes the second bullet to instead delete the function if it's 7422 // defaulted on its first declaration, unless it's "an assignment operator, 7423 // and its return type differs or its parameter type is not a reference". 7424 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7425 bool ShouldDeleteForTypeMismatch = false; 7426 unsigned ExpectedParams = 1; 7427 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7428 ExpectedParams = 0; 7429 if (MD->getNumParams() != ExpectedParams) { 7430 // This checks for default arguments: a copy or move constructor with a 7431 // default argument is classified as a default constructor, and assignment 7432 // operations and destructors can't have default arguments. 7433 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7434 << CSM << MD->getSourceRange(); 7435 HadError = true; 7436 } else if (MD->isVariadic()) { 7437 if (DeleteOnTypeMismatch) 7438 ShouldDeleteForTypeMismatch = true; 7439 else { 7440 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7441 << CSM << MD->getSourceRange(); 7442 HadError = true; 7443 } 7444 } 7445 7446 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7447 7448 bool CanHaveConstParam = false; 7449 if (CSM == CXXCopyConstructor) 7450 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7451 else if (CSM == CXXCopyAssignment) 7452 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7453 7454 QualType ReturnType = Context.VoidTy; 7455 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7456 // Check for return type matching. 7457 ReturnType = Type->getReturnType(); 7458 7459 QualType DeclType = Context.getTypeDeclType(RD); 7460 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7461 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7462 7463 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7464 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7465 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7466 HadError = true; 7467 } 7468 7469 // A defaulted special member cannot have cv-qualifiers. 7470 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7471 if (DeleteOnTypeMismatch) 7472 ShouldDeleteForTypeMismatch = true; 7473 else { 7474 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7475 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7476 HadError = true; 7477 } 7478 } 7479 } 7480 7481 // Check for parameter type matching. 7482 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7483 bool HasConstParam = false; 7484 if (ExpectedParams && ArgType->isReferenceType()) { 7485 // Argument must be reference to possibly-const T. 7486 QualType ReferentType = ArgType->getPointeeType(); 7487 HasConstParam = ReferentType.isConstQualified(); 7488 7489 if (ReferentType.isVolatileQualified()) { 7490 if (DeleteOnTypeMismatch) 7491 ShouldDeleteForTypeMismatch = true; 7492 else { 7493 Diag(MD->getLocation(), 7494 diag::err_defaulted_special_member_volatile_param) << CSM; 7495 HadError = true; 7496 } 7497 } 7498 7499 if (HasConstParam && !CanHaveConstParam) { 7500 if (DeleteOnTypeMismatch) 7501 ShouldDeleteForTypeMismatch = true; 7502 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7503 Diag(MD->getLocation(), 7504 diag::err_defaulted_special_member_copy_const_param) 7505 << (CSM == CXXCopyAssignment); 7506 // FIXME: Explain why this special member can't be const. 7507 HadError = true; 7508 } else { 7509 Diag(MD->getLocation(), 7510 diag::err_defaulted_special_member_move_const_param) 7511 << (CSM == CXXMoveAssignment); 7512 HadError = true; 7513 } 7514 } 7515 } else if (ExpectedParams) { 7516 // A copy assignment operator can take its argument by value, but a 7517 // defaulted one cannot. 7518 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")(static_cast <bool> (CSM == CXXCopyAssignment &&
"unexpected non-ref argument") ? void (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7518, __extension__ __PRETTY_FUNCTION__
))
; 7519 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7520 HadError = true; 7521 } 7522 7523 // C++11 [dcl.fct.def.default]p2: 7524 // An explicitly-defaulted function may be declared constexpr only if it 7525 // would have been implicitly declared as constexpr, 7526 // Do not apply this rule to members of class templates, since core issue 1358 7527 // makes such functions always instantiate to constexpr functions. For 7528 // functions which cannot be constexpr (for non-constructors in C++11 and for 7529 // destructors in C++14 and C++17), this is checked elsewhere. 7530 // 7531 // FIXME: This should not apply if the member is deleted. 7532 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7533 HasConstParam); 7534 if ((getLangOpts().CPlusPlus20 || 7535 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7536 : isa<CXXConstructorDecl>(MD))) && 7537 MD->isConstexpr() && !Constexpr && 7538 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7539 Diag(MD->getBeginLoc(), MD->isConsteval() 7540 ? diag::err_incorrect_defaulted_consteval 7541 : diag::err_incorrect_defaulted_constexpr) 7542 << CSM; 7543 // FIXME: Explain why the special member can't be constexpr. 7544 HadError = true; 7545 } 7546 7547 if (First) { 7548 // C++2a [dcl.fct.def.default]p3: 7549 // If a function is explicitly defaulted on its first declaration, it is 7550 // implicitly considered to be constexpr if the implicit declaration 7551 // would be. 7552 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7553 ? ConstexprSpecKind::Consteval 7554 : ConstexprSpecKind::Constexpr) 7555 : ConstexprSpecKind::Unspecified); 7556 7557 if (!Type->hasExceptionSpec()) { 7558 // C++2a [except.spec]p3: 7559 // If a declaration of a function does not have a noexcept-specifier 7560 // [and] is defaulted on its first declaration, [...] the exception 7561 // specification is as specified below 7562 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7563 EPI.ExceptionSpec.Type = EST_Unevaluated; 7564 EPI.ExceptionSpec.SourceDecl = MD; 7565 MD->setType(Context.getFunctionType(ReturnType, 7566 llvm::makeArrayRef(&ArgType, 7567 ExpectedParams), 7568 EPI)); 7569 } 7570 } 7571 7572 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7573 if (First) { 7574 SetDeclDeleted(MD, MD->getLocation()); 7575 if (!inTemplateInstantiation() && !HadError) { 7576 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7577 if (ShouldDeleteForTypeMismatch) { 7578 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7579 } else { 7580 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7581 } 7582 } 7583 if (ShouldDeleteForTypeMismatch && !HadError) { 7584 Diag(MD->getLocation(), 7585 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7586 } 7587 } else { 7588 // C++11 [dcl.fct.def.default]p4: 7589 // [For a] user-provided explicitly-defaulted function [...] if such a 7590 // function is implicitly defined as deleted, the program is ill-formed. 7591 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7592 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")(static_cast <bool> (!ShouldDeleteForTypeMismatch &&
"deleted non-first decl") ? void (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7592, __extension__ __PRETTY_FUNCTION__
))
; 7593 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7594 HadError = true; 7595 } 7596 } 7597 7598 return HadError; 7599} 7600 7601namespace { 7602/// Helper class for building and checking a defaulted comparison. 7603/// 7604/// Defaulted functions are built in two phases: 7605/// 7606/// * First, the set of operations that the function will perform are 7607/// identified, and some of them are checked. If any of the checked 7608/// operations is invalid in certain ways, the comparison function is 7609/// defined as deleted and no body is built. 7610/// * Then, if the function is not defined as deleted, the body is built. 7611/// 7612/// This is accomplished by performing two visitation steps over the eventual 7613/// body of the function. 7614template<typename Derived, typename ResultList, typename Result, 7615 typename Subobject> 7616class DefaultedComparisonVisitor { 7617public: 7618 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7619 7620 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7621 DefaultedComparisonKind DCK) 7622 : S(S), RD(RD), FD(FD), DCK(DCK) { 7623 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7624 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7625 // UnresolvedSet to avoid this copy. 7626 Fns.assign(Info->getUnqualifiedLookups().begin(), 7627 Info->getUnqualifiedLookups().end()); 7628 } 7629 } 7630 7631 ResultList visit() { 7632 // The type of an lvalue naming a parameter of this function. 7633 QualType ParamLvalType = 7634 FD->getParamDecl(0)->getType().getNonReferenceType(); 7635 7636 ResultList Results; 7637 7638 switch (DCK) { 7639 case DefaultedComparisonKind::None: 7640 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7640)
; 7641 7642 case DefaultedComparisonKind::Equal: 7643 case DefaultedComparisonKind::ThreeWay: 7644 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7645 return Results; 7646 7647 case DefaultedComparisonKind::NotEqual: 7648 case DefaultedComparisonKind::Relational: 7649 Results.add(getDerived().visitExpandedSubobject( 7650 ParamLvalType, getDerived().getCompleteObject())); 7651 return Results; 7652 } 7653 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 7653)
; 7654 } 7655 7656protected: 7657 Derived &getDerived() { return static_cast<Derived&>(*this); } 7658 7659 /// Visit the expanded list of subobjects of the given type, as specified in 7660 /// C++2a [class.compare.default]. 7661 /// 7662 /// \return \c true if the ResultList object said we're done, \c false if not. 7663 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7664 Qualifiers Quals) { 7665 // C++2a [class.compare.default]p4: 7666 // The direct base class subobjects of C 7667 for (CXXBaseSpecifier &Base : Record->bases()) 7668 if (Results.add(getDerived().visitSubobject( 7669 S.Context.getQualifiedType(Base.getType(), Quals), 7670 getDerived().getBase(&Base)))) 7671 return true; 7672 7673 // followed by the non-static data members of C 7674 for (FieldDecl *Field : Record->fields()) { 7675 // Recursively expand anonymous structs. 7676 if (Field->isAnonymousStructOrUnion()) { 7677 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7678 Quals)) 7679 return true; 7680 continue; 7681 } 7682 7683 // Figure out the type of an lvalue denoting this field. 7684 Qualifiers FieldQuals = Quals; 7685 if (Field->isMutable()) 7686 FieldQuals.removeConst(); 7687 QualType FieldType = 7688 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7689 7690 if (Results.add(getDerived().visitSubobject( 7691 FieldType, getDerived().getField(Field)))) 7692 return true; 7693 } 7694 7695 // form a list of subobjects. 7696 return false; 7697 } 7698 7699 Result visitSubobject(QualType Type, Subobject Subobj) { 7700 // In that list, any subobject of array type is recursively expanded 7701 const ArrayType *AT = S.Context.getAsArrayType(Type); 7702 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7703 return getDerived().visitSubobjectArray(CAT->getElementType(), 7704 CAT->getSize(), Subobj); 7705 return getDerived().visitExpandedSubobject(Type, Subobj); 7706 } 7707 7708 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7709 Subobject Subobj) { 7710 return getDerived().visitSubobject(Type, Subobj); 7711 } 7712 7713protected: 7714 Sema &S; 7715 CXXRecordDecl *RD; 7716 FunctionDecl *FD; 7717 DefaultedComparisonKind DCK; 7718 UnresolvedSet<16> Fns; 7719}; 7720 7721/// Information about a defaulted comparison, as determined by 7722/// DefaultedComparisonAnalyzer. 7723struct DefaultedComparisonInfo { 7724 bool Deleted = false; 7725 bool Constexpr = true; 7726 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7727 7728 static DefaultedComparisonInfo deleted() { 7729 DefaultedComparisonInfo Deleted; 7730 Deleted.Deleted = true; 7731 return Deleted; 7732 } 7733 7734 bool add(const DefaultedComparisonInfo &R) { 7735 Deleted |= R.Deleted; 7736 Constexpr &= R.Constexpr; 7737 Category = commonComparisonType(Category, R.Category); 7738 return Deleted; 7739 } 7740}; 7741 7742/// An element in the expanded list of subobjects of a defaulted comparison, as 7743/// specified in C++2a [class.compare.default]p4. 7744struct DefaultedComparisonSubobject { 7745 enum { CompleteObject, Member, Base } Kind; 7746 NamedDecl *Decl; 7747 SourceLocation Loc; 7748}; 7749 7750/// A visitor over the notional body of a defaulted comparison that determines 7751/// whether that body would be deleted or constexpr. 7752class DefaultedComparisonAnalyzer 7753 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7754 DefaultedComparisonInfo, 7755 DefaultedComparisonInfo, 7756 DefaultedComparisonSubobject> { 7757public: 7758 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7759 7760private: 7761 DiagnosticKind Diagnose; 7762 7763public: 7764 using Base = DefaultedComparisonVisitor; 7765 using Result = DefaultedComparisonInfo; 7766 using Subobject = DefaultedComparisonSubobject; 7767 7768 friend Base; 7769 7770 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7771 DefaultedComparisonKind DCK, 7772 DiagnosticKind Diagnose = NoDiagnostics) 7773 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7774 7775 Result visit() { 7776 if ((DCK == DefaultedComparisonKind::Equal || 7777 DCK == DefaultedComparisonKind::ThreeWay) && 7778 RD->hasVariantMembers()) { 7779 // C++2a [class.compare.default]p2 [P2002R0]: 7780 // A defaulted comparison operator function for class C is defined as 7781 // deleted if [...] C has variant members. 7782 if (Diagnose == ExplainDeleted) { 7783 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7784 << FD << RD->isUnion() << RD; 7785 } 7786 return Result::deleted(); 7787 } 7788 7789 return Base::visit(); 7790 } 7791 7792private: 7793 Subobject getCompleteObject() { 7794 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7795 } 7796 7797 Subobject getBase(CXXBaseSpecifier *Base) { 7798 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7799 Base->getBaseTypeLoc()}; 7800 } 7801 7802 Subobject getField(FieldDecl *Field) { 7803 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7804 } 7805 7806 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7807 // C++2a [class.compare.default]p2 [P2002R0]: 7808 // A defaulted <=> or == operator function for class C is defined as 7809 // deleted if any non-static data member of C is of reference type 7810 if (Type->isReferenceType()) { 7811 if (Diagnose == ExplainDeleted) { 7812 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7813 << FD << RD; 7814 } 7815 return Result::deleted(); 7816 } 7817 7818 // [...] Let xi be an lvalue denoting the ith element [...] 7819 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7820 Expr *Args[] = {&Xi, &Xi}; 7821 7822 // All operators start by trying to apply that same operator recursively. 7823 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7824 assert(OO != OO_None && "not an overloaded operator!")(static_cast <bool> (OO != OO_None && "not an overloaded operator!"
) ? void (0) : __assert_fail ("OO != OO_None && \"not an overloaded operator!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7824, __extension__ __PRETTY_FUNCTION__
))
; 7825 return visitBinaryOperator(OO, Args, Subobj); 7826 } 7827 7828 Result 7829 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7830 Subobject Subobj, 7831 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7832 // Note that there is no need to consider rewritten candidates here if 7833 // we've already found there is no viable 'operator<=>' candidate (and are 7834 // considering synthesizing a '<=>' from '==' and '<'). 7835 OverloadCandidateSet CandidateSet( 7836 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7837 OverloadCandidateSet::OperatorRewriteInfo( 7838 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7839 7840 /// C++2a [class.compare.default]p1 [P2002R0]: 7841 /// [...] the defaulted function itself is never a candidate for overload 7842 /// resolution [...] 7843 CandidateSet.exclude(FD); 7844 7845 if (Args[0]->getType()->isOverloadableType()) 7846 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7847 else 7848 // FIXME: We determine whether this is a valid expression by checking to 7849 // see if there's a viable builtin operator candidate for it. That isn't 7850 // really what the rules ask us to do, but should give the right results. 7851 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7852 7853 Result R; 7854 7855 OverloadCandidateSet::iterator Best; 7856 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7857 case OR_Success: { 7858 // C++2a [class.compare.secondary]p2 [P2002R0]: 7859 // The operator function [...] is defined as deleted if [...] the 7860 // candidate selected by overload resolution is not a rewritten 7861 // candidate. 7862 if ((DCK == DefaultedComparisonKind::NotEqual || 7863 DCK == DefaultedComparisonKind::Relational) && 7864 !Best->RewriteKind) { 7865 if (Diagnose == ExplainDeleted) { 7866 if (Best->Function) { 7867 S.Diag(Best->Function->getLocation(), 7868 diag::note_defaulted_comparison_not_rewritten_callee) 7869 << FD; 7870 } else { 7871 assert(Best->Conversions.size() == 2 &&(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7874, __extension__ __PRETTY_FUNCTION__
))
7872 Best->Conversions[0].isUserDefined() &&(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7874, __extension__ __PRETTY_FUNCTION__
))
7873 "non-user-defined conversion from class to built-in "(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7874, __extension__ __PRETTY_FUNCTION__
))
7874 "comparison")(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7874, __extension__ __PRETTY_FUNCTION__
))
; 7875 S.Diag(Best->Conversions[0] 7876 .UserDefined.FoundConversionFunction.getDecl() 7877 ->getLocation(), 7878 diag::note_defaulted_comparison_not_rewritten_conversion) 7879 << FD; 7880 } 7881 } 7882 return Result::deleted(); 7883 } 7884 7885 // Throughout C++2a [class.compare]: if overload resolution does not 7886 // result in a usable function, the candidate function is defined as 7887 // deleted. This requires that we selected an accessible function. 7888 // 7889 // Note that this only considers the access of the function when named 7890 // within the type of the subobject, and not the access path for any 7891 // derived-to-base conversion. 7892 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7893 if (ArgClass && Best->FoundDecl.getDecl() && 7894 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7895 QualType ObjectType = Subobj.Kind == Subobject::Member 7896 ? Args[0]->getType() 7897 : S.Context.getRecordType(RD); 7898 if (!S.isMemberAccessibleForDeletion( 7899 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7900 Diagnose == ExplainDeleted 7901 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7902 << FD << Subobj.Kind << Subobj.Decl 7903 : S.PDiag())) 7904 return Result::deleted(); 7905 } 7906 7907 bool NeedsDeducing = 7908 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7909 7910 if (FunctionDecl *BestFD = Best->Function) { 7911 // C++2a [class.compare.default]p3 [P2002R0]: 7912 // A defaulted comparison function is constexpr-compatible if 7913 // [...] no overlod resolution performed [...] results in a 7914 // non-constexpr function. 7915 assert(!BestFD->isDeleted() && "wrong overload resolution result")(static_cast <bool> (!BestFD->isDeleted() &&
"wrong overload resolution result") ? void (0) : __assert_fail
("!BestFD->isDeleted() && \"wrong overload resolution result\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7915, __extension__ __PRETTY_FUNCTION__
))
; 7916 // If it's not constexpr, explain why not. 7917 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7918 if (Subobj.Kind != Subobject::CompleteObject) 7919 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7920 << Subobj.Kind << Subobj.Decl; 7921 S.Diag(BestFD->getLocation(), 7922 diag::note_defaulted_comparison_not_constexpr_here); 7923 // Bail out after explaining; we don't want any more notes. 7924 return Result::deleted(); 7925 } 7926 R.Constexpr &= BestFD->isConstexpr(); 7927 7928 if (NeedsDeducing) { 7929 // If any callee has an undeduced return type, deduce it now. 7930 // FIXME: It's not clear how a failure here should be handled. For 7931 // now, we produce an eager diagnostic, because that is forward 7932 // compatible with most (all?) other reasonable options. 7933 if (BestFD->getReturnType()->isUndeducedType() && 7934 S.DeduceReturnType(BestFD, FD->getLocation(), 7935 /*Diagnose=*/false)) { 7936 // Don't produce a duplicate error when asked to explain why the 7937 // comparison is deleted: we diagnosed that when initially checking 7938 // the defaulted operator. 7939 if (Diagnose == NoDiagnostics) { 7940 S.Diag( 7941 FD->getLocation(), 7942 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7943 << Subobj.Kind << Subobj.Decl; 7944 S.Diag( 7945 Subobj.Loc, 7946 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7947 << Subobj.Kind << Subobj.Decl; 7948 S.Diag(BestFD->getLocation(), 7949 diag::note_defaulted_comparison_cannot_deduce_callee) 7950 << Subobj.Kind << Subobj.Decl; 7951 } 7952 return Result::deleted(); 7953 } 7954 auto *Info = S.Context.CompCategories.lookupInfoForType( 7955 BestFD->getCallResultType()); 7956 if (!Info) { 7957 if (Diagnose == ExplainDeleted) { 7958 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7959 << Subobj.Kind << Subobj.Decl 7960 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7961 S.Diag(BestFD->getLocation(), 7962 diag::note_defaulted_comparison_cannot_deduce_callee) 7963 << Subobj.Kind << Subobj.Decl; 7964 } 7965 return Result::deleted(); 7966 } 7967 R.Category = Info->Kind; 7968 } 7969 } else { 7970 QualType T = Best->BuiltinParamTypes[0]; 7971 assert(T == Best->BuiltinParamTypes[1] &&(static_cast <bool> (T == Best->BuiltinParamTypes[1]
&& "builtin comparison for different types?") ? void
(0) : __assert_fail ("T == Best->BuiltinParamTypes[1] && \"builtin comparison for different types?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7972, __extension__ __PRETTY_FUNCTION__
))
7972 "builtin comparison for different types?")(static_cast <bool> (T == Best->BuiltinParamTypes[1]
&& "builtin comparison for different types?") ? void
(0) : __assert_fail ("T == Best->BuiltinParamTypes[1] && \"builtin comparison for different types?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7972, __extension__ __PRETTY_FUNCTION__
))
; 7973 assert(Best->BuiltinParamTypes[2].isNull() &&(static_cast <bool> (Best->BuiltinParamTypes[2].isNull
() && "invalid builtin comparison") ? void (0) : __assert_fail
("Best->BuiltinParamTypes[2].isNull() && \"invalid builtin comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7974, __extension__ __PRETTY_FUNCTION__
))
7974 "invalid builtin comparison")(static_cast <bool> (Best->BuiltinParamTypes[2].isNull
() && "invalid builtin comparison") ? void (0) : __assert_fail
("Best->BuiltinParamTypes[2].isNull() && \"invalid builtin comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7974, __extension__ __PRETTY_FUNCTION__
))
; 7975 7976 if (NeedsDeducing) { 7977 Optional<ComparisonCategoryType> Cat = 7978 getComparisonCategoryForBuiltinCmp(T); 7979 assert(Cat && "no category for builtin comparison?")(static_cast <bool> (Cat && "no category for builtin comparison?"
) ? void (0) : __assert_fail ("Cat && \"no category for builtin comparison?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7979, __extension__ __PRETTY_FUNCTION__
))
; 7980 R.Category = *Cat; 7981 } 7982 } 7983 7984 // Note that we might be rewriting to a different operator. That call is 7985 // not considered until we come to actually build the comparison function. 7986 break; 7987 } 7988 7989 case OR_Ambiguous: 7990 if (Diagnose == ExplainDeleted) { 7991 unsigned Kind = 0; 7992 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7993 Kind = OO == OO_EqualEqual ? 1 : 2; 7994 CandidateSet.NoteCandidates( 7995 PartialDiagnosticAt( 7996 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7997 << FD << Kind << Subobj.Kind << Subobj.Decl), 7998 S, OCD_AmbiguousCandidates, Args); 7999 } 8000 R = Result::deleted(); 8001 break; 8002 8003 case OR_Deleted: 8004 if (Diagnose == ExplainDeleted) { 8005 if ((DCK == DefaultedComparisonKind::NotEqual || 8006 DCK == DefaultedComparisonKind::Relational) && 8007 !Best->RewriteKind) { 8008 S.Diag(Best->Function->getLocation(), 8009 diag::note_defaulted_comparison_not_rewritten_callee) 8010 << FD; 8011 } else { 8012 S.Diag(Subobj.Loc, 8013 diag::note_defaulted_comparison_calls_deleted) 8014 << FD << Subobj.Kind << Subobj.Decl; 8015 S.NoteDeletedFunction(Best->Function); 8016 } 8017 } 8018 R = Result::deleted(); 8019 break; 8020 8021 case OR_No_Viable_Function: 8022 // If there's no usable candidate, we're done unless we can rewrite a 8023 // '<=>' in terms of '==' and '<'. 8024 if (OO == OO_Spaceship && 8025 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 8026 // For any kind of comparison category return type, we need a usable 8027 // '==' and a usable '<'. 8028 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 8029 &CandidateSet))) 8030 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 8031 break; 8032 } 8033 8034 if (Diagnose == ExplainDeleted) { 8035 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 8036 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 8037 8038 // For a three-way comparison, list both the candidates for the 8039 // original operator and the candidates for the synthesized operator. 8040 if (SpaceshipCandidates) { 8041 SpaceshipCandidates->NoteCandidates( 8042 S, Args, 8043 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8044 Args, FD->getLocation())); 8045 S.Diag(Subobj.Loc, 8046 diag::note_defaulted_comparison_no_viable_function_synthesized) 8047 << (OO == OO_EqualEqual ? 0 : 1); 8048 } 8049 8050 CandidateSet.NoteCandidates( 8051 S, Args, 8052 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8053 FD->getLocation())); 8054 } 8055 R = Result::deleted(); 8056 break; 8057 } 8058 8059 return R; 8060 } 8061}; 8062 8063/// A list of statements. 8064struct StmtListResult { 8065 bool IsInvalid = false; 8066 llvm::SmallVector<Stmt*, 16> Stmts; 8067 8068 bool add(const StmtResult &S) { 8069 IsInvalid |= S.isInvalid(); 8070 if (IsInvalid) 8071 return true; 8072 Stmts.push_back(S.get()); 8073 return false; 8074 } 8075}; 8076 8077/// A visitor over the notional body of a defaulted comparison that synthesizes 8078/// the actual body. 8079class DefaultedComparisonSynthesizer 8080 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8081 StmtListResult, StmtResult, 8082 std::pair<ExprResult, ExprResult>> { 8083 SourceLocation Loc; 8084 unsigned ArrayDepth = 0; 8085 8086public: 8087 using Base = DefaultedComparisonVisitor; 8088 using ExprPair = std::pair<ExprResult, ExprResult>; 8089 8090 friend Base; 8091 8092 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8093 DefaultedComparisonKind DCK, 8094 SourceLocation BodyLoc) 8095 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8096 8097 /// Build a suitable function body for this defaulted comparison operator. 8098 StmtResult build() { 8099 Sema::CompoundScopeRAII CompoundScope(S); 8100 8101 StmtListResult Stmts = visit(); 8102 if (Stmts.IsInvalid) 8103 return StmtError(); 8104 8105 ExprResult RetVal; 8106 switch (DCK) { 8107 case DefaultedComparisonKind::None: 8108 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8108)
; 8109 8110 case DefaultedComparisonKind::Equal: { 8111 // C++2a [class.eq]p3: 8112 // [...] compar[e] the corresponding elements [...] until the first 8113 // index i where xi == yi yields [...] false. If no such index exists, 8114 // V is true. Otherwise, V is false. 8115 // 8116 // Join the comparisons with '&&'s and return the result. Use a right 8117 // fold (traversing the conditions right-to-left), because that 8118 // short-circuits more naturally. 8119 auto OldStmts = std::move(Stmts.Stmts); 8120 Stmts.Stmts.clear(); 8121 ExprResult CmpSoFar; 8122 // Finish a particular comparison chain. 8123 auto FinishCmp = [&] { 8124 if (Expr *Prior = CmpSoFar.get()) { 8125 // Convert the last expression to 'return ...;' 8126 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8127 RetVal = CmpSoFar; 8128 // Convert any prior comparison to 'if (!(...)) return false;' 8129 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8130 return true; 8131 CmpSoFar = ExprResult(); 8132 } 8133 return false; 8134 }; 8135 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8136 Expr *E = dyn_cast<Expr>(EAsStmt); 8137 if (!E) { 8138 // Found an array comparison. 8139 if (FinishCmp() || Stmts.add(EAsStmt)) 8140 return StmtError(); 8141 continue; 8142 } 8143 8144 if (CmpSoFar.isUnset()) { 8145 CmpSoFar = E; 8146 continue; 8147 } 8148 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8149 if (CmpSoFar.isInvalid()) 8150 return StmtError(); 8151 } 8152 if (FinishCmp()) 8153 return StmtError(); 8154 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8155 // If no such index exists, V is true. 8156 if (RetVal.isUnset()) 8157 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8158 break; 8159 } 8160 8161 case DefaultedComparisonKind::ThreeWay: { 8162 // Per C++2a [class.spaceship]p3, as a fallback add: 8163 // return static_cast<R>(std::strong_ordering::equal); 8164 QualType StrongOrdering = S.CheckComparisonCategoryType( 8165 ComparisonCategoryType::StrongOrdering, Loc, 8166 Sema::ComparisonCategoryUsage::DefaultedOperator); 8167 if (StrongOrdering.isNull()) 8168 return StmtError(); 8169 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8170 .getValueInfo(ComparisonCategoryResult::Equal) 8171 ->VD; 8172 RetVal = getDecl(EqualVD); 8173 if (RetVal.isInvalid()) 8174 return StmtError(); 8175 RetVal = buildStaticCastToR(RetVal.get()); 8176 break; 8177 } 8178 8179 case DefaultedComparisonKind::NotEqual: 8180 case DefaultedComparisonKind::Relational: 8181 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8182 break; 8183 } 8184 8185 // Build the final return statement. 8186 if (RetVal.isInvalid()) 8187 return StmtError(); 8188 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8189 if (ReturnStmt.isInvalid()) 8190 return StmtError(); 8191 Stmts.Stmts.push_back(ReturnStmt.get()); 8192 8193 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8194 } 8195 8196private: 8197 ExprResult getDecl(ValueDecl *VD) { 8198 return S.BuildDeclarationNameExpr( 8199 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8200 } 8201 8202 ExprResult getParam(unsigned I) { 8203 ParmVarDecl *PD = FD->getParamDecl(I); 8204 return getDecl(PD); 8205 } 8206 8207 ExprPair getCompleteObject() { 8208 unsigned Param = 0; 8209 ExprResult LHS; 8210 if (isa<CXXMethodDecl>(FD)) { 8211 // LHS is '*this'. 8212 LHS = S.ActOnCXXThis(Loc); 8213 if (!LHS.isInvalid()) 8214 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8215 } else { 8216 LHS = getParam(Param++); 8217 } 8218 ExprResult RHS = getParam(Param++); 8219 assert(Param == FD->getNumParams())(static_cast <bool> (Param == FD->getNumParams()) ? void
(0) : __assert_fail ("Param == FD->getNumParams()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8219, __extension__ __PRETTY_FUNCTION__))
; 8220 return {LHS, RHS}; 8221 } 8222 8223 ExprPair getBase(CXXBaseSpecifier *Base) { 8224 ExprPair Obj = getCompleteObject(); 8225 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8226 return {ExprError(), ExprError()}; 8227 CXXCastPath Path = {Base}; 8228 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8229 CK_DerivedToBase, VK_LValue, &Path), 8230 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8231 CK_DerivedToBase, VK_LValue, &Path)}; 8232 } 8233 8234 ExprPair getField(FieldDecl *Field) { 8235 ExprPair Obj = getCompleteObject(); 8236 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8237 return {ExprError(), ExprError()}; 8238 8239 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8240 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8241 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8242 CXXScopeSpec(), Field, Found, NameInfo), 8243 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8244 CXXScopeSpec(), Field, Found, NameInfo)}; 8245 } 8246 8247 // FIXME: When expanding a subobject, register a note in the code synthesis 8248 // stack to say which subobject we're comparing. 8249 8250 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8251 if (Cond.isInvalid()) 8252 return StmtError(); 8253 8254 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8255 if (NotCond.isInvalid()) 8256 return StmtError(); 8257 8258 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8259 assert(!False.isInvalid() && "should never fail")(static_cast <bool> (!False.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!False.isInvalid() && \"should never fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8259, __extension__ __PRETTY_FUNCTION__
))
; 8260 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8261 if (ReturnFalse.isInvalid()) 8262 return StmtError(); 8263 8264 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8265 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8266 Sema::ConditionKind::Boolean), 8267 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8268 } 8269 8270 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8271 ExprPair Subobj) { 8272 QualType SizeType = S.Context.getSizeType(); 8273 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8274 8275 // Build 'size_t i$n = 0'. 8276 IdentifierInfo *IterationVarName = nullptr; 8277 { 8278 SmallString<8> Str; 8279 llvm::raw_svector_ostream OS(Str); 8280 OS << "i" << ArrayDepth; 8281 IterationVarName = &S.Context.Idents.get(OS.str()); 8282 } 8283 VarDecl *IterationVar = VarDecl::Create( 8284 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8285 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8286 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8287 IterationVar->setInit( 8288 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8289 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8290 8291 auto IterRef = [&] { 8292 ExprResult Ref = S.BuildDeclarationNameExpr( 8293 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8294 IterationVar); 8295 assert(!Ref.isInvalid() && "can't reference our own variable?")(static_cast <bool> (!Ref.isInvalid() && "can't reference our own variable?"
) ? void (0) : __assert_fail ("!Ref.isInvalid() && \"can't reference our own variable?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8295, __extension__ __PRETTY_FUNCTION__
))
; 8296 return Ref.get(); 8297 }; 8298 8299 // Build 'i$n != Size'. 8300 ExprResult Cond = S.CreateBuiltinBinOp( 8301 Loc, BO_NE, IterRef(), 8302 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8303 assert(!Cond.isInvalid() && "should never fail")(static_cast <bool> (!Cond.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!Cond.isInvalid() && \"should never fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8303, __extension__ __PRETTY_FUNCTION__
))
; 8304 8305 // Build '++i$n'. 8306 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8307 assert(!Inc.isInvalid() && "should never fail")(static_cast <bool> (!Inc.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!Inc.isInvalid() && \"should never fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8307, __extension__ __PRETTY_FUNCTION__
))
; 8308 8309 // Build 'a[i$n]' and 'b[i$n]'. 8310 auto Index = [&](ExprResult E) { 8311 if (E.isInvalid()) 8312 return ExprError(); 8313 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8314 }; 8315 Subobj.first = Index(Subobj.first); 8316 Subobj.second = Index(Subobj.second); 8317 8318 // Compare the array elements. 8319 ++ArrayDepth; 8320 StmtResult Substmt = visitSubobject(Type, Subobj); 8321 --ArrayDepth; 8322 8323 if (Substmt.isInvalid()) 8324 return StmtError(); 8325 8326 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8327 // For outer levels or for an 'operator<=>' we already have a suitable 8328 // statement that returns as necessary. 8329 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8330 assert(DCK == DefaultedComparisonKind::Equal &&(static_cast <bool> (DCK == DefaultedComparisonKind::Equal
&& "should have non-expression statement") ? void (0
) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8331, __extension__ __PRETTY_FUNCTION__
))
8331 "should have non-expression statement")(static_cast <bool> (DCK == DefaultedComparisonKind::Equal
&& "should have non-expression statement") ? void (0
) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8331, __extension__ __PRETTY_FUNCTION__
))
; 8332 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8333 if (Substmt.isInvalid()) 8334 return StmtError(); 8335 } 8336 8337 // Build 'for (...) ...' 8338 return S.ActOnForStmt(Loc, Loc, Init, 8339 S.ActOnCondition(nullptr, Loc, Cond.get(), 8340 Sema::ConditionKind::Boolean), 8341 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8342 Substmt.get()); 8343 } 8344 8345 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8346 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8347 return StmtError(); 8348 8349 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8350 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8351 ExprResult Op; 8352 if (Type->isOverloadableType()) 8353 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8354 Obj.second.get(), /*PerformADL=*/true, 8355 /*AllowRewrittenCandidates=*/true, FD); 8356 else 8357 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8358 if (Op.isInvalid()) 8359 return StmtError(); 8360 8361 switch (DCK) { 8362 case DefaultedComparisonKind::None: 8363 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8363)
; 8364 8365 case DefaultedComparisonKind::Equal: 8366 // Per C++2a [class.eq]p2, each comparison is individually contextually 8367 // converted to bool. 8368 Op = S.PerformContextuallyConvertToBool(Op.get()); 8369 if (Op.isInvalid()) 8370 return StmtError(); 8371 return Op.get(); 8372 8373 case DefaultedComparisonKind::ThreeWay: { 8374 // Per C++2a [class.spaceship]p3, form: 8375 // if (R cmp = static_cast<R>(op); cmp != 0) 8376 // return cmp; 8377 QualType R = FD->getReturnType(); 8378 Op = buildStaticCastToR(Op.get()); 8379 if (Op.isInvalid()) 8380 return StmtError(); 8381 8382 // R cmp = ...; 8383 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8384 VarDecl *VD = 8385 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8386 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8387 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8388 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8389 8390 // cmp != 0 8391 ExprResult VDRef = getDecl(VD); 8392 if (VDRef.isInvalid()) 8393 return StmtError(); 8394 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8395 Expr *Zero = 8396 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8397 ExprResult Comp; 8398 if (VDRef.get()->getType()->isOverloadableType()) 8399 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8400 true, FD); 8401 else 8402 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8403 if (Comp.isInvalid()) 8404 return StmtError(); 8405 Sema::ConditionResult Cond = S.ActOnCondition( 8406 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8407 if (Cond.isInvalid()) 8408 return StmtError(); 8409 8410 // return cmp; 8411 VDRef = getDecl(VD); 8412 if (VDRef.isInvalid()) 8413 return StmtError(); 8414 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8415 if (ReturnStmt.isInvalid()) 8416 return StmtError(); 8417 8418 // if (...) 8419 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8420 Loc, ReturnStmt.get(), 8421 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8422 } 8423 8424 case DefaultedComparisonKind::NotEqual: 8425 case DefaultedComparisonKind::Relational: 8426 // C++2a [class.compare.secondary]p2: 8427 // Otherwise, the operator function yields x @ y. 8428 return Op.get(); 8429 } 8430 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8430)
; 8431 } 8432 8433 /// Build "static_cast<R>(E)". 8434 ExprResult buildStaticCastToR(Expr *E) { 8435 QualType R = FD->getReturnType(); 8436 assert(!R->isUndeducedType() && "type should have been deduced already")(static_cast <bool> (!R->isUndeducedType() &&
"type should have been deduced already") ? void (0) : __assert_fail
("!R->isUndeducedType() && \"type should have been deduced already\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8436, __extension__ __PRETTY_FUNCTION__
))
; 8437 8438 // Don't bother forming a no-op cast in the common case. 8439 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8440 return E; 8441 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8442 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8443 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8444 } 8445}; 8446} 8447 8448/// Perform the unqualified lookups that might be needed to form a defaulted 8449/// comparison function for the given operator. 8450static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8451 UnresolvedSetImpl &Operators, 8452 OverloadedOperatorKind Op) { 8453 auto Lookup = [&](OverloadedOperatorKind OO) { 8454 Self.LookupOverloadedOperatorName(OO, S, Operators); 8455 }; 8456 8457 // Every defaulted operator looks up itself. 8458 Lookup(Op); 8459 // ... and the rewritten form of itself, if any. 8460 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8461 Lookup(ExtraOp); 8462 8463 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8464 // synthesize a three-way comparison from '<' and '=='. In a dependent 8465 // context, we also need to look up '==' in case we implicitly declare a 8466 // defaulted 'operator=='. 8467 if (Op == OO_Spaceship) { 8468 Lookup(OO_ExclaimEqual); 8469 Lookup(OO_Less); 8470 Lookup(OO_EqualEqual); 8471 } 8472} 8473 8474bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8475 DefaultedComparisonKind DCK) { 8476 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison")(static_cast <bool> (DCK != DefaultedComparisonKind::None
&& "not a defaulted comparison") ? void (0) : __assert_fail
("DCK != DefaultedComparisonKind::None && \"not a defaulted comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8476, __extension__ __PRETTY_FUNCTION__
))
; 8477 8478 // Perform any unqualified lookups we're going to need to default this 8479 // function. 8480 if (S) { 8481 UnresolvedSet<32> Operators; 8482 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8483 FD->getOverloadedOperator()); 8484 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8485 Context, Operators.pairs())); 8486 } 8487 8488 // C++2a [class.compare.default]p1: 8489 // A defaulted comparison operator function for some class C shall be a 8490 // non-template function declared in the member-specification of C that is 8491 // -- a non-static const member of C having one parameter of type 8492 // const C&, or 8493 // -- a friend of C having two parameters of type const C& or two 8494 // parameters of type C. 8495 8496 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8497 bool IsMethod = isa<CXXMethodDecl>(FD); 8498 if (IsMethod) { 8499 auto *MD = cast<CXXMethodDecl>(FD); 8500 assert(!MD->isStatic() && "comparison function cannot be a static member")(static_cast <bool> (!MD->isStatic() && "comparison function cannot be a static member"
) ? void (0) : __assert_fail ("!MD->isStatic() && \"comparison function cannot be a static member\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8500, __extension__ __PRETTY_FUNCTION__
))
; 8501 8502 // If we're out-of-class, this is the class we're comparing. 8503 if (!RD) 8504 RD = MD->getParent(); 8505 8506 if (!MD->isConst()) { 8507 SourceLocation InsertLoc; 8508 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8509 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8510 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8511 // corresponding defaulted 'operator<=>' already. 8512 if (!MD->isImplicit()) { 8513 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8514 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8515 } 8516 8517 // Add the 'const' to the type to recover. 8518 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8519 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8520 EPI.TypeQuals.addConst(); 8521 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8522 FPT->getParamTypes(), EPI)); 8523 } 8524 } 8525 8526 if (FD->getNumParams() != (IsMethod ? 1 : 2)) { 8527 // Let's not worry about using a variadic template pack here -- who would do 8528 // such a thing? 8529 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args) 8530 << int(IsMethod) << int(DCK); 8531 return true; 8532 } 8533 8534 const ParmVarDecl *KnownParm = nullptr; 8535 for (const ParmVarDecl *Param : FD->parameters()) { 8536 QualType ParmTy = Param->getType(); 8537 if (ParmTy->isDependentType()) 8538 continue; 8539 if (!KnownParm) { 8540 auto CTy = ParmTy; 8541 // Is it `T const &`? 8542 bool Ok = !IsMethod; 8543 QualType ExpectedTy; 8544 if (RD) 8545 ExpectedTy = Context.getRecordType(RD); 8546 if (auto *Ref = CTy->getAs<ReferenceType>()) { 8547 CTy = Ref->getPointeeType(); 8548 if (RD) 8549 ExpectedTy.addConst(); 8550 Ok = true; 8551 } 8552 8553 // Is T a class? 8554 if (!Ok) { 8555 } else if (RD) { 8556 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy)) 8557 Ok = false; 8558 } else if (auto *CRD = CTy->getAsRecordDecl()) { 8559 RD = cast<CXXRecordDecl>(CRD); 8560 } else { 8561 Ok = false; 8562 } 8563 8564 if (Ok) { 8565 KnownParm = Param; 8566 } else { 8567 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8568 // corresponding defaulted 'operator<=>' already. 8569 if (!FD->isImplicit()) { 8570 if (RD) { 8571 QualType PlainTy = Context.getRecordType(RD); 8572 QualType RefTy = 8573 Context.getLValueReferenceType(PlainTy.withConst()); 8574 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8575 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy 8576 << Param->getSourceRange(); 8577 } else { 8578 assert(!IsMethod && "should know expected type for method")(static_cast <bool> (!IsMethod && "should know expected type for method"
) ? void (0) : __assert_fail ("!IsMethod && \"should know expected type for method\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8578, __extension__ __PRETTY_FUNCTION__
))
; 8579 Diag(FD->getLocation(), 8580 diag::err_defaulted_comparison_param_unknown) 8581 << int(DCK) << ParmTy << Param->getSourceRange(); 8582 } 8583 } 8584 return true; 8585 } 8586 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) { 8587 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8588 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange() 8589 << ParmTy << Param->getSourceRange(); 8590 return true; 8591 } 8592 } 8593 8594 assert(RD && "must have determined class")(static_cast <bool> (RD && "must have determined class"
) ? void (0) : __assert_fail ("RD && \"must have determined class\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8594, __extension__ __PRETTY_FUNCTION__
))
; 8595 if (IsMethod) { 8596 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 8597 // In-class, must be a friend decl. 8598 assert(FD->getFriendObjectKind() && "expected a friend declaration")(static_cast <bool> (FD->getFriendObjectKind() &&
"expected a friend declaration") ? void (0) : __assert_fail (
"FD->getFriendObjectKind() && \"expected a friend declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8598, __extension__ __PRETTY_FUNCTION__
))
; 8599 } else { 8600 // Out of class, require the defaulted comparison to be a friend (of a 8601 // complete type). 8602 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD), 8603 diag::err_defaulted_comparison_not_friend, int(DCK), 8604 int(1))) 8605 return true; 8606 8607 if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) { 8608 return FD->getCanonicalDecl() == 8609 F->getFriendDecl()->getCanonicalDecl(); 8610 }) == RD->friends().end()) { 8611 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend) 8612 << int(DCK) << int(0) << RD; 8613 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at); 8614 return true; 8615 } 8616 } 8617 8618 // C++2a [class.eq]p1, [class.rel]p1: 8619 // A [defaulted comparison other than <=>] shall have a declared return 8620 // type bool. 8621 if (DCK != DefaultedComparisonKind::ThreeWay && 8622 !FD->getDeclaredReturnType()->isDependentType() && 8623 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8624 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8625 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8626 << FD->getReturnTypeSourceRange(); 8627 return true; 8628 } 8629 // C++2a [class.spaceship]p2 [P2002R0]: 8630 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8631 // R shall not contain a placeholder type. 8632 if (DCK == DefaultedComparisonKind::ThreeWay && 8633 FD->getDeclaredReturnType()->getContainedDeducedType() && 8634 !Context.hasSameType(FD->getDeclaredReturnType(), 8635 Context.getAutoDeductType())) { 8636 Diag(FD->getLocation(), 8637 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8638 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8639 << FD->getReturnTypeSourceRange(); 8640 return true; 8641 } 8642 8643 // For a defaulted function in a dependent class, defer all remaining checks 8644 // until instantiation. 8645 if (RD->isDependentType()) 8646 return false; 8647 8648 // Determine whether the function should be defined as deleted. 8649 DefaultedComparisonInfo Info = 8650 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8651 8652 bool First = FD == FD->getCanonicalDecl(); 8653 8654 // If we want to delete the function, then do so; there's nothing else to 8655 // check in that case. 8656 if (Info.Deleted) { 8657 if (!First) { 8658 // C++11 [dcl.fct.def.default]p4: 8659 // [For a] user-provided explicitly-defaulted function [...] if such a 8660 // function is implicitly defined as deleted, the program is ill-formed. 8661 // 8662 // This is really just a consequence of the general rule that you can 8663 // only delete a function on its first declaration. 8664 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8665 << FD->isImplicit() << (int)DCK; 8666 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8667 DefaultedComparisonAnalyzer::ExplainDeleted) 8668 .visit(); 8669 return true; 8670 } 8671 8672 SetDeclDeleted(FD, FD->getLocation()); 8673 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8674 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8675 << (int)DCK; 8676 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8677 DefaultedComparisonAnalyzer::ExplainDeleted) 8678 .visit(); 8679 } 8680 return false; 8681 } 8682 8683 // C++2a [class.spaceship]p2: 8684 // The return type is deduced as the common comparison type of R0, R1, ... 8685 if (DCK == DefaultedComparisonKind::ThreeWay && 8686 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8687 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8688 if (RetLoc.isInvalid()) 8689 RetLoc = FD->getBeginLoc(); 8690 // FIXME: Should we really care whether we have the complete type and the 8691 // 'enumerator' constants here? A forward declaration seems sufficient. 8692 QualType Cat = CheckComparisonCategoryType( 8693 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8694 if (Cat.isNull()) 8695 return true; 8696 Context.adjustDeducedFunctionResultType( 8697 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8698 } 8699 8700 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8701 // An explicitly-defaulted function that is not defined as deleted may be 8702 // declared constexpr or consteval only if it is constexpr-compatible. 8703 // C++2a [class.compare.default]p3 [P2002R0]: 8704 // A defaulted comparison function is constexpr-compatible if it satisfies 8705 // the requirements for a constexpr function [...] 8706 // The only relevant requirements are that the parameter and return types are 8707 // literal types. The remaining conditions are checked by the analyzer. 8708 if (FD->isConstexpr()) { 8709 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8710 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8711 !Info.Constexpr) { 8712 Diag(FD->getBeginLoc(), 8713 diag::err_incorrect_defaulted_comparison_constexpr) 8714 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8715 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8716 DefaultedComparisonAnalyzer::ExplainConstexpr) 8717 .visit(); 8718 } 8719 } 8720 8721 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8722 // If a constexpr-compatible function is explicitly defaulted on its first 8723 // declaration, it is implicitly considered to be constexpr. 8724 // FIXME: Only applying this to the first declaration seems problematic, as 8725 // simple reorderings can affect the meaning of the program. 8726 if (First && !FD->isConstexpr() && Info.Constexpr) 8727 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8728 8729 // C++2a [except.spec]p3: 8730 // If a declaration of a function does not have a noexcept-specifier 8731 // [and] is defaulted on its first declaration, [...] the exception 8732 // specification is as specified below 8733 if (FD->getExceptionSpecType() == EST_None) { 8734 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8735 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8736 EPI.ExceptionSpec.Type = EST_Unevaluated; 8737 EPI.ExceptionSpec.SourceDecl = FD; 8738 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8739 FPT->getParamTypes(), EPI)); 8740 } 8741 8742 return false; 8743} 8744 8745void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8746 FunctionDecl *Spaceship) { 8747 Sema::CodeSynthesisContext Ctx; 8748 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8749 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8750 Ctx.Entity = Spaceship; 8751 pushCodeSynthesisContext(Ctx); 8752 8753 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8754 EqualEqual->setImplicit(); 8755 8756 popCodeSynthesisContext(); 8757} 8758 8759void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8760 DefaultedComparisonKind DCK) { 8761 assert(FD->isDefaulted() && !FD->isDeleted() &&(static_cast <bool> (FD->isDefaulted() && !FD
->isDeleted() && !FD->doesThisDeclarationHaveABody
()) ? void (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8762, __extension__ __PRETTY_FUNCTION__
))
8762 !FD->doesThisDeclarationHaveABody())(static_cast <bool> (FD->isDefaulted() && !FD
->isDeleted() && !FD->doesThisDeclarationHaveABody
()) ? void (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8762, __extension__ __PRETTY_FUNCTION__
))
; 8763 if (FD->willHaveBody() || FD->isInvalidDecl()) 8764 return; 8765 8766 SynthesizedFunctionScope Scope(*this, FD); 8767 8768 // Add a context note for diagnostics produced after this point. 8769 Scope.addContextNote(UseLoc); 8770 8771 { 8772 // Build and set up the function body. 8773 // The first parameter has type maybe-ref-to maybe-const T, use that to get 8774 // the type of the class being compared. 8775 auto PT = FD->getParamDecl(0)->getType(); 8776 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl(); 8777 SourceLocation BodyLoc = 8778 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8779 StmtResult Body = 8780 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8781 if (Body.isInvalid()) { 8782 FD->setInvalidDecl(); 8783 return; 8784 } 8785 FD->setBody(Body.get()); 8786 FD->markUsed(Context); 8787 } 8788 8789 // The exception specification is needed because we are defining the 8790 // function. Note that this will reuse the body we just built. 8791 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8792 8793 if (ASTMutationListener *L = getASTMutationListener()) 8794 L->CompletedImplicitDefinition(FD); 8795} 8796 8797static Sema::ImplicitExceptionSpecification 8798ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8799 FunctionDecl *FD, 8800 Sema::DefaultedComparisonKind DCK) { 8801 ComputingExceptionSpec CES(S, FD, Loc); 8802 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8803 8804 if (FD->isInvalidDecl()) 8805 return ExceptSpec; 8806 8807 // The common case is that we just defined the comparison function. In that 8808 // case, just look at whether the body can throw. 8809 if (FD->hasBody()) { 8810 ExceptSpec.CalledStmt(FD->getBody()); 8811 } else { 8812 // Otherwise, build a body so we can check it. This should ideally only 8813 // happen when we're not actually marking the function referenced. (This is 8814 // only really important for efficiency: we don't want to build and throw 8815 // away bodies for comparison functions more than we strictly need to.) 8816 8817 // Pretend to synthesize the function body in an unevaluated context. 8818 // Note that we can't actually just go ahead and define the function here: 8819 // we are not permitted to mark its callees as referenced. 8820 Sema::SynthesizedFunctionScope Scope(S, FD); 8821 EnterExpressionEvaluationContext Context( 8822 S, Sema::ExpressionEvaluationContext::Unevaluated); 8823 8824 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8825 SourceLocation BodyLoc = 8826 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8827 StmtResult Body = 8828 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8829 if (!Body.isInvalid()) 8830 ExceptSpec.CalledStmt(Body.get()); 8831 8832 // FIXME: Can we hold onto this body and just transform it to potentially 8833 // evaluated when we're asked to define the function rather than rebuilding 8834 // it? Either that, or we should only build the bits of the body that we 8835 // need (the expressions, not the statements). 8836 } 8837 8838 return ExceptSpec; 8839} 8840 8841void Sema::CheckDelayedMemberExceptionSpecs() { 8842 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8843 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8844 8845 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8846 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8847 8848 // Perform any deferred checking of exception specifications for virtual 8849 // destructors. 8850 for (auto &Check : Overriding) 8851 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8852 8853 // Perform any deferred checking of exception specifications for befriended 8854 // special members. 8855 for (auto &Check : Equivalent) 8856 CheckEquivalentExceptionSpec(Check.second, Check.first); 8857} 8858 8859namespace { 8860/// CRTP base class for visiting operations performed by a special member 8861/// function (or inherited constructor). 8862template<typename Derived> 8863struct SpecialMemberVisitor { 8864 Sema &S; 8865 CXXMethodDecl *MD; 8866 Sema::CXXSpecialMember CSM; 8867 Sema::InheritedConstructorInfo *ICI; 8868 8869 // Properties of the special member, computed for convenience. 8870 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8871 8872 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8873 Sema::InheritedConstructorInfo *ICI) 8874 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8875 switch (CSM) { 8876 case Sema::CXXDefaultConstructor: 8877 case Sema::CXXCopyConstructor: 8878 case Sema::CXXMoveConstructor: 8879 IsConstructor = true; 8880 break; 8881 case Sema::CXXCopyAssignment: 8882 case Sema::CXXMoveAssignment: 8883 IsAssignment = true; 8884 break; 8885 case Sema::CXXDestructor: 8886 break; 8887 case Sema::CXXInvalid: 8888 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8888)
; 8889 } 8890 8891 if (MD->getNumParams()) { 8892 if (const ReferenceType *RT = 8893 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8894 ConstArg = RT->getPointeeType().isConstQualified(); 8895 } 8896 } 8897 8898 Derived &getDerived() { return static_cast<Derived&>(*this); } 8899 8900 /// Is this a "move" special member? 8901 bool isMove() const { 8902 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8903 } 8904 8905 /// Look up the corresponding special member in the given class. 8906 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8907 unsigned Quals, bool IsMutable) { 8908 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8909 ConstArg && !IsMutable); 8910 } 8911 8912 /// Look up the constructor for the specified base class to see if it's 8913 /// overridden due to this being an inherited constructor. 8914 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8915 if (!ICI) 8916 return {}; 8917 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8917, __extension__ __PRETTY_FUNCTION__
))
; 8918 auto *BaseCtor = 8919 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8920 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8921 return MD; 8922 return {}; 8923 } 8924 8925 /// A base or member subobject. 8926 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8927 8928 /// Get the location to use for a subobject in diagnostics. 8929 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8930 // FIXME: For an indirect virtual base, the direct base leading to 8931 // the indirect virtual base would be a more useful choice. 8932 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8933 return B->getBaseTypeLoc(); 8934 else 8935 return Subobj.get<FieldDecl*>()->getLocation(); 8936 } 8937 8938 enum BasesToVisit { 8939 /// Visit all non-virtual (direct) bases. 8940 VisitNonVirtualBases, 8941 /// Visit all direct bases, virtual or not. 8942 VisitDirectBases, 8943 /// Visit all non-virtual bases, and all virtual bases if the class 8944 /// is not abstract. 8945 VisitPotentiallyConstructedBases, 8946 /// Visit all direct or virtual bases. 8947 VisitAllBases 8948 }; 8949 8950 // Visit the bases and members of the class. 8951 bool visit(BasesToVisit Bases) { 8952 CXXRecordDecl *RD = MD->getParent(); 8953 8954 if (Bases == VisitPotentiallyConstructedBases) 8955 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8956 8957 for (auto &B : RD->bases()) 8958 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8959 getDerived().visitBase(&B)) 8960 return true; 8961 8962 if (Bases == VisitAllBases) 8963 for (auto &B : RD->vbases()) 8964 if (getDerived().visitBase(&B)) 8965 return true; 8966 8967 for (auto *F : RD->fields()) 8968 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8969 getDerived().visitField(F)) 8970 return true; 8971 8972 return false; 8973 } 8974}; 8975} 8976 8977namespace { 8978struct SpecialMemberDeletionInfo 8979 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8980 bool Diagnose; 8981 8982 SourceLocation Loc; 8983 8984 bool AllFieldsAreConst; 8985 8986 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8987 Sema::CXXSpecialMember CSM, 8988 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8989 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8990 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8991 8992 bool inUnion() const { return MD->getParent()->isUnion(); } 8993 8994 Sema::CXXSpecialMember getEffectiveCSM() { 8995 return ICI ? Sema::CXXInvalid : CSM; 8996 } 8997 8998 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8999 9000 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 9001 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 9002 9003 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 9004 bool shouldDeleteForField(FieldDecl *FD); 9005 bool shouldDeleteForAllConstMembers(); 9006 9007 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 9008 unsigned Quals); 9009 bool shouldDeleteForSubobjectCall(Subobject Subobj, 9010 Sema::SpecialMemberOverloadResult SMOR, 9011 bool IsDtorCallInCtor); 9012 9013 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 9014}; 9015} 9016 9017/// Is the given special member inaccessible when used on the given 9018/// sub-object. 9019bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 9020 CXXMethodDecl *target) { 9021 /// If we're operating on a base class, the object type is the 9022 /// type of this special member. 9023 QualType objectTy; 9024 AccessSpecifier access = target->getAccess(); 9025 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 9026 objectTy = S.Context.getTypeDeclType(MD->getParent()); 9027 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 9028 9029 // If we're operating on a field, the object type is the type of the field. 9030 } else { 9031 objectTy = S.Context.getTypeDeclType(target->getParent()); 9032 } 9033 9034 return S.isMemberAccessibleForDeletion( 9035 target->getParent(), DeclAccessPair::make(target, access), objectTy); 9036} 9037 9038/// Check whether we should delete a special member due to the implicit 9039/// definition containing a call to a special member of a subobject. 9040bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 9041 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 9042 bool IsDtorCallInCtor) { 9043 CXXMethodDecl *Decl = SMOR.getMethod(); 9044 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9045 9046 int DiagKind = -1; 9047 9048 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 9049 DiagKind = !Decl ? 0 : 1; 9050 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9051 DiagKind = 2; 9052 else if (!isAccessible(Subobj, Decl)) 9053 DiagKind = 3; 9054 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 9055 !Decl->isTrivial()) { 9056 // A member of a union must have a trivial corresponding special member. 9057 // As a weird special case, a destructor call from a union's constructor 9058 // must be accessible and non-deleted, but need not be trivial. Such a 9059 // destructor is never actually called, but is semantically checked as 9060 // if it were. 9061 DiagKind = 4; 9062 } 9063 9064 if (DiagKind == -1) 9065 return false; 9066 9067 if (Diagnose) { 9068 if (Field) { 9069 S.Diag(Field->getLocation(), 9070 diag::note_deleted_special_member_class_subobject) 9071 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 9072 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 9073 } else { 9074 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 9075 S.Diag(Base->getBeginLoc(), 9076 diag::note_deleted_special_member_class_subobject) 9077 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9078 << Base->getType() << DiagKind << IsDtorCallInCtor 9079 << /*IsObjCPtr*/false; 9080 } 9081 9082 if (DiagKind == 1) 9083 S.NoteDeletedFunction(Decl); 9084 // FIXME: Explain inaccessibility if DiagKind == 3. 9085 } 9086 9087 return true; 9088} 9089 9090/// Check whether we should delete a special member function due to having a 9091/// direct or virtual base class or non-static data member of class type M. 9092bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 9093 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 9094 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9095 bool IsMutable = Field && Field->isMutable(); 9096 9097 // C++11 [class.ctor]p5: 9098 // -- any direct or virtual base class, or non-static data member with no 9099 // brace-or-equal-initializer, has class type M (or array thereof) and 9100 // either M has no default constructor or overload resolution as applied 9101 // to M's default constructor results in an ambiguity or in a function 9102 // that is deleted or inaccessible 9103 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9104 // -- a direct or virtual base class B that cannot be copied/moved because 9105 // overload resolution, as applied to B's corresponding special member, 9106 // results in an ambiguity or a function that is deleted or inaccessible 9107 // from the defaulted special member 9108 // C++11 [class.dtor]p5: 9109 // -- any direct or virtual base class [...] has a type with a destructor 9110 // that is deleted or inaccessible 9111 if (!(CSM == Sema::CXXDefaultConstructor && 9112 Field && Field->hasInClassInitializer()) && 9113 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9114 false)) 9115 return true; 9116 9117 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9118 // -- any direct or virtual base class or non-static data member has a 9119 // type with a destructor that is deleted or inaccessible 9120 if (IsConstructor) { 9121 Sema::SpecialMemberOverloadResult SMOR = 9122 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9123 false, false, false, false, false); 9124 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9125 return true; 9126 } 9127 9128 return false; 9129} 9130 9131bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9132 FieldDecl *FD, QualType FieldType) { 9133 // The defaulted special functions are defined as deleted if this is a variant 9134 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9135 // type under ARC. 9136 if (!FieldType.hasNonTrivialObjCLifetime()) 9137 return false; 9138 9139 // Don't make the defaulted default constructor defined as deleted if the 9140 // member has an in-class initializer. 9141 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9142 return false; 9143 9144 if (Diagnose) { 9145 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9146 S.Diag(FD->getLocation(), 9147 diag::note_deleted_special_member_class_subobject) 9148 << getEffectiveCSM() << ParentClass << /*IsField*/true 9149 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9150 } 9151 9152 return true; 9153} 9154 9155/// Check whether we should delete a special member function due to the class 9156/// having a particular direct or virtual base class. 9157bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9158 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9159 // If program is correct, BaseClass cannot be null, but if it is, the error 9160 // must be reported elsewhere. 9161 if (!BaseClass) 9162 return false; 9163 // If we have an inheriting constructor, check whether we're calling an 9164 // inherited constructor instead of a default constructor. 9165 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9166 if (auto *BaseCtor = SMOR.getMethod()) { 9167 // Note that we do not check access along this path; other than that, 9168 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9169 // FIXME: Check that the base has a usable destructor! Sink this into 9170 // shouldDeleteForClassSubobject. 9171 if (BaseCtor->isDeleted() && Diagnose) { 9172 S.Diag(Base->getBeginLoc(), 9173 diag::note_deleted_special_member_class_subobject) 9174 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9175 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9176 << /*IsObjCPtr*/false; 9177 S.NoteDeletedFunction(BaseCtor); 9178 } 9179 return BaseCtor->isDeleted(); 9180 } 9181 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9182} 9183 9184/// Check whether we should delete a special member function due to the class 9185/// having a particular non-static data member. 9186bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9187 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9188 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9189 9190 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9191 return true; 9192 9193 if (CSM == Sema::CXXDefaultConstructor) { 9194 // For a default constructor, all references must be initialized in-class 9195 // and, if a union, it must have a non-const member. 9196 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9197 if (Diagnose) 9198 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9199 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9200 return true; 9201 } 9202 // C++11 [class.ctor]p5: any non-variant non-static data member of 9203 // const-qualified type (or array thereof) with no 9204 // brace-or-equal-initializer does not have a user-provided default 9205 // constructor. 9206 if (!inUnion() && FieldType.isConstQualified() && 9207 !FD->hasInClassInitializer() && 9208 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9209 if (Diagnose) 9210 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9211 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9212 return true; 9213 } 9214 9215 if (inUnion() && !FieldType.isConstQualified()) 9216 AllFieldsAreConst = false; 9217 } else if (CSM == Sema::CXXCopyConstructor) { 9218 // For a copy constructor, data members must not be of rvalue reference 9219 // type. 9220 if (FieldType->isRValueReferenceType()) { 9221 if (Diagnose) 9222 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9223 << MD->getParent() << FD << FieldType; 9224 return true; 9225 } 9226 } else if (IsAssignment) { 9227 // For an assignment operator, data members must not be of reference type. 9228 if (FieldType->isReferenceType()) { 9229 if (Diagnose) 9230 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9231 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9232 return true; 9233 } 9234 if (!FieldRecord && FieldType.isConstQualified()) { 9235 // C++11 [class.copy]p23: 9236 // -- a non-static data member of const non-class type (or array thereof) 9237 if (Diagnose) 9238 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9239 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9240 return true; 9241 } 9242 } 9243 9244 if (FieldRecord) { 9245 // Some additional restrictions exist on the variant members. 9246 if (!inUnion() && FieldRecord->isUnion() && 9247 FieldRecord->isAnonymousStructOrUnion()) { 9248 bool AllVariantFieldsAreConst = true; 9249 9250 // FIXME: Handle anonymous unions declared within anonymous unions. 9251 for (auto *UI : FieldRecord->fields()) { 9252 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9253 9254 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9255 return true; 9256 9257 if (!UnionFieldType.isConstQualified()) 9258 AllVariantFieldsAreConst = false; 9259 9260 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9261 if (UnionFieldRecord && 9262 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9263 UnionFieldType.getCVRQualifiers())) 9264 return true; 9265 } 9266 9267 // At least one member in each anonymous union must be non-const 9268 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9269 !FieldRecord->field_empty()) { 9270 if (Diagnose) 9271 S.Diag(FieldRecord->getLocation(), 9272 diag::note_deleted_default_ctor_all_const) 9273 << !!ICI << MD->getParent() << /*anonymous union*/1; 9274 return true; 9275 } 9276 9277 // Don't check the implicit member of the anonymous union type. 9278 // This is technically non-conformant but supported, and we have a 9279 // diagnostic for this elsewhere. 9280 return false; 9281 } 9282 9283 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9284 FieldType.getCVRQualifiers())) 9285 return true; 9286 } 9287 9288 return false; 9289} 9290 9291/// C++11 [class.ctor] p5: 9292/// A defaulted default constructor for a class X is defined as deleted if 9293/// X is a union and all of its variant members are of const-qualified type. 9294bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9295 // This is a silly definition, because it gives an empty union a deleted 9296 // default constructor. Don't do that. 9297 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9298 bool AnyFields = false; 9299 for (auto *F : MD->getParent()->fields()) 9300 if ((AnyFields = !F->isUnnamedBitfield())) 9301 break; 9302 if (!AnyFields) 9303 return false; 9304 if (Diagnose) 9305 S.Diag(MD->getParent()->getLocation(), 9306 diag::note_deleted_default_ctor_all_const) 9307 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9308 return true; 9309 } 9310 return false; 9311} 9312 9313/// Determine whether a defaulted special member function should be defined as 9314/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9315/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9316bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9317 InheritedConstructorInfo *ICI, 9318 bool Diagnose) { 9319 if (MD->isInvalidDecl()) 9320 return false; 9321 CXXRecordDecl *RD = MD->getParent(); 9322 assert(!RD->isDependentType() && "do deletion after instantiation")(static_cast <bool> (!RD->isDependentType() &&
"do deletion after instantiation") ? void (0) : __assert_fail
("!RD->isDependentType() && \"do deletion after instantiation\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9322, __extension__ __PRETTY_FUNCTION__
))
; 9323 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9324 return false; 9325 9326 // C++11 [expr.lambda.prim]p19: 9327 // The closure type associated with a lambda-expression has a 9328 // deleted (8.4.3) default constructor and a deleted copy 9329 // assignment operator. 9330 // C++2a adds back these operators if the lambda has no lambda-capture. 9331 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9332 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9333 if (Diagnose) 9334 Diag(RD->getLocation(), diag::note_lambda_decl); 9335 return true; 9336 } 9337 9338 // For an anonymous struct or union, the copy and assignment special members 9339 // will never be used, so skip the check. For an anonymous union declared at 9340 // namespace scope, the constructor and destructor are used. 9341 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9342 RD->isAnonymousStructOrUnion()) 9343 return false; 9344 9345 // C++11 [class.copy]p7, p18: 9346 // If the class definition declares a move constructor or move assignment 9347 // operator, an implicitly declared copy constructor or copy assignment 9348 // operator is defined as deleted. 9349 if (MD->isImplicit() && 9350 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9351 CXXMethodDecl *UserDeclaredMove = nullptr; 9352 9353 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9354 // deletion of the corresponding copy operation, not both copy operations. 9355 // MSVC 2015 has adopted the standards conforming behavior. 9356 bool DeletesOnlyMatchingCopy = 9357 getLangOpts().MSVCCompat && 9358 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9359 9360 if (RD->hasUserDeclaredMoveConstructor() && 9361 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9362 if (!Diagnose) return true; 9363 9364 // Find any user-declared move constructor. 9365 for (auto *I : RD->ctors()) { 9366 if (I->isMoveConstructor()) { 9367 UserDeclaredMove = I; 9368 break; 9369 } 9370 } 9371 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9371,
__extension__ __PRETTY_FUNCTION__))
; 9372 } else if (RD->hasUserDeclaredMoveAssignment() && 9373 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9374 if (!Diagnose) return true; 9375 9376 // Find any user-declared move assignment operator. 9377 for (auto *I : RD->methods()) { 9378 if (I->isMoveAssignmentOperator()) { 9379 UserDeclaredMove = I; 9380 break; 9381 } 9382 } 9383 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9383,
__extension__ __PRETTY_FUNCTION__))
; 9384 } 9385 9386 if (UserDeclaredMove) { 9387 Diag(UserDeclaredMove->getLocation(), 9388 diag::note_deleted_copy_user_declared_move) 9389 << (CSM == CXXCopyAssignment) << RD 9390 << UserDeclaredMove->isMoveAssignmentOperator(); 9391 return true; 9392 } 9393 } 9394 9395 // Do access control from the special member function 9396 ContextRAII MethodContext(*this, MD); 9397 9398 // C++11 [class.dtor]p5: 9399 // -- for a virtual destructor, lookup of the non-array deallocation function 9400 // results in an ambiguity or in a function that is deleted or inaccessible 9401 if (CSM == CXXDestructor && MD->isVirtual()) { 9402 FunctionDecl *OperatorDelete = nullptr; 9403 DeclarationName Name = 9404 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9405 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9406 OperatorDelete, /*Diagnose*/false)) { 9407 if (Diagnose) 9408 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9409 return true; 9410 } 9411 } 9412 9413 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9414 9415 // Per DR1611, do not consider virtual bases of constructors of abstract 9416 // classes, since we are not going to construct them. 9417 // Per DR1658, do not consider virtual bases of destructors of abstract 9418 // classes either. 9419 // Per DR2180, for assignment operators we only assign (and thus only 9420 // consider) direct bases. 9421 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9422 : SMI.VisitPotentiallyConstructedBases)) 9423 return true; 9424 9425 if (SMI.shouldDeleteForAllConstMembers()) 9426 return true; 9427 9428 if (getLangOpts().CUDA) { 9429 // We should delete the special member in CUDA mode if target inference 9430 // failed. 9431 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9432 // is treated as certain special member, which may not reflect what special 9433 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9434 // expects CSM to match MD, therefore recalculate CSM. 9435 assert(ICI || CSM == getSpecialMember(MD))(static_cast <bool> (ICI || CSM == getSpecialMember(MD)
) ? void (0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9435, __extension__ __PRETTY_FUNCTION__
))
; 9436 auto RealCSM = CSM; 9437 if (ICI) 9438 RealCSM = getSpecialMember(MD); 9439 9440 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9441 SMI.ConstArg, Diagnose); 9442 } 9443 9444 return false; 9445} 9446 9447void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9448 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9449 assert(DFK && "not a defaultable function")(static_cast <bool> (DFK && "not a defaultable function"
) ? void (0) : __assert_fail ("DFK && \"not a defaultable function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9449, __extension__ __PRETTY_FUNCTION__
))
; 9450 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted")(static_cast <bool> (FD->isDefaulted() && FD
->isDeleted() && "not defaulted and deleted") ? void
(0) : __assert_fail ("FD->isDefaulted() && FD->isDeleted() && \"not defaulted and deleted\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9450, __extension__ __PRETTY_FUNCTION__
))
; 9451 9452 if (DFK.isSpecialMember()) { 9453 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9454 nullptr, /*Diagnose=*/true); 9455 } else { 9456 DefaultedComparisonAnalyzer( 9457 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9458 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9459 .visit(); 9460 } 9461} 9462 9463/// Perform lookup for a special member of the specified kind, and determine 9464/// whether it is trivial. If the triviality can be determined without the 9465/// lookup, skip it. This is intended for use when determining whether a 9466/// special member of a containing object is trivial, and thus does not ever 9467/// perform overload resolution for default constructors. 9468/// 9469/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9470/// member that was most likely to be intended to be trivial, if any. 9471/// 9472/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9473/// determine whether the special member is trivial. 9474static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9475 Sema::CXXSpecialMember CSM, unsigned Quals, 9476 bool ConstRHS, 9477 Sema::TrivialABIHandling TAH, 9478 CXXMethodDecl **Selected) { 9479 if (Selected) 9480 *Selected = nullptr; 9481 9482 switch (CSM) { 9483 case Sema::CXXInvalid: 9484 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9484)
; 9485 9486 case Sema::CXXDefaultConstructor: 9487 // C++11 [class.ctor]p5: 9488 // A default constructor is trivial if: 9489 // - all the [direct subobjects] have trivial default constructors 9490 // 9491 // Note, no overload resolution is performed in this case. 9492 if (RD->hasTrivialDefaultConstructor()) 9493 return true; 9494 9495 if (Selected) { 9496 // If there's a default constructor which could have been trivial, dig it 9497 // out. Otherwise, if there's any user-provided default constructor, point 9498 // to that as an example of why there's not a trivial one. 9499 CXXConstructorDecl *DefCtor = nullptr; 9500 if (RD->needsImplicitDefaultConstructor()) 9501 S.DeclareImplicitDefaultConstructor(RD); 9502 for (auto *CI : RD->ctors()) { 9503 if (!CI->isDefaultConstructor()) 9504 continue; 9505 DefCtor = CI; 9506 if (!DefCtor->isUserProvided()) 9507 break; 9508 } 9509 9510 *Selected = DefCtor; 9511 } 9512 9513 return false; 9514 9515 case Sema::CXXDestructor: 9516 // C++11 [class.dtor]p5: 9517 // A destructor is trivial if: 9518 // - all the direct [subobjects] have trivial destructors 9519 if (RD->hasTrivialDestructor() || 9520 (TAH == Sema::TAH_ConsiderTrivialABI && 9521 RD->hasTrivialDestructorForCall())) 9522 return true; 9523 9524 if (Selected) { 9525 if (RD->needsImplicitDestructor()) 9526 S.DeclareImplicitDestructor(RD); 9527 *Selected = RD->getDestructor(); 9528 } 9529 9530 return false; 9531 9532 case Sema::CXXCopyConstructor: 9533 // C++11 [class.copy]p12: 9534 // A copy constructor is trivial if: 9535 // - the constructor selected to copy each direct [subobject] is trivial 9536 if (RD->hasTrivialCopyConstructor() || 9537 (TAH == Sema::TAH_ConsiderTrivialABI && 9538 RD->hasTrivialCopyConstructorForCall())) { 9539 if (Quals == Qualifiers::Const) 9540 // We must either select the trivial copy constructor or reach an 9541 // ambiguity; no need to actually perform overload resolution. 9542 return true; 9543 } else if (!Selected) { 9544 return false; 9545 } 9546 // In C++98, we are not supposed to perform overload resolution here, but we 9547 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9548 // cases like B as having a non-trivial copy constructor: 9549 // struct A { template<typename T> A(T&); }; 9550 // struct B { mutable A a; }; 9551 goto NeedOverloadResolution; 9552 9553 case Sema::CXXCopyAssignment: 9554 // C++11 [class.copy]p25: 9555 // A copy assignment operator is trivial if: 9556 // - the assignment operator selected to copy each direct [subobject] is 9557 // trivial 9558 if (RD->hasTrivialCopyAssignment()) { 9559 if (Quals == Qualifiers::Const) 9560 return true; 9561 } else if (!Selected) { 9562 return false; 9563 } 9564 // In C++98, we are not supposed to perform overload resolution here, but we 9565 // treat that as a language defect. 9566 goto NeedOverloadResolution; 9567 9568 case Sema::CXXMoveConstructor: 9569 case Sema::CXXMoveAssignment: 9570 NeedOverloadResolution: 9571 Sema::SpecialMemberOverloadResult SMOR = 9572 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9573 9574 // The standard doesn't describe how to behave if the lookup is ambiguous. 9575 // We treat it as not making the member non-trivial, just like the standard 9576 // mandates for the default constructor. This should rarely matter, because 9577 // the member will also be deleted. 9578 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9579 return true; 9580 9581 if (!SMOR.getMethod()) { 9582 assert(SMOR.getKind() ==(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9583, __extension__ __PRETTY_FUNCTION__
))
9583 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9583, __extension__ __PRETTY_FUNCTION__
))
; 9584 return false; 9585 } 9586 9587 // We deliberately don't check if we found a deleted special member. We're 9588 // not supposed to! 9589 if (Selected) 9590 *Selected = SMOR.getMethod(); 9591 9592 if (TAH == Sema::TAH_ConsiderTrivialABI && 9593 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9594 return SMOR.getMethod()->isTrivialForCall(); 9595 return SMOR.getMethod()->isTrivial(); 9596 } 9597 9598 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9598)
; 9599} 9600 9601static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9602 for (auto *CI : RD->ctors()) 9603 if (!CI->isImplicit()) 9604 return CI; 9605 9606 // Look for constructor templates. 9607 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9608 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9609 if (CXXConstructorDecl *CD = 9610 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9611 return CD; 9612 } 9613 9614 return nullptr; 9615} 9616 9617/// The kind of subobject we are checking for triviality. The values of this 9618/// enumeration are used in diagnostics. 9619enum TrivialSubobjectKind { 9620 /// The subobject is a base class. 9621 TSK_BaseClass, 9622 /// The subobject is a non-static data member. 9623 TSK_Field, 9624 /// The object is actually the complete object. 9625 TSK_CompleteObject 9626}; 9627 9628/// Check whether the special member selected for a given type would be trivial. 9629static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9630 QualType SubType, bool ConstRHS, 9631 Sema::CXXSpecialMember CSM, 9632 TrivialSubobjectKind Kind, 9633 Sema::TrivialABIHandling TAH, bool Diagnose) { 9634 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9635 if (!SubRD) 9636 return true; 9637 9638 CXXMethodDecl *Selected; 9639 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9640 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9641 return true; 9642 9643 if (Diagnose) { 9644 if (ConstRHS) 9645 SubType.addConst(); 9646 9647 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9648 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9649 << Kind << SubType.getUnqualifiedType(); 9650 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9651 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9652 } else if (!Selected) 9653 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9654 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9655 else if (Selected->isUserProvided()) { 9656 if (Kind == TSK_CompleteObject) 9657 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9658 << Kind << SubType.getUnqualifiedType() << CSM; 9659 else { 9660 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9661 << Kind << SubType.getUnqualifiedType() << CSM; 9662 S.Diag(Selected->getLocation(), diag::note_declared_at); 9663 } 9664 } else { 9665 if (Kind != TSK_CompleteObject) 9666 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9667 << Kind << SubType.getUnqualifiedType() << CSM; 9668 9669 // Explain why the defaulted or deleted special member isn't trivial. 9670 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9671 Diagnose); 9672 } 9673 } 9674 9675 return false; 9676} 9677 9678/// Check whether the members of a class type allow a special member to be 9679/// trivial. 9680static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9681 Sema::CXXSpecialMember CSM, 9682 bool ConstArg, 9683 Sema::TrivialABIHandling TAH, 9684 bool Diagnose) { 9685 for (const auto *FI : RD->fields()) { 9686 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9687 continue; 9688 9689 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9690 9691 // Pretend anonymous struct or union members are members of this class. 9692 if (FI->isAnonymousStructOrUnion()) { 9693 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9694 CSM, ConstArg, TAH, Diagnose)) 9695 return false; 9696 continue; 9697 } 9698 9699 // C++11 [class.ctor]p5: 9700 // A default constructor is trivial if [...] 9701 // -- no non-static data member of its class has a 9702 // brace-or-equal-initializer 9703 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9704 if (Diagnose) 9705 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9706 << FI; 9707 return false; 9708 } 9709 9710 // Objective C ARC 4.3.5: 9711 // [...] nontrivally ownership-qualified types are [...] not trivially 9712 // default constructible, copy constructible, move constructible, copy 9713 // assignable, move assignable, or destructible [...] 9714 if (FieldType.hasNonTrivialObjCLifetime()) { 9715 if (Diagnose) 9716 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9717 << RD << FieldType.getObjCLifetime(); 9718 return false; 9719 } 9720 9721 bool ConstRHS = ConstArg && !FI->isMutable(); 9722 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9723 CSM, TSK_Field, TAH, Diagnose)) 9724 return false; 9725 } 9726 9727 return true; 9728} 9729 9730/// Diagnose why the specified class does not have a trivial special member of 9731/// the given kind. 9732void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9733 QualType Ty = Context.getRecordType(RD); 9734 9735 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9736 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9737 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9738 /*Diagnose*/true); 9739} 9740 9741/// Determine whether a defaulted or deleted special member function is trivial, 9742/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9743/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9744bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9745 TrivialABIHandling TAH, bool Diagnose) { 9746 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")(static_cast <bool> (!MD->isUserProvided() &&
CSM != CXXInvalid && "not special enough") ? void (0
) : __assert_fail ("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9746, __extension__ __PRETTY_FUNCTION__
))
; 9747 9748 CXXRecordDecl *RD = MD->getParent(); 9749 9750 bool ConstArg = false; 9751 9752 // C++11 [class.copy]p12, p25: [DR1593] 9753 // A [special member] is trivial if [...] its parameter-type-list is 9754 // equivalent to the parameter-type-list of an implicit declaration [...] 9755 switch (CSM) { 9756 case CXXDefaultConstructor: 9757 case CXXDestructor: 9758 // Trivial default constructors and destructors cannot have parameters. 9759 break; 9760 9761 case CXXCopyConstructor: 9762 case CXXCopyAssignment: { 9763 // Trivial copy operations always have const, non-volatile parameter types. 9764 ConstArg = true; 9765 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9766 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9767 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9768 if (Diagnose) 9769 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9770 << Param0->getSourceRange() << Param0->getType() 9771 << Context.getLValueReferenceType( 9772 Context.getRecordType(RD).withConst()); 9773 return false; 9774 } 9775 break; 9776 } 9777 9778 case CXXMoveConstructor: 9779 case CXXMoveAssignment: { 9780 // Trivial move operations always have non-cv-qualified parameters. 9781 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9782 const RValueReferenceType *RT = 9783 Param0->getType()->getAs<RValueReferenceType>(); 9784 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9785 if (Diagnose) 9786 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9787 << Param0->getSourceRange() << Param0->getType() 9788 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9789 return false; 9790 } 9791 break; 9792 } 9793 9794 case CXXInvalid: 9795 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9795)
; 9796 } 9797 9798 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9799 if (Diagnose) 9800 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9801 diag::note_nontrivial_default_arg) 9802 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9803 return false; 9804 } 9805 if (MD->isVariadic()) { 9806 if (Diagnose) 9807 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9808 return false; 9809 } 9810 9811 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9812 // A copy/move [constructor or assignment operator] is trivial if 9813 // -- the [member] selected to copy/move each direct base class subobject 9814 // is trivial 9815 // 9816 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9817 // A [default constructor or destructor] is trivial if 9818 // -- all the direct base classes have trivial [default constructors or 9819 // destructors] 9820 for (const auto &BI : RD->bases()) 9821 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9822 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9823 return false; 9824 9825 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9826 // A copy/move [constructor or assignment operator] for a class X is 9827 // trivial if 9828 // -- for each non-static data member of X that is of class type (or array 9829 // thereof), the constructor selected to copy/move that member is 9830 // trivial 9831 // 9832 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9833 // A [default constructor or destructor] is trivial if 9834 // -- for all of the non-static data members of its class that are of class 9835 // type (or array thereof), each such class has a trivial [default 9836 // constructor or destructor] 9837 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9838 return false; 9839 9840 // C++11 [class.dtor]p5: 9841 // A destructor is trivial if [...] 9842 // -- the destructor is not virtual 9843 if (CSM == CXXDestructor && MD->isVirtual()) { 9844 if (Diagnose) 9845 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9846 return false; 9847 } 9848 9849 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9850 // A [special member] for class X is trivial if [...] 9851 // -- class X has no virtual functions and no virtual base classes 9852 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9853 if (!Diagnose) 9854 return false; 9855 9856 if (RD->getNumVBases()) { 9857 // Check for virtual bases. We already know that the corresponding 9858 // member in all bases is trivial, so vbases must all be direct. 9859 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9860 assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail
("BS.isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp", 9860, __extension__
__PRETTY_FUNCTION__))
; 9861 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9862 return false; 9863 } 9864 9865 // Must have a virtual method. 9866 for (const auto *MI : RD->methods()) { 9867 if (MI->isVirtual()) { 9868 SourceLocation MLoc = MI->getBeginLoc(); 9869 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9870 return false; 9871 } 9872 } 9873 9874 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9874)
; 9875 } 9876 9877 // Looks like it's trivial! 9878 return true; 9879} 9880 9881namespace { 9882struct FindHiddenVirtualMethod { 9883 Sema *S; 9884 CXXMethodDecl *Method; 9885 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9886 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9887 9888private: 9889 /// Check whether any most overridden method from MD in Methods 9890 static bool CheckMostOverridenMethods( 9891 const CXXMethodDecl *MD, 9892 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9893 if (MD->size_overridden_methods() == 0) 9894 return Methods.count(MD->getCanonicalDecl()); 9895 for (const CXXMethodDecl *O : MD->overridden_methods()) 9896 if (CheckMostOverridenMethods(O, Methods)) 9897 return true; 9898 return false; 9899 } 9900 9901public: 9902 /// Member lookup function that determines whether a given C++ 9903 /// method overloads virtual methods in a base class without overriding any, 9904 /// to be used with CXXRecordDecl::lookupInBases(). 9905 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9906 RecordDecl *BaseRecord = 9907 Specifier->getType()->castAs<RecordType>()->getDecl(); 9908 9909 DeclarationName Name = Method->getDeclName(); 9910 assert(Name.getNameKind() == DeclarationName::Identifier)(static_cast <bool> (Name.getNameKind() == DeclarationName
::Identifier) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9910, __extension__ __PRETTY_FUNCTION__
))
; 9911 9912 bool foundSameNameMethod = false; 9913 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9914 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9915 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9916 NamedDecl *D = *Path.Decls; 9917 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9918 MD = MD->getCanonicalDecl(); 9919 foundSameNameMethod = true; 9920 // Interested only in hidden virtual methods. 9921 if (!MD->isVirtual()) 9922 continue; 9923 // If the method we are checking overrides a method from its base 9924 // don't warn about the other overloaded methods. Clang deviates from 9925 // GCC by only diagnosing overloads of inherited virtual functions that 9926 // do not override any other virtual functions in the base. GCC's 9927 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9928 // function from a base class. These cases may be better served by a 9929 // warning (not specific to virtual functions) on call sites when the 9930 // call would select a different function from the base class, were it 9931 // visible. 9932 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9933 if (!S->IsOverload(Method, MD, false)) 9934 return true; 9935 // Collect the overload only if its hidden. 9936 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9937 overloadedMethods.push_back(MD); 9938 } 9939 } 9940 9941 if (foundSameNameMethod) 9942 OverloadedMethods.append(overloadedMethods.begin(), 9943 overloadedMethods.end()); 9944 return foundSameNameMethod; 9945 } 9946}; 9947} // end anonymous namespace 9948 9949/// Add the most overridden methods from MD to Methods 9950static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9951 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9952 if (MD->size_overridden_methods() == 0) 9953 Methods.insert(MD->getCanonicalDecl()); 9954 else 9955 for (const CXXMethodDecl *O : MD->overridden_methods()) 9956 AddMostOverridenMethods(O, Methods); 9957} 9958 9959/// Check if a method overloads virtual methods in a base class without 9960/// overriding any. 9961void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9962 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9963 if (!MD->getDeclName().isIdentifier()) 9964 return; 9965 9966 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9967 /*bool RecordPaths=*/false, 9968 /*bool DetectVirtual=*/false); 9969 FindHiddenVirtualMethod FHVM; 9970 FHVM.Method = MD; 9971 FHVM.S = this; 9972 9973 // Keep the base methods that were overridden or introduced in the subclass 9974 // by 'using' in a set. A base method not in this set is hidden. 9975 CXXRecordDecl *DC = MD->getParent(); 9976 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9977 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9978 NamedDecl *ND = *I; 9979 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9980 ND = shad->getTargetDecl(); 9981 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9982 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9983 } 9984 9985 if (DC->lookupInBases(FHVM, Paths)) 9986 OverloadedMethods = FHVM.OverloadedMethods; 9987} 9988 9989void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9990 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9991 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9992 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9993 PartialDiagnostic PD = PDiag( 9994 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9995 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9996 Diag(overloadedMD->getLocation(), PD); 9997 } 9998} 9999 10000/// Diagnose methods which overload virtual methods in a base class 10001/// without overriding any. 10002void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 10003 if (MD->isInvalidDecl()) 10004 return; 10005 10006 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 10007 return; 10008 10009 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 10010 FindHiddenVirtualMethods(MD, OverloadedMethods); 10011 if (!OverloadedMethods.empty()) { 10012 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 10013 << MD << (OverloadedMethods.size() > 1); 10014 10015 NoteHiddenVirtualMethods(MD, OverloadedMethods); 10016 } 10017} 10018 10019void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 10020 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 10021 // No diagnostics if this is a template instantiation. 10022 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 10023 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10024 diag::ext_cannot_use_trivial_abi) << &RD; 10025 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10026 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 10027 } 10028 RD.dropAttr<TrivialABIAttr>(); 10029 }; 10030 10031 // Ill-formed if the copy and move constructors are deleted. 10032 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 10033 // If the type is dependent, then assume it might have 10034 // implicit copy or move ctor because we won't know yet at this point. 10035 if (RD.isDependentType()) 10036 return true; 10037 if (RD.needsImplicitCopyConstructor() && 10038 !RD.defaultedCopyConstructorIsDeleted()) 10039 return true; 10040 if (RD.needsImplicitMoveConstructor() && 10041 !RD.defaultedMoveConstructorIsDeleted()) 10042 return true; 10043 for (const CXXConstructorDecl *CD : RD.ctors()) 10044 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 10045 return true; 10046 return false; 10047 }; 10048 10049 if (!HasNonDeletedCopyOrMoveConstructor()) { 10050 PrintDiagAndRemoveAttr(0); 10051 return; 10052 } 10053 10054 // Ill-formed if the struct has virtual functions. 10055 if (RD.isPolymorphic()) { 10056 PrintDiagAndRemoveAttr(1); 10057 return; 10058 } 10059 10060 for (const auto &B : RD.bases()) { 10061 // Ill-formed if the base class is non-trivial for the purpose of calls or a 10062 // virtual base. 10063 if (!B.getType()->isDependentType() && 10064 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 10065 PrintDiagAndRemoveAttr(2); 10066 return; 10067 } 10068 10069 if (B.isVirtual()) { 10070 PrintDiagAndRemoveAttr(3); 10071 return; 10072 } 10073 } 10074 10075 for (const auto *FD : RD.fields()) { 10076 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 10077 // non-trivial for the purpose of calls. 10078 QualType FT = FD->getType(); 10079 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 10080 PrintDiagAndRemoveAttr(4); 10081 return; 10082 } 10083 10084 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 10085 if (!RT->isDependentType() && 10086 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 10087 PrintDiagAndRemoveAttr(5); 10088 return; 10089 } 10090 } 10091} 10092 10093void Sema::ActOnFinishCXXMemberSpecification( 10094 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 10095 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 10096 if (!TagDecl) 10097 return; 10098 10099 AdjustDeclIfTemplate(TagDecl); 10100 10101 for (const ParsedAttr &AL : AttrList) { 10102 if (AL.getKind() != ParsedAttr::AT_Visibility) 10103 continue; 10104 AL.setInvalid(); 10105 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10106 } 10107 10108 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 10109 // strict aliasing violation! 10110 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 10111 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 10112 10113 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10114} 10115 10116/// Find the equality comparison functions that should be implicitly declared 10117/// in a given class definition, per C++2a [class.compare.default]p3. 10118static void findImplicitlyDeclaredEqualityComparisons( 10119 ASTContext &Ctx, CXXRecordDecl *RD, 10120 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10121 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10122 if (!RD->lookup(EqEq).empty()) 10123 // Member operator== explicitly declared: no implicit operator==s. 10124 return; 10125 10126 // Traverse friends looking for an '==' or a '<=>'. 10127 for (FriendDecl *Friend : RD->friends()) { 10128 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10129 if (!FD) continue; 10130 10131 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10132 // Friend operator== explicitly declared: no implicit operator==s. 10133 Spaceships.clear(); 10134 return; 10135 } 10136 10137 if (FD->getOverloadedOperator() == OO_Spaceship && 10138 FD->isExplicitlyDefaulted()) 10139 Spaceships.push_back(FD); 10140 } 10141 10142 // Look for members named 'operator<=>'. 10143 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10144 for (NamedDecl *ND : RD->lookup(Cmp)) { 10145 // Note that we could find a non-function here (either a function template 10146 // or a using-declaration). Neither case results in an implicit 10147 // 'operator=='. 10148 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10149 if (FD->isExplicitlyDefaulted()) 10150 Spaceships.push_back(FD); 10151 } 10152} 10153 10154/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10155/// special functions, such as the default constructor, copy 10156/// constructor, or destructor, to the given C++ class (C++ 10157/// [special]p1). This routine can only be executed just before the 10158/// definition of the class is complete. 10159void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10160 // Don't add implicit special members to templated classes. 10161 // FIXME: This means unqualified lookups for 'operator=' within a class 10162 // template don't work properly. 10163 if (!ClassDecl->isDependentType()) { 10164 if (ClassDecl->needsImplicitDefaultConstructor()) { 10165 ++getASTContext().NumImplicitDefaultConstructors; 10166 10167 if (ClassDecl->hasInheritedConstructor()) 10168 DeclareImplicitDefaultConstructor(ClassDecl); 10169 } 10170 10171 if (ClassDecl->needsImplicitCopyConstructor()) { 10172 ++getASTContext().NumImplicitCopyConstructors; 10173 10174 // If the properties or semantics of the copy constructor couldn't be 10175 // determined while the class was being declared, force a declaration 10176 // of it now. 10177 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10178 ClassDecl->hasInheritedConstructor()) 10179 DeclareImplicitCopyConstructor(ClassDecl); 10180 // For the MS ABI we need to know whether the copy ctor is deleted. A 10181 // prerequisite for deleting the implicit copy ctor is that the class has 10182 // a move ctor or move assignment that is either user-declared or whose 10183 // semantics are inherited from a subobject. FIXME: We should provide a 10184 // more direct way for CodeGen to ask whether the constructor was deleted. 10185 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10186 (ClassDecl->hasUserDeclaredMoveConstructor() || 10187 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10188 ClassDecl->hasUserDeclaredMoveAssignment() || 10189 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10190 DeclareImplicitCopyConstructor(ClassDecl); 10191 } 10192 10193 if (getLangOpts().CPlusPlus11 && 10194 ClassDecl->needsImplicitMoveConstructor()) { 10195 ++getASTContext().NumImplicitMoveConstructors; 10196 10197 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10198 ClassDecl->hasInheritedConstructor()) 10199 DeclareImplicitMoveConstructor(ClassDecl); 10200 } 10201 10202 if (ClassDecl->needsImplicitCopyAssignment()) { 10203 ++getASTContext().NumImplicitCopyAssignmentOperators; 10204 10205 // If we have a dynamic class, then the copy assignment operator may be 10206 // virtual, so we have to declare it immediately. This ensures that, e.g., 10207 // it shows up in the right place in the vtable and that we diagnose 10208 // problems with the implicit exception specification. 10209 if (ClassDecl->isDynamicClass() || 10210 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10211 ClassDecl->hasInheritedAssignment()) 10212 DeclareImplicitCopyAssignment(ClassDecl); 10213 } 10214 10215 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10216 ++getASTContext().NumImplicitMoveAssignmentOperators; 10217 10218 // Likewise for the move assignment operator. 10219 if (ClassDecl->isDynamicClass() || 10220 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10221 ClassDecl->hasInheritedAssignment()) 10222 DeclareImplicitMoveAssignment(ClassDecl); 10223 } 10224 10225 if (ClassDecl->needsImplicitDestructor()) { 10226 ++getASTContext().NumImplicitDestructors; 10227 10228 // If we have a dynamic class, then the destructor may be virtual, so we 10229 // have to declare the destructor immediately. This ensures that, e.g., it 10230 // shows up in the right place in the vtable and that we diagnose problems 10231 // with the implicit exception specification. 10232 if (ClassDecl->isDynamicClass() || 10233 ClassDecl->needsOverloadResolutionForDestructor()) 10234 DeclareImplicitDestructor(ClassDecl); 10235 } 10236 } 10237 10238 // C++2a [class.compare.default]p3: 10239 // If the member-specification does not explicitly declare any member or 10240 // friend named operator==, an == operator function is declared implicitly 10241 // for each defaulted three-way comparison operator function defined in 10242 // the member-specification 10243 // FIXME: Consider doing this lazily. 10244 // We do this during the initial parse for a class template, not during 10245 // instantiation, so that we can handle unqualified lookups for 'operator==' 10246 // when parsing the template. 10247 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10248 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10249 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10250 DefaultedSpaceships); 10251 for (auto *FD : DefaultedSpaceships) 10252 DeclareImplicitEqualityComparison(ClassDecl, FD); 10253 } 10254} 10255 10256unsigned 10257Sema::ActOnReenterTemplateScope(Decl *D, 10258 llvm::function_ref<Scope *()> EnterScope) { 10259 if (!D) 10260 return 0; 10261 AdjustDeclIfTemplate(D); 10262 10263 // In order to get name lookup right, reenter template scopes in order from 10264 // outermost to innermost. 10265 SmallVector<TemplateParameterList *, 4> ParameterLists; 10266 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10267 10268 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10269 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10270 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10271 10272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10273 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10274 ParameterLists.push_back(FTD->getTemplateParameters()); 10275 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10276 LookupDC = VD->getDeclContext(); 10277 10278 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10279 ParameterLists.push_back(VTD->getTemplateParameters()); 10280 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10281 ParameterLists.push_back(PSD->getTemplateParameters()); 10282 } 10283 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10284 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10285 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10286 10287 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10288 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10289 ParameterLists.push_back(CTD->getTemplateParameters()); 10290 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10291 ParameterLists.push_back(PSD->getTemplateParameters()); 10292 } 10293 } 10294 // FIXME: Alias declarations and concepts. 10295 10296 unsigned Count = 0; 10297 Scope *InnermostTemplateScope = nullptr; 10298 for (TemplateParameterList *Params : ParameterLists) { 10299 // Ignore explicit specializations; they don't contribute to the template 10300 // depth. 10301 if (Params->size() == 0) 10302 continue; 10303 10304 InnermostTemplateScope = EnterScope(); 10305 for (NamedDecl *Param : *Params) { 10306 if (Param->getDeclName()) { 10307 InnermostTemplateScope->AddDecl(Param); 10308 IdResolver.AddDecl(Param); 10309 } 10310 } 10311 ++Count; 10312 } 10313 10314 // Associate the new template scopes with the corresponding entities. 10315 if (InnermostTemplateScope) { 10316 assert(LookupDC && "no enclosing DeclContext for template lookup")(static_cast <bool> (LookupDC && "no enclosing DeclContext for template lookup"
) ? void (0) : __assert_fail ("LookupDC && \"no enclosing DeclContext for template lookup\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10316, __extension__ __PRETTY_FUNCTION__
))
; 10317 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10318 } 10319 10320 return Count; 10321} 10322 10323void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10324 if (!RecordD) return; 10325 AdjustDeclIfTemplate(RecordD); 10326 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10327 PushDeclContext(S, Record); 10328} 10329 10330void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10331 if (!RecordD) return; 10332 PopDeclContext(); 10333} 10334 10335/// This is used to implement the constant expression evaluation part of the 10336/// attribute enable_if extension. There is nothing in standard C++ which would 10337/// require reentering parameters. 10338void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10339 if (!Param) 10340 return; 10341 10342 S->AddDecl(Param); 10343 if (Param->getDeclName()) 10344 IdResolver.AddDecl(Param); 10345} 10346 10347/// ActOnStartDelayedCXXMethodDeclaration - We have completed 10348/// parsing a top-level (non-nested) C++ class, and we are now 10349/// parsing those parts of the given Method declaration that could 10350/// not be parsed earlier (C++ [class.mem]p2), such as default 10351/// arguments. This action should enter the scope of the given 10352/// Method declaration as if we had just parsed the qualified method 10353/// name. However, it should not bring the parameters into scope; 10354/// that will be performed by ActOnDelayedCXXMethodParameter. 10355void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10356} 10357 10358/// ActOnDelayedCXXMethodParameter - We've already started a delayed 10359/// C++ method declaration. We're (re-)introducing the given 10360/// function parameter into scope for use in parsing later parts of 10361/// the method declaration. For example, we could see an 10362/// ActOnParamDefaultArgument event for this parameter. 10363void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10364 if (!ParamD) 10365 return; 10366 10367 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10368 10369 S->AddDecl(Param); 10370 if (Param->getDeclName()) 10371 IdResolver.AddDecl(Param); 10372} 10373 10374/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10375/// processing the delayed method declaration for Method. The method 10376/// declaration is now considered finished. There may be a separate 10377/// ActOnStartOfFunctionDef action later (not necessarily 10378/// immediately!) for this method, if it was also defined inside the 10379/// class body. 10380void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10381 if (!MethodD) 10382 return; 10383 10384 AdjustDeclIfTemplate(MethodD); 10385 10386 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10387 10388 // Now that we have our default arguments, check the constructor 10389 // again. It could produce additional diagnostics or affect whether 10390 // the class has implicitly-declared destructors, among other 10391 // things. 10392 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10393 CheckConstructor(Constructor); 10394 10395 // Check the default arguments, which we may have added. 10396 if (!Method->isInvalidDecl()) 10397 CheckCXXDefaultArguments(Method); 10398} 10399 10400// Emit the given diagnostic for each non-address-space qualifier. 10401// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10402static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10403 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10404 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10405 bool DiagOccured = false; 10406 FTI.MethodQualifiers->forEachQualifier( 10407 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10408 SourceLocation SL) { 10409 // This diagnostic should be emitted on any qualifier except an addr 10410 // space qualifier. However, forEachQualifier currently doesn't visit 10411 // addr space qualifiers, so there's no way to write this condition 10412 // right now; we just diagnose on everything. 10413 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10414 DiagOccured = true; 10415 }); 10416 if (DiagOccured) 10417 D.setInvalidType(); 10418 } 10419} 10420 10421/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10422/// the well-formedness of the constructor declarator @p D with type @p 10423/// R. If there are any errors in the declarator, this routine will 10424/// emit diagnostics and set the invalid bit to true. In any case, the type 10425/// will be updated to reflect a well-formed type for the constructor and 10426/// returned. 10427QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10428 StorageClass &SC) { 10429 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10430 10431 // C++ [class.ctor]p3: 10432 // A constructor shall not be virtual (10.3) or static (9.4). A 10433 // constructor can be invoked for a const, volatile or const 10434 // volatile object. A constructor shall not be declared const, 10435 // volatile, or const volatile (9.3.2). 10436 if (isVirtual) { 10437 if (!D.isInvalidType()) 10438 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10439 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10440 << SourceRange(D.getIdentifierLoc()); 10441 D.setInvalidType(); 10442 } 10443 if (SC == SC_Static) { 10444 if (!D.isInvalidType()) 10445 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10446 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10447 << SourceRange(D.getIdentifierLoc()); 10448 D.setInvalidType(); 10449 SC = SC_None; 10450 } 10451 10452 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10453 diagnoseIgnoredQualifiers( 10454 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10455 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10456 D.getDeclSpec().getRestrictSpecLoc(), 10457 D.getDeclSpec().getAtomicSpecLoc()); 10458 D.setInvalidType(); 10459 } 10460 10461 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10462 10463 // C++0x [class.ctor]p4: 10464 // A constructor shall not be declared with a ref-qualifier. 10465 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10466 if (FTI.hasRefQualifier()) { 10467 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10468 << FTI.RefQualifierIsLValueRef 10469 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10470 D.setInvalidType(); 10471 } 10472 10473 // Rebuild the function type "R" without any type qualifiers (in 10474 // case any of the errors above fired) and with "void" as the 10475 // return type, since constructors don't have return types. 10476 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10477 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10478 return R; 10479 10480 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10481 EPI.TypeQuals = Qualifiers(); 10482 EPI.RefQualifier = RQ_None; 10483 10484 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10485} 10486 10487/// CheckConstructor - Checks a fully-formed constructor for 10488/// well-formedness, issuing any diagnostics required. Returns true if 10489/// the constructor declarator is invalid. 10490void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10491 CXXRecordDecl *ClassDecl 10492 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10493 if (!ClassDecl) 10494 return Constructor->setInvalidDecl(); 10495 10496 // C++ [class.copy]p3: 10497 // A declaration of a constructor for a class X is ill-formed if 10498 // its first parameter is of type (optionally cv-qualified) X and 10499 // either there are no other parameters or else all other 10500 // parameters have default arguments. 10501 if (!Constructor->isInvalidDecl() && 10502 Constructor->hasOneParamOrDefaultArgs() && 10503 Constructor->getTemplateSpecializationKind() != 10504 TSK_ImplicitInstantiation) { 10505 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10506 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10507 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10508 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10509 const char *ConstRef 10510 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10511 : " const &"; 10512 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10513 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10514 10515 // FIXME: Rather that making the constructor invalid, we should endeavor 10516 // to fix the type. 10517 Constructor->setInvalidDecl(); 10518 } 10519 } 10520} 10521 10522/// CheckDestructor - Checks a fully-formed destructor definition for 10523/// well-formedness, issuing any diagnostics required. Returns true 10524/// on error. 10525bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10526 CXXRecordDecl *RD = Destructor->getParent(); 10527 10528 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10529 SourceLocation Loc; 10530 10531 if (!Destructor->isImplicit()) 10532 Loc = Destructor->getLocation(); 10533 else 10534 Loc = RD->getLocation(); 10535 10536 // If we have a virtual destructor, look up the deallocation function 10537 if (FunctionDecl *OperatorDelete = 10538 FindDeallocationFunctionForDestructor(Loc, RD)) { 10539 Expr *ThisArg = nullptr; 10540 10541 // If the notional 'delete this' expression requires a non-trivial 10542 // conversion from 'this' to the type of a destroying operator delete's 10543 // first parameter, perform that conversion now. 10544 if (OperatorDelete->isDestroyingOperatorDelete()) { 10545 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10546 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10547 // C++ [class.dtor]p13: 10548 // ... as if for the expression 'delete this' appearing in a 10549 // non-virtual destructor of the destructor's class. 10550 ContextRAII SwitchContext(*this, Destructor); 10551 ExprResult This = 10552 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10553 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")(static_cast <bool> (!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? void (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10553, __extension__ __PRETTY_FUNCTION__
))
; 10554 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10555 if (This.isInvalid()) { 10556 // FIXME: Register this as a context note so that it comes out 10557 // in the right order. 10558 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10559 return true; 10560 } 10561 ThisArg = This.get(); 10562 } 10563 } 10564 10565 DiagnoseUseOfDecl(OperatorDelete, Loc); 10566 MarkFunctionReferenced(Loc, OperatorDelete); 10567 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10568 } 10569 } 10570 10571 return false; 10572} 10573 10574/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10575/// the well-formednes of the destructor declarator @p D with type @p 10576/// R. If there are any errors in the declarator, this routine will 10577/// emit diagnostics and set the declarator to invalid. Even if this happens, 10578/// will be updated to reflect a well-formed type for the destructor and 10579/// returned. 10580QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10581 StorageClass& SC) { 10582 // C++ [class.dtor]p1: 10583 // [...] A typedef-name that names a class is a class-name 10584 // (7.1.3); however, a typedef-name that names a class shall not 10585 // be used as the identifier in the declarator for a destructor 10586 // declaration. 10587 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10588 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10589 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10590 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10591 else if (const TemplateSpecializationType *TST = 10592 DeclaratorType->getAs<TemplateSpecializationType>()) 10593 if (TST->isTypeAlias()) 10594 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10595 << DeclaratorType << 1; 10596 10597 // C++ [class.dtor]p2: 10598 // A destructor is used to destroy objects of its class type. A 10599 // destructor takes no parameters, and no return type can be 10600 // specified for it (not even void). The address of a destructor 10601 // shall not be taken. A destructor shall not be static. A 10602 // destructor can be invoked for a const, volatile or const 10603 // volatile object. A destructor shall not be declared const, 10604 // volatile or const volatile (9.3.2). 10605 if (SC == SC_Static) { 10606 if (!D.isInvalidType()) 10607 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10608 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10609 << SourceRange(D.getIdentifierLoc()) 10610 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10611 10612 SC = SC_None; 10613 } 10614 if (!D.isInvalidType()) { 10615 // Destructors don't have return types, but the parser will 10616 // happily parse something like: 10617 // 10618 // class X { 10619 // float ~X(); 10620 // }; 10621 // 10622 // The return type will be eliminated later. 10623 if (D.getDeclSpec().hasTypeSpecifier()) 10624 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10625 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10626 << SourceRange(D.getIdentifierLoc()); 10627 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10628 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10629 SourceLocation(), 10630 D.getDeclSpec().getConstSpecLoc(), 10631 D.getDeclSpec().getVolatileSpecLoc(), 10632 D.getDeclSpec().getRestrictSpecLoc(), 10633 D.getDeclSpec().getAtomicSpecLoc()); 10634 D.setInvalidType(); 10635 } 10636 } 10637 10638 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10639 10640 // C++0x [class.dtor]p2: 10641 // A destructor shall not be declared with a ref-qualifier. 10642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10643 if (FTI.hasRefQualifier()) { 10644 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10645 << FTI.RefQualifierIsLValueRef 10646 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10647 D.setInvalidType(); 10648 } 10649 10650 // Make sure we don't have any parameters. 10651 if (FTIHasNonVoidParameters(FTI)) { 10652 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10653 10654 // Delete the parameters. 10655 FTI.freeParams(); 10656 D.setInvalidType(); 10657 } 10658 10659 // Make sure the destructor isn't variadic. 10660 if (FTI.isVariadic) { 10661 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10662 D.setInvalidType(); 10663 } 10664 10665 // Rebuild the function type "R" without any type qualifiers or 10666 // parameters (in case any of the errors above fired) and with 10667 // "void" as the return type, since destructors don't have return 10668 // types. 10669 if (!D.isInvalidType()) 10670 return R; 10671 10672 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10673 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10674 EPI.Variadic = false; 10675 EPI.TypeQuals = Qualifiers(); 10676 EPI.RefQualifier = RQ_None; 10677 return Context.getFunctionType(Context.VoidTy, None, EPI); 10678} 10679 10680static void extendLeft(SourceRange &R, SourceRange Before) { 10681 if (Before.isInvalid()) 10682 return; 10683 R.setBegin(Before.getBegin()); 10684 if (R.getEnd().isInvalid()) 10685 R.setEnd(Before.getEnd()); 10686} 10687 10688static void extendRight(SourceRange &R, SourceRange After) { 10689 if (After.isInvalid()) 10690 return; 10691 if (R.getBegin().isInvalid()) 10692 R.setBegin(After.getBegin()); 10693 R.setEnd(After.getEnd()); 10694} 10695 10696/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10697/// well-formednes of the conversion function declarator @p D with 10698/// type @p R. If there are any errors in the declarator, this routine 10699/// will emit diagnostics and return true. Otherwise, it will return 10700/// false. Either way, the type @p R will be updated to reflect a 10701/// well-formed type for the conversion operator. 10702void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10703 StorageClass& SC) { 10704 // C++ [class.conv.fct]p1: 10705 // Neither parameter types nor return type can be specified. The 10706 // type of a conversion function (8.3.5) is "function taking no 10707 // parameter returning conversion-type-id." 10708 if (SC == SC_Static) { 10709 if (!D.isInvalidType()) 10710 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10711 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10712 << D.getName().getSourceRange(); 10713 D.setInvalidType(); 10714 SC = SC_None; 10715 } 10716 10717 TypeSourceInfo *ConvTSI = nullptr; 10718 QualType ConvType = 10719 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10720 10721 const DeclSpec &DS = D.getDeclSpec(); 10722 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10723 // Conversion functions don't have return types, but the parser will 10724 // happily parse something like: 10725 // 10726 // class X { 10727 // float operator bool(); 10728 // }; 10729 // 10730 // The return type will be changed later anyway. 10731 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10732 << SourceRange(DS.getTypeSpecTypeLoc()) 10733 << SourceRange(D.getIdentifierLoc()); 10734 D.setInvalidType(); 10735 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10736 // It's also plausible that the user writes type qualifiers in the wrong 10737 // place, such as: 10738 // struct S { const operator int(); }; 10739 // FIXME: we could provide a fixit to move the qualifiers onto the 10740 // conversion type. 10741 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10742 << SourceRange(D.getIdentifierLoc()) << 0; 10743 D.setInvalidType(); 10744 } 10745 10746 const auto *Proto = R->castAs<FunctionProtoType>(); 10747 10748 // Make sure we don't have any parameters. 10749 if (Proto->getNumParams() > 0) { 10750 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10751 10752 // Delete the parameters. 10753 D.getFunctionTypeInfo().freeParams(); 10754 D.setInvalidType(); 10755 } else if (Proto->isVariadic()) { 10756 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10757 D.setInvalidType(); 10758 } 10759 10760 // Diagnose "&operator bool()" and other such nonsense. This 10761 // is actually a gcc extension which we don't support. 10762 if (Proto->getReturnType() != ConvType) { 10763 bool NeedsTypedef = false; 10764 SourceRange Before, After; 10765 10766 // Walk the chunks and extract information on them for our diagnostic. 10767 bool PastFunctionChunk = false; 10768 for (auto &Chunk : D.type_objects()) { 10769 switch (Chunk.Kind) { 10770 case DeclaratorChunk::Function: 10771 if (!PastFunctionChunk) { 10772 if (Chunk.Fun.HasTrailingReturnType) { 10773 TypeSourceInfo *TRT = nullptr; 10774 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10775 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10776 } 10777 PastFunctionChunk = true; 10778 break; 10779 } 10780 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 10781 case DeclaratorChunk::Array: 10782 NeedsTypedef = true; 10783 extendRight(After, Chunk.getSourceRange()); 10784 break; 10785 10786 case DeclaratorChunk::Pointer: 10787 case DeclaratorChunk::BlockPointer: 10788 case DeclaratorChunk::Reference: 10789 case DeclaratorChunk::MemberPointer: 10790 case DeclaratorChunk::Pipe: 10791 extendLeft(Before, Chunk.getSourceRange()); 10792 break; 10793 10794 case DeclaratorChunk::Paren: 10795 extendLeft(Before, Chunk.Loc); 10796 extendRight(After, Chunk.EndLoc); 10797 break; 10798 } 10799 } 10800 10801 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10802 After.isValid() ? After.getBegin() : 10803 D.getIdentifierLoc(); 10804 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10805 DB << Before << After; 10806 10807 if (!NeedsTypedef) { 10808 DB << /*don't need a typedef*/0; 10809 10810 // If we can provide a correct fix-it hint, do so. 10811 if (After.isInvalid() && ConvTSI) { 10812 SourceLocation InsertLoc = 10813 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10814 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10815 << FixItHint::CreateInsertionFromRange( 10816 InsertLoc, CharSourceRange::getTokenRange(Before)) 10817 << FixItHint::CreateRemoval(Before); 10818 } 10819 } else if (!Proto->getReturnType()->isDependentType()) { 10820 DB << /*typedef*/1 << Proto->getReturnType(); 10821 } else if (getLangOpts().CPlusPlus11) { 10822 DB << /*alias template*/2 << Proto->getReturnType(); 10823 } else { 10824 DB << /*might not be fixable*/3; 10825 } 10826 10827 // Recover by incorporating the other type chunks into the result type. 10828 // Note, this does *not* change the name of the function. This is compatible 10829 // with the GCC extension: 10830 // struct S { &operator int(); } s; 10831 // int &r = s.operator int(); // ok in GCC 10832 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10833 ConvType = Proto->getReturnType(); 10834 } 10835 10836 // C++ [class.conv.fct]p4: 10837 // The conversion-type-id shall not represent a function type nor 10838 // an array type. 10839 if (ConvType->isArrayType()) { 10840 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10841 ConvType = Context.getPointerType(ConvType); 10842 D.setInvalidType(); 10843 } else if (ConvType->isFunctionType()) { 10844 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10845 ConvType = Context.getPointerType(ConvType); 10846 D.setInvalidType(); 10847 } 10848 10849 // Rebuild the function type "R" without any parameters (in case any 10850 // of the errors above fired) and with the conversion type as the 10851 // return type. 10852 if (D.isInvalidType()) 10853 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10854 10855 // C++0x explicit conversion operators. 10856 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10857 Diag(DS.getExplicitSpecLoc(), 10858 getLangOpts().CPlusPlus11 10859 ? diag::warn_cxx98_compat_explicit_conversion_functions 10860 : diag::ext_explicit_conversion_functions) 10861 << SourceRange(DS.getExplicitSpecRange()); 10862} 10863 10864/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10865/// the declaration of the given C++ conversion function. This routine 10866/// is responsible for recording the conversion function in the C++ 10867/// class, if possible. 10868Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10869 assert(Conversion && "Expected to receive a conversion function declaration")(static_cast <bool> (Conversion && "Expected to receive a conversion function declaration"
) ? void (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10869, __extension__ __PRETTY_FUNCTION__
))
; 10870 10871 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10872 10873 // Make sure we aren't redeclaring the conversion function. 10874 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10875 // C++ [class.conv.fct]p1: 10876 // [...] A conversion function is never used to convert a 10877 // (possibly cv-qualified) object to the (possibly cv-qualified) 10878 // same object type (or a reference to it), to a (possibly 10879 // cv-qualified) base class of that type (or a reference to it), 10880 // or to (possibly cv-qualified) void. 10881 QualType ClassType 10882 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10883 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10884 ConvType = ConvTypeRef->getPointeeType(); 10885 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10886 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10887 /* Suppress diagnostics for instantiations. */; 10888 else if (Conversion->size_overridden_methods() != 0) 10889 /* Suppress diagnostics for overriding virtual function in a base class. */; 10890 else if (ConvType->isRecordType()) { 10891 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10892 if (ConvType == ClassType) 10893 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10894 << ClassType; 10895 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10896 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10897 << ClassType << ConvType; 10898 } else if (ConvType->isVoidType()) { 10899 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10900 << ClassType << ConvType; 10901 } 10902 10903 if (FunctionTemplateDecl *ConversionTemplate 10904 = Conversion->getDescribedFunctionTemplate()) 10905 return ConversionTemplate; 10906 10907 return Conversion; 10908} 10909 10910namespace { 10911/// Utility class to accumulate and print a diagnostic listing the invalid 10912/// specifier(s) on a declaration. 10913struct BadSpecifierDiagnoser { 10914 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10915 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10916 ~BadSpecifierDiagnoser() { 10917 Diagnostic << Specifiers; 10918 } 10919 10920 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10921 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10922 } 10923 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10924 return check(SpecLoc, 10925 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10926 } 10927 void check(SourceLocation SpecLoc, const char *Spec) { 10928 if (SpecLoc.isInvalid()) return; 10929 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10930 if (!Specifiers.empty()) Specifiers += " "; 10931 Specifiers += Spec; 10932 } 10933 10934 Sema &S; 10935 Sema::SemaDiagnosticBuilder Diagnostic; 10936 std::string Specifiers; 10937}; 10938} 10939 10940/// Check the validity of a declarator that we parsed for a deduction-guide. 10941/// These aren't actually declarators in the grammar, so we need to check that 10942/// the user didn't specify any pieces that are not part of the deduction-guide 10943/// grammar. 10944void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10945 StorageClass &SC) { 10946 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10947 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10948 assert(GuidedTemplateDecl && "missing template decl for deduction guide")(static_cast <bool> (GuidedTemplateDecl && "missing template decl for deduction guide"
) ? void (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10948, __extension__ __PRETTY_FUNCTION__
))
; 10949 10950 // C++ [temp.deduct.guide]p3: 10951 // A deduction-gide shall be declared in the same scope as the 10952 // corresponding class template. 10953 if (!CurContext->getRedeclContext()->Equals( 10954 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10955 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10956 << GuidedTemplateDecl; 10957 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10958 } 10959 10960 auto &DS = D.getMutableDeclSpec(); 10961 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10962 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10963 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10964 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10965 BadSpecifierDiagnoser Diagnoser( 10966 *this, D.getIdentifierLoc(), 10967 diag::err_deduction_guide_invalid_specifier); 10968 10969 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10970 DS.ClearStorageClassSpecs(); 10971 SC = SC_None; 10972 10973 // 'explicit' is permitted. 10974 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10975 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10976 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10977 DS.ClearConstexprSpec(); 10978 10979 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10980 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10981 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10982 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10983 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10984 DS.ClearTypeQualifiers(); 10985 10986 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10987 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10988 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10989 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10990 DS.ClearTypeSpecType(); 10991 } 10992 10993 if (D.isInvalidType()) 10994 return; 10995 10996 // Check the declarator is simple enough. 10997 bool FoundFunction = false; 10998 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10999 if (Chunk.Kind == DeclaratorChunk::Paren) 11000 continue; 11001 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 11002 Diag(D.getDeclSpec().getBeginLoc(), 11003 diag::err_deduction_guide_with_complex_decl) 11004 << D.getSourceRange(); 11005 break; 11006 } 11007 if (!Chunk.Fun.hasTrailingReturnType()) { 11008 Diag(D.getName().getBeginLoc(), 11009 diag::err_deduction_guide_no_trailing_return_type); 11010 break; 11011 } 11012 11013 // Check that the return type is written as a specialization of 11014 // the template specified as the deduction-guide's name. 11015 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 11016 TypeSourceInfo *TSI = nullptr; 11017 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 11018 assert(TSI && "deduction guide has valid type but invalid return type?")(static_cast <bool> (TSI && "deduction guide has valid type but invalid return type?"
) ? void (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11018, __extension__ __PRETTY_FUNCTION__
))
; 11019 bool AcceptableReturnType = false; 11020 bool MightInstantiateToSpecialization = false; 11021 if (auto RetTST = 11022 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 11023 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 11024 bool TemplateMatches = 11025 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 11026 // FIXME: We should consider other template kinds (using, qualified), 11027 // otherwise we will emit bogus diagnostics. 11028 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 11029 AcceptableReturnType = true; 11030 else { 11031 // This could still instantiate to the right type, unless we know it 11032 // names the wrong class template. 11033 auto *TD = SpecifiedName.getAsTemplateDecl(); 11034 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 11035 !TemplateMatches); 11036 } 11037 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 11038 MightInstantiateToSpecialization = true; 11039 } 11040 11041 if (!AcceptableReturnType) { 11042 Diag(TSI->getTypeLoc().getBeginLoc(), 11043 diag::err_deduction_guide_bad_trailing_return_type) 11044 << GuidedTemplate << TSI->getType() 11045 << MightInstantiateToSpecialization 11046 << TSI->getTypeLoc().getSourceRange(); 11047 } 11048 11049 // Keep going to check that we don't have any inner declarator pieces (we 11050 // could still have a function returning a pointer to a function). 11051 FoundFunction = true; 11052 } 11053 11054 if (D.isFunctionDefinition()) 11055 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 11056} 11057 11058//===----------------------------------------------------------------------===// 11059// Namespace Handling 11060//===----------------------------------------------------------------------===// 11061 11062/// Diagnose a mismatch in 'inline' qualifiers when a namespace is 11063/// reopened. 11064static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 11065 SourceLocation Loc, 11066 IdentifierInfo *II, bool *IsInline, 11067 NamespaceDecl *PrevNS) { 11068 assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline()
) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11068, __extension__ __PRETTY_FUNCTION__
))
; 11069 11070 // 'inline' must appear on the original definition, but not necessarily 11071 // on all extension definitions, so the note should point to the first 11072 // definition to avoid confusion. 11073 PrevNS = PrevNS->getFirstDecl(); 11074 11075 if (PrevNS->isInline()) 11076 // The user probably just forgot the 'inline', so suggest that it 11077 // be added back. 11078 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 11079 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 11080 else 11081 S.Diag(Loc, diag::err_inline_namespace_mismatch); 11082 11083 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 11084 *IsInline = PrevNS->isInline(); 11085} 11086 11087/// ActOnStartNamespaceDef - This is called at the start of a namespace 11088/// definition. 11089Decl *Sema::ActOnStartNamespaceDef( 11090 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 11091 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 11092 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 11093 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 11094 // For anonymous namespace, take the location of the left brace. 11095 SourceLocation Loc = II ? IdentLoc : LBrace; 11096 bool IsInline = InlineLoc.isValid(); 11097 bool IsInvalid = false; 11098 bool IsStd = false; 11099 bool AddToKnown = false; 11100 Scope *DeclRegionScope = NamespcScope->getParent(); 11101 11102 NamespaceDecl *PrevNS = nullptr; 11103 if (II) { 11104 // C++ [namespace.def]p2: 11105 // The identifier in an original-namespace-definition shall not 11106 // have been previously defined in the declarative region in 11107 // which the original-namespace-definition appears. The 11108 // identifier in an original-namespace-definition is the name of 11109 // the namespace. Subsequently in that declarative region, it is 11110 // treated as an original-namespace-name. 11111 // 11112 // Since namespace names are unique in their scope, and we don't 11113 // look through using directives, just look for any ordinary names 11114 // as if by qualified name lookup. 11115 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11116 ForExternalRedeclaration); 11117 LookupQualifiedName(R, CurContext->getRedeclContext()); 11118 NamedDecl *PrevDecl = 11119 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11120 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11121 11122 if (PrevNS) { 11123 // This is an extended namespace definition. 11124 if (IsInline != PrevNS->isInline()) 11125 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11126 &IsInline, PrevNS); 11127 } else if (PrevDecl) { 11128 // This is an invalid name redefinition. 11129 Diag(Loc, diag::err_redefinition_different_kind) 11130 << II; 11131 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11132 IsInvalid = true; 11133 // Continue on to push Namespc as current DeclContext and return it. 11134 } else if (II->isStr("std") && 11135 CurContext->getRedeclContext()->isTranslationUnit()) { 11136 // This is the first "real" definition of the namespace "std", so update 11137 // our cache of the "std" namespace to point at this definition. 11138 PrevNS = getStdNamespace(); 11139 IsStd = true; 11140 AddToKnown = !IsInline; 11141 } else { 11142 // We've seen this namespace for the first time. 11143 AddToKnown = !IsInline; 11144 } 11145 } else { 11146 // Anonymous namespaces. 11147 11148 // Determine whether the parent already has an anonymous namespace. 11149 DeclContext *Parent = CurContext->getRedeclContext(); 11150 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11151 PrevNS = TU->getAnonymousNamespace(); 11152 } else { 11153 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11154 PrevNS = ND->getAnonymousNamespace(); 11155 } 11156 11157 if (PrevNS && IsInline != PrevNS->isInline()) 11158 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11159 &IsInline, PrevNS); 11160 } 11161 11162 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11163 StartLoc, Loc, II, PrevNS); 11164 if (IsInvalid) 11165 Namespc->setInvalidDecl(); 11166 11167 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11168 AddPragmaAttributes(DeclRegionScope, Namespc); 11169 11170 // FIXME: Should we be merging attributes? 11171 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11172 PushNamespaceVisibilityAttr(Attr, Loc); 11173 11174 if (IsStd) 11175 StdNamespace = Namespc; 11176 if (AddToKnown) 11177 KnownNamespaces[Namespc] = false; 11178 11179 if (II) { 11180 PushOnScopeChains(Namespc, DeclRegionScope); 11181 } else { 11182 // Link the anonymous namespace into its parent. 11183 DeclContext *Parent = CurContext->getRedeclContext(); 11184 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11185 TU->setAnonymousNamespace(Namespc); 11186 } else { 11187 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11188 } 11189 11190 CurContext->addDecl(Namespc); 11191 11192 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11193 // behaves as if it were replaced by 11194 // namespace unique { /* empty body */ } 11195 // using namespace unique; 11196 // namespace unique { namespace-body } 11197 // where all occurrences of 'unique' in a translation unit are 11198 // replaced by the same identifier and this identifier differs 11199 // from all other identifiers in the entire program. 11200 11201 // We just create the namespace with an empty name and then add an 11202 // implicit using declaration, just like the standard suggests. 11203 // 11204 // CodeGen enforces the "universally unique" aspect by giving all 11205 // declarations semantically contained within an anonymous 11206 // namespace internal linkage. 11207 11208 if (!PrevNS) { 11209 UD = UsingDirectiveDecl::Create(Context, Parent, 11210 /* 'using' */ LBrace, 11211 /* 'namespace' */ SourceLocation(), 11212 /* qualifier */ NestedNameSpecifierLoc(), 11213 /* identifier */ SourceLocation(), 11214 Namespc, 11215 /* Ancestor */ Parent); 11216 UD->setImplicit(); 11217 Parent->addDecl(UD); 11218 } 11219 } 11220 11221 ActOnDocumentableDecl(Namespc); 11222 11223 // Although we could have an invalid decl (i.e. the namespace name is a 11224 // redefinition), push it as current DeclContext and try to continue parsing. 11225 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11226 // for the namespace has the declarations that showed up in that particular 11227 // namespace definition. 11228 PushDeclContext(NamespcScope, Namespc); 11229 return Namespc; 11230} 11231 11232/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11233/// is a namespace alias, returns the namespace it points to. 11234static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11235 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11236 return AD->getNamespace(); 11237 return dyn_cast_or_null<NamespaceDecl>(D); 11238} 11239 11240/// ActOnFinishNamespaceDef - This callback is called after a namespace is 11241/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11242void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11243 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11244 assert(Namespc && "Invalid parameter, expected NamespaceDecl")(static_cast <bool> (Namespc && "Invalid parameter, expected NamespaceDecl"
) ? void (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11244, __extension__ __PRETTY_FUNCTION__
))
; 11245 Namespc->setRBraceLoc(RBrace); 11246 PopDeclContext(); 11247 if (Namespc->hasAttr<VisibilityAttr>()) 11248 PopPragmaVisibility(true, RBrace); 11249 // If this namespace contains an export-declaration, export it now. 11250 if (DeferredExportedNamespaces.erase(Namespc)) 11251 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11252} 11253 11254CXXRecordDecl *Sema::getStdBadAlloc() const { 11255 return cast_or_null<CXXRecordDecl>( 11256 StdBadAlloc.get(Context.getExternalSource())); 11257} 11258 11259EnumDecl *Sema::getStdAlignValT() const { 11260 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11261} 11262 11263NamespaceDecl *Sema::getStdNamespace() const { 11264 return cast_or_null<NamespaceDecl>( 11265 StdNamespace.get(Context.getExternalSource())); 11266} 11267 11268NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11269 if (!StdExperimentalNamespaceCache) { 11270 if (auto Std = getStdNamespace()) { 11271 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11272 SourceLocation(), LookupNamespaceName); 11273 if (!LookupQualifiedName(Result, Std) || 11274 !(StdExperimentalNamespaceCache = 11275 Result.getAsSingle<NamespaceDecl>())) 11276 Result.suppressDiagnostics(); 11277 } 11278 } 11279 return StdExperimentalNamespaceCache; 11280} 11281 11282namespace { 11283 11284enum UnsupportedSTLSelect { 11285 USS_InvalidMember, 11286 USS_MissingMember, 11287 USS_NonTrivial, 11288 USS_Other 11289}; 11290 11291struct InvalidSTLDiagnoser { 11292 Sema &S; 11293 SourceLocation Loc; 11294 QualType TyForDiags; 11295 11296 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11297 const VarDecl *VD = nullptr) { 11298 { 11299 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11300 << TyForDiags << ((int)Sel); 11301 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11302 assert(!Name.empty())(static_cast <bool> (!Name.empty()) ? void (0) : __assert_fail
("!Name.empty()", "clang/lib/Sema/SemaDeclCXX.cpp", 11302, __extension__
__PRETTY_FUNCTION__))
; 11303 D << Name; 11304 } 11305 } 11306 if (Sel == USS_InvalidMember) { 11307 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11308 << VD << VD->getSourceRange(); 11309 } 11310 return QualType(); 11311 } 11312}; 11313} // namespace 11314 11315QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11316 SourceLocation Loc, 11317 ComparisonCategoryUsage Usage) { 11318 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11319, __extension__ __PRETTY_FUNCTION__
))
11319 "Looking for comparison category type outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11319, __extension__ __PRETTY_FUNCTION__
))
; 11320 11321 // Use an elaborated type for diagnostics which has a name containing the 11322 // prepended 'std' namespace but not any inline namespace names. 11323 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11324 auto *NNS = 11325 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11326 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11327 }; 11328 11329 // Check if we've already successfully checked the comparison category type 11330 // before. If so, skip checking it again. 11331 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11332 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11333 // The only thing we need to check is that the type has a reachable 11334 // definition in the current context. 11335 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11336 return QualType(); 11337 11338 return Info->getType(); 11339 } 11340 11341 // If lookup failed 11342 if (!Info) { 11343 std::string NameForDiags = "std::"; 11344 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11345 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11346 << NameForDiags << (int)Usage; 11347 return QualType(); 11348 } 11349 11350 assert(Info->Kind == Kind)(static_cast <bool> (Info->Kind == Kind) ? void (0) :
__assert_fail ("Info->Kind == Kind", "clang/lib/Sema/SemaDeclCXX.cpp"
, 11350, __extension__ __PRETTY_FUNCTION__))
; 11351 assert(Info->Record)(static_cast <bool> (Info->Record) ? void (0) : __assert_fail
("Info->Record", "clang/lib/Sema/SemaDeclCXX.cpp", 11351,
__extension__ __PRETTY_FUNCTION__))
; 11352 11353 // Update the Record decl in case we encountered a forward declaration on our 11354 // first pass. FIXME: This is a bit of a hack. 11355 if (Info->Record->hasDefinition()) 11356 Info->Record = Info->Record->getDefinition(); 11357 11358 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11359 return QualType(); 11360 11361 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11362 11363 if (!Info->Record->isTriviallyCopyable()) 11364 return UnsupportedSTLError(USS_NonTrivial); 11365 11366 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11367 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11368 // Tolerate empty base classes. 11369 if (Base->isEmpty()) 11370 continue; 11371 // Reject STL implementations which have at least one non-empty base. 11372 return UnsupportedSTLError(); 11373 } 11374 11375 // Check that the STL has implemented the types using a single integer field. 11376 // This expectation allows better codegen for builtin operators. We require: 11377 // (1) The class has exactly one field. 11378 // (2) The field is an integral or enumeration type. 11379 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11380 if (std::distance(FIt, FEnd) != 1 || 11381 !FIt->getType()->isIntegralOrEnumerationType()) { 11382 return UnsupportedSTLError(); 11383 } 11384 11385 // Build each of the require values and store them in Info. 11386 for (ComparisonCategoryResult CCR : 11387 ComparisonCategories::getPossibleResultsForType(Kind)) { 11388 StringRef MemName = ComparisonCategories::getResultString(CCR); 11389 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11390 11391 if (!ValInfo) 11392 return UnsupportedSTLError(USS_MissingMember, MemName); 11393 11394 VarDecl *VD = ValInfo->VD; 11395 assert(VD && "should not be null!")(static_cast <bool> (VD && "should not be null!"
) ? void (0) : __assert_fail ("VD && \"should not be null!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11395, __extension__ __PRETTY_FUNCTION__
))
; 11396 11397 // Attempt to diagnose reasons why the STL definition of this type 11398 // might be foobar, including it failing to be a constant expression. 11399 // TODO Handle more ways the lookup or result can be invalid. 11400 if (!VD->isStaticDataMember() || 11401 !VD->isUsableInConstantExpressions(Context)) 11402 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11403 11404 // Attempt to evaluate the var decl as a constant expression and extract 11405 // the value of its first field as a ICE. If this fails, the STL 11406 // implementation is not supported. 11407 if (!ValInfo->hasValidIntValue()) 11408 return UnsupportedSTLError(); 11409 11410 MarkVariableReferenced(Loc, VD); 11411 } 11412 11413 // We've successfully built the required types and expressions. Update 11414 // the cache and return the newly cached value. 11415 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11416 return Info->getType(); 11417} 11418 11419/// Retrieve the special "std" namespace, which may require us to 11420/// implicitly define the namespace. 11421NamespaceDecl *Sema::getOrCreateStdNamespace() { 11422 if (!StdNamespace) { 11423 // The "std" namespace has not yet been defined, so build one implicitly. 11424 StdNamespace = NamespaceDecl::Create(Context, 11425 Context.getTranslationUnitDecl(), 11426 /*Inline=*/false, 11427 SourceLocation(), SourceLocation(), 11428 &PP.getIdentifierTable().get("std"), 11429 /*PrevDecl=*/nullptr); 11430 getStdNamespace()->setImplicit(true); 11431 } 11432 11433 return getStdNamespace(); 11434} 11435 11436bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11437 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11438, __extension__ __PRETTY_FUNCTION__
))
11438 "Looking for std::initializer_list outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11438, __extension__ __PRETTY_FUNCTION__
))
; 11439 11440 // We're looking for implicit instantiations of 11441 // template <typename E> class std::initializer_list. 11442 11443 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11444 return false; 11445 11446 ClassTemplateDecl *Template = nullptr; 11447 const TemplateArgument *Arguments = nullptr; 11448 11449 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11450 11451 ClassTemplateSpecializationDecl *Specialization = 11452 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11453 if (!Specialization) 11454 return false; 11455 11456 Template = Specialization->getSpecializedTemplate(); 11457 Arguments = Specialization->getTemplateArgs().data(); 11458 } else if (const TemplateSpecializationType *TST = 11459 Ty->getAs<TemplateSpecializationType>()) { 11460 Template = dyn_cast_or_null<ClassTemplateDecl>( 11461 TST->getTemplateName().getAsTemplateDecl()); 11462 Arguments = TST->getArgs(); 11463 } 11464 if (!Template) 11465 return false; 11466 11467 if (!StdInitializerList) { 11468 // Haven't recognized std::initializer_list yet, maybe this is it. 11469 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11470 if (TemplateClass->getIdentifier() != 11471 &PP.getIdentifierTable().get("initializer_list") || 11472 !getStdNamespace()->InEnclosingNamespaceSetOf( 11473 TemplateClass->getDeclContext())) 11474 return false; 11475 // This is a template called std::initializer_list, but is it the right 11476 // template? 11477 TemplateParameterList *Params = Template->getTemplateParameters(); 11478 if (Params->getMinRequiredArguments() != 1) 11479 return false; 11480 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11481 return false; 11482 11483 // It's the right template. 11484 StdInitializerList = Template; 11485 } 11486 11487 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11488 return false; 11489 11490 // This is an instance of std::initializer_list. Find the argument type. 11491 if (Element) 11492 *Element = Arguments[0].getAsType(); 11493 return true; 11494} 11495 11496static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11497 NamespaceDecl *Std = S.getStdNamespace(); 11498 if (!Std) { 11499 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11500 return nullptr; 11501 } 11502 11503 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11504 Loc, Sema::LookupOrdinaryName); 11505 if (!S.LookupQualifiedName(Result, Std)) { 11506 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11507 return nullptr; 11508 } 11509 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11510 if (!Template) { 11511 Result.suppressDiagnostics(); 11512 // We found something weird. Complain about the first thing we found. 11513 NamedDecl *Found = *Result.begin(); 11514 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11515 return nullptr; 11516 } 11517 11518 // We found some template called std::initializer_list. Now verify that it's 11519 // correct. 11520 TemplateParameterList *Params = Template->getTemplateParameters(); 11521 if (Params->getMinRequiredArguments() != 1 || 11522 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11523 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11524 return nullptr; 11525 } 11526 11527 return Template; 11528} 11529 11530QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11531 if (!StdInitializerList) { 11532 StdInitializerList = LookupStdInitializerList(*this, Loc); 11533 if (!StdInitializerList) 11534 return QualType(); 11535 } 11536 11537 TemplateArgumentListInfo Args(Loc, Loc); 11538 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11539 Context.getTrivialTypeSourceInfo(Element, 11540 Loc))); 11541 return Context.getCanonicalType( 11542 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11543} 11544 11545bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11546 // C++ [dcl.init.list]p2: 11547 // A constructor is an initializer-list constructor if its first parameter 11548 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11549 // std::initializer_list<E> for some type E, and either there are no other 11550 // parameters or else all other parameters have default arguments. 11551 if (!Ctor->hasOneParamOrDefaultArgs()) 11552 return false; 11553 11554 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11555 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11556 ArgType = RT->getPointeeType().getUnqualifiedType(); 11557 11558 return isStdInitializerList(ArgType, nullptr); 11559} 11560 11561/// Determine whether a using statement is in a context where it will be 11562/// apply in all contexts. 11563static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11564 switch (CurContext->getDeclKind()) { 11565 case Decl::TranslationUnit: 11566 return true; 11567 case Decl::LinkageSpec: 11568 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11569 default: 11570 return false; 11571 } 11572} 11573 11574namespace { 11575 11576// Callback to only accept typo corrections that are namespaces. 11577class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11578public: 11579 bool ValidateCandidate(const TypoCorrection &candidate) override { 11580 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11581 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11582 return false; 11583 } 11584 11585 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11586 return std::make_unique<NamespaceValidatorCCC>(*this); 11587 } 11588}; 11589 11590} 11591 11592static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11593 CXXScopeSpec &SS, 11594 SourceLocation IdentLoc, 11595 IdentifierInfo *Ident) { 11596 R.clear(); 11597 NamespaceValidatorCCC CCC{}; 11598 if (TypoCorrection Corrected = 11599 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11600 Sema::CTK_ErrorRecovery)) { 11601 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11602 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11603 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11604 Ident->getName().equals(CorrectedStr); 11605 S.diagnoseTypo(Corrected, 11606 S.PDiag(diag::err_using_directive_member_suggest) 11607 << Ident << DC << DroppedSpecifier << SS.getRange(), 11608 S.PDiag(diag::note_namespace_defined_here)); 11609 } else { 11610 S.diagnoseTypo(Corrected, 11611 S.PDiag(diag::err_using_directive_suggest) << Ident, 11612 S.PDiag(diag::note_namespace_defined_here)); 11613 } 11614 R.addDecl(Corrected.getFoundDecl()); 11615 return true; 11616 } 11617 return false; 11618} 11619 11620Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11621 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11622 SourceLocation IdentLoc, 11623 IdentifierInfo *NamespcName, 11624 const ParsedAttributesView &AttrList) { 11625 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11625, __extension__ __PRETTY_FUNCTION__
))
; 11626 assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName."
) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11626, __extension__ __PRETTY_FUNCTION__
))
; 11627 assert(IdentLoc.isValid() && "Invalid NamespceName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid NamespceName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11627, __extension__ __PRETTY_FUNCTION__
))
; 11628 11629 // This can only happen along a recovery path. 11630 while (S->isTemplateParamScope()) 11631 S = S->getParent(); 11632 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11632, __extension__ __PRETTY_FUNCTION__
))
; 11633 11634 UsingDirectiveDecl *UDir = nullptr; 11635 NestedNameSpecifier *Qualifier = nullptr; 11636 if (SS.isSet()) 11637 Qualifier = SS.getScopeRep(); 11638 11639 // Lookup namespace name. 11640 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11641 LookupParsedName(R, S, &SS); 11642 if (R.isAmbiguous()) 11643 return nullptr; 11644 11645 if (R.empty()) { 11646 R.clear(); 11647 // Allow "using namespace std;" or "using namespace ::std;" even if 11648 // "std" hasn't been defined yet, for GCC compatibility. 11649 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11650 NamespcName->isStr("std")) { 11651 Diag(IdentLoc, diag::ext_using_undefined_std); 11652 R.addDecl(getOrCreateStdNamespace()); 11653 R.resolveKind(); 11654 } 11655 // Otherwise, attempt typo correction. 11656 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11657 } 11658 11659 if (!R.empty()) { 11660 NamedDecl *Named = R.getRepresentativeDecl(); 11661 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11662 assert(NS && "expected namespace decl")(static_cast <bool> (NS && "expected namespace decl"
) ? void (0) : __assert_fail ("NS && \"expected namespace decl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11662, __extension__ __PRETTY_FUNCTION__
))
; 11663 11664 // The use of a nested name specifier may trigger deprecation warnings. 11665 DiagnoseUseOfDecl(Named, IdentLoc); 11666 11667 // C++ [namespace.udir]p1: 11668 // A using-directive specifies that the names in the nominated 11669 // namespace can be used in the scope in which the 11670 // using-directive appears after the using-directive. During 11671 // unqualified name lookup (3.4.1), the names appear as if they 11672 // were declared in the nearest enclosing namespace which 11673 // contains both the using-directive and the nominated 11674 // namespace. [Note: in this context, "contains" means "contains 11675 // directly or indirectly". ] 11676 11677 // Find enclosing context containing both using-directive and 11678 // nominated namespace. 11679 DeclContext *CommonAncestor = NS; 11680 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11681 CommonAncestor = CommonAncestor->getParent(); 11682 11683 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11684 SS.getWithLocInContext(Context), 11685 IdentLoc, Named, CommonAncestor); 11686 11687 if (IsUsingDirectiveInToplevelContext(CurContext) && 11688 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11689 Diag(IdentLoc, diag::warn_using_directive_in_header); 11690 } 11691 11692 PushUsingDirective(S, UDir); 11693 } else { 11694 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11695 } 11696 11697 if (UDir) 11698 ProcessDeclAttributeList(S, UDir, AttrList); 11699 11700 return UDir; 11701} 11702 11703void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11704 // If the scope has an associated entity and the using directive is at 11705 // namespace or translation unit scope, add the UsingDirectiveDecl into 11706 // its lookup structure so qualified name lookup can find it. 11707 DeclContext *Ctx = S->getEntity(); 11708 if (Ctx && !Ctx->isFunctionOrMethod()) 11709 Ctx->addDecl(UDir); 11710 else 11711 // Otherwise, it is at block scope. The using-directives will affect lookup 11712 // only to the end of the scope. 11713 S->PushUsingDirective(UDir); 11714} 11715 11716Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11717 SourceLocation UsingLoc, 11718 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11719 UnqualifiedId &Name, 11720 SourceLocation EllipsisLoc, 11721 const ParsedAttributesView &AttrList) { 11722 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11722, __extension__ __PRETTY_FUNCTION__
))
; 11723 11724 if (SS.isEmpty()) { 11725 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11726 return nullptr; 11727 } 11728 11729 switch (Name.getKind()) { 11730 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11731 case UnqualifiedIdKind::IK_Identifier: 11732 case UnqualifiedIdKind::IK_OperatorFunctionId: 11733 case UnqualifiedIdKind::IK_LiteralOperatorId: 11734 case UnqualifiedIdKind::IK_ConversionFunctionId: 11735 break; 11736 11737 case UnqualifiedIdKind::IK_ConstructorName: 11738 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11739 // C++11 inheriting constructors. 11740 Diag(Name.getBeginLoc(), 11741 getLangOpts().CPlusPlus11 11742 ? diag::warn_cxx98_compat_using_decl_constructor 11743 : diag::err_using_decl_constructor) 11744 << SS.getRange(); 11745 11746 if (getLangOpts().CPlusPlus11) break; 11747 11748 return nullptr; 11749 11750 case UnqualifiedIdKind::IK_DestructorName: 11751 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11752 return nullptr; 11753 11754 case UnqualifiedIdKind::IK_TemplateId: 11755 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11756 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11757 return nullptr; 11758 11759 case UnqualifiedIdKind::IK_DeductionGuideName: 11760 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11760)
; 11761 } 11762 11763 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11764 DeclarationName TargetName = TargetNameInfo.getName(); 11765 if (!TargetName) 11766 return nullptr; 11767 11768 // Warn about access declarations. 11769 if (UsingLoc.isInvalid()) { 11770 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11771 ? diag::err_access_decl 11772 : diag::warn_access_decl_deprecated) 11773 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11774 } 11775 11776 if (EllipsisLoc.isInvalid()) { 11777 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11778 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11779 return nullptr; 11780 } else { 11781 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11782 !TargetNameInfo.containsUnexpandedParameterPack()) { 11783 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11784 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11785 EllipsisLoc = SourceLocation(); 11786 } 11787 } 11788 11789 NamedDecl *UD = 11790 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11791 SS, TargetNameInfo, EllipsisLoc, AttrList, 11792 /*IsInstantiation*/ false, 11793 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11794 if (UD) 11795 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11796 11797 return UD; 11798} 11799 11800Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11801 SourceLocation UsingLoc, 11802 SourceLocation EnumLoc, 11803 const DeclSpec &DS) { 11804 switch (DS.getTypeSpecType()) { 11805 case DeclSpec::TST_error: 11806 // This will already have been diagnosed 11807 return nullptr; 11808 11809 case DeclSpec::TST_enum: 11810 break; 11811 11812 case DeclSpec::TST_typename: 11813 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11814 return nullptr; 11815 11816 default: 11817 llvm_unreachable("unexpected DeclSpec type")::llvm::llvm_unreachable_internal("unexpected DeclSpec type",
"clang/lib/Sema/SemaDeclCXX.cpp", 11817)
; 11818 } 11819 11820 // As with enum-decls, we ignore attributes for now. 11821 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11822 if (auto *Def = Enum->getDefinition()) 11823 Enum = Def; 11824 11825 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11826 DS.getTypeSpecTypeNameLoc(), Enum); 11827 if (UD) 11828 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11829 11830 return UD; 11831} 11832 11833/// Determine whether a using declaration considers the given 11834/// declarations as "equivalent", e.g., if they are redeclarations of 11835/// the same entity or are both typedefs of the same type. 11836static bool 11837IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11838 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11839 return true; 11840 11841 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11842 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11843 return Context.hasSameType(TD1->getUnderlyingType(), 11844 TD2->getUnderlyingType()); 11845 11846 // Two using_if_exists using-declarations are equivalent if both are 11847 // unresolved. 11848 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11849 isa<UnresolvedUsingIfExistsDecl>(D2)) 11850 return true; 11851 11852 return false; 11853} 11854 11855 11856/// Determines whether to create a using shadow decl for a particular 11857/// decl, given the set of decls existing prior to this using lookup. 11858bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11859 const LookupResult &Previous, 11860 UsingShadowDecl *&PrevShadow) { 11861 // Diagnose finding a decl which is not from a base class of the 11862 // current class. We do this now because there are cases where this 11863 // function will silently decide not to build a shadow decl, which 11864 // will pre-empt further diagnostics. 11865 // 11866 // We don't need to do this in C++11 because we do the check once on 11867 // the qualifier. 11868 // 11869 // FIXME: diagnose the following if we care enough: 11870 // struct A { int foo; }; 11871 // struct B : A { using A::foo; }; 11872 // template <class T> struct C : A {}; 11873 // template <class T> struct D : C<T> { using B::foo; } // <--- 11874 // This is invalid (during instantiation) in C++03 because B::foo 11875 // resolves to the using decl in B, which is not a base class of D<T>. 11876 // We can't diagnose it immediately because C<T> is an unknown 11877 // specialization. The UsingShadowDecl in D<T> then points directly 11878 // to A::foo, which will look well-formed when we instantiate. 11879 // The right solution is to not collapse the shadow-decl chain. 11880 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11881 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11882 DeclContext *OrigDC = Orig->getDeclContext(); 11883 11884 // Handle enums and anonymous structs. 11885 if (isa<EnumDecl>(OrigDC)) 11886 OrigDC = OrigDC->getParent(); 11887 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11888 while (OrigRec->isAnonymousStructOrUnion()) 11889 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11890 11891 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11892 if (OrigDC == CurContext) { 11893 Diag(Using->getLocation(), 11894 diag::err_using_decl_nested_name_specifier_is_current_class) 11895 << Using->getQualifierLoc().getSourceRange(); 11896 Diag(Orig->getLocation(), diag::note_using_decl_target); 11897 Using->setInvalidDecl(); 11898 return true; 11899 } 11900 11901 Diag(Using->getQualifierLoc().getBeginLoc(), 11902 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11903 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11904 << Using->getQualifierLoc().getSourceRange(); 11905 Diag(Orig->getLocation(), diag::note_using_decl_target); 11906 Using->setInvalidDecl(); 11907 return true; 11908 } 11909 } 11910 11911 if (Previous.empty()) return false; 11912 11913 NamedDecl *Target = Orig; 11914 if (isa<UsingShadowDecl>(Target)) 11915 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11916 11917 // If the target happens to be one of the previous declarations, we 11918 // don't have a conflict. 11919 // 11920 // FIXME: but we might be increasing its access, in which case we 11921 // should redeclare it. 11922 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11923 bool FoundEquivalentDecl = false; 11924 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11925 I != E; ++I) { 11926 NamedDecl *D = (*I)->getUnderlyingDecl(); 11927 // We can have UsingDecls in our Previous results because we use the same 11928 // LookupResult for checking whether the UsingDecl itself is a valid 11929 // redeclaration. 11930 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11931 continue; 11932 11933 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11934 // C++ [class.mem]p19: 11935 // If T is the name of a class, then [every named member other than 11936 // a non-static data member] shall have a name different from T 11937 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11938 !isa<IndirectFieldDecl>(Target) && 11939 !isa<UnresolvedUsingValueDecl>(Target) && 11940 DiagnoseClassNameShadow( 11941 CurContext, 11942 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11943 return true; 11944 } 11945 11946 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11947 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11948 PrevShadow = Shadow; 11949 FoundEquivalentDecl = true; 11950 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11951 // We don't conflict with an existing using shadow decl of an equivalent 11952 // declaration, but we're not a redeclaration of it. 11953 FoundEquivalentDecl = true; 11954 } 11955 11956 if (isVisible(D)) 11957 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11958 } 11959 11960 if (FoundEquivalentDecl) 11961 return false; 11962 11963 // Always emit a diagnostic for a mismatch between an unresolved 11964 // using_if_exists and a resolved using declaration in either direction. 11965 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11966 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11967 if (!NonTag && !Tag) 11968 return false; 11969 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11970 Diag(Target->getLocation(), diag::note_using_decl_target); 11971 Diag((NonTag ? NonTag : Tag)->getLocation(), 11972 diag::note_using_decl_conflict); 11973 BUD->setInvalidDecl(); 11974 return true; 11975 } 11976 11977 if (FunctionDecl *FD = Target->getAsFunction()) { 11978 NamedDecl *OldDecl = nullptr; 11979 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11980 /*IsForUsingDecl*/ true)) { 11981 case Ovl_Overload: 11982 return false; 11983 11984 case Ovl_NonFunction: 11985 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11986 break; 11987 11988 // We found a decl with the exact signature. 11989 case Ovl_Match: 11990 // If we're in a record, we want to hide the target, so we 11991 // return true (without a diagnostic) to tell the caller not to 11992 // build a shadow decl. 11993 if (CurContext->isRecord()) 11994 return true; 11995 11996 // If we're not in a record, this is an error. 11997 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11998 break; 11999 } 12000 12001 Diag(Target->getLocation(), diag::note_using_decl_target); 12002 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 12003 BUD->setInvalidDecl(); 12004 return true; 12005 } 12006 12007 // Target is not a function. 12008 12009 if (isa<TagDecl>(Target)) { 12010 // No conflict between a tag and a non-tag. 12011 if (!Tag) return false; 12012 12013 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12014 Diag(Target->getLocation(), diag::note_using_decl_target); 12015 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 12016 BUD->setInvalidDecl(); 12017 return true; 12018 } 12019 12020 // No conflict between a tag and a non-tag. 12021 if (!NonTag) return false; 12022 12023 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12024 Diag(Target->getLocation(), diag::note_using_decl_target); 12025 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 12026 BUD->setInvalidDecl(); 12027 return true; 12028} 12029 12030/// Determine whether a direct base class is a virtual base class. 12031static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 12032 if (!Derived->getNumVBases()) 12033 return false; 12034 for (auto &B : Derived->bases()) 12035 if (B.getType()->getAsCXXRecordDecl() == Base) 12036 return B.isVirtual(); 12037 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "clang/lib/Sema/SemaDeclCXX.cpp"
, 12037)
; 12038} 12039 12040/// Builds a shadow declaration corresponding to a 'using' declaration. 12041UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 12042 NamedDecl *Orig, 12043 UsingShadowDecl *PrevDecl) { 12044 // If we resolved to another shadow declaration, just coalesce them. 12045 NamedDecl *Target = Orig; 12046 if (isa<UsingShadowDecl>(Target)) { 12047 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 12048 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")(static_cast <bool> (!isa<UsingShadowDecl>(Target
) && "nested shadow declaration") ? void (0) : __assert_fail
("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12048, __extension__ __PRETTY_FUNCTION__
))
; 12049 } 12050 12051 NamedDecl *NonTemplateTarget = Target; 12052 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 12053 NonTemplateTarget = TargetTD->getTemplatedDecl(); 12054 12055 UsingShadowDecl *Shadow; 12056 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 12057 UsingDecl *Using = cast<UsingDecl>(BUD); 12058 bool IsVirtualBase = 12059 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 12060 Using->getQualifier()->getAsRecordDecl()); 12061 Shadow = ConstructorUsingShadowDecl::Create( 12062 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 12063 } else { 12064 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 12065 Target->getDeclName(), BUD, Target); 12066 } 12067 BUD->addShadowDecl(Shadow); 12068 12069 Shadow->setAccess(BUD->getAccess()); 12070 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 12071 Shadow->setInvalidDecl(); 12072 12073 Shadow->setPreviousDecl(PrevDecl); 12074 12075 if (S) 12076 PushOnScopeChains(Shadow, S); 12077 else 12078 CurContext->addDecl(Shadow); 12079 12080 12081 return Shadow; 12082} 12083 12084/// Hides a using shadow declaration. This is required by the current 12085/// using-decl implementation when a resolvable using declaration in a 12086/// class is followed by a declaration which would hide or override 12087/// one or more of the using decl's targets; for example: 12088/// 12089/// struct Base { void foo(int); }; 12090/// struct Derived : Base { 12091/// using Base::foo; 12092/// void foo(int); 12093/// }; 12094/// 12095/// The governing language is C++03 [namespace.udecl]p12: 12096/// 12097/// When a using-declaration brings names from a base class into a 12098/// derived class scope, member functions in the derived class 12099/// override and/or hide member functions with the same name and 12100/// parameter types in a base class (rather than conflicting). 12101/// 12102/// There are two ways to implement this: 12103/// (1) optimistically create shadow decls when they're not hidden 12104/// by existing declarations, or 12105/// (2) don't create any shadow decls (or at least don't make them 12106/// visible) until we've fully parsed/instantiated the class. 12107/// The problem with (1) is that we might have to retroactively remove 12108/// a shadow decl, which requires several O(n) operations because the 12109/// decl structures are (very reasonably) not designed for removal. 12110/// (2) avoids this but is very fiddly and phase-dependent. 12111void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12112 if (Shadow->getDeclName().getNameKind() == 12113 DeclarationName::CXXConversionFunctionName) 12114 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12115 12116 // Remove it from the DeclContext... 12117 Shadow->getDeclContext()->removeDecl(Shadow); 12118 12119 // ...and the scope, if applicable... 12120 if (S) { 12121 S->RemoveDecl(Shadow); 12122 IdResolver.RemoveDecl(Shadow); 12123 } 12124 12125 // ...and the using decl. 12126 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12127 12128 // TODO: complain somehow if Shadow was used. It shouldn't 12129 // be possible for this to happen, because...? 12130} 12131 12132/// Find the base specifier for a base class with the given type. 12133static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12134 QualType DesiredBase, 12135 bool &AnyDependentBases) { 12136 // Check whether the named type is a direct base class. 12137 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12138 .getUnqualifiedType(); 12139 for (auto &Base : Derived->bases()) { 12140 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12141 if (CanonicalDesiredBase == BaseType) 12142 return &Base; 12143 if (BaseType->isDependentType()) 12144 AnyDependentBases = true; 12145 } 12146 return nullptr; 12147} 12148 12149namespace { 12150class UsingValidatorCCC final : public CorrectionCandidateCallback { 12151public: 12152 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12153 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12154 : HasTypenameKeyword(HasTypenameKeyword), 12155 IsInstantiation(IsInstantiation), OldNNS(NNS), 12156 RequireMemberOf(RequireMemberOf) {} 12157 12158 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12159 NamedDecl *ND = Candidate.getCorrectionDecl(); 12160 12161 // Keywords are not valid here. 12162 if (!ND || isa<NamespaceDecl>(ND)) 12163 return false; 12164 12165 // Completely unqualified names are invalid for a 'using' declaration. 12166 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12167 return false; 12168 12169 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12170 // reject. 12171 12172 if (RequireMemberOf) { 12173 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12174 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12175 // No-one ever wants a using-declaration to name an injected-class-name 12176 // of a base class, unless they're declaring an inheriting constructor. 12177 ASTContext &Ctx = ND->getASTContext(); 12178 if (!Ctx.getLangOpts().CPlusPlus11) 12179 return false; 12180 QualType FoundType = Ctx.getRecordType(FoundRecord); 12181 12182 // Check that the injected-class-name is named as a member of its own 12183 // type; we don't want to suggest 'using Derived::Base;', since that 12184 // means something else. 12185 NestedNameSpecifier *Specifier = 12186 Candidate.WillReplaceSpecifier() 12187 ? Candidate.getCorrectionSpecifier() 12188 : OldNNS; 12189 if (!Specifier->getAsType() || 12190 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12191 return false; 12192 12193 // Check that this inheriting constructor declaration actually names a 12194 // direct base class of the current class. 12195 bool AnyDependentBases = false; 12196 if (!findDirectBaseWithType(RequireMemberOf, 12197 Ctx.getRecordType(FoundRecord), 12198 AnyDependentBases) && 12199 !AnyDependentBases) 12200 return false; 12201 } else { 12202 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12203 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12204 return false; 12205 12206 // FIXME: Check that the base class member is accessible? 12207 } 12208 } else { 12209 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12210 if (FoundRecord && FoundRecord->isInjectedClassName()) 12211 return false; 12212 } 12213 12214 if (isa<TypeDecl>(ND)) 12215 return HasTypenameKeyword || !IsInstantiation; 12216 12217 return !HasTypenameKeyword; 12218 } 12219 12220 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12221 return std::make_unique<UsingValidatorCCC>(*this); 12222 } 12223 12224private: 12225 bool HasTypenameKeyword; 12226 bool IsInstantiation; 12227 NestedNameSpecifier *OldNNS; 12228 CXXRecordDecl *RequireMemberOf; 12229}; 12230} // end anonymous namespace 12231 12232/// Remove decls we can't actually see from a lookup being used to declare 12233/// shadow using decls. 12234/// 12235/// \param S - The scope of the potential shadow decl 12236/// \param Previous - The lookup of a potential shadow decl's name. 12237void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12238 // It is really dumb that we have to do this. 12239 LookupResult::Filter F = Previous.makeFilter(); 12240 while (F.hasNext()) { 12241 NamedDecl *D = F.next(); 12242 if (!isDeclInScope(D, CurContext, S)) 12243 F.erase(); 12244 // If we found a local extern declaration that's not ordinarily visible, 12245 // and this declaration is being added to a non-block scope, ignore it. 12246 // We're only checking for scope conflicts here, not also for violations 12247 // of the linkage rules. 12248 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12249 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12250 F.erase(); 12251 } 12252 F.done(); 12253} 12254 12255/// Builds a using declaration. 12256/// 12257/// \param IsInstantiation - Whether this call arises from an 12258/// instantiation of an unresolved using declaration. We treat 12259/// the lookup differently for these declarations. 12260NamedDecl *Sema::BuildUsingDeclaration( 12261 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12262 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12263 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12264 const ParsedAttributesView &AttrList, bool IsInstantiation, 12265 bool IsUsingIfExists) { 12266 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12266, __extension__ __PRETTY_FUNCTION__
))
; 12267 SourceLocation IdentLoc = NameInfo.getLoc(); 12268 assert(IdentLoc.isValid() && "Invalid TargetName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid TargetName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12268, __extension__ __PRETTY_FUNCTION__
))
; 12269 12270 // FIXME: We ignore attributes for now. 12271 12272 // For an inheriting constructor declaration, the name of the using 12273 // declaration is the name of a constructor in this class, not in the 12274 // base class. 12275 DeclarationNameInfo UsingName = NameInfo; 12276 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12277 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12278 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12279 Context.getCanonicalType(Context.getRecordType(RD)))); 12280 12281 // Do the redeclaration lookup in the current scope. 12282 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12283 ForVisibleRedeclaration); 12284 Previous.setHideTags(false); 12285 if (S) { 12286 LookupName(Previous, S); 12287 12288 FilterUsingLookup(S, Previous); 12289 } else { 12290 assert(IsInstantiation && "no scope in non-instantiation")(static_cast <bool> (IsInstantiation && "no scope in non-instantiation"
) ? void (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12290, __extension__ __PRETTY_FUNCTION__
))
; 12291 if (CurContext->isRecord()) 12292 LookupQualifiedName(Previous, CurContext); 12293 else { 12294 // No redeclaration check is needed here; in non-member contexts we 12295 // diagnosed all possible conflicts with other using-declarations when 12296 // building the template: 12297 // 12298 // For a dependent non-type using declaration, the only valid case is 12299 // if we instantiate to a single enumerator. We check for conflicts 12300 // between shadow declarations we introduce, and we check in the template 12301 // definition for conflicts between a non-type using declaration and any 12302 // other declaration, which together covers all cases. 12303 // 12304 // A dependent typename using declaration will never successfully 12305 // instantiate, since it will always name a class member, so we reject 12306 // that in the template definition. 12307 } 12308 } 12309 12310 // Check for invalid redeclarations. 12311 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12312 SS, IdentLoc, Previous)) 12313 return nullptr; 12314 12315 // 'using_if_exists' doesn't make sense on an inherited constructor. 12316 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12317 DeclarationName::CXXConstructorName) { 12318 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12319 return nullptr; 12320 } 12321 12322 DeclContext *LookupContext = computeDeclContext(SS); 12323 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12324 if (!LookupContext || EllipsisLoc.isValid()) { 12325 NamedDecl *D; 12326 // Dependent scope, or an unexpanded pack 12327 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12328 SS, NameInfo, IdentLoc)) 12329 return nullptr; 12330 12331 if (HasTypenameKeyword) { 12332 // FIXME: not all declaration name kinds are legal here 12333 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12334 UsingLoc, TypenameLoc, 12335 QualifierLoc, 12336 IdentLoc, NameInfo.getName(), 12337 EllipsisLoc); 12338 } else { 12339 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12340 QualifierLoc, NameInfo, EllipsisLoc); 12341 } 12342 D->setAccess(AS); 12343 CurContext->addDecl(D); 12344 ProcessDeclAttributeList(S, D, AttrList); 12345 return D; 12346 } 12347 12348 auto Build = [&](bool Invalid) { 12349 UsingDecl *UD = 12350 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12351 UsingName, HasTypenameKeyword); 12352 UD->setAccess(AS); 12353 CurContext->addDecl(UD); 12354 ProcessDeclAttributeList(S, UD, AttrList); 12355 UD->setInvalidDecl(Invalid); 12356 return UD; 12357 }; 12358 auto BuildInvalid = [&]{ return Build(true); }; 12359 auto BuildValid = [&]{ return Build(false); }; 12360 12361 if (RequireCompleteDeclContext(SS, LookupContext)) 12362 return BuildInvalid(); 12363 12364 // Look up the target name. 12365 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12366 12367 // Unlike most lookups, we don't always want to hide tag 12368 // declarations: tag names are visible through the using declaration 12369 // even if hidden by ordinary names, *except* in a dependent context 12370 // where they may be used by two-phase lookup. 12371 if (!IsInstantiation) 12372 R.setHideTags(false); 12373 12374 // For the purposes of this lookup, we have a base object type 12375 // equal to that of the current context. 12376 if (CurContext->isRecord()) { 12377 R.setBaseObjectType( 12378 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12379 } 12380 12381 LookupQualifiedName(R, LookupContext); 12382 12383 // Validate the context, now we have a lookup 12384 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12385 IdentLoc, &R)) 12386 return nullptr; 12387 12388 if (R.empty() && IsUsingIfExists) 12389 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12390 UsingName.getName()), 12391 AS_public); 12392 12393 // Try to correct typos if possible. If constructor name lookup finds no 12394 // results, that means the named class has no explicit constructors, and we 12395 // suppressed declaring implicit ones (probably because it's dependent or 12396 // invalid). 12397 if (R.empty() && 12398 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12399 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12400 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12401 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12402 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12403 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12404 CurContext->isStdNamespace() && 12405 isa<TranslationUnitDecl>(LookupContext) && 12406 getSourceManager().isInSystemHeader(UsingLoc)) 12407 return nullptr; 12408 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12409 dyn_cast<CXXRecordDecl>(CurContext)); 12410 if (TypoCorrection Corrected = 12411 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12412 CTK_ErrorRecovery)) { 12413 // We reject candidates where DroppedSpecifier == true, hence the 12414 // literal '0' below. 12415 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12416 << NameInfo.getName() << LookupContext << 0 12417 << SS.getRange()); 12418 12419 // If we picked a correction with no attached Decl we can't do anything 12420 // useful with it, bail out. 12421 NamedDecl *ND = Corrected.getCorrectionDecl(); 12422 if (!ND) 12423 return BuildInvalid(); 12424 12425 // If we corrected to an inheriting constructor, handle it as one. 12426 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12427 if (RD && RD->isInjectedClassName()) { 12428 // The parent of the injected class name is the class itself. 12429 RD = cast<CXXRecordDecl>(RD->getParent()); 12430 12431 // Fix up the information we'll use to build the using declaration. 12432 if (Corrected.WillReplaceSpecifier()) { 12433 NestedNameSpecifierLocBuilder Builder; 12434 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12435 QualifierLoc.getSourceRange()); 12436 QualifierLoc = Builder.getWithLocInContext(Context); 12437 } 12438 12439 // In this case, the name we introduce is the name of a derived class 12440 // constructor. 12441 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12442 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12443 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12444 UsingName.setNamedTypeInfo(nullptr); 12445 for (auto *Ctor : LookupConstructors(RD)) 12446 R.addDecl(Ctor); 12447 R.resolveKind(); 12448 } else { 12449 // FIXME: Pick up all the declarations if we found an overloaded 12450 // function. 12451 UsingName.setName(ND->getDeclName()); 12452 R.addDecl(ND); 12453 } 12454 } else { 12455 Diag(IdentLoc, diag::err_no_member) 12456 << NameInfo.getName() << LookupContext << SS.getRange(); 12457 return BuildInvalid(); 12458 } 12459 } 12460 12461 if (R.isAmbiguous()) 12462 return BuildInvalid(); 12463 12464 if (HasTypenameKeyword) { 12465 // If we asked for a typename and got a non-type decl, error out. 12466 if (!R.getAsSingle<TypeDecl>() && 12467 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12468 Diag(IdentLoc, diag::err_using_typename_non_type); 12469 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12470 Diag((*I)->getUnderlyingDecl()->getLocation(), 12471 diag::note_using_decl_target); 12472 return BuildInvalid(); 12473 } 12474 } else { 12475 // If we asked for a non-typename and we got a type, error out, 12476 // but only if this is an instantiation of an unresolved using 12477 // decl. Otherwise just silently find the type name. 12478 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12479 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12480 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12481 return BuildInvalid(); 12482 } 12483 } 12484 12485 // C++14 [namespace.udecl]p6: 12486 // A using-declaration shall not name a namespace. 12487 if (R.getAsSingle<NamespaceDecl>()) { 12488 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12489 << SS.getRange(); 12490 return BuildInvalid(); 12491 } 12492 12493 UsingDecl *UD = BuildValid(); 12494 12495 // Some additional rules apply to inheriting constructors. 12496 if (UsingName.getName().getNameKind() == 12497 DeclarationName::CXXConstructorName) { 12498 // Suppress access diagnostics; the access check is instead performed at the 12499 // point of use for an inheriting constructor. 12500 R.suppressDiagnostics(); 12501 if (CheckInheritingConstructorUsingDecl(UD)) 12502 return UD; 12503 } 12504 12505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12506 UsingShadowDecl *PrevDecl = nullptr; 12507 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12508 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12509 } 12510 12511 return UD; 12512} 12513 12514NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12515 SourceLocation UsingLoc, 12516 SourceLocation EnumLoc, 12517 SourceLocation NameLoc, 12518 EnumDecl *ED) { 12519 bool Invalid = false; 12520 12521 if (CurContext->getRedeclContext()->isRecord()) { 12522 /// In class scope, check if this is a duplicate, for better a diagnostic. 12523 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12524 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12525 ForVisibleRedeclaration); 12526 12527 LookupName(Previous, S); 12528 12529 for (NamedDecl *D : Previous) 12530 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12531 if (UED->getEnumDecl() == ED) { 12532 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12533 << SourceRange(EnumLoc, NameLoc); 12534 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12535 Invalid = true; 12536 break; 12537 } 12538 } 12539 12540 if (RequireCompleteEnumDecl(ED, NameLoc)) 12541 Invalid = true; 12542 12543 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12544 EnumLoc, NameLoc, ED); 12545 UD->setAccess(AS); 12546 CurContext->addDecl(UD); 12547 12548 if (Invalid) { 12549 UD->setInvalidDecl(); 12550 return UD; 12551 } 12552 12553 // Create the shadow decls for each enumerator 12554 for (EnumConstantDecl *EC : ED->enumerators()) { 12555 UsingShadowDecl *PrevDecl = nullptr; 12556 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12557 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12558 ForVisibleRedeclaration); 12559 LookupName(Previous, S); 12560 FilterUsingLookup(S, Previous); 12561 12562 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12563 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12564 } 12565 12566 return UD; 12567} 12568 12569NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12570 ArrayRef<NamedDecl *> Expansions) { 12571 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 12573, __extension__ __PRETTY_FUNCTION__
))
12572 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 12573, __extension__ __PRETTY_FUNCTION__
))
12573 isa<UsingPackDecl>(InstantiatedFrom))(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 12573, __extension__ __PRETTY_FUNCTION__
))
; 12574 12575 auto *UPD = 12576 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12577 UPD->setAccess(InstantiatedFrom->getAccess()); 12578 CurContext->addDecl(UPD); 12579 return UPD; 12580} 12581 12582/// Additional checks for a using declaration referring to a constructor name. 12583bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12584 assert(!UD->hasTypename() && "expecting a constructor name")(static_cast <bool> (!UD->hasTypename() && "expecting a constructor name"
) ? void (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12584, __extension__ __PRETTY_FUNCTION__
))
; 12585 12586 const Type *SourceType = UD->getQualifier()->getAsType(); 12587 assert(SourceType &&(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12588, __extension__ __PRETTY_FUNCTION__
))
12588 "Using decl naming constructor doesn't have type in scope spec.")(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12588, __extension__ __PRETTY_FUNCTION__
))
; 12589 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12590 12591 // Check whether the named type is a direct base class. 12592 bool AnyDependentBases = false; 12593 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12594 AnyDependentBases); 12595 if (!Base && !AnyDependentBases) { 12596 Diag(UD->getUsingLoc(), 12597 diag::err_using_decl_constructor_not_in_direct_base) 12598 << UD->getNameInfo().getSourceRange() 12599 << QualType(SourceType, 0) << TargetClass; 12600 UD->setInvalidDecl(); 12601 return true; 12602 } 12603 12604 if (Base) 12605 Base->setInheritConstructors(); 12606 12607 return false; 12608} 12609 12610/// Checks that the given using declaration is not an invalid 12611/// redeclaration. Note that this is checking only for the using decl 12612/// itself, not for any ill-formedness among the UsingShadowDecls. 12613bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12614 bool HasTypenameKeyword, 12615 const CXXScopeSpec &SS, 12616 SourceLocation NameLoc, 12617 const LookupResult &Prev) { 12618 NestedNameSpecifier *Qual = SS.getScopeRep(); 12619 12620 // C++03 [namespace.udecl]p8: 12621 // C++0x [namespace.udecl]p10: 12622 // A using-declaration is a declaration and can therefore be used 12623 // repeatedly where (and only where) multiple declarations are 12624 // allowed. 12625 // 12626 // That's in non-member contexts. 12627 if (!CurContext->getRedeclContext()->isRecord()) { 12628 // A dependent qualifier outside a class can only ever resolve to an 12629 // enumeration type. Therefore it conflicts with any other non-type 12630 // declaration in the same scope. 12631 // FIXME: How should we check for dependent type-type conflicts at block 12632 // scope? 12633 if (Qual->isDependent() && !HasTypenameKeyword) { 12634 for (auto *D : Prev) { 12635 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12636 bool OldCouldBeEnumerator = 12637 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12638 Diag(NameLoc, 12639 OldCouldBeEnumerator ? diag::err_redefinition 12640 : diag::err_redefinition_different_kind) 12641 << Prev.getLookupName(); 12642 Diag(D->getLocation(), diag::note_previous_definition); 12643 return true; 12644 } 12645 } 12646 } 12647 return false; 12648 } 12649 12650 const NestedNameSpecifier *CNNS = 12651 Context.getCanonicalNestedNameSpecifier(Qual); 12652 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12653 NamedDecl *D = *I; 12654 12655 bool DTypename; 12656 NestedNameSpecifier *DQual; 12657 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12658 DTypename = UD->hasTypename(); 12659 DQual = UD->getQualifier(); 12660 } else if (UnresolvedUsingValueDecl *UD 12661 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12662 DTypename = false; 12663 DQual = UD->getQualifier(); 12664 } else if (UnresolvedUsingTypenameDecl *UD 12665 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12666 DTypename = true; 12667 DQual = UD->getQualifier(); 12668 } else continue; 12669 12670 // using decls differ if one says 'typename' and the other doesn't. 12671 // FIXME: non-dependent using decls? 12672 if (HasTypenameKeyword != DTypename) continue; 12673 12674 // using decls differ if they name different scopes (but note that 12675 // template instantiation can cause this check to trigger when it 12676 // didn't before instantiation). 12677 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12678 continue; 12679 12680 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12681 Diag(D->getLocation(), diag::note_using_decl) << 1; 12682 return true; 12683 } 12684 12685 return false; 12686} 12687 12688/// Checks that the given nested-name qualifier used in a using decl 12689/// in the current context is appropriately related to the current 12690/// scope. If an error is found, diagnoses it and returns true. 12691/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12692/// result of that lookup. UD is likewise nullptr, except when we have an 12693/// already-populated UsingDecl whose shadow decls contain the same information 12694/// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12695bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12696 const CXXScopeSpec &SS, 12697 const DeclarationNameInfo &NameInfo, 12698 SourceLocation NameLoc, 12699 const LookupResult *R, const UsingDecl *UD) { 12700 DeclContext *NamedContext = computeDeclContext(SS); 12701 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&(static_cast <bool> (bool(NamedContext) == (R || UD) &&
!(R && UD) && "resolvable context must have exactly one set of decls"
) ? void (0) : __assert_fail ("bool(NamedContext) == (R || UD) && !(R && UD) && \"resolvable context must have exactly one set of decls\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12702, __extension__ __PRETTY_FUNCTION__
))
12702 "resolvable context must have exactly one set of decls")(static_cast <bool> (bool(NamedContext) == (R || UD) &&
!(R && UD) && "resolvable context must have exactly one set of decls"
) ? void (0) : __assert_fail ("bool(NamedContext) == (R || UD) && !(R && UD) && \"resolvable context must have exactly one set of decls\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12702, __extension__ __PRETTY_FUNCTION__
))
; 12703 12704 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12705 // relationship. 12706 bool Cxx20Enumerator = false; 12707 if (NamedContext) { 12708 EnumConstantDecl *EC = nullptr; 12709 if (R) 12710 EC = R->getAsSingle<EnumConstantDecl>(); 12711 else if (UD && UD->shadow_size() == 1) 12712 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12713 if (EC) 12714 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12715 12716 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12717 // C++14 [namespace.udecl]p7: 12718 // A using-declaration shall not name a scoped enumerator. 12719 // C++20 p1099 permits enumerators. 12720 if (EC && R && ED->isScoped()) 12721 Diag(SS.getBeginLoc(), 12722 getLangOpts().CPlusPlus20 12723 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12724 : diag::ext_using_decl_scoped_enumerator) 12725 << SS.getRange(); 12726 12727 // We want to consider the scope of the enumerator 12728 NamedContext = ED->getDeclContext(); 12729 } 12730 } 12731 12732 if (!CurContext->isRecord()) { 12733 // C++03 [namespace.udecl]p3: 12734 // C++0x [namespace.udecl]p8: 12735 // A using-declaration for a class member shall be a member-declaration. 12736 // C++20 [namespace.udecl]p7 12737 // ... other than an enumerator ... 12738 12739 // If we weren't able to compute a valid scope, it might validly be a 12740 // dependent class or enumeration scope. If we have a 'typename' keyword, 12741 // the scope must resolve to a class type. 12742 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12743 : !HasTypename) 12744 return false; // OK 12745 12746 Diag(NameLoc, 12747 Cxx20Enumerator 12748 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12749 : diag::err_using_decl_can_not_refer_to_class_member) 12750 << SS.getRange(); 12751 12752 if (Cxx20Enumerator) 12753 return false; // OK 12754 12755 auto *RD = NamedContext 12756 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12757 : nullptr; 12758 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12759 // See if there's a helpful fixit 12760 12761 if (!R) { 12762 // We will have already diagnosed the problem on the template 12763 // definition, Maybe we should do so again? 12764 } else if (R->getAsSingle<TypeDecl>()) { 12765 if (getLangOpts().CPlusPlus11) { 12766 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12767 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12768 << 0 // alias declaration 12769 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12770 NameInfo.getName().getAsString() + 12771 " = "); 12772 } else { 12773 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12774 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12775 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12776 << 1 // typedef declaration 12777 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12778 << FixItHint::CreateInsertion( 12779 InsertLoc, " " + NameInfo.getName().getAsString()); 12780 } 12781 } else if (R->getAsSingle<VarDecl>()) { 12782 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12783 // repeating the type of the static data member here. 12784 FixItHint FixIt; 12785 if (getLangOpts().CPlusPlus11) { 12786 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12787 FixIt = FixItHint::CreateReplacement( 12788 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12789 } 12790 12791 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12792 << 2 // reference declaration 12793 << FixIt; 12794 } else if (R->getAsSingle<EnumConstantDecl>()) { 12795 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12796 // repeating the type of the enumeration here, and we can't do so if 12797 // the type is anonymous. 12798 FixItHint FixIt; 12799 if (getLangOpts().CPlusPlus11) { 12800 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12801 FixIt = FixItHint::CreateReplacement( 12802 UsingLoc, 12803 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12804 } 12805 12806 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12807 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12808 << FixIt; 12809 } 12810 } 12811 12812 return true; // Fail 12813 } 12814 12815 // If the named context is dependent, we can't decide much. 12816 if (!NamedContext) { 12817 // FIXME: in C++0x, we can diagnose if we can prove that the 12818 // nested-name-specifier does not refer to a base class, which is 12819 // still possible in some cases. 12820 12821 // Otherwise we have to conservatively report that things might be 12822 // okay. 12823 return false; 12824 } 12825 12826 // The current scope is a record. 12827 if (!NamedContext->isRecord()) { 12828 // Ideally this would point at the last name in the specifier, 12829 // but we don't have that level of source info. 12830 Diag(SS.getBeginLoc(), 12831 Cxx20Enumerator 12832 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12833 : diag::err_using_decl_nested_name_specifier_is_not_class) 12834 << SS.getScopeRep() << SS.getRange(); 12835 12836 if (Cxx20Enumerator) 12837 return false; // OK 12838 12839 return true; 12840 } 12841 12842 if (!NamedContext->isDependentContext() && 12843 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12844 return true; 12845 12846 if (getLangOpts().CPlusPlus11) { 12847 // C++11 [namespace.udecl]p3: 12848 // In a using-declaration used as a member-declaration, the 12849 // nested-name-specifier shall name a base class of the class 12850 // being defined. 12851 12852 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12853 cast<CXXRecordDecl>(NamedContext))) { 12854 12855 if (Cxx20Enumerator) { 12856 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12857 << SS.getRange(); 12858 return false; 12859 } 12860 12861 if (CurContext == NamedContext) { 12862 Diag(SS.getBeginLoc(), 12863 diag::err_using_decl_nested_name_specifier_is_current_class) 12864 << SS.getRange(); 12865 return !getLangOpts().CPlusPlus20; 12866 } 12867 12868 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12869 Diag(SS.getBeginLoc(), 12870 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12871 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12872 << SS.getRange(); 12873 } 12874 return true; 12875 } 12876 12877 return false; 12878 } 12879 12880 // C++03 [namespace.udecl]p4: 12881 // A using-declaration used as a member-declaration shall refer 12882 // to a member of a base class of the class being defined [etc.]. 12883 12884 // Salient point: SS doesn't have to name a base class as long as 12885 // lookup only finds members from base classes. Therefore we can 12886 // diagnose here only if we can prove that that can't happen, 12887 // i.e. if the class hierarchies provably don't intersect. 12888 12889 // TODO: it would be nice if "definitely valid" results were cached 12890 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12891 // need to be repeated. 12892 12893 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12894 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12895 Bases.insert(Base); 12896 return true; 12897 }; 12898 12899 // Collect all bases. Return false if we find a dependent base. 12900 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12901 return false; 12902 12903 // Returns true if the base is dependent or is one of the accumulated base 12904 // classes. 12905 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12906 return !Bases.count(Base); 12907 }; 12908 12909 // Return false if the class has a dependent base or if it or one 12910 // of its bases is present in the base set of the current context. 12911 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12912 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12913 return false; 12914 12915 Diag(SS.getRange().getBegin(), 12916 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12917 << SS.getScopeRep() 12918 << cast<CXXRecordDecl>(CurContext) 12919 << SS.getRange(); 12920 12921 return true; 12922} 12923 12924Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12925 MultiTemplateParamsArg TemplateParamLists, 12926 SourceLocation UsingLoc, UnqualifiedId &Name, 12927 const ParsedAttributesView &AttrList, 12928 TypeResult Type, Decl *DeclFromDeclSpec) { 12929 // Skip up to the relevant declaration scope. 12930 while (S->isTemplateParamScope()) 12931 S = S->getParent(); 12932 assert((S->getFlags() & Scope::DeclScope) &&(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12933, __extension__ __PRETTY_FUNCTION__
))
12933 "got alias-declaration outside of declaration scope")(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12933, __extension__ __PRETTY_FUNCTION__
))
; 12934 12935 if (Type.isInvalid()) 12936 return nullptr; 12937 12938 bool Invalid = false; 12939 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12940 TypeSourceInfo *TInfo = nullptr; 12941 GetTypeFromParser(Type.get(), &TInfo); 12942 12943 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12944 return nullptr; 12945 12946 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12947 UPPC_DeclarationType)) { 12948 Invalid = true; 12949 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12950 TInfo->getTypeLoc().getBeginLoc()); 12951 } 12952 12953 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12954 TemplateParamLists.size() 12955 ? forRedeclarationInCurContext() 12956 : ForVisibleRedeclaration); 12957 LookupName(Previous, S); 12958 12959 // Warn about shadowing the name of a template parameter. 12960 if (Previous.isSingleResult() && 12961 Previous.getFoundDecl()->isTemplateParameter()) { 12962 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12963 Previous.clear(); 12964 } 12965 12966 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&(static_cast <bool> (Name.Kind == UnqualifiedIdKind::IK_Identifier
&& "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12967, __extension__ __PRETTY_FUNCTION__
))
12967 "name in alias declaration must be an identifier")(static_cast <bool> (Name.Kind == UnqualifiedIdKind::IK_Identifier
&& "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12967, __extension__ __PRETTY_FUNCTION__
))
; 12968 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12969 Name.StartLocation, 12970 Name.Identifier, TInfo); 12971 12972 NewTD->setAccess(AS); 12973 12974 if (Invalid) 12975 NewTD->setInvalidDecl(); 12976 12977 ProcessDeclAttributeList(S, NewTD, AttrList); 12978 AddPragmaAttributes(S, NewTD); 12979 12980 CheckTypedefForVariablyModifiedType(S, NewTD); 12981 Invalid |= NewTD->isInvalidDecl(); 12982 12983 bool Redeclaration = false; 12984 12985 NamedDecl *NewND; 12986 if (TemplateParamLists.size()) { 12987 TypeAliasTemplateDecl *OldDecl = nullptr; 12988 TemplateParameterList *OldTemplateParams = nullptr; 12989 12990 if (TemplateParamLists.size() != 1) { 12991 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12992 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12993 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12994 } 12995 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12996 12997 // Check that we can declare a template here. 12998 if (CheckTemplateDeclScope(S, TemplateParams)) 12999 return nullptr; 13000 13001 // Only consider previous declarations in the same scope. 13002 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 13003 /*ExplicitInstantiationOrSpecialization*/false); 13004 if (!Previous.empty()) { 13005 Redeclaration = true; 13006 13007 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 13008 if (!OldDecl && !Invalid) { 13009 Diag(UsingLoc, diag::err_redefinition_different_kind) 13010 << Name.Identifier; 13011 13012 NamedDecl *OldD = Previous.getRepresentativeDecl(); 13013 if (OldD->getLocation().isValid()) 13014 Diag(OldD->getLocation(), diag::note_previous_definition); 13015 13016 Invalid = true; 13017 } 13018 13019 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 13020 if (TemplateParameterListsAreEqual(TemplateParams, 13021 OldDecl->getTemplateParameters(), 13022 /*Complain=*/true, 13023 TPL_TemplateMatch)) 13024 OldTemplateParams = 13025 OldDecl->getMostRecentDecl()->getTemplateParameters(); 13026 else 13027 Invalid = true; 13028 13029 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 13030 if (!Invalid && 13031 !Context.hasSameType(OldTD->getUnderlyingType(), 13032 NewTD->getUnderlyingType())) { 13033 // FIXME: The C++0x standard does not clearly say this is ill-formed, 13034 // but we can't reasonably accept it. 13035 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 13036 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 13037 if (OldTD->getLocation().isValid()) 13038 Diag(OldTD->getLocation(), diag::note_previous_definition); 13039 Invalid = true; 13040 } 13041 } 13042 } 13043 13044 // Merge any previous default template arguments into our parameters, 13045 // and check the parameter list. 13046 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 13047 TPC_TypeAliasTemplate)) 13048 return nullptr; 13049 13050 TypeAliasTemplateDecl *NewDecl = 13051 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 13052 Name.Identifier, TemplateParams, 13053 NewTD); 13054 NewTD->setDescribedAliasTemplate(NewDecl); 13055 13056 NewDecl->setAccess(AS); 13057 13058 if (Invalid) 13059 NewDecl->setInvalidDecl(); 13060 else if (OldDecl) { 13061 NewDecl->setPreviousDecl(OldDecl); 13062 CheckRedeclarationInModule(NewDecl, OldDecl); 13063 } 13064 13065 NewND = NewDecl; 13066 } else { 13067 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 13068 setTagNameForLinkagePurposes(TD, NewTD); 13069 handleTagNumbering(TD, S); 13070 } 13071 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 13072 NewND = NewTD; 13073 } 13074 13075 PushOnScopeChains(NewND, S); 13076 ActOnDocumentableDecl(NewND); 13077 return NewND; 13078} 13079 13080Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 13081 SourceLocation AliasLoc, 13082 IdentifierInfo *Alias, CXXScopeSpec &SS, 13083 SourceLocation IdentLoc, 13084 IdentifierInfo *Ident) { 13085 13086 // Lookup the namespace name. 13087 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 13088 LookupParsedName(R, S, &SS); 13089 13090 if (R.isAmbiguous()) 13091 return nullptr; 13092 13093 if (R.empty()) { 13094 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 13095 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 13096 return nullptr; 13097 } 13098 } 13099 assert(!R.isAmbiguous() && !R.empty())(static_cast <bool> (!R.isAmbiguous() && !R.empty
()) ? void (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13099, __extension__ __PRETTY_FUNCTION__
))
; 13100 NamedDecl *ND = R.getRepresentativeDecl(); 13101 13102 // Check if we have a previous declaration with the same name. 13103 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 13104 ForVisibleRedeclaration); 13105 LookupName(PrevR, S); 13106 13107 // Check we're not shadowing a template parameter. 13108 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 13109 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 13110 PrevR.clear(); 13111 } 13112 13113 // Filter out any other lookup result from an enclosing scope. 13114 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13115 /*AllowInlineNamespace*/false); 13116 13117 // Find the previous declaration and check that we can redeclare it. 13118 NamespaceAliasDecl *Prev = nullptr; 13119 if (PrevR.isSingleResult()) { 13120 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13121 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13122 // We already have an alias with the same name that points to the same 13123 // namespace; check that it matches. 13124 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13125 Prev = AD; 13126 } else if (isVisible(PrevDecl)) { 13127 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13128 << Alias; 13129 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13130 << AD->getNamespace(); 13131 return nullptr; 13132 } 13133 } else if (isVisible(PrevDecl)) { 13134 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13135 ? diag::err_redefinition 13136 : diag::err_redefinition_different_kind; 13137 Diag(AliasLoc, DiagID) << Alias; 13138 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13139 return nullptr; 13140 } 13141 } 13142 13143 // The use of a nested name specifier may trigger deprecation warnings. 13144 DiagnoseUseOfDecl(ND, IdentLoc); 13145 13146 NamespaceAliasDecl *AliasDecl = 13147 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13148 Alias, SS.getWithLocInContext(Context), 13149 IdentLoc, ND); 13150 if (Prev) 13151 AliasDecl->setPreviousDecl(Prev); 13152 13153 PushOnScopeChains(AliasDecl, S); 13154 return AliasDecl; 13155} 13156 13157namespace { 13158struct SpecialMemberExceptionSpecInfo 13159 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13160 SourceLocation Loc; 13161 Sema::ImplicitExceptionSpecification ExceptSpec; 13162 13163 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13164 Sema::CXXSpecialMember CSM, 13165 Sema::InheritedConstructorInfo *ICI, 13166 SourceLocation Loc) 13167 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13168 13169 bool visitBase(CXXBaseSpecifier *Base); 13170 bool visitField(FieldDecl *FD); 13171 13172 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13173 unsigned Quals); 13174 13175 void visitSubobjectCall(Subobject Subobj, 13176 Sema::SpecialMemberOverloadResult SMOR); 13177}; 13178} 13179 13180bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13181 auto *RT = Base->getType()->getAs<RecordType>(); 13182 if (!RT) 13183 return false; 13184 13185 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13186 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13187 if (auto *BaseCtor = SMOR.getMethod()) { 13188 visitSubobjectCall(Base, BaseCtor); 13189 return false; 13190 } 13191 13192 visitClassSubobject(BaseClass, Base, 0); 13193 return false; 13194} 13195 13196bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13197 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13198 Expr *E = FD->getInClassInitializer(); 13199 if (!E) 13200 // FIXME: It's a little wasteful to build and throw away a 13201 // CXXDefaultInitExpr here. 13202 // FIXME: We should have a single context note pointing at Loc, and 13203 // this location should be MD->getLocation() instead, since that's 13204 // the location where we actually use the default init expression. 13205 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13206 if (E) 13207 ExceptSpec.CalledExpr(E); 13208 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13209 ->getAs<RecordType>()) { 13210 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13211 FD->getType().getCVRQualifiers()); 13212 } 13213 return false; 13214} 13215 13216void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13217 Subobject Subobj, 13218 unsigned Quals) { 13219 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13220 bool IsMutable = Field && Field->isMutable(); 13221 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13222} 13223 13224void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13225 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13226 // Note, if lookup fails, it doesn't matter what exception specification we 13227 // choose because the special member will be deleted. 13228 if (CXXMethodDecl *MD = SMOR.getMethod()) 13229 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13230} 13231 13232bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13233 llvm::APSInt Result; 13234 ExprResult Converted = CheckConvertedConstantExpression( 13235 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13236 ExplicitSpec.setExpr(Converted.get()); 13237 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13238 ExplicitSpec.setKind(Result.getBoolValue() 13239 ? ExplicitSpecKind::ResolvedTrue 13240 : ExplicitSpecKind::ResolvedFalse); 13241 return true; 13242 } 13243 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13244 return false; 13245} 13246 13247ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13248 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13249 if (!ExplicitExpr->isTypeDependent()) 13250 tryResolveExplicitSpecifier(ES); 13251 return ES; 13252} 13253 13254static Sema::ImplicitExceptionSpecification 13255ComputeDefaultedSpecialMemberExceptionSpec( 13256 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13257 Sema::InheritedConstructorInfo *ICI) { 13258 ComputingExceptionSpec CES(S, MD, Loc); 13259 13260 CXXRecordDecl *ClassDecl = MD->getParent(); 13261 13262 // C++ [except.spec]p14: 13263 // An implicitly declared special member function (Clause 12) shall have an 13264 // exception-specification. [...] 13265 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13266 if (ClassDecl->isInvalidDecl()) 13267 return Info.ExceptSpec; 13268 13269 // FIXME: If this diagnostic fires, we're probably missing a check for 13270 // attempting to resolve an exception specification before it's known 13271 // at a higher level. 13272 if (S.RequireCompleteType(MD->getLocation(), 13273 S.Context.getRecordType(ClassDecl), 13274 diag::err_exception_spec_incomplete_type)) 13275 return Info.ExceptSpec; 13276 13277 // C++1z [except.spec]p7: 13278 // [Look for exceptions thrown by] a constructor selected [...] to 13279 // initialize a potentially constructed subobject, 13280 // C++1z [except.spec]p8: 13281 // The exception specification for an implicitly-declared destructor, or a 13282 // destructor without a noexcept-specifier, is potentially-throwing if and 13283 // only if any of the destructors for any of its potentially constructed 13284 // subojects is potentially throwing. 13285 // FIXME: We respect the first rule but ignore the "potentially constructed" 13286 // in the second rule to resolve a core issue (no number yet) that would have 13287 // us reject: 13288 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13289 // struct B : A {}; 13290 // struct C : B { void f(); }; 13291 // ... due to giving B::~B() a non-throwing exception specification. 13292 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13293 : Info.VisitAllBases); 13294 13295 return Info.ExceptSpec; 13296} 13297 13298namespace { 13299/// RAII object to register a special member as being currently declared. 13300struct DeclaringSpecialMember { 13301 Sema &S; 13302 Sema::SpecialMemberDecl D; 13303 Sema::ContextRAII SavedContext; 13304 bool WasAlreadyBeingDeclared; 13305 13306 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13307 : S(S), D(RD, CSM), SavedContext(S, RD) { 13308 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13309 if (WasAlreadyBeingDeclared) 13310 // This almost never happens, but if it does, ensure that our cache 13311 // doesn't contain a stale result. 13312 S.SpecialMemberCache.clear(); 13313 else { 13314 // Register a note to be produced if we encounter an error while 13315 // declaring the special member. 13316 Sema::CodeSynthesisContext Ctx; 13317 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13318 // FIXME: We don't have a location to use here. Using the class's 13319 // location maintains the fiction that we declare all special members 13320 // with the class, but (1) it's not clear that lying about that helps our 13321 // users understand what's going on, and (2) there may be outer contexts 13322 // on the stack (some of which are relevant) and printing them exposes 13323 // our lies. 13324 Ctx.PointOfInstantiation = RD->getLocation(); 13325 Ctx.Entity = RD; 13326 Ctx.SpecialMember = CSM; 13327 S.pushCodeSynthesisContext(Ctx); 13328 } 13329 } 13330 ~DeclaringSpecialMember() { 13331 if (!WasAlreadyBeingDeclared) { 13332 S.SpecialMembersBeingDeclared.erase(D); 13333 S.popCodeSynthesisContext(); 13334 } 13335 } 13336 13337 /// Are we already trying to declare this special member? 13338 bool isAlreadyBeingDeclared() const { 13339 return WasAlreadyBeingDeclared; 13340 } 13341}; 13342} 13343 13344void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13345 // Look up any existing declarations, but don't trigger declaration of all 13346 // implicit special members with this name. 13347 DeclarationName Name = FD->getDeclName(); 13348 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13349 ForExternalRedeclaration); 13350 for (auto *D : FD->getParent()->lookup(Name)) 13351 if (auto *Acceptable = R.getAcceptableDecl(D)) 13352 R.addDecl(Acceptable); 13353 R.resolveKind(); 13354 R.suppressDiagnostics(); 13355 13356 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false, 13357 FD->isThisDeclarationADefinition()); 13358} 13359 13360void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13361 QualType ResultTy, 13362 ArrayRef<QualType> Args) { 13363 // Build an exception specification pointing back at this constructor. 13364 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13365 13366 LangAS AS = getDefaultCXXMethodAddrSpace(); 13367 if (AS != LangAS::Default) { 13368 EPI.TypeQuals.addAddressSpace(AS); 13369 } 13370 13371 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13372 SpecialMem->setType(QT); 13373 13374 // During template instantiation of implicit special member functions we need 13375 // a reliable TypeSourceInfo for the function prototype in order to allow 13376 // functions to be substituted. 13377 if (inTemplateInstantiation() && 13378 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13379 TypeSourceInfo *TSI = 13380 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13381 SpecialMem->setTypeSourceInfo(TSI); 13382 } 13383} 13384 13385CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13386 CXXRecordDecl *ClassDecl) { 13387 // C++ [class.ctor]p5: 13388 // A default constructor for a class X is a constructor of class X 13389 // that can be called without an argument. If there is no 13390 // user-declared constructor for class X, a default constructor is 13391 // implicitly declared. An implicitly-declared default constructor 13392 // is an inline public member of its class. 13393 assert(ClassDecl->needsImplicitDefaultConstructor() &&(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13394, __extension__ __PRETTY_FUNCTION__
))
13394 "Should not build implicit default constructor!")(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13394, __extension__ __PRETTY_FUNCTION__
))
; 13395 13396 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13397 if (DSM.isAlreadyBeingDeclared()) 13398 return nullptr; 13399 13400 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13401 CXXDefaultConstructor, 13402 false); 13403 13404 // Create the actual constructor declaration. 13405 CanQualType ClassType 13406 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13407 SourceLocation ClassLoc = ClassDecl->getLocation(); 13408 DeclarationName Name 13409 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13410 DeclarationNameInfo NameInfo(Name, ClassLoc); 13411 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13412 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13413 /*TInfo=*/nullptr, ExplicitSpecifier(), 13414 getCurFPFeatures().isFPConstrained(), 13415 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13416 Constexpr ? ConstexprSpecKind::Constexpr 13417 : ConstexprSpecKind::Unspecified); 13418 DefaultCon->setAccess(AS_public); 13419 DefaultCon->setDefaulted(); 13420 13421 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13422 13423 if (getLangOpts().CUDA) 13424 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13425 DefaultCon, 13426 /* ConstRHS */ false, 13427 /* Diagnose */ false); 13428 13429 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13430 // constructors is easy to compute. 13431 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13432 13433 // Note that we have declared this constructor. 13434 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13435 13436 Scope *S = getScopeForContext(ClassDecl); 13437 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13438 13439 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13440 SetDeclDeleted(DefaultCon, ClassLoc); 13441 13442 if (S) 13443 PushOnScopeChains(DefaultCon, S, false); 13444 ClassDecl->addDecl(DefaultCon); 13445 13446 return DefaultCon; 13447} 13448 13449void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13450 CXXConstructorDecl *Constructor) { 13451 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13454, __extension__ __PRETTY_FUNCTION__
))
13452 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13454, __extension__ __PRETTY_FUNCTION__
))
13453 !Constructor->isDeleted()) &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13454, __extension__ __PRETTY_FUNCTION__
))
13454 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13454, __extension__ __PRETTY_FUNCTION__
))
; 13455 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13456 return; 13457 13458 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13459 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13459, __extension__ __PRETTY_FUNCTION__
))
; 13460 13461 SynthesizedFunctionScope Scope(*this, Constructor); 13462 13463 // The exception specification is needed because we are defining the 13464 // function. 13465 ResolveExceptionSpec(CurrentLocation, 13466 Constructor->getType()->castAs<FunctionProtoType>()); 13467 MarkVTableUsed(CurrentLocation, ClassDecl); 13468 13469 // Add a context note for diagnostics produced after this point. 13470 Scope.addContextNote(CurrentLocation); 13471 13472 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13473 Constructor->setInvalidDecl(); 13474 return; 13475 } 13476 13477 SourceLocation Loc = Constructor->getEndLoc().isValid() 13478 ? Constructor->getEndLoc() 13479 : Constructor->getLocation(); 13480 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13481 Constructor->markUsed(Context); 13482 13483 if (ASTMutationListener *L = getASTMutationListener()) { 13484 L->CompletedImplicitDefinition(Constructor); 13485 } 13486 13487 DiagnoseUninitializedFields(*this, Constructor); 13488} 13489 13490void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13491 // Perform any delayed checks on exception specifications. 13492 CheckDelayedMemberExceptionSpecs(); 13493} 13494 13495/// Find or create the fake constructor we synthesize to model constructing an 13496/// object of a derived class via a constructor of a base class. 13497CXXConstructorDecl * 13498Sema::findInheritingConstructor(SourceLocation Loc, 13499 CXXConstructorDecl *BaseCtor, 13500 ConstructorUsingShadowDecl *Shadow) { 13501 CXXRecordDecl *Derived = Shadow->getParent(); 13502 SourceLocation UsingLoc = Shadow->getLocation(); 13503 13504 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13505 // For now we use the name of the base class constructor as a member of the 13506 // derived class to indicate a (fake) inherited constructor name. 13507 DeclarationName Name = BaseCtor->getDeclName(); 13508 13509 // Check to see if we already have a fake constructor for this inherited 13510 // constructor call. 13511 for (NamedDecl *Ctor : Derived->lookup(Name)) 13512 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13513 ->getInheritedConstructor() 13514 .getConstructor(), 13515 BaseCtor)) 13516 return cast<CXXConstructorDecl>(Ctor); 13517 13518 DeclarationNameInfo NameInfo(Name, UsingLoc); 13519 TypeSourceInfo *TInfo = 13520 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13521 FunctionProtoTypeLoc ProtoLoc = 13522 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13523 13524 // Check the inherited constructor is valid and find the list of base classes 13525 // from which it was inherited. 13526 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13527 13528 bool Constexpr = 13529 BaseCtor->isConstexpr() && 13530 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13531 false, BaseCtor, &ICI); 13532 13533 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13534 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13535 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13536 /*isInline=*/true, 13537 /*isImplicitlyDeclared=*/true, 13538 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13539 InheritedConstructor(Shadow, BaseCtor), 13540 BaseCtor->getTrailingRequiresClause()); 13541 if (Shadow->isInvalidDecl()) 13542 DerivedCtor->setInvalidDecl(); 13543 13544 // Build an unevaluated exception specification for this fake constructor. 13545 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13546 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13547 EPI.ExceptionSpec.Type = EST_Unevaluated; 13548 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13549 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13550 FPT->getParamTypes(), EPI)); 13551 13552 // Build the parameter declarations. 13553 SmallVector<ParmVarDecl *, 16> ParamDecls; 13554 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13555 TypeSourceInfo *TInfo = 13556 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13557 ParmVarDecl *PD = ParmVarDecl::Create( 13558 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13559 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13560 PD->setScopeInfo(0, I); 13561 PD->setImplicit(); 13562 // Ensure attributes are propagated onto parameters (this matters for 13563 // format, pass_object_size, ...). 13564 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13565 ParamDecls.push_back(PD); 13566 ProtoLoc.setParam(I, PD); 13567 } 13568 13569 // Set up the new constructor. 13570 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")(static_cast <bool> (!BaseCtor->isDeleted() &&
"should not use deleted constructor") ? void (0) : __assert_fail
("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13570, __extension__ __PRETTY_FUNCTION__
))
; 13571 DerivedCtor->setAccess(BaseCtor->getAccess()); 13572 DerivedCtor->setParams(ParamDecls); 13573 Derived->addDecl(DerivedCtor); 13574 13575 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13576 SetDeclDeleted(DerivedCtor, UsingLoc); 13577 13578 return DerivedCtor; 13579} 13580 13581void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13582 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13583 Ctor->getInheritedConstructor().getShadowDecl()); 13584 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13585 /*Diagnose*/true); 13586} 13587 13588void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13589 CXXConstructorDecl *Constructor) { 13590 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13591 assert(Constructor->getInheritedConstructor() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13593, __extension__ __PRETTY_FUNCTION__
))
13592 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13593, __extension__ __PRETTY_FUNCTION__
))
13593 !Constructor->isDeleted())(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13593, __extension__ __PRETTY_FUNCTION__
))
; 13594 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13595 return; 13596 13597 // Initializations are performed "as if by a defaulted default constructor", 13598 // so enter the appropriate scope. 13599 SynthesizedFunctionScope Scope(*this, Constructor); 13600 13601 // The exception specification is needed because we are defining the 13602 // function. 13603 ResolveExceptionSpec(CurrentLocation, 13604 Constructor->getType()->castAs<FunctionProtoType>()); 13605 MarkVTableUsed(CurrentLocation, ClassDecl); 13606 13607 // Add a context note for diagnostics produced after this point. 13608 Scope.addContextNote(CurrentLocation); 13609 13610 ConstructorUsingShadowDecl *Shadow = 13611 Constructor->getInheritedConstructor().getShadowDecl(); 13612 CXXConstructorDecl *InheritedCtor = 13613 Constructor->getInheritedConstructor().getConstructor(); 13614 13615 // [class.inhctor.init]p1: 13616 // initialization proceeds as if a defaulted default constructor is used to 13617 // initialize the D object and each base class subobject from which the 13618 // constructor was inherited 13619 13620 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13621 CXXRecordDecl *RD = Shadow->getParent(); 13622 SourceLocation InitLoc = Shadow->getLocation(); 13623 13624 // Build explicit initializers for all base classes from which the 13625 // constructor was inherited. 13626 SmallVector<CXXCtorInitializer*, 8> Inits; 13627 for (bool VBase : {false, true}) { 13628 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13629 if (B.isVirtual() != VBase) 13630 continue; 13631 13632 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13633 if (!BaseRD) 13634 continue; 13635 13636 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13637 if (!BaseCtor.first) 13638 continue; 13639 13640 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13641 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13642 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13643 13644 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13645 Inits.push_back(new (Context) CXXCtorInitializer( 13646 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13647 SourceLocation())); 13648 } 13649 } 13650 13651 // We now proceed as if for a defaulted default constructor, with the relevant 13652 // initializers replaced. 13653 13654 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13655 Constructor->setInvalidDecl(); 13656 return; 13657 } 13658 13659 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13660 Constructor->markUsed(Context); 13661 13662 if (ASTMutationListener *L = getASTMutationListener()) { 13663 L->CompletedImplicitDefinition(Constructor); 13664 } 13665 13666 DiagnoseUninitializedFields(*this, Constructor); 13667} 13668 13669CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13670 // C++ [class.dtor]p2: 13671 // If a class has no user-declared destructor, a destructor is 13672 // declared implicitly. An implicitly-declared destructor is an 13673 // inline public member of its class. 13674 assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13674, __extension__ __PRETTY_FUNCTION__
))
; 13675 13676 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13677 if (DSM.isAlreadyBeingDeclared()) 13678 return nullptr; 13679 13680 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13681 CXXDestructor, 13682 false); 13683 13684 // Create the actual destructor declaration. 13685 CanQualType ClassType 13686 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13687 SourceLocation ClassLoc = ClassDecl->getLocation(); 13688 DeclarationName Name 13689 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13690 DeclarationNameInfo NameInfo(Name, ClassLoc); 13691 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13692 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13693 getCurFPFeatures().isFPConstrained(), 13694 /*isInline=*/true, 13695 /*isImplicitlyDeclared=*/true, 13696 Constexpr ? ConstexprSpecKind::Constexpr 13697 : ConstexprSpecKind::Unspecified); 13698 Destructor->setAccess(AS_public); 13699 Destructor->setDefaulted(); 13700 13701 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13702 13703 if (getLangOpts().CUDA) 13704 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13705 Destructor, 13706 /* ConstRHS */ false, 13707 /* Diagnose */ false); 13708 13709 // We don't need to use SpecialMemberIsTrivial here; triviality for 13710 // destructors is easy to compute. 13711 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13712 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13713 ClassDecl->hasTrivialDestructorForCall()); 13714 13715 // Note that we have declared this destructor. 13716 ++getASTContext().NumImplicitDestructorsDeclared; 13717 13718 Scope *S = getScopeForContext(ClassDecl); 13719 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13720 13721 // We can't check whether an implicit destructor is deleted before we complete 13722 // the definition of the class, because its validity depends on the alignment 13723 // of the class. We'll check this from ActOnFields once the class is complete. 13724 if (ClassDecl->isCompleteDefinition() && 13725 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13726 SetDeclDeleted(Destructor, ClassLoc); 13727 13728 // Introduce this destructor into its scope. 13729 if (S) 13730 PushOnScopeChains(Destructor, S, false); 13731 ClassDecl->addDecl(Destructor); 13732 13733 return Destructor; 13734} 13735 13736void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13737 CXXDestructorDecl *Destructor) { 13738 assert((Destructor->isDefaulted() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13741, __extension__ __PRETTY_FUNCTION__
))
13739 !Destructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13741, __extension__ __PRETTY_FUNCTION__
))
13740 !Destructor->isDeleted()) &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13741, __extension__ __PRETTY_FUNCTION__
))
13741 "DefineImplicitDestructor - call it for implicit default dtor")(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13741, __extension__ __PRETTY_FUNCTION__
))
; 13742 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13743 return; 13744 13745 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13746 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")(static_cast <bool> (ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13746, __extension__ __PRETTY_FUNCTION__
))
; 13747 13748 SynthesizedFunctionScope Scope(*this, Destructor); 13749 13750 // The exception specification is needed because we are defining the 13751 // function. 13752 ResolveExceptionSpec(CurrentLocation, 13753 Destructor->getType()->castAs<FunctionProtoType>()); 13754 MarkVTableUsed(CurrentLocation, ClassDecl); 13755 13756 // Add a context note for diagnostics produced after this point. 13757 Scope.addContextNote(CurrentLocation); 13758 13759 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13760 Destructor->getParent()); 13761 13762 if (CheckDestructor(Destructor)) { 13763 Destructor->setInvalidDecl(); 13764 return; 13765 } 13766 13767 SourceLocation Loc = Destructor->getEndLoc().isValid() 13768 ? Destructor->getEndLoc() 13769 : Destructor->getLocation(); 13770 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13771 Destructor->markUsed(Context); 13772 13773 if (ASTMutationListener *L = getASTMutationListener()) { 13774 L->CompletedImplicitDefinition(Destructor); 13775 } 13776} 13777 13778void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13779 CXXDestructorDecl *Destructor) { 13780 if (Destructor->isInvalidDecl()) 13781 return; 13782 13783 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13784 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && "implicit complete dtors unneeded outside MS ABI"
) ? void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13785, __extension__ __PRETTY_FUNCTION__
))
13785 "implicit complete dtors unneeded outside MS ABI")(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && "implicit complete dtors unneeded outside MS ABI"
) ? void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13785, __extension__ __PRETTY_FUNCTION__
))
; 13786 assert(ClassDecl->getNumVBases() > 0 &&(static_cast <bool> (ClassDecl->getNumVBases() > 0
&& "complete dtor only exists for classes with vbases"
) ? void (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13787, __extension__ __PRETTY_FUNCTION__
))
13787 "complete dtor only exists for classes with vbases")(static_cast <bool> (ClassDecl->getNumVBases() > 0
&& "complete dtor only exists for classes with vbases"
) ? void (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13787, __extension__ __PRETTY_FUNCTION__
))
; 13788 13789 SynthesizedFunctionScope Scope(*this, Destructor); 13790 13791 // Add a context note for diagnostics produced after this point. 13792 Scope.addContextNote(CurrentLocation); 13793 13794 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13795} 13796 13797/// Perform any semantic analysis which needs to be delayed until all 13798/// pending class member declarations have been parsed. 13799void Sema::ActOnFinishCXXMemberDecls() { 13800 // If the context is an invalid C++ class, just suppress these checks. 13801 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13802 if (Record->isInvalidDecl()) { 13803 DelayedOverridingExceptionSpecChecks.clear(); 13804 DelayedEquivalentExceptionSpecChecks.clear(); 13805 return; 13806 } 13807 checkForMultipleExportedDefaultConstructors(*this, Record); 13808 } 13809} 13810 13811void Sema::ActOnFinishCXXNonNestedClass() { 13812 referenceDLLExportedClassMethods(); 13813 13814 if (!DelayedDllExportMemberFunctions.empty()) { 13815 SmallVector<CXXMethodDecl*, 4> WorkList; 13816 std::swap(DelayedDllExportMemberFunctions, WorkList); 13817 for (CXXMethodDecl *M : WorkList) { 13818 DefineDefaultedFunction(*this, M, M->getLocation()); 13819 13820 // Pass the method to the consumer to get emitted. This is not necessary 13821 // for explicit instantiation definitions, as they will get emitted 13822 // anyway. 13823 if (M->getParent()->getTemplateSpecializationKind() != 13824 TSK_ExplicitInstantiationDefinition) 13825 ActOnFinishInlineFunctionDef(M); 13826 } 13827 } 13828} 13829 13830void Sema::referenceDLLExportedClassMethods() { 13831 if (!DelayedDllExportClasses.empty()) { 13832 // Calling ReferenceDllExportedMembers might cause the current function to 13833 // be called again, so use a local copy of DelayedDllExportClasses. 13834 SmallVector<CXXRecordDecl *, 4> WorkList; 13835 std::swap(DelayedDllExportClasses, WorkList); 13836 for (CXXRecordDecl *Class : WorkList) 13837 ReferenceDllExportedMembers(*this, Class); 13838 } 13839} 13840 13841void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13842 assert(getLangOpts().CPlusPlus11 &&(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13843, __extension__ __PRETTY_FUNCTION__
))
13843 "adjusting dtor exception specs was introduced in c++11")(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13843, __extension__ __PRETTY_FUNCTION__
))
; 13844 13845 if (Destructor->isDependentContext()) 13846 return; 13847 13848 // C++11 [class.dtor]p3: 13849 // A declaration of a destructor that does not have an exception- 13850 // specification is implicitly considered to have the same exception- 13851 // specification as an implicit declaration. 13852 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13853 if (DtorType->hasExceptionSpec()) 13854 return; 13855 13856 // Replace the destructor's type, building off the existing one. Fortunately, 13857 // the only thing of interest in the destructor type is its extended info. 13858 // The return and arguments are fixed. 13859 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13860 EPI.ExceptionSpec.Type = EST_Unevaluated; 13861 EPI.ExceptionSpec.SourceDecl = Destructor; 13862 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13863 13864 // FIXME: If the destructor has a body that could throw, and the newly created 13865 // spec doesn't allow exceptions, we should emit a warning, because this 13866 // change in behavior can break conforming C++03 programs at runtime. 13867 // However, we don't have a body or an exception specification yet, so it 13868 // needs to be done somewhere else. 13869} 13870 13871namespace { 13872/// An abstract base class for all helper classes used in building the 13873// copy/move operators. These classes serve as factory functions and help us 13874// avoid using the same Expr* in the AST twice. 13875class ExprBuilder { 13876 ExprBuilder(const ExprBuilder&) = delete; 13877 ExprBuilder &operator=(const ExprBuilder&) = delete; 13878 13879protected: 13880 static Expr *assertNotNull(Expr *E) { 13881 assert(E && "Expression construction must not fail.")(static_cast <bool> (E && "Expression construction must not fail."
) ? void (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13881, __extension__ __PRETTY_FUNCTION__
))
; 13882 return E; 13883 } 13884 13885public: 13886 ExprBuilder() {} 13887 virtual ~ExprBuilder() {} 13888 13889 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13890}; 13891 13892class RefBuilder: public ExprBuilder { 13893 VarDecl *Var; 13894 QualType VarType; 13895 13896public: 13897 Expr *build(Sema &S, SourceLocation Loc) const override { 13898 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13899 } 13900 13901 RefBuilder(VarDecl *Var, QualType VarType) 13902 : Var(Var), VarType(VarType) {} 13903}; 13904 13905class ThisBuilder: public ExprBuilder { 13906public: 13907 Expr *build(Sema &S, SourceLocation Loc) const override { 13908 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13909 } 13910}; 13911 13912class CastBuilder: public ExprBuilder { 13913 const ExprBuilder &Builder; 13914 QualType Type; 13915 ExprValueKind Kind; 13916 const CXXCastPath &Path; 13917 13918public: 13919 Expr *build(Sema &S, SourceLocation Loc) const override { 13920 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13921 CK_UncheckedDerivedToBase, Kind, 13922 &Path).get()); 13923 } 13924 13925 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13926 const CXXCastPath &Path) 13927 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13928}; 13929 13930class DerefBuilder: public ExprBuilder { 13931 const ExprBuilder &Builder; 13932 13933public: 13934 Expr *build(Sema &S, SourceLocation Loc) const override { 13935 return assertNotNull( 13936 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13937 } 13938 13939 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13940}; 13941 13942class MemberBuilder: public ExprBuilder { 13943 const ExprBuilder &Builder; 13944 QualType Type; 13945 CXXScopeSpec SS; 13946 bool IsArrow; 13947 LookupResult &MemberLookup; 13948 13949public: 13950 Expr *build(Sema &S, SourceLocation Loc) const override { 13951 return assertNotNull(S.BuildMemberReferenceExpr( 13952 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13953 nullptr, MemberLookup, nullptr, nullptr).get()); 13954 } 13955 13956 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13957 LookupResult &MemberLookup) 13958 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13959 MemberLookup(MemberLookup) {} 13960}; 13961 13962class MoveCastBuilder: public ExprBuilder { 13963 const ExprBuilder &Builder; 13964 13965public: 13966 Expr *build(Sema &S, SourceLocation Loc) const override { 13967 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13968 } 13969 13970 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13971}; 13972 13973class LvalueConvBuilder: public ExprBuilder { 13974 const ExprBuilder &Builder; 13975 13976public: 13977 Expr *build(Sema &S, SourceLocation Loc) const override { 13978 return assertNotNull( 13979 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13980 } 13981 13982 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13983}; 13984 13985class SubscriptBuilder: public ExprBuilder { 13986 const ExprBuilder &Base; 13987 const ExprBuilder &Index; 13988 13989public: 13990 Expr *build(Sema &S, SourceLocation Loc) const override { 13991 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13992 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13993 } 13994 13995 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13996 : Base(Base), Index(Index) {} 13997}; 13998 13999} // end anonymous namespace 14000 14001/// When generating a defaulted copy or move assignment operator, if a field 14002/// should be copied with __builtin_memcpy rather than via explicit assignments, 14003/// do so. This optimization only applies for arrays of scalars, and for arrays 14004/// of class type where the selected copy/move-assignment operator is trivial. 14005static StmtResult 14006buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 14007 const ExprBuilder &ToB, const ExprBuilder &FromB) { 14008 // Compute the size of the memory buffer to be copied. 14009 QualType SizeType = S.Context.getSizeType(); 14010 llvm::APInt Size(S.Context.getTypeSize(SizeType), 14011 S.Context.getTypeSizeInChars(T).getQuantity()); 14012 14013 // Take the address of the field references for "from" and "to". We 14014 // directly construct UnaryOperators here because semantic analysis 14015 // does not permit us to take the address of an xvalue. 14016 Expr *From = FromB.build(S, Loc); 14017 From = UnaryOperator::Create( 14018 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 14019 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14020 Expr *To = ToB.build(S, Loc); 14021 To = UnaryOperator::Create( 14022 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 14023 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14024 14025 const Type *E = T->getBaseElementTypeUnsafe(); 14026 bool NeedsCollectableMemCpy = 14027 E->isRecordType() && 14028 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 14029 14030 // Create a reference to the __builtin_objc_memmove_collectable function 14031 StringRef MemCpyName = NeedsCollectableMemCpy ? 14032 "__builtin_objc_memmove_collectable" : 14033 "__builtin_memcpy"; 14034 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 14035 Sema::LookupOrdinaryName); 14036 S.LookupName(R, S.TUScope, true); 14037 14038 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 14039 if (!MemCpy) 14040 // Something went horribly wrong earlier, and we will have complained 14041 // about it. 14042 return StmtError(); 14043 14044 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 14045 VK_PRValue, Loc, nullptr); 14046 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? void (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14046, __extension__ __PRETTY_FUNCTION__
))
; 14047 14048 Expr *CallArgs[] = { 14049 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 14050 }; 14051 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 14052 Loc, CallArgs, Loc); 14053 14054 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14054, __extension__ __PRETTY_FUNCTION__
))
; 14055 return Call.getAs<Stmt>(); 14056} 14057 14058/// Builds a statement that copies/moves the given entity from \p From to 14059/// \c To. 14060/// 14061/// This routine is used to copy/move the members of a class with an 14062/// implicitly-declared copy/move assignment operator. When the entities being 14063/// copied are arrays, this routine builds for loops to copy them. 14064/// 14065/// \param S The Sema object used for type-checking. 14066/// 14067/// \param Loc The location where the implicit copy/move is being generated. 14068/// 14069/// \param T The type of the expressions being copied/moved. Both expressions 14070/// must have this type. 14071/// 14072/// \param To The expression we are copying/moving to. 14073/// 14074/// \param From The expression we are copying/moving from. 14075/// 14076/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 14077/// Otherwise, it's a non-static member subobject. 14078/// 14079/// \param Copying Whether we're copying or moving. 14080/// 14081/// \param Depth Internal parameter recording the depth of the recursion. 14082/// 14083/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 14084/// if a memcpy should be used instead. 14085static StmtResult 14086buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 14087 const ExprBuilder &To, const ExprBuilder &From, 14088 bool CopyingBaseSubobject, bool Copying, 14089 unsigned Depth = 0) { 14090 // C++11 [class.copy]p28: 14091 // Each subobject is assigned in the manner appropriate to its type: 14092 // 14093 // - if the subobject is of class type, as if by a call to operator= with 14094 // the subobject as the object expression and the corresponding 14095 // subobject of x as a single function argument (as if by explicit 14096 // qualification; that is, ignoring any possible virtual overriding 14097 // functions in more derived classes); 14098 // 14099 // C++03 [class.copy]p13: 14100 // - if the subobject is of class type, the copy assignment operator for 14101 // the class is used (as if by explicit qualification; that is, 14102 // ignoring any possible virtual overriding functions in more derived 14103 // classes); 14104 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 14105 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 14106 14107 // Look for operator=. 14108 DeclarationName Name 14109 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14110 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14111 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14112 14113 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14114 // operator. 14115 if (!S.getLangOpts().CPlusPlus11) { 14116 LookupResult::Filter F = OpLookup.makeFilter(); 14117 while (F.hasNext()) { 14118 NamedDecl *D = F.next(); 14119 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14120 if (Method->isCopyAssignmentOperator() || 14121 (!Copying && Method->isMoveAssignmentOperator())) 14122 continue; 14123 14124 F.erase(); 14125 } 14126 F.done(); 14127 } 14128 14129 // Suppress the protected check (C++ [class.protected]) for each of the 14130 // assignment operators we found. This strange dance is required when 14131 // we're assigning via a base classes's copy-assignment operator. To 14132 // ensure that we're getting the right base class subobject (without 14133 // ambiguities), we need to cast "this" to that subobject type; to 14134 // ensure that we don't go through the virtual call mechanism, we need 14135 // to qualify the operator= name with the base class (see below). However, 14136 // this means that if the base class has a protected copy assignment 14137 // operator, the protected member access check will fail. So, we 14138 // rewrite "protected" access to "public" access in this case, since we 14139 // know by construction that we're calling from a derived class. 14140 if (CopyingBaseSubobject) { 14141 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14142 L != LEnd; ++L) { 14143 if (L.getAccess() == AS_protected) 14144 L.setAccess(AS_public); 14145 } 14146 } 14147 14148 // Create the nested-name-specifier that will be used to qualify the 14149 // reference to operator=; this is required to suppress the virtual 14150 // call mechanism. 14151 CXXScopeSpec SS; 14152 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14153 SS.MakeTrivial(S.Context, 14154 NestedNameSpecifier::Create(S.Context, nullptr, false, 14155 CanonicalT), 14156 Loc); 14157 14158 // Create the reference to operator=. 14159 ExprResult OpEqualRef 14160 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14161 SS, /*TemplateKWLoc=*/SourceLocation(), 14162 /*FirstQualifierInScope=*/nullptr, 14163 OpLookup, 14164 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14165 /*SuppressQualifierCheck=*/true); 14166 if (OpEqualRef.isInvalid()) 14167 return StmtError(); 14168 14169 // Build the call to the assignment operator. 14170 14171 Expr *FromInst = From.build(S, Loc); 14172 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14173 OpEqualRef.getAs<Expr>(), 14174 Loc, FromInst, Loc); 14175 if (Call.isInvalid()) 14176 return StmtError(); 14177 14178 // If we built a call to a trivial 'operator=' while copying an array, 14179 // bail out. We'll replace the whole shebang with a memcpy. 14180 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14181 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14182 return StmtResult((Stmt*)nullptr); 14183 14184 // Convert to an expression-statement, and clean up any produced 14185 // temporaries. 14186 return S.ActOnExprStmt(Call); 14187 } 14188 14189 // - if the subobject is of scalar type, the built-in assignment 14190 // operator is used. 14191 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14192 if (!ArrayTy) { 14193 ExprResult Assignment = S.CreateBuiltinBinOp( 14194 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14195 if (Assignment.isInvalid()) 14196 return StmtError(); 14197 return S.ActOnExprStmt(Assignment); 14198 } 14199 14200 // - if the subobject is an array, each element is assigned, in the 14201 // manner appropriate to the element type; 14202 14203 // Construct a loop over the array bounds, e.g., 14204 // 14205 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14206 // 14207 // that will copy each of the array elements. 14208 QualType SizeType = S.Context.getSizeType(); 14209 14210 // Create the iteration variable. 14211 IdentifierInfo *IterationVarName = nullptr; 14212 { 14213 SmallString<8> Str; 14214 llvm::raw_svector_ostream OS(Str); 14215 OS << "__i" << Depth; 14216 IterationVarName = &S.Context.Idents.get(OS.str()); 14217 } 14218 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14219 IterationVarName, SizeType, 14220 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14221 SC_None); 14222 14223 // Initialize the iteration variable to zero. 14224 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14225 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14226 14227 // Creates a reference to the iteration variable. 14228 RefBuilder IterationVarRef(IterationVar, SizeType); 14229 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14230 14231 // Create the DeclStmt that holds the iteration variable. 14232 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14233 14234 // Subscript the "from" and "to" expressions with the iteration variable. 14235 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14236 MoveCastBuilder FromIndexMove(FromIndexCopy); 14237 const ExprBuilder *FromIndex; 14238 if (Copying) 14239 FromIndex = &FromIndexCopy; 14240 else 14241 FromIndex = &FromIndexMove; 14242 14243 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14244 14245 // Build the copy/move for an individual element of the array. 14246 StmtResult Copy = 14247 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14248 ToIndex, *FromIndex, CopyingBaseSubobject, 14249 Copying, Depth + 1); 14250 // Bail out if copying fails or if we determined that we should use memcpy. 14251 if (Copy.isInvalid() || !Copy.get()) 14252 return Copy; 14253 14254 // Create the comparison against the array bound. 14255 llvm::APInt Upper 14256 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14257 Expr *Comparison = BinaryOperator::Create( 14258 S.Context, IterationVarRefRVal.build(S, Loc), 14259 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14260 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14261 S.CurFPFeatureOverrides()); 14262 14263 // Create the pre-increment of the iteration variable. We can determine 14264 // whether the increment will overflow based on the value of the array 14265 // bound. 14266 Expr *Increment = UnaryOperator::Create( 14267 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14268 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14269 14270 // Construct the loop that copies all elements of this array. 14271 return S.ActOnForStmt( 14272 Loc, Loc, InitStmt, 14273 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14274 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14275} 14276 14277static StmtResult 14278buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14279 const ExprBuilder &To, const ExprBuilder &From, 14280 bool CopyingBaseSubobject, bool Copying) { 14281 // Maybe we should use a memcpy? 14282 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14283 T.isTriviallyCopyableType(S.Context)) 14284 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14285 14286 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14287 CopyingBaseSubobject, 14288 Copying, 0)); 14289 14290 // If we ended up picking a trivial assignment operator for an array of a 14291 // non-trivially-copyable class type, just emit a memcpy. 14292 if (!Result.isInvalid() && !Result.get()) 14293 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14294 14295 return Result; 14296} 14297 14298CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14299 // Note: The following rules are largely analoguous to the copy 14300 // constructor rules. Note that virtual bases are not taken into account 14301 // for determining the argument type of the operator. Note also that 14302 // operators taking an object instead of a reference are allowed. 14303 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14303, __extension__ __PRETTY_FUNCTION__
))
; 14304 14305 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14306 if (DSM.isAlreadyBeingDeclared()) 14307 return nullptr; 14308 14309 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14310 LangAS AS = getDefaultCXXMethodAddrSpace(); 14311 if (AS != LangAS::Default) 14312 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14313 QualType RetType = Context.getLValueReferenceType(ArgType); 14314 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14315 if (Const) 14316 ArgType = ArgType.withConst(); 14317 14318 ArgType = Context.getLValueReferenceType(ArgType); 14319 14320 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14321 CXXCopyAssignment, 14322 Const); 14323 14324 // An implicitly-declared copy assignment operator is an inline public 14325 // member of its class. 14326 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14327 SourceLocation ClassLoc = ClassDecl->getLocation(); 14328 DeclarationNameInfo NameInfo(Name, ClassLoc); 14329 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14330 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14331 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14332 getCurFPFeatures().isFPConstrained(), 14333 /*isInline=*/true, 14334 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14335 SourceLocation()); 14336 CopyAssignment->setAccess(AS_public); 14337 CopyAssignment->setDefaulted(); 14338 CopyAssignment->setImplicit(); 14339 14340 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14341 14342 if (getLangOpts().CUDA) 14343 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14344 CopyAssignment, 14345 /* ConstRHS */ Const, 14346 /* Diagnose */ false); 14347 14348 // Add the parameter to the operator. 14349 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14350 ClassLoc, ClassLoc, 14351 /*Id=*/nullptr, ArgType, 14352 /*TInfo=*/nullptr, SC_None, 14353 nullptr); 14354 CopyAssignment->setParams(FromParam); 14355 14356 CopyAssignment->setTrivial( 14357 ClassDecl->needsOverloadResolutionForCopyAssignment() 14358 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14359 : ClassDecl->hasTrivialCopyAssignment()); 14360 14361 // Note that we have added this copy-assignment operator. 14362 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14363 14364 Scope *S = getScopeForContext(ClassDecl); 14365 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14366 14367 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14368 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14369 SetDeclDeleted(CopyAssignment, ClassLoc); 14370 } 14371 14372 if (S) 14373 PushOnScopeChains(CopyAssignment, S, false); 14374 ClassDecl->addDecl(CopyAssignment); 14375 14376 return CopyAssignment; 14377} 14378 14379/// Diagnose an implicit copy operation for a class which is odr-used, but 14380/// which is deprecated because the class has a user-declared copy constructor, 14381/// copy assignment operator, or destructor. 14382static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14383 assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0
) : __assert_fail ("CopyOp->isImplicit()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14383, __extension__ __PRETTY_FUNCTION__))
; 14384 14385 CXXRecordDecl *RD = CopyOp->getParent(); 14386 CXXMethodDecl *UserDeclaredOperation = nullptr; 14387 14388 // In Microsoft mode, assignment operations don't affect constructors and 14389 // vice versa. 14390 if (RD->hasUserDeclaredDestructor()) { 14391 UserDeclaredOperation = RD->getDestructor(); 14392 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14393 RD->hasUserDeclaredCopyConstructor() && 14394 !S.getLangOpts().MSVCCompat) { 14395 // Find any user-declared copy constructor. 14396 for (auto *I : RD->ctors()) { 14397 if (I->isCopyConstructor()) { 14398 UserDeclaredOperation = I; 14399 break; 14400 } 14401 } 14402 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14402, __extension__ __PRETTY_FUNCTION__))
; 14403 } else if (isa<CXXConstructorDecl>(CopyOp) && 14404 RD->hasUserDeclaredCopyAssignment() && 14405 !S.getLangOpts().MSVCCompat) { 14406 // Find any user-declared move assignment operator. 14407 for (auto *I : RD->methods()) { 14408 if (I->isCopyAssignmentOperator()) { 14409 UserDeclaredOperation = I; 14410 break; 14411 } 14412 } 14413 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14413, __extension__ __PRETTY_FUNCTION__))
; 14414 } 14415 14416 if (UserDeclaredOperation) { 14417 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14418 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14419 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14420 unsigned DiagID = 14421 (UDOIsUserProvided && UDOIsDestructor) 14422 ? diag::warn_deprecated_copy_with_user_provided_dtor 14423 : (UDOIsUserProvided && !UDOIsDestructor) 14424 ? diag::warn_deprecated_copy_with_user_provided_copy 14425 : (!UDOIsUserProvided && UDOIsDestructor) 14426 ? diag::warn_deprecated_copy_with_dtor 14427 : diag::warn_deprecated_copy; 14428 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14429 << RD << IsCopyAssignment; 14430 } 14431} 14432 14433void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14434 CXXMethodDecl *CopyAssignOperator) { 14435 assert((CopyAssignOperator->isDefaulted() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14440, __extension__ __PRETTY_FUNCTION__
))
14436 CopyAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14440, __extension__ __PRETTY_FUNCTION__
))
14437 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14440, __extension__ __PRETTY_FUNCTION__
))
14438 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14440, __extension__ __PRETTY_FUNCTION__
))
14439 !CopyAssignOperator->isDeleted()) &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14440, __extension__ __PRETTY_FUNCTION__
))
14440 "DefineImplicitCopyAssignment called for wrong function")(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14440, __extension__ __PRETTY_FUNCTION__
))
; 14441 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14442 return; 14443 14444 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14445 if (ClassDecl->isInvalidDecl()) { 14446 CopyAssignOperator->setInvalidDecl(); 14447 return; 14448 } 14449 14450 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14451 14452 // The exception specification is needed because we are defining the 14453 // function. 14454 ResolveExceptionSpec(CurrentLocation, 14455 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14456 14457 // Add a context note for diagnostics produced after this point. 14458 Scope.addContextNote(CurrentLocation); 14459 14460 // C++11 [class.copy]p18: 14461 // The [definition of an implicitly declared copy assignment operator] is 14462 // deprecated if the class has a user-declared copy constructor or a 14463 // user-declared destructor. 14464 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14465 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14466 14467 // C++0x [class.copy]p30: 14468 // The implicitly-defined or explicitly-defaulted copy assignment operator 14469 // for a non-union class X performs memberwise copy assignment of its 14470 // subobjects. The direct base classes of X are assigned first, in the 14471 // order of their declaration in the base-specifier-list, and then the 14472 // immediate non-static data members of X are assigned, in the order in 14473 // which they were declared in the class definition. 14474 14475 // The statements that form the synthesized function body. 14476 SmallVector<Stmt*, 8> Statements; 14477 14478 // The parameter for the "other" object, which we are copying from. 14479 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14480 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14481 QualType OtherRefType = Other->getType(); 14482 if (const LValueReferenceType *OtherRef 14483 = OtherRefType->getAs<LValueReferenceType>()) { 14484 OtherRefType = OtherRef->getPointeeType(); 14485 OtherQuals = OtherRefType.getQualifiers(); 14486 } 14487 14488 // Our location for everything implicitly-generated. 14489 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14490 ? CopyAssignOperator->getEndLoc() 14491 : CopyAssignOperator->getLocation(); 14492 14493 // Builds a DeclRefExpr for the "other" object. 14494 RefBuilder OtherRef(Other, OtherRefType); 14495 14496 // Builds the "this" pointer. 14497 ThisBuilder This; 14498 14499 // Assign base classes. 14500 bool Invalid = false; 14501 for (auto &Base : ClassDecl->bases()) { 14502 // Form the assignment: 14503 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14504 QualType BaseType = Base.getType().getUnqualifiedType(); 14505 if (!BaseType->isRecordType()) { 14506 Invalid = true; 14507 continue; 14508 } 14509 14510 CXXCastPath BasePath; 14511 BasePath.push_back(&Base); 14512 14513 // Construct the "from" expression, which is an implicit cast to the 14514 // appropriately-qualified base type. 14515 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14516 VK_LValue, BasePath); 14517 14518 // Dereference "this". 14519 DerefBuilder DerefThis(This); 14520 CastBuilder To(DerefThis, 14521 Context.getQualifiedType( 14522 BaseType, CopyAssignOperator->getMethodQualifiers()), 14523 VK_LValue, BasePath); 14524 14525 // Build the copy. 14526 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14527 To, From, 14528 /*CopyingBaseSubobject=*/true, 14529 /*Copying=*/true); 14530 if (Copy.isInvalid()) { 14531 CopyAssignOperator->setInvalidDecl(); 14532 return; 14533 } 14534 14535 // Success! Record the copy. 14536 Statements.push_back(Copy.getAs<Expr>()); 14537 } 14538 14539 // Assign non-static members. 14540 for (auto *Field : ClassDecl->fields()) { 14541 // FIXME: We should form some kind of AST representation for the implied 14542 // memcpy in a union copy operation. 14543 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14544 continue; 14545 14546 if (Field->isInvalidDecl()) { 14547 Invalid = true; 14548 continue; 14549 } 14550 14551 // Check for members of reference type; we can't copy those. 14552 if (Field->getType()->isReferenceType()) { 14553 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14554 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14555 Diag(Field->getLocation(), diag::note_declared_at); 14556 Invalid = true; 14557 continue; 14558 } 14559 14560 // Check for members of const-qualified, non-class type. 14561 QualType BaseType = Context.getBaseElementType(Field->getType()); 14562 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14563 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14564 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14565 Diag(Field->getLocation(), diag::note_declared_at); 14566 Invalid = true; 14567 continue; 14568 } 14569 14570 // Suppress assigning zero-width bitfields. 14571 if (Field->isZeroLengthBitField(Context)) 14572 continue; 14573 14574 QualType FieldType = Field->getType().getNonReferenceType(); 14575 if (FieldType->isIncompleteArrayType()) { 14576 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", 14577, __extension__ __PRETTY_FUNCTION__
))
14577 "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", 14577, __extension__ __PRETTY_FUNCTION__
))
; 14578 continue; 14579 } 14580 14581 // Build references to the field in the object we're copying from and to. 14582 CXXScopeSpec SS; // Intentionally empty 14583 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14584 LookupMemberName); 14585 MemberLookup.addDecl(Field); 14586 MemberLookup.resolveKind(); 14587 14588 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14589 14590 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14591 14592 // Build the copy of this field. 14593 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14594 To, From, 14595 /*CopyingBaseSubobject=*/false, 14596 /*Copying=*/true); 14597 if (Copy.isInvalid()) { 14598 CopyAssignOperator->setInvalidDecl(); 14599 return; 14600 } 14601 14602 // Success! Record the copy. 14603 Statements.push_back(Copy.getAs<Stmt>()); 14604 } 14605 14606 if (!Invalid) { 14607 // Add a "return *this;" 14608 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14609 14610 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14611 if (Return.isInvalid()) 14612 Invalid = true; 14613 else 14614 Statements.push_back(Return.getAs<Stmt>()); 14615 } 14616 14617 if (Invalid) { 14618 CopyAssignOperator->setInvalidDecl(); 14619 return; 14620 } 14621 14622 StmtResult Body; 14623 { 14624 CompoundScopeRAII CompoundScope(*this); 14625 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14626 /*isStmtExpr=*/false); 14627 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14627, __extension__ __PRETTY_FUNCTION__
))
; 14628 } 14629 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14630 CopyAssignOperator->markUsed(Context); 14631 14632 if (ASTMutationListener *L = getASTMutationListener()) { 14633 L->CompletedImplicitDefinition(CopyAssignOperator); 14634 } 14635} 14636 14637CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14638 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14638, __extension__ __PRETTY_FUNCTION__
))
; 14639 14640 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14641 if (DSM.isAlreadyBeingDeclared()) 14642 return nullptr; 14643 14644 // Note: The following rules are largely analoguous to the move 14645 // constructor rules. 14646 14647 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14648 LangAS AS = getDefaultCXXMethodAddrSpace(); 14649 if (AS != LangAS::Default) 14650 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14651 QualType RetType = Context.getLValueReferenceType(ArgType); 14652 ArgType = Context.getRValueReferenceType(ArgType); 14653 14654 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14655 CXXMoveAssignment, 14656 false); 14657 14658 // An implicitly-declared move assignment operator is an inline public 14659 // member of its class. 14660 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14661 SourceLocation ClassLoc = ClassDecl->getLocation(); 14662 DeclarationNameInfo NameInfo(Name, ClassLoc); 14663 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14664 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14665 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14666 getCurFPFeatures().isFPConstrained(), 14667 /*isInline=*/true, 14668 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14669 SourceLocation()); 14670 MoveAssignment->setAccess(AS_public); 14671 MoveAssignment->setDefaulted(); 14672 MoveAssignment->setImplicit(); 14673 14674 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14675 14676 if (getLangOpts().CUDA) 14677 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14678 MoveAssignment, 14679 /* ConstRHS */ false, 14680 /* Diagnose */ false); 14681 14682 // Add the parameter to the operator. 14683 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14684 ClassLoc, ClassLoc, 14685 /*Id=*/nullptr, ArgType, 14686 /*TInfo=*/nullptr, SC_None, 14687 nullptr); 14688 MoveAssignment->setParams(FromParam); 14689 14690 MoveAssignment->setTrivial( 14691 ClassDecl->needsOverloadResolutionForMoveAssignment() 14692 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14693 : ClassDecl->hasTrivialMoveAssignment()); 14694 14695 // Note that we have added this copy-assignment operator. 14696 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14697 14698 Scope *S = getScopeForContext(ClassDecl); 14699 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14700 14701 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14702 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14703 SetDeclDeleted(MoveAssignment, ClassLoc); 14704 } 14705 14706 if (S) 14707 PushOnScopeChains(MoveAssignment, S, false); 14708 ClassDecl->addDecl(MoveAssignment); 14709 14710 return MoveAssignment; 14711} 14712 14713/// Check if we're implicitly defining a move assignment operator for a class 14714/// with virtual bases. Such a move assignment might move-assign the virtual 14715/// base multiple times. 14716static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14717 SourceLocation CurrentLocation) { 14718 assert(!Class->isDependentContext() && "should not define dependent move")(static_cast <bool> (!Class->isDependentContext() &&
"should not define dependent move") ? void (0) : __assert_fail
("!Class->isDependentContext() && \"should not define dependent move\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14718, __extension__ __PRETTY_FUNCTION__
))
; 14719 14720 // Only a virtual base could get implicitly move-assigned multiple times. 14721 // Only a non-trivial move assignment can observe this. We only want to 14722 // diagnose if we implicitly define an assignment operator that assigns 14723 // two base classes, both of which move-assign the same virtual base. 14724 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14725 Class->getNumBases() < 2) 14726 return; 14727 14728 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14729 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14730 VBaseMap VBases; 14731 14732 for (auto &BI : Class->bases()) { 14733 Worklist.push_back(&BI); 14734 while (!Worklist.empty()) { 14735 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14736 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14737 14738 // If the base has no non-trivial move assignment operators, 14739 // we don't care about moves from it. 14740 if (!Base->hasNonTrivialMoveAssignment()) 14741 continue; 14742 14743 // If there's nothing virtual here, skip it. 14744 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14745 continue; 14746 14747 // If we're not actually going to call a move assignment for this base, 14748 // or the selected move assignment is trivial, skip it. 14749 Sema::SpecialMemberOverloadResult SMOR = 14750 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14751 /*ConstArg*/false, /*VolatileArg*/false, 14752 /*RValueThis*/true, /*ConstThis*/false, 14753 /*VolatileThis*/false); 14754 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14755 !SMOR.getMethod()->isMoveAssignmentOperator()) 14756 continue; 14757 14758 if (BaseSpec->isVirtual()) { 14759 // We're going to move-assign this virtual base, and its move 14760 // assignment operator is not trivial. If this can happen for 14761 // multiple distinct direct bases of Class, diagnose it. (If it 14762 // only happens in one base, we'll diagnose it when synthesizing 14763 // that base class's move assignment operator.) 14764 CXXBaseSpecifier *&Existing = 14765 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14766 .first->second; 14767 if (Existing && Existing != &BI) { 14768 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14769 << Class << Base; 14770 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14771 << (Base->getCanonicalDecl() == 14772 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14773 << Base << Existing->getType() << Existing->getSourceRange(); 14774 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14775 << (Base->getCanonicalDecl() == 14776 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14777 << Base << BI.getType() << BaseSpec->getSourceRange(); 14778 14779 // Only diagnose each vbase once. 14780 Existing = nullptr; 14781 } 14782 } else { 14783 // Only walk over bases that have defaulted move assignment operators. 14784 // We assume that any user-provided move assignment operator handles 14785 // the multiple-moves-of-vbase case itself somehow. 14786 if (!SMOR.getMethod()->isDefaulted()) 14787 continue; 14788 14789 // We're going to move the base classes of Base. Add them to the list. 14790 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases())); 14791 } 14792 } 14793 } 14794} 14795 14796void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14797 CXXMethodDecl *MoveAssignOperator) { 14798 assert((MoveAssignOperator->isDefaulted() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14803, __extension__ __PRETTY_FUNCTION__
))
14799 MoveAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14803, __extension__ __PRETTY_FUNCTION__
))
14800 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14803, __extension__ __PRETTY_FUNCTION__
))
14801 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14803, __extension__ __PRETTY_FUNCTION__
))
14802 !MoveAssignOperator->isDeleted()) &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14803, __extension__ __PRETTY_FUNCTION__
))
14803 "DefineImplicitMoveAssignment called for wrong function")(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14803, __extension__ __PRETTY_FUNCTION__
))
; 14804 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14805 return; 14806 14807 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14808 if (ClassDecl->isInvalidDecl()) { 14809 MoveAssignOperator->setInvalidDecl(); 14810 return; 14811 } 14812 14813 // C++0x [class.copy]p28: 14814 // The implicitly-defined or move assignment operator for a non-union class 14815 // X performs memberwise move assignment of its subobjects. The direct base 14816 // classes of X are assigned first, in the order of their declaration in the 14817 // base-specifier-list, and then the immediate non-static data members of X 14818 // are assigned, in the order in which they were declared in the class 14819 // definition. 14820 14821 // Issue a warning if our implicit move assignment operator will move 14822 // from a virtual base more than once. 14823 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14824 14825 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14826 14827 // The exception specification is needed because we are defining the 14828 // function. 14829 ResolveExceptionSpec(CurrentLocation, 14830 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14831 14832 // Add a context note for diagnostics produced after this point. 14833 Scope.addContextNote(CurrentLocation); 14834 14835 // The statements that form the synthesized function body. 14836 SmallVector<Stmt*, 8> Statements; 14837 14838 // The parameter for the "other" object, which we are move from. 14839 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14840 QualType OtherRefType = 14841 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14842 14843 // Our location for everything implicitly-generated. 14844 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14845 ? MoveAssignOperator->getEndLoc() 14846 : MoveAssignOperator->getLocation(); 14847 14848 // Builds a reference to the "other" object. 14849 RefBuilder OtherRef(Other, OtherRefType); 14850 // Cast to rvalue. 14851 MoveCastBuilder MoveOther(OtherRef); 14852 14853 // Builds the "this" pointer. 14854 ThisBuilder This; 14855 14856 // Assign base classes. 14857 bool Invalid = false; 14858 for (auto &Base : ClassDecl->bases()) { 14859 // C++11 [class.copy]p28: 14860 // It is unspecified whether subobjects representing virtual base classes 14861 // are assigned more than once by the implicitly-defined copy assignment 14862 // operator. 14863 // FIXME: Do not assign to a vbase that will be assigned by some other base 14864 // class. For a move-assignment, this can result in the vbase being moved 14865 // multiple times. 14866 14867 // Form the assignment: 14868 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14869 QualType BaseType = Base.getType().getUnqualifiedType(); 14870 if (!BaseType->isRecordType()) { 14871 Invalid = true; 14872 continue; 14873 } 14874 14875 CXXCastPath BasePath; 14876 BasePath.push_back(&Base); 14877 14878 // Construct the "from" expression, which is an implicit cast to the 14879 // appropriately-qualified base type. 14880 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14881 14882 // Dereference "this". 14883 DerefBuilder DerefThis(This); 14884 14885 // Implicitly cast "this" to the appropriately-qualified base type. 14886 CastBuilder To(DerefThis, 14887 Context.getQualifiedType( 14888 BaseType, MoveAssignOperator->getMethodQualifiers()), 14889 VK_LValue, BasePath); 14890 14891 // Build the move. 14892 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14893 To, From, 14894 /*CopyingBaseSubobject=*/true, 14895 /*Copying=*/false); 14896 if (Move.isInvalid()) { 14897 MoveAssignOperator->setInvalidDecl(); 14898 return; 14899 } 14900 14901 // Success! Record the move. 14902 Statements.push_back(Move.getAs<Expr>()); 14903 } 14904 14905 // Assign non-static members. 14906 for (auto *Field : ClassDecl->fields()) { 14907 // FIXME: We should form some kind of AST representation for the implied 14908 // memcpy in a union copy operation. 14909 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14910 continue; 14911 14912 if (Field->isInvalidDecl()) { 14913 Invalid = true; 14914 continue; 14915 } 14916 14917 // Check for members of reference type; we can't move those. 14918 if (Field->getType()->isReferenceType()) { 14919 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14920 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14921 Diag(Field->getLocation(), diag::note_declared_at); 14922 Invalid = true; 14923 continue; 14924 } 14925 14926 // Check for members of const-qualified, non-class type. 14927 QualType BaseType = Context.getBaseElementType(Field->getType()); 14928 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14929 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14930 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14931 Diag(Field->getLocation(), diag::note_declared_at); 14932 Invalid = true; 14933 continue; 14934 } 14935 14936 // Suppress assigning zero-width bitfields. 14937 if (Field->isZeroLengthBitField(Context)) 14938 continue; 14939 14940 QualType FieldType = Field->getType().getNonReferenceType(); 14941 if (FieldType->isIncompleteArrayType()) { 14942 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", 14943, __extension__ __PRETTY_FUNCTION__
))
14943 "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", 14943, __extension__ __PRETTY_FUNCTION__
))
; 14944 continue; 14945 } 14946 14947 // Build references to the field in the object we're copying from and to. 14948 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14949 LookupMemberName); 14950 MemberLookup.addDecl(Field); 14951 MemberLookup.resolveKind(); 14952 MemberBuilder From(MoveOther, OtherRefType, 14953 /*IsArrow=*/false, MemberLookup); 14954 MemberBuilder To(This, getCurrentThisType(), 14955 /*IsArrow=*/true, MemberLookup); 14956 14957 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14959, __extension__ __PRETTY_FUNCTION__
))
14958 "Member reference with rvalue base must be rvalue except for reference "(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14959, __extension__ __PRETTY_FUNCTION__
))
14959 "members, which aren't allowed for move assignment.")(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14959, __extension__ __PRETTY_FUNCTION__
))
; 14960 14961 // Build the move of this field. 14962 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14963 To, From, 14964 /*CopyingBaseSubobject=*/false, 14965 /*Copying=*/false); 14966 if (Move.isInvalid()) { 14967 MoveAssignOperator->setInvalidDecl(); 14968 return; 14969 } 14970 14971 // Success! Record the copy. 14972 Statements.push_back(Move.getAs<Stmt>()); 14973 } 14974 14975 if (!Invalid) { 14976 // Add a "return *this;" 14977 ExprResult ThisObj = 14978 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14979 14980 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14981 if (Return.isInvalid()) 14982 Invalid = true; 14983 else 14984 Statements.push_back(Return.getAs<Stmt>()); 14985 } 14986 14987 if (Invalid) { 14988 MoveAssignOperator->setInvalidDecl(); 14989 return; 14990 } 14991 14992 StmtResult Body; 14993 { 14994 CompoundScopeRAII CompoundScope(*this); 14995 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14996 /*isStmtExpr=*/false); 14997 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14997, __extension__ __PRETTY_FUNCTION__
))
; 14998 } 14999 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 15000 MoveAssignOperator->markUsed(Context); 15001 15002 if (ASTMutationListener *L = getASTMutationListener()) { 15003 L->CompletedImplicitDefinition(MoveAssignOperator); 15004 } 15005} 15006 15007CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 15008 CXXRecordDecl *ClassDecl) { 15009 // C++ [class.copy]p4: 15010 // If the class definition does not explicitly declare a copy 15011 // constructor, one is declared implicitly. 15012 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15012, __extension__ __PRETTY_FUNCTION__
))
; 15013 15014 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 15015 if (DSM.isAlreadyBeingDeclared()) 15016 return nullptr; 15017 15018 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15019 QualType ArgType = ClassType; 15020 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 15021 if (Const) 15022 ArgType = ArgType.withConst(); 15023 15024 LangAS AS = getDefaultCXXMethodAddrSpace(); 15025 if (AS != LangAS::Default) 15026 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 15027 15028 ArgType = Context.getLValueReferenceType(ArgType); 15029 15030 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15031 CXXCopyConstructor, 15032 Const); 15033 15034 DeclarationName Name 15035 = Context.DeclarationNames.getCXXConstructorName( 15036 Context.getCanonicalType(ClassType)); 15037 SourceLocation ClassLoc = ClassDecl->getLocation(); 15038 DeclarationNameInfo NameInfo(Name, ClassLoc); 15039 15040 // An implicitly-declared copy constructor is an inline public 15041 // member of its class. 15042 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 15043 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15044 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15045 /*isInline=*/true, 15046 /*isImplicitlyDeclared=*/true, 15047 Constexpr ? ConstexprSpecKind::Constexpr 15048 : ConstexprSpecKind::Unspecified); 15049 CopyConstructor->setAccess(AS_public); 15050 CopyConstructor->setDefaulted(); 15051 15052 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 15053 15054 if (getLangOpts().CUDA) 15055 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 15056 CopyConstructor, 15057 /* ConstRHS */ Const, 15058 /* Diagnose */ false); 15059 15060 // During template instantiation of special member functions we need a 15061 // reliable TypeSourceInfo for the parameter types in order to allow functions 15062 // to be substituted. 15063 TypeSourceInfo *TSI = nullptr; 15064 if (inTemplateInstantiation() && ClassDecl->isLambda()) 15065 TSI = Context.getTrivialTypeSourceInfo(ArgType); 15066 15067 // Add the parameter to the constructor. 15068 ParmVarDecl *FromParam = 15069 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 15070 /*IdentifierInfo=*/nullptr, ArgType, 15071 /*TInfo=*/TSI, SC_None, nullptr); 15072 CopyConstructor->setParams(FromParam); 15073 15074 CopyConstructor->setTrivial( 15075 ClassDecl->needsOverloadResolutionForCopyConstructor() 15076 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 15077 : ClassDecl->hasTrivialCopyConstructor()); 15078 15079 CopyConstructor->setTrivialForCall( 15080 ClassDecl->hasAttr<TrivialABIAttr>() || 15081 (ClassDecl->needsOverloadResolutionForCopyConstructor() 15082 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 15083 TAH_ConsiderTrivialABI) 15084 : ClassDecl->hasTrivialCopyConstructorForCall())); 15085 15086 // Note that we have declared this constructor. 15087 ++getASTContext().NumImplicitCopyConstructorsDeclared; 15088 15089 Scope *S = getScopeForContext(ClassDecl); 15090 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 15091 15092 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 15093 ClassDecl->setImplicitCopyConstructorIsDeleted(); 15094 SetDeclDeleted(CopyConstructor, ClassLoc); 15095 } 15096 15097 if (S) 15098 PushOnScopeChains(CopyConstructor, S, false); 15099 ClassDecl->addDecl(CopyConstructor); 15100 15101 return CopyConstructor; 15102} 15103 15104void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 15105 CXXConstructorDecl *CopyConstructor) { 15106 assert((CopyConstructor->isDefaulted() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15110, __extension__ __PRETTY_FUNCTION__
))
15107 CopyConstructor->isCopyConstructor() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15110, __extension__ __PRETTY_FUNCTION__
))
15108 !CopyConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15110, __extension__ __PRETTY_FUNCTION__
))
15109 !CopyConstructor->isDeleted()) &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15110, __extension__ __PRETTY_FUNCTION__
))
15110 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15110, __extension__ __PRETTY_FUNCTION__
))
; 15111 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15112 return; 15113 15114 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15115 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15115, __extension__ __PRETTY_FUNCTION__
))
; 15116 15117 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15118 15119 // The exception specification is needed because we are defining the 15120 // function. 15121 ResolveExceptionSpec(CurrentLocation, 15122 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15123 MarkVTableUsed(CurrentLocation, ClassDecl); 15124 15125 // Add a context note for diagnostics produced after this point. 15126 Scope.addContextNote(CurrentLocation); 15127 15128 // C++11 [class.copy]p7: 15129 // The [definition of an implicitly declared copy constructor] is 15130 // deprecated if the class has a user-declared copy assignment operator 15131 // or a user-declared destructor. 15132 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15133 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15134 15135 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15136 CopyConstructor->setInvalidDecl(); 15137 } else { 15138 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15139 ? CopyConstructor->getEndLoc() 15140 : CopyConstructor->getLocation(); 15141 Sema::CompoundScopeRAII CompoundScope(*this); 15142 CopyConstructor->setBody( 15143 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15144 CopyConstructor->markUsed(Context); 15145 } 15146 15147 if (ASTMutationListener *L = getASTMutationListener()) { 15148 L->CompletedImplicitDefinition(CopyConstructor); 15149 } 15150} 15151 15152CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15153 CXXRecordDecl *ClassDecl) { 15154 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15154, __extension__ __PRETTY_FUNCTION__
))
; 15155 15156 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15157 if (DSM.isAlreadyBeingDeclared()) 15158 return nullptr; 15159 15160 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15161 15162 QualType ArgType = ClassType; 15163 LangAS AS = getDefaultCXXMethodAddrSpace(); 15164 if (AS != LangAS::Default) 15165 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15166 ArgType = Context.getRValueReferenceType(ArgType); 15167 15168 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15169 CXXMoveConstructor, 15170 false); 15171 15172 DeclarationName Name 15173 = Context.DeclarationNames.getCXXConstructorName( 15174 Context.getCanonicalType(ClassType)); 15175 SourceLocation ClassLoc = ClassDecl->getLocation(); 15176 DeclarationNameInfo NameInfo(Name, ClassLoc); 15177 15178 // C++11 [class.copy]p11: 15179 // An implicitly-declared copy/move constructor is an inline public 15180 // member of its class. 15181 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15182 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15183 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15184 /*isInline=*/true, 15185 /*isImplicitlyDeclared=*/true, 15186 Constexpr ? ConstexprSpecKind::Constexpr 15187 : ConstexprSpecKind::Unspecified); 15188 MoveConstructor->setAccess(AS_public); 15189 MoveConstructor->setDefaulted(); 15190 15191 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15192 15193 if (getLangOpts().CUDA) 15194 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15195 MoveConstructor, 15196 /* ConstRHS */ false, 15197 /* Diagnose */ false); 15198 15199 // Add the parameter to the constructor. 15200 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15201 ClassLoc, ClassLoc, 15202 /*IdentifierInfo=*/nullptr, 15203 ArgType, /*TInfo=*/nullptr, 15204 SC_None, nullptr); 15205 MoveConstructor->setParams(FromParam); 15206 15207 MoveConstructor->setTrivial( 15208 ClassDecl->needsOverloadResolutionForMoveConstructor() 15209 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15210 : ClassDecl->hasTrivialMoveConstructor()); 15211 15212 MoveConstructor->setTrivialForCall( 15213 ClassDecl->hasAttr<TrivialABIAttr>() || 15214 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15215 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15216 TAH_ConsiderTrivialABI) 15217 : ClassDecl->hasTrivialMoveConstructorForCall())); 15218 15219 // Note that we have declared this constructor. 15220 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15221 15222 Scope *S = getScopeForContext(ClassDecl); 15223 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15224 15225 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15226 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15227 SetDeclDeleted(MoveConstructor, ClassLoc); 15228 } 15229 15230 if (S) 15231 PushOnScopeChains(MoveConstructor, S, false); 15232 ClassDecl->addDecl(MoveConstructor); 15233 15234 return MoveConstructor; 15235} 15236 15237void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15238 CXXConstructorDecl *MoveConstructor) { 15239 assert((MoveConstructor->isDefaulted() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15243, __extension__ __PRETTY_FUNCTION__
))
15240 MoveConstructor->isMoveConstructor() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15243, __extension__ __PRETTY_FUNCTION__
))
15241 !MoveConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15243, __extension__ __PRETTY_FUNCTION__
))
15242 !MoveConstructor->isDeleted()) &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15243, __extension__ __PRETTY_FUNCTION__
))
15243 "DefineImplicitMoveConstructor - call it for implicit move ctor")(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15243, __extension__ __PRETTY_FUNCTION__
))
; 15244 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15245 return; 15246 15247 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15248 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15248, __extension__ __PRETTY_FUNCTION__
))
; 15249 15250 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15251 15252 // The exception specification is needed because we are defining the 15253 // function. 15254 ResolveExceptionSpec(CurrentLocation, 15255 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15256 MarkVTableUsed(CurrentLocation, ClassDecl); 15257 15258 // Add a context note for diagnostics produced after this point. 15259 Scope.addContextNote(CurrentLocation); 15260 15261 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15262 MoveConstructor->setInvalidDecl(); 15263 } else { 15264 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15265 ? MoveConstructor->getEndLoc() 15266 : MoveConstructor->getLocation(); 15267 Sema::CompoundScopeRAII CompoundScope(*this); 15268 MoveConstructor->setBody(ActOnCompoundStmt( 15269 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15270 MoveConstructor->markUsed(Context); 15271 } 15272 15273 if (ASTMutationListener *L = getASTMutationListener()) { 15274 L->CompletedImplicitDefinition(MoveConstructor); 15275 } 15276} 15277 15278bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15279 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15280} 15281 15282void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15283 SourceLocation CurrentLocation, 15284 CXXConversionDecl *Conv) { 15285 SynthesizedFunctionScope Scope(*this, Conv); 15286 assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15286, __extension__ __PRETTY_FUNCTION__
))
; 15287 15288 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15289 CallingConv CC = 15290 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15291 15292 CXXRecordDecl *Lambda = Conv->getParent(); 15293 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15294 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15295 15296 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15297 CallOp = InstantiateFunctionDeclaration( 15298 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15299 if (!CallOp) 15300 return; 15301 15302 Invoker = InstantiateFunctionDeclaration( 15303 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15304 if (!Invoker) 15305 return; 15306 } 15307 15308 if (CallOp->isInvalidDecl()) 15309 return; 15310 15311 // Mark the call operator referenced (and add to pending instantiations 15312 // if necessary). 15313 // For both the conversion and static-invoker template specializations 15314 // we construct their body's in this function, so no need to add them 15315 // to the PendingInstantiations. 15316 MarkFunctionReferenced(CurrentLocation, CallOp); 15317 15318 // Fill in the __invoke function with a dummy implementation. IR generation 15319 // will fill in the actual details. Update its type in case it contained 15320 // an 'auto'. 15321 Invoker->markUsed(Context); 15322 Invoker->setReferenced(); 15323 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15324 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15325 15326 // Construct the body of the conversion function { return __invoke; }. 15327 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15328 VK_LValue, Conv->getLocation()); 15329 assert(FunctionRef && "Can't refer to __invoke function?")(static_cast <bool> (FunctionRef && "Can't refer to __invoke function?"
) ? void (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15329, __extension__ __PRETTY_FUNCTION__
))
; 15330 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15331 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15332 Conv->getLocation())); 15333 Conv->markUsed(Context); 15334 Conv->setReferenced(); 15335 15336 if (ASTMutationListener *L = getASTMutationListener()) { 15337 L->CompletedImplicitDefinition(Conv); 15338 L->CompletedImplicitDefinition(Invoker); 15339 } 15340} 15341 15342 15343 15344void Sema::DefineImplicitLambdaToBlockPointerConversion( 15345 SourceLocation CurrentLocation, 15346 CXXConversionDecl *Conv) 15347{ 15348 assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda
()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15348, __extension__ __PRETTY_FUNCTION__
))
; 15349 15350 SynthesizedFunctionScope Scope(*this, Conv); 15351 15352 // Copy-initialize the lambda object as needed to capture it. 15353 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15354 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15355 15356 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15357 Conv->getLocation(), 15358 Conv, DerefThis); 15359 15360 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15361 // behavior. Note that only the general conversion function does this 15362 // (since it's unusable otherwise); in the case where we inline the 15363 // block literal, it has block literal lifetime semantics. 15364 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15365 BuildBlock = ImplicitCastExpr::Create( 15366 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15367 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15368 15369 if (BuildBlock.isInvalid()) { 15370 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15371 Conv->setInvalidDecl(); 15372 return; 15373 } 15374 15375 // Create the return statement that returns the block from the conversion 15376 // function. 15377 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15378 if (Return.isInvalid()) { 15379 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15380 Conv->setInvalidDecl(); 15381 return; 15382 } 15383 15384 // Set the body of the conversion function. 15385 Stmt *ReturnS = Return.get(); 15386 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15387 Conv->getLocation())); 15388 Conv->markUsed(Context); 15389 15390 // We're done; notify the mutation listener, if any. 15391 if (ASTMutationListener *L = getASTMutationListener()) { 15392 L->CompletedImplicitDefinition(Conv); 15393 } 15394} 15395 15396/// Determine whether the given list arguments contains exactly one 15397/// "real" (non-default) argument. 15398static bool hasOneRealArgument(MultiExprArg Args) { 15399 switch (Args.size()) { 15400 case 0: 15401 return false; 15402 15403 default: 15404 if (!Args[1]->isDefaultArgument()) 15405 return false; 15406 15407 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 15408 case 1: 15409 return !Args[0]->isDefaultArgument(); 15410 } 15411 15412 return false; 15413} 15414 15415ExprResult 15416Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15417 NamedDecl *FoundDecl, 15418 CXXConstructorDecl *Constructor, 15419 MultiExprArg ExprArgs, 15420 bool HadMultipleCandidates, 15421 bool IsListInitialization, 15422 bool IsStdInitListInitialization, 15423 bool RequiresZeroInit, 15424 unsigned ConstructKind, 15425 SourceRange ParenRange) { 15426 bool Elidable = false; 15427 15428 // C++0x [class.copy]p34: 15429 // When certain criteria are met, an implementation is allowed to 15430 // omit the copy/move construction of a class object, even if the 15431 // copy/move constructor and/or destructor for the object have 15432 // side effects. [...] 15433 // - when a temporary class object that has not been bound to a 15434 // reference (12.2) would be copied/moved to a class object 15435 // with the same cv-unqualified type, the copy/move operation 15436 // can be omitted by constructing the temporary object 15437 // directly into the target of the omitted copy/move 15438 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15439 // FIXME: Converting constructors should also be accepted. 15440 // But to fix this, the logic that digs down into a CXXConstructExpr 15441 // to find the source object needs to handle it. 15442 // Right now it assumes the source object is passed directly as the 15443 // first argument. 15444 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15445 Expr *SubExpr = ExprArgs[0]; 15446 // FIXME: Per above, this is also incorrect if we want to accept 15447 // converting constructors, as isTemporaryObject will 15448 // reject temporaries with different type from the 15449 // CXXRecord itself. 15450 Elidable = SubExpr->isTemporaryObject( 15451 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15452 } 15453 15454 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15455 FoundDecl, Constructor, 15456 Elidable, ExprArgs, HadMultipleCandidates, 15457 IsListInitialization, 15458 IsStdInitListInitialization, RequiresZeroInit, 15459 ConstructKind, ParenRange); 15460} 15461 15462ExprResult 15463Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15464 NamedDecl *FoundDecl, 15465 CXXConstructorDecl *Constructor, 15466 bool Elidable, 15467 MultiExprArg ExprArgs, 15468 bool HadMultipleCandidates, 15469 bool IsListInitialization, 15470 bool IsStdInitListInitialization, 15471 bool RequiresZeroInit, 15472 unsigned ConstructKind, 15473 SourceRange ParenRange) { 15474 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15475 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15476 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15477 return ExprError(); 15478 } 15479 15480 return BuildCXXConstructExpr( 15481 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15482 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15483 RequiresZeroInit, ConstructKind, ParenRange); 15484} 15485 15486/// BuildCXXConstructExpr - Creates a complete call to a constructor, 15487/// including handling of its default argument expressions. 15488ExprResult 15489Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15490 CXXConstructorDecl *Constructor, 15491 bool Elidable, 15492 MultiExprArg ExprArgs, 15493 bool HadMultipleCandidates, 15494 bool IsListInitialization, 15495 bool IsStdInitListInitialization, 15496 bool RequiresZeroInit, 15497 unsigned ConstructKind, 15498 SourceRange ParenRange) { 15499 assert(declaresSameEntity((static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15502, __extension__ __PRETTY_FUNCTION__
))
15500 Constructor->getParent(),(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15502, __extension__ __PRETTY_FUNCTION__
))
15501 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15502, __extension__ __PRETTY_FUNCTION__
))
15502 "given constructor for wrong type")(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15502, __extension__ __PRETTY_FUNCTION__
))
; 15503 MarkFunctionReferenced(ConstructLoc, Constructor); 15504 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15505 return ExprError(); 15506 if (getLangOpts().SYCLIsDevice && 15507 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15508 return ExprError(); 15509 15510 return CheckForImmediateInvocation( 15511 CXXConstructExpr::Create( 15512 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15513 HadMultipleCandidates, IsListInitialization, 15514 IsStdInitListInitialization, RequiresZeroInit, 15515 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15516 ParenRange), 15517 Constructor); 15518} 15519 15520ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15521 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15521, __extension__ __PRETTY_FUNCTION__
))
; 15522 15523 // If we already have the in-class initializer nothing needs to be done. 15524 if (Field->getInClassInitializer()) 15525 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15526 15527 // If we might have already tried and failed to instantiate, don't try again. 15528 if (Field->isInvalidDecl()) 15529 return ExprError(); 15530 15531 // Maybe we haven't instantiated the in-class initializer. Go check the 15532 // pattern FieldDecl to see if it has one. 15533 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15534 15535 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15536 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15537 DeclContext::lookup_result Lookup = 15538 ClassPattern->lookup(Field->getDeclName()); 15539 15540 FieldDecl *Pattern = nullptr; 15541 for (auto L : Lookup) { 15542 if (isa<FieldDecl>(L)) { 15543 Pattern = cast<FieldDecl>(L); 15544 break; 15545 } 15546 } 15547 assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!"
) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15547, __extension__ __PRETTY_FUNCTION__
))
; 15548 15549 if (!Pattern->hasInClassInitializer() || 15550 InstantiateInClassInitializer(Loc, Field, Pattern, 15551 getTemplateInstantiationArgs(Field))) { 15552 // Don't diagnose this again. 15553 Field->setInvalidDecl(); 15554 return ExprError(); 15555 } 15556 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15557 } 15558 15559 // DR1351: 15560 // If the brace-or-equal-initializer of a non-static data member 15561 // invokes a defaulted default constructor of its class or of an 15562 // enclosing class in a potentially evaluated subexpression, the 15563 // program is ill-formed. 15564 // 15565 // This resolution is unworkable: the exception specification of the 15566 // default constructor can be needed in an unevaluated context, in 15567 // particular, in the operand of a noexcept-expression, and we can be 15568 // unable to compute an exception specification for an enclosed class. 15569 // 15570 // Any attempt to resolve the exception specification of a defaulted default 15571 // constructor before the initializer is lexically complete will ultimately 15572 // come here at which point we can diagnose it. 15573 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15574 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15575 << OutermostClass << Field; 15576 Diag(Field->getEndLoc(), 15577 diag::note_default_member_initializer_not_yet_parsed); 15578 // Recover by marking the field invalid, unless we're in a SFINAE context. 15579 if (!isSFINAEContext()) 15580 Field->setInvalidDecl(); 15581 return ExprError(); 15582} 15583 15584void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15585 if (VD->isInvalidDecl()) return; 15586 // If initializing the variable failed, don't also diagnose problems with 15587 // the destructor, they're likely related. 15588 if (VD->getInit() && VD->getInit()->containsErrors()) 15589 return; 15590 15591 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15592 if (ClassDecl->isInvalidDecl()) return; 15593 if (ClassDecl->hasIrrelevantDestructor()) return; 15594 if (ClassDecl->isDependentContext()) return; 15595 15596 if (VD->isNoDestroy(getASTContext())) 15597 return; 15598 15599 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15600 15601 // If this is an array, we'll require the destructor during initialization, so 15602 // we can skip over this. We still want to emit exit-time destructor warnings 15603 // though. 15604 if (!VD->getType()->isArrayType()) { 15605 MarkFunctionReferenced(VD->getLocation(), Destructor); 15606 CheckDestructorAccess(VD->getLocation(), Destructor, 15607 PDiag(diag::err_access_dtor_var) 15608 << VD->getDeclName() << VD->getType()); 15609 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15610 } 15611 15612 if (Destructor->isTrivial()) return; 15613 15614 // If the destructor is constexpr, check whether the variable has constant 15615 // destruction now. 15616 if (Destructor->isConstexpr()) { 15617 bool HasConstantInit = false; 15618 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15619 HasConstantInit = VD->evaluateValue(); 15620 SmallVector<PartialDiagnosticAt, 8> Notes; 15621 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15622 HasConstantInit) { 15623 Diag(VD->getLocation(), 15624 diag::err_constexpr_var_requires_const_destruction) << VD; 15625 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15626 Diag(Notes[I].first, Notes[I].second); 15627 } 15628 } 15629 15630 if (!VD->hasGlobalStorage()) return; 15631 15632 // Emit warning for non-trivial dtor in global scope (a real global, 15633 // class-static, function-static). 15634 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15635 15636 // TODO: this should be re-enabled for static locals by !CXAAtExit 15637 if (!VD->isStaticLocal()) 15638 Diag(VD->getLocation(), diag::warn_global_destructor); 15639} 15640 15641/// Given a constructor and the set of arguments provided for the 15642/// constructor, convert the arguments and add any required default arguments 15643/// to form a proper call to this constructor. 15644/// 15645/// \returns true if an error occurred, false otherwise. 15646bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15647 QualType DeclInitType, MultiExprArg ArgsPtr, 15648 SourceLocation Loc, 15649 SmallVectorImpl<Expr *> &ConvertedArgs, 15650 bool AllowExplicit, 15651 bool IsListInitialization) { 15652 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15653 unsigned NumArgs = ArgsPtr.size(); 15654 Expr **Args = ArgsPtr.data(); 15655 15656 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15657 unsigned NumParams = Proto->getNumParams(); 15658 15659 // If too few arguments are available, we'll fill in the rest with defaults. 15660 if (NumArgs < NumParams) 15661 ConvertedArgs.reserve(NumParams); 15662 else 15663 ConvertedArgs.reserve(NumArgs); 15664 15665 VariadicCallType CallType = 15666 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15667 SmallVector<Expr *, 8> AllArgs; 15668 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15669 Proto, 0, 15670 llvm::makeArrayRef(Args, NumArgs), 15671 AllArgs, 15672 CallType, AllowExplicit, 15673 IsListInitialization); 15674 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15675 15676 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15677 15678 CheckConstructorCall(Constructor, DeclInitType, 15679 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15680 Proto, Loc); 15681 15682 return Invalid; 15683} 15684 15685static inline bool 15686CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15687 const FunctionDecl *FnDecl) { 15688 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15689 if (isa<NamespaceDecl>(DC)) { 15690 return SemaRef.Diag(FnDecl->getLocation(), 15691 diag::err_operator_new_delete_declared_in_namespace) 15692 << FnDecl->getDeclName(); 15693 } 15694 15695 if (isa<TranslationUnitDecl>(DC) && 15696 FnDecl->getStorageClass() == SC_Static) { 15697 return SemaRef.Diag(FnDecl->getLocation(), 15698 diag::err_operator_new_delete_declared_static) 15699 << FnDecl->getDeclName(); 15700 } 15701 15702 return false; 15703} 15704 15705static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15706 const PointerType *PtrTy) { 15707 auto &Ctx = SemaRef.Context; 15708 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15709 PtrQuals.removeAddressSpace(); 15710 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15711 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15712} 15713 15714static inline bool 15715CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15716 CanQualType ExpectedResultType, 15717 CanQualType ExpectedFirstParamType, 15718 unsigned DependentParamTypeDiag, 15719 unsigned InvalidParamTypeDiag) { 15720 QualType ResultType = 15721 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15722 15723 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15724 // The operator is valid on any address space for OpenCL. 15725 // Drop address space from actual and expected result types. 15726 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15727 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15728 15729 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15730 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15731 } 15732 15733 // Check that the result type is what we expect. 15734 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15735 // Reject even if the type is dependent; an operator delete function is 15736 // required to have a non-dependent result type. 15737 return SemaRef.Diag( 15738 FnDecl->getLocation(), 15739 ResultType->isDependentType() 15740 ? diag::err_operator_new_delete_dependent_result_type 15741 : diag::err_operator_new_delete_invalid_result_type) 15742 << FnDecl->getDeclName() << ExpectedResultType; 15743 } 15744 15745 // A function template must have at least 2 parameters. 15746 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15747 return SemaRef.Diag(FnDecl->getLocation(), 15748 diag::err_operator_new_delete_template_too_few_parameters) 15749 << FnDecl->getDeclName(); 15750 15751 // The function decl must have at least 1 parameter. 15752 if (FnDecl->getNumParams() == 0) 15753 return SemaRef.Diag(FnDecl->getLocation(), 15754 diag::err_operator_new_delete_too_few_parameters) 15755 << FnDecl->getDeclName(); 15756 15757 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15758 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15759 // The operator is valid on any address space for OpenCL. 15760 // Drop address space from actual and expected first parameter types. 15761 if (const auto *PtrTy = 15762 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15763 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15764 15765 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15766 ExpectedFirstParamType = 15767 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15768 } 15769 15770 // Check that the first parameter type is what we expect. 15771 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15772 ExpectedFirstParamType) { 15773 // The first parameter type is not allowed to be dependent. As a tentative 15774 // DR resolution, we allow a dependent parameter type if it is the right 15775 // type anyway, to allow destroying operator delete in class templates. 15776 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15777 ? DependentParamTypeDiag 15778 : InvalidParamTypeDiag) 15779 << FnDecl->getDeclName() << ExpectedFirstParamType; 15780 } 15781 15782 return false; 15783} 15784 15785static bool 15786CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15787 // C++ [basic.stc.dynamic.allocation]p1: 15788 // A program is ill-formed if an allocation function is declared in a 15789 // namespace scope other than global scope or declared static in global 15790 // scope. 15791 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15792 return true; 15793 15794 CanQualType SizeTy = 15795 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15796 15797 // C++ [basic.stc.dynamic.allocation]p1: 15798 // The return type shall be void*. The first parameter shall have type 15799 // std::size_t. 15800 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15801 SizeTy, 15802 diag::err_operator_new_dependent_param_type, 15803 diag::err_operator_new_param_type)) 15804 return true; 15805 15806 // C++ [basic.stc.dynamic.allocation]p1: 15807 // The first parameter shall not have an associated default argument. 15808 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15809 return SemaRef.Diag(FnDecl->getLocation(), 15810 diag::err_operator_new_default_arg) 15811 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15812 15813 return false; 15814} 15815 15816static bool 15817CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15818 // C++ [basic.stc.dynamic.deallocation]p1: 15819 // A program is ill-formed if deallocation functions are declared in a 15820 // namespace scope other than global scope or declared static in global 15821 // scope. 15822 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15823 return true; 15824 15825 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15826 15827 // C++ P0722: 15828 // Within a class C, the first parameter of a destroying operator delete 15829 // shall be of type C *. The first parameter of any other deallocation 15830 // function shall be of type void *. 15831 CanQualType ExpectedFirstParamType = 15832 MD && MD->isDestroyingOperatorDelete() 15833 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15834 SemaRef.Context.getRecordType(MD->getParent()))) 15835 : SemaRef.Context.VoidPtrTy; 15836 15837 // C++ [basic.stc.dynamic.deallocation]p2: 15838 // Each deallocation function shall return void 15839 if (CheckOperatorNewDeleteTypes( 15840 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15841 diag::err_operator_delete_dependent_param_type, 15842 diag::err_operator_delete_param_type)) 15843 return true; 15844 15845 // C++ P0722: 15846 // A destroying operator delete shall be a usual deallocation function. 15847 if (MD && !MD->getParent()->isDependentContext() && 15848 MD->isDestroyingOperatorDelete() && 15849 !SemaRef.isUsualDeallocationFunction(MD)) { 15850 SemaRef.Diag(MD->getLocation(), 15851 diag::err_destroying_operator_delete_not_usual); 15852 return true; 15853 } 15854 15855 return false; 15856} 15857 15858/// CheckOverloadedOperatorDeclaration - Check whether the declaration 15859/// of this overloaded operator is well-formed. If so, returns false; 15860/// otherwise, emits appropriate diagnostics and returns true. 15861bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15862 assert(FnDecl && FnDecl->isOverloadedOperator() &&(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15863, __extension__ __PRETTY_FUNCTION__
))
15863 "Expected an overloaded operator declaration")(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15863, __extension__ __PRETTY_FUNCTION__
))
; 15864 15865 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15866 15867 // C++ [over.oper]p5: 15868 // The allocation and deallocation functions, operator new, 15869 // operator new[], operator delete and operator delete[], are 15870 // described completely in 3.7.3. The attributes and restrictions 15871 // found in the rest of this subclause do not apply to them unless 15872 // explicitly stated in 3.7.3. 15873 if (Op == OO_Delete || Op == OO_Array_Delete) 15874 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15875 15876 if (Op == OO_New || Op == OO_Array_New) 15877 return CheckOperatorNewDeclaration(*this, FnDecl); 15878 15879 // C++ [over.oper]p6: 15880 // An operator function shall either be a non-static member 15881 // function or be a non-member function and have at least one 15882 // parameter whose type is a class, a reference to a class, an 15883 // enumeration, or a reference to an enumeration. 15884 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15885 if (MethodDecl->isStatic()) 15886 return Diag(FnDecl->getLocation(), 15887 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15888 } else { 15889 bool ClassOrEnumParam = false; 15890 for (auto Param : FnDecl->parameters()) { 15891 QualType ParamType = Param->getType().getNonReferenceType(); 15892 if (ParamType->isDependentType() || ParamType->isRecordType() || 15893 ParamType->isEnumeralType()) { 15894 ClassOrEnumParam = true; 15895 break; 15896 } 15897 } 15898 15899 if (!ClassOrEnumParam) 15900 return Diag(FnDecl->getLocation(), 15901 diag::err_operator_overload_needs_class_or_enum) 15902 << FnDecl->getDeclName(); 15903 } 15904 15905 // C++ [over.oper]p8: 15906 // An operator function cannot have default arguments (8.3.6), 15907 // except where explicitly stated below. 15908 // 15909 // Only the function-call operator (C++ [over.call]p1) and the subscript 15910 // operator (CWG2507) allow default arguments. 15911 if (Op != OO_Call) { 15912 ParmVarDecl *FirstDefaultedParam = nullptr; 15913 for (auto Param : FnDecl->parameters()) { 15914 if (Param->hasDefaultArg()) { 15915 FirstDefaultedParam = Param; 15916 break; 15917 } 15918 } 15919 if (FirstDefaultedParam) { 15920 if (Op == OO_Subscript) { 15921 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b 15922 ? diag::ext_subscript_overload 15923 : diag::error_subscript_overload) 15924 << FnDecl->getDeclName() << 1 15925 << FirstDefaultedParam->getDefaultArgRange(); 15926 } else { 15927 return Diag(FirstDefaultedParam->getLocation(), 15928 diag::err_operator_overload_default_arg) 15929 << FnDecl->getDeclName() 15930 << FirstDefaultedParam->getDefaultArgRange(); 15931 } 15932 } 15933 } 15934 15935 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15936 { false, false, false } 15937#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15938 , { Unary, Binary, MemberOnly } 15939#include "clang/Basic/OperatorKinds.def" 15940 }; 15941 15942 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15943 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15944 bool MustBeMemberOperator = OperatorUses[Op][2]; 15945 15946 // C++ [over.oper]p8: 15947 // [...] Operator functions cannot have more or fewer parameters 15948 // than the number required for the corresponding operator, as 15949 // described in the rest of this subclause. 15950 unsigned NumParams = FnDecl->getNumParams() 15951 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15952 if (Op != OO_Call && Op != OO_Subscript && 15953 ((NumParams == 1 && !CanBeUnaryOperator) || 15954 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) || 15955 (NumParams > 2))) { 15956 // We have the wrong number of parameters. 15957 unsigned ErrorKind; 15958 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15959 ErrorKind = 2; // 2 -> unary or binary. 15960 } else if (CanBeUnaryOperator) { 15961 ErrorKind = 0; // 0 -> unary 15962 } else { 15963 assert(CanBeBinaryOperator &&(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15964, __extension__ __PRETTY_FUNCTION__
))
15964 "All non-call overloaded operators are unary or binary!")(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15964, __extension__ __PRETTY_FUNCTION__
))
; 15965 ErrorKind = 1; // 1 -> binary 15966 } 15967 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15968 << FnDecl->getDeclName() << NumParams << ErrorKind; 15969 } 15970 15971 if (Op == OO_Subscript && NumParams != 2) { 15972 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b 15973 ? diag::ext_subscript_overload 15974 : diag::error_subscript_overload) 15975 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2); 15976 } 15977 15978 // Overloaded operators other than operator() and operator[] cannot be 15979 // variadic. 15980 if (Op != OO_Call && 15981 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15982 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15983 << FnDecl->getDeclName(); 15984 } 15985 15986 // Some operators must be non-static member functions. 15987 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15988 return Diag(FnDecl->getLocation(), 15989 diag::err_operator_overload_must_be_member) 15990 << FnDecl->getDeclName(); 15991 } 15992 15993 // C++ [over.inc]p1: 15994 // The user-defined function called operator++ implements the 15995 // prefix and postfix ++ operator. If this function is a member 15996 // function with no parameters, or a non-member function with one 15997 // parameter of class or enumeration type, it defines the prefix 15998 // increment operator ++ for objects of that type. If the function 15999 // is a member function with one parameter (which shall be of type 16000 // int) or a non-member function with two parameters (the second 16001 // of which shall be of type int), it defines the postfix 16002 // increment operator ++ for objects of that type. 16003 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 16004 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 16005 QualType ParamType = LastParam->getType(); 16006 16007 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 16008 !ParamType->isDependentType()) 16009 return Diag(LastParam->getLocation(), 16010 diag::err_operator_overload_post_incdec_must_be_int) 16011 << LastParam->getType() << (Op == OO_MinusMinus); 16012 } 16013 16014 return false; 16015} 16016 16017static bool 16018checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 16019 FunctionTemplateDecl *TpDecl) { 16020 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 16021 16022 // Must have one or two template parameters. 16023 if (TemplateParams->size() == 1) { 16024 NonTypeTemplateParmDecl *PmDecl = 16025 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 16026 16027 // The template parameter must be a char parameter pack. 16028 if (PmDecl && PmDecl->isTemplateParameterPack() && 16029 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 16030 return false; 16031 16032 // C++20 [over.literal]p5: 16033 // A string literal operator template is a literal operator template 16034 // whose template-parameter-list comprises a single non-type 16035 // template-parameter of class type. 16036 // 16037 // As a DR resolution, we also allow placeholders for deduced class 16038 // template specializations. 16039 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 16040 !PmDecl->isTemplateParameterPack() && 16041 (PmDecl->getType()->isRecordType() || 16042 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 16043 return false; 16044 } else if (TemplateParams->size() == 2) { 16045 TemplateTypeParmDecl *PmType = 16046 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 16047 NonTypeTemplateParmDecl *PmArgs = 16048 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 16049 16050 // The second template parameter must be a parameter pack with the 16051 // first template parameter as its type. 16052 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 16053 PmArgs->isTemplateParameterPack()) { 16054 const TemplateTypeParmType *TArgs = 16055 PmArgs->getType()->getAs<TemplateTypeParmType>(); 16056 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 16057 TArgs->getIndex() == PmType->getIndex()) { 16058 if (!SemaRef.inTemplateInstantiation()) 16059 SemaRef.Diag(TpDecl->getLocation(), 16060 diag::ext_string_literal_operator_template); 16061 return false; 16062 } 16063 } 16064 } 16065 16066 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 16067 diag::err_literal_operator_template) 16068 << TpDecl->getTemplateParameters()->getSourceRange(); 16069 return true; 16070} 16071 16072/// CheckLiteralOperatorDeclaration - Check whether the declaration 16073/// of this literal operator function is well-formed. If so, returns 16074/// false; otherwise, emits appropriate diagnostics and returns true. 16075bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 16076 if (isa<CXXMethodDecl>(FnDecl)) { 16077 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 16078 << FnDecl->getDeclName(); 16079 return true; 16080 } 16081 16082 if (FnDecl->isExternC()) { 16083 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 16084 if (const LinkageSpecDecl *LSD = 16085 FnDecl->getDeclContext()->getExternCContext()) 16086 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 16087 return true; 16088 } 16089 16090 // This might be the definition of a literal operator template. 16091 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 16092 16093 // This might be a specialization of a literal operator template. 16094 if (!TpDecl) 16095 TpDecl = FnDecl->getPrimaryTemplate(); 16096 16097 // template <char...> type operator "" name() and 16098 // template <class T, T...> type operator "" name() are the only valid 16099 // template signatures, and the only valid signatures with no parameters. 16100 // 16101 // C++20 also allows template <SomeClass T> type operator "" name(). 16102 if (TpDecl) { 16103 if (FnDecl->param_size() != 0) { 16104 Diag(FnDecl->getLocation(), 16105 diag::err_literal_operator_template_with_params); 16106 return true; 16107 } 16108 16109 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 16110 return true; 16111 16112 } else if (FnDecl->param_size() == 1) { 16113 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 16114 16115 QualType ParamType = Param->getType().getUnqualifiedType(); 16116 16117 // Only unsigned long long int, long double, any character type, and const 16118 // char * are allowed as the only parameters. 16119 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 16120 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 16121 Context.hasSameType(ParamType, Context.CharTy) || 16122 Context.hasSameType(ParamType, Context.WideCharTy) || 16123 Context.hasSameType(ParamType, Context.Char8Ty) || 16124 Context.hasSameType(ParamType, Context.Char16Ty) || 16125 Context.hasSameType(ParamType, Context.Char32Ty)) { 16126 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 16127 QualType InnerType = Ptr->getPointeeType(); 16128 16129 // Pointer parameter must be a const char *. 16130 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16131 Context.CharTy) && 16132 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16133 Diag(Param->getSourceRange().getBegin(), 16134 diag::err_literal_operator_param) 16135 << ParamType << "'const char *'" << Param->getSourceRange(); 16136 return true; 16137 } 16138 16139 } else if (ParamType->isRealFloatingType()) { 16140 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16141 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16142 return true; 16143 16144 } else if (ParamType->isIntegerType()) { 16145 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16146 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16147 return true; 16148 16149 } else { 16150 Diag(Param->getSourceRange().getBegin(), 16151 diag::err_literal_operator_invalid_param) 16152 << ParamType << Param->getSourceRange(); 16153 return true; 16154 } 16155 16156 } else if (FnDecl->param_size() == 2) { 16157 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16158 16159 // First, verify that the first parameter is correct. 16160 16161 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16162 16163 // Two parameter function must have a pointer to const as a 16164 // first parameter; let's strip those qualifiers. 16165 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16166 16167 if (!PT) { 16168 Diag((*Param)->getSourceRange().getBegin(), 16169 diag::err_literal_operator_param) 16170 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16171 return true; 16172 } 16173 16174 QualType PointeeType = PT->getPointeeType(); 16175 // First parameter must be const 16176 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16177 Diag((*Param)->getSourceRange().getBegin(), 16178 diag::err_literal_operator_param) 16179 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16180 return true; 16181 } 16182 16183 QualType InnerType = PointeeType.getUnqualifiedType(); 16184 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16185 // const char32_t* are allowed as the first parameter to a two-parameter 16186 // function 16187 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16188 Context.hasSameType(InnerType, Context.WideCharTy) || 16189 Context.hasSameType(InnerType, Context.Char8Ty) || 16190 Context.hasSameType(InnerType, Context.Char16Ty) || 16191 Context.hasSameType(InnerType, Context.Char32Ty))) { 16192 Diag((*Param)->getSourceRange().getBegin(), 16193 diag::err_literal_operator_param) 16194 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16195 return true; 16196 } 16197 16198 // Move on to the second and final parameter. 16199 ++Param; 16200 16201 // The second parameter must be a std::size_t. 16202 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16203 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16204 Diag((*Param)->getSourceRange().getBegin(), 16205 diag::err_literal_operator_param) 16206 << SecondParamType << Context.getSizeType() 16207 << (*Param)->getSourceRange(); 16208 return true; 16209 } 16210 } else { 16211 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16212 return true; 16213 } 16214 16215 // Parameters are good. 16216 16217 // A parameter-declaration-clause containing a default argument is not 16218 // equivalent to any of the permitted forms. 16219 for (auto Param : FnDecl->parameters()) { 16220 if (Param->hasDefaultArg()) { 16221 Diag(Param->getDefaultArgRange().getBegin(), 16222 diag::err_literal_operator_default_argument) 16223 << Param->getDefaultArgRange(); 16224 break; 16225 } 16226 } 16227 16228 StringRef LiteralName 16229 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16230 if (LiteralName[0] != '_' && 16231 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16232 // C++11 [usrlit.suffix]p1: 16233 // Literal suffix identifiers that do not start with an underscore 16234 // are reserved for future standardization. 16235 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16236 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16237 } 16238 16239 return false; 16240} 16241 16242/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16243/// linkage specification, including the language and (if present) 16244/// the '{'. ExternLoc is the location of the 'extern', Lang is the 16245/// language string literal. LBraceLoc, if valid, provides the location of 16246/// the '{' brace. Otherwise, this linkage specification does not 16247/// have any braces. 16248Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16249 Expr *LangStr, 16250 SourceLocation LBraceLoc) { 16251 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16252 if (!Lit->isAscii()) { 16253 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16254 << LangStr->getSourceRange(); 16255 return nullptr; 16256 } 16257 16258 StringRef Lang = Lit->getString(); 16259 LinkageSpecDecl::LanguageIDs Language; 16260 if (Lang == "C") 16261 Language = LinkageSpecDecl::lang_c; 16262 else if (Lang == "C++") 16263 Language = LinkageSpecDecl::lang_cxx; 16264 else { 16265 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16266 << LangStr->getSourceRange(); 16267 return nullptr; 16268 } 16269 16270 // FIXME: Add all the various semantics of linkage specifications 16271 16272 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16273 LangStr->getExprLoc(), Language, 16274 LBraceLoc.isValid()); 16275 16276 /// C++ [module.unit]p7.2.3 16277 /// - Otherwise, if the declaration 16278 /// - ... 16279 /// - ... 16280 /// - appears within a linkage-specification, 16281 /// it is attached to the global module. 16282 /// 16283 /// If the declaration is already in global module fragment, we don't 16284 /// need to attach it again. 16285 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) { 16286 Module *GlobalModule = 16287 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true); 16288 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16289 D->setLocalOwningModule(GlobalModule); 16290 } 16291 16292 CurContext->addDecl(D); 16293 PushDeclContext(S, D); 16294 return D; 16295} 16296 16297/// ActOnFinishLinkageSpecification - Complete the definition of 16298/// the C++ linkage specification LinkageSpec. If RBraceLoc is 16299/// valid, it's the position of the closing '}' brace in a linkage 16300/// specification that uses braces. 16301Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16302 Decl *LinkageSpec, 16303 SourceLocation RBraceLoc) { 16304 if (RBraceLoc.isValid()) { 16305 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16306 LSDecl->setRBraceLoc(RBraceLoc); 16307 } 16308 16309 // If the current module doesn't has Parent, it implies that the 16310 // LinkageSpec isn't in the module created by itself. So we don't 16311 // need to pop it. 16312 if (getLangOpts().CPlusPlusModules && getCurrentModule() && 16313 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent) 16314 PopGlobalModuleFragment(); 16315 16316 PopDeclContext(); 16317 return LinkageSpec; 16318} 16319 16320Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16321 const ParsedAttributesView &AttrList, 16322 SourceLocation SemiLoc) { 16323 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16324 // Attribute declarations appertain to empty declaration so we handle 16325 // them here. 16326 ProcessDeclAttributeList(S, ED, AttrList); 16327 16328 CurContext->addDecl(ED); 16329 return ED; 16330} 16331 16332/// Perform semantic analysis for the variable declaration that 16333/// occurs within a C++ catch clause, returning the newly-created 16334/// variable. 16335VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16336 TypeSourceInfo *TInfo, 16337 SourceLocation StartLoc, 16338 SourceLocation Loc, 16339 IdentifierInfo *Name) { 16340 bool Invalid = false; 16341 QualType ExDeclType = TInfo->getType(); 16342 16343 // Arrays and functions decay. 16344 if (ExDeclType->isArrayType()) 16345 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16346 else if (ExDeclType->isFunctionType()) 16347 ExDeclType = Context.getPointerType(ExDeclType); 16348 16349 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16350 // The exception-declaration shall not denote a pointer or reference to an 16351 // incomplete type, other than [cv] void*. 16352 // N2844 forbids rvalue references. 16353 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16354 Diag(Loc, diag::err_catch_rvalue_ref); 16355 Invalid = true; 16356 } 16357 16358 if (ExDeclType->isVariablyModifiedType()) { 16359 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16360 Invalid = true; 16361 } 16362 16363 QualType BaseType = ExDeclType; 16364 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16365 unsigned DK = diag::err_catch_incomplete; 16366 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16367 BaseType = Ptr->getPointeeType(); 16368 Mode = 1; 16369 DK = diag::err_catch_incomplete_ptr; 16370 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16371 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16372 BaseType = Ref->getPointeeType(); 16373 Mode = 2; 16374 DK = diag::err_catch_incomplete_ref; 16375 } 16376 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16377 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16378 Invalid = true; 16379 16380 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16381 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16382 Invalid = true; 16383 } 16384 16385 if (!Invalid && !ExDeclType->isDependentType() && 16386 RequireNonAbstractType(Loc, ExDeclType, 16387 diag::err_abstract_type_in_decl, 16388 AbstractVariableType)) 16389 Invalid = true; 16390 16391 // Only the non-fragile NeXT runtime currently supports C++ catches 16392 // of ObjC types, and no runtime supports catching ObjC types by value. 16393 if (!Invalid && getLangOpts().ObjC) { 16394 QualType T = ExDeclType; 16395 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16396 T = RT->getPointeeType(); 16397 16398 if (T->isObjCObjectType()) { 16399 Diag(Loc, diag::err_objc_object_catch); 16400 Invalid = true; 16401 } else if (T->isObjCObjectPointerType()) { 16402 // FIXME: should this be a test for macosx-fragile specifically? 16403 if (getLangOpts().ObjCRuntime.isFragile()) 16404 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16405 } 16406 } 16407 16408 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16409 ExDeclType, TInfo, SC_None); 16410 ExDecl->setExceptionVariable(true); 16411 16412 // In ARC, infer 'retaining' for variables of retainable type. 16413 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16414 Invalid = true; 16415 16416 if (!Invalid && !ExDeclType->isDependentType()) { 16417 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16418 // Insulate this from anything else we might currently be parsing. 16419 EnterExpressionEvaluationContext scope( 16420 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16421 16422 // C++ [except.handle]p16: 16423 // The object declared in an exception-declaration or, if the 16424 // exception-declaration does not specify a name, a temporary (12.2) is 16425 // copy-initialized (8.5) from the exception object. [...] 16426 // The object is destroyed when the handler exits, after the destruction 16427 // of any automatic objects initialized within the handler. 16428 // 16429 // We just pretend to initialize the object with itself, then make sure 16430 // it can be destroyed later. 16431 QualType initType = Context.getExceptionObjectType(ExDeclType); 16432 16433 InitializedEntity entity = 16434 InitializedEntity::InitializeVariable(ExDecl); 16435 InitializationKind initKind = 16436 InitializationKind::CreateCopy(Loc, SourceLocation()); 16437 16438 Expr *opaqueValue = 16439 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16440 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16441 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16442 if (result.isInvalid()) 16443 Invalid = true; 16444 else { 16445 // If the constructor used was non-trivial, set this as the 16446 // "initializer". 16447 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16448 if (!construct->getConstructor()->isTrivial()) { 16449 Expr *init = MaybeCreateExprWithCleanups(construct); 16450 ExDecl->setInit(init); 16451 } 16452 16453 // And make sure it's destructable. 16454 FinalizeVarWithDestructor(ExDecl, recordType); 16455 } 16456 } 16457 } 16458 16459 if (Invalid) 16460 ExDecl->setInvalidDecl(); 16461 16462 return ExDecl; 16463} 16464 16465/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16466/// handler. 16467Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16468 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16469 bool Invalid = D.isInvalidType(); 16470 16471 // Check for unexpanded parameter packs. 16472 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16473 UPPC_ExceptionType)) { 16474 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16475 D.getIdentifierLoc()); 16476 Invalid = true; 16477 } 16478 16479 IdentifierInfo *II = D.getIdentifier(); 16480 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16481 LookupOrdinaryName, 16482 ForVisibleRedeclaration)) { 16483 // The scope should be freshly made just for us. There is just no way 16484 // it contains any previous declaration, except for function parameters in 16485 // a function-try-block's catch statement. 16486 assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void
(0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "clang/lib/Sema/SemaDeclCXX.cpp"
, 16486, __extension__ __PRETTY_FUNCTION__))
; 16487 if (isDeclInScope(PrevDecl, CurContext, S)) { 16488 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16489 << D.getIdentifier(); 16490 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16491 Invalid = true; 16492 } else if (PrevDecl->isTemplateParameter()) 16493 // Maybe we will complain about the shadowed template parameter. 16494 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16495 } 16496 16497 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16498 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16499 << D.getCXXScopeSpec().getRange(); 16500 Invalid = true; 16501 } 16502 16503 VarDecl *ExDecl = BuildExceptionDeclaration( 16504 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16505 if (Invalid) 16506 ExDecl->setInvalidDecl(); 16507 16508 // Add the exception declaration into this scope. 16509 if (II) 16510 PushOnScopeChains(ExDecl, S); 16511 else 16512 CurContext->addDecl(ExDecl); 16513 16514 ProcessDeclAttributes(S, ExDecl, D); 16515 return ExDecl; 16516} 16517 16518Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16519 Expr *AssertExpr, 16520 Expr *AssertMessageExpr, 16521 SourceLocation RParenLoc) { 16522 StringLiteral *AssertMessage = 16523 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16524 16525 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16526 return nullptr; 16527 16528 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16529 AssertMessage, RParenLoc, false); 16530} 16531 16532Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16533 Expr *AssertExpr, 16534 StringLiteral *AssertMessage, 16535 SourceLocation RParenLoc, 16536 bool Failed) { 16537 assert(AssertExpr != nullptr && "Expected non-null condition")(static_cast <bool> (AssertExpr != nullptr && "Expected non-null condition"
) ? void (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16537, __extension__ __PRETTY_FUNCTION__
))
; 16538 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16539 !Failed) { 16540 // In a static_assert-declaration, the constant-expression shall be a 16541 // constant expression that can be contextually converted to bool. 16542 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16543 if (Converted.isInvalid()) 16544 Failed = true; 16545 16546 ExprResult FullAssertExpr = 16547 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16548 /*DiscardedValue*/ false, 16549 /*IsConstexpr*/ true); 16550 if (FullAssertExpr.isInvalid()) 16551 Failed = true; 16552 else 16553 AssertExpr = FullAssertExpr.get(); 16554 16555 llvm::APSInt Cond; 16556 if (!Failed && VerifyIntegerConstantExpression( 16557 AssertExpr, &Cond, 16558 diag::err_static_assert_expression_is_not_constant) 16559 .isInvalid()) 16560 Failed = true; 16561 16562 if (!Failed && !Cond) { 16563 SmallString<256> MsgBuffer; 16564 llvm::raw_svector_ostream Msg(MsgBuffer); 16565 if (AssertMessage) 16566 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16567 16568 Expr *InnerCond = nullptr; 16569 std::string InnerCondDescription; 16570 std::tie(InnerCond, InnerCondDescription) = 16571 findFailedBooleanCondition(Converted.get()); 16572 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16573 // Drill down into concept specialization expressions to see why they 16574 // weren't satisfied. 16575 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16576 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16577 ConstraintSatisfaction Satisfaction; 16578 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16579 DiagnoseUnsatisfiedConstraint(Satisfaction); 16580 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16581 && !isa<IntegerLiteral>(InnerCond)) { 16582 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16583 << InnerCondDescription << !AssertMessage 16584 << Msg.str() << InnerCond->getSourceRange(); 16585 } else { 16586 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16587 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16588 } 16589 Failed = true; 16590 } 16591 } else { 16592 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16593 /*DiscardedValue*/false, 16594 /*IsConstexpr*/true); 16595 if (FullAssertExpr.isInvalid()) 16596 Failed = true; 16597 else 16598 AssertExpr = FullAssertExpr.get(); 16599 } 16600 16601 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16602 AssertExpr, AssertMessage, RParenLoc, 16603 Failed); 16604 16605 CurContext->addDecl(Decl); 16606 return Decl; 16607} 16608 16609/// Perform semantic analysis of the given friend type declaration. 16610/// 16611/// \returns A friend declaration that. 16612FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16613 SourceLocation FriendLoc, 16614 TypeSourceInfo *TSInfo) { 16615 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")(static_cast <bool> (TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? void (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16615, __extension__ __PRETTY_FUNCTION__
))
; 16616 16617 QualType T = TSInfo->getType(); 16618 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16619 16620 // C++03 [class.friend]p2: 16621 // An elaborated-type-specifier shall be used in a friend declaration 16622 // for a class.* 16623 // 16624 // * The class-key of the elaborated-type-specifier is required. 16625 if (!CodeSynthesisContexts.empty()) { 16626 // Do not complain about the form of friend template types during any kind 16627 // of code synthesis. For template instantiation, we will have complained 16628 // when the template was defined. 16629 } else { 16630 if (!T->isElaboratedTypeSpecifier()) { 16631 // If we evaluated the type to a record type, suggest putting 16632 // a tag in front. 16633 if (const RecordType *RT = T->getAs<RecordType>()) { 16634 RecordDecl *RD = RT->getDecl(); 16635 16636 SmallString<16> InsertionText(" "); 16637 InsertionText += RD->getKindName(); 16638 16639 Diag(TypeRange.getBegin(), 16640 getLangOpts().CPlusPlus11 ? 16641 diag::warn_cxx98_compat_unelaborated_friend_type : 16642 diag::ext_unelaborated_friend_type) 16643 << (unsigned) RD->getTagKind() 16644 << T 16645 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16646 InsertionText); 16647 } else { 16648 Diag(FriendLoc, 16649 getLangOpts().CPlusPlus11 ? 16650 diag::warn_cxx98_compat_nonclass_type_friend : 16651 diag::ext_nonclass_type_friend) 16652 << T 16653 << TypeRange; 16654 } 16655 } else if (T->getAs<EnumType>()) { 16656 Diag(FriendLoc, 16657 getLangOpts().CPlusPlus11 ? 16658 diag::warn_cxx98_compat_enum_friend : 16659 diag::ext_enum_friend) 16660 << T 16661 << TypeRange; 16662 } 16663 16664 // C++11 [class.friend]p3: 16665 // A friend declaration that does not declare a function shall have one 16666 // of the following forms: 16667 // friend elaborated-type-specifier ; 16668 // friend simple-type-specifier ; 16669 // friend typename-specifier ; 16670 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16671 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16672 } 16673 16674 // If the type specifier in a friend declaration designates a (possibly 16675 // cv-qualified) class type, that class is declared as a friend; otherwise, 16676 // the friend declaration is ignored. 16677 return FriendDecl::Create(Context, CurContext, 16678 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16679 FriendLoc); 16680} 16681 16682/// Handle a friend tag declaration where the scope specifier was 16683/// templated. 16684Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16685 unsigned TagSpec, SourceLocation TagLoc, 16686 CXXScopeSpec &SS, IdentifierInfo *Name, 16687 SourceLocation NameLoc, 16688 const ParsedAttributesView &Attr, 16689 MultiTemplateParamsArg TempParamLists) { 16690 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16691 16692 bool IsMemberSpecialization = false; 16693 bool Invalid = false; 16694 16695 if (TemplateParameterList *TemplateParams = 16696 MatchTemplateParametersToScopeSpecifier( 16697 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16698 IsMemberSpecialization, Invalid)) { 16699 if (TemplateParams->size() > 0) { 16700 // This is a declaration of a class template. 16701 if (Invalid) 16702 return nullptr; 16703 16704 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16705 NameLoc, Attr, TemplateParams, AS_public, 16706 /*ModulePrivateLoc=*/SourceLocation(), 16707 FriendLoc, TempParamLists.size() - 1, 16708 TempParamLists.data()).get(); 16709 } else { 16710 // The "template<>" header is extraneous. 16711 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16712 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16713 IsMemberSpecialization = true; 16714 } 16715 } 16716 16717 if (Invalid) return nullptr; 16718 16719 bool isAllExplicitSpecializations = true; 16720 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16721 if (TempParamLists[I]->size()) { 16722 isAllExplicitSpecializations = false; 16723 break; 16724 } 16725 } 16726 16727 // FIXME: don't ignore attributes. 16728 16729 // If it's explicit specializations all the way down, just forget 16730 // about the template header and build an appropriate non-templated 16731 // friend. TODO: for source fidelity, remember the headers. 16732 if (isAllExplicitSpecializations) { 16733 if (SS.isEmpty()) { 16734 bool Owned = false; 16735 bool IsDependent = false; 16736 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16737 Attr, AS_public, 16738 /*ModulePrivateLoc=*/SourceLocation(), 16739 MultiTemplateParamsArg(), Owned, IsDependent, 16740 /*ScopedEnumKWLoc=*/SourceLocation(), 16741 /*ScopedEnumUsesClassTag=*/false, 16742 /*UnderlyingType=*/TypeResult(), 16743 /*IsTypeSpecifier=*/false, 16744 /*IsTemplateParamOrArg=*/false); 16745 } 16746 16747 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16748 ElaboratedTypeKeyword Keyword 16749 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16750 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16751 *Name, NameLoc); 16752 if (T.isNull()) 16753 return nullptr; 16754 16755 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16756 if (isa<DependentNameType>(T)) { 16757 DependentNameTypeLoc TL = 16758 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16759 TL.setElaboratedKeywordLoc(TagLoc); 16760 TL.setQualifierLoc(QualifierLoc); 16761 TL.setNameLoc(NameLoc); 16762 } else { 16763 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16764 TL.setElaboratedKeywordLoc(TagLoc); 16765 TL.setQualifierLoc(QualifierLoc); 16766 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16767 } 16768 16769 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16770 TSI, FriendLoc, TempParamLists); 16771 Friend->setAccess(AS_public); 16772 CurContext->addDecl(Friend); 16773 return Friend; 16774 } 16775 16776 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")(static_cast <bool> (SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? void (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16776, __extension__ __PRETTY_FUNCTION__
))
; 16777 16778 16779 16780 // Handle the case of a templated-scope friend class. e.g. 16781 // template <class T> class A<T>::B; 16782 // FIXME: we don't support these right now. 16783 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16784 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16785 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16786 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16787 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16788 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16789 TL.setElaboratedKeywordLoc(TagLoc); 16790 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16791 TL.setNameLoc(NameLoc); 16792 16793 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16794 TSI, FriendLoc, TempParamLists); 16795 Friend->setAccess(AS_public); 16796 Friend->setUnsupportedFriend(true); 16797 CurContext->addDecl(Friend); 16798 return Friend; 16799} 16800 16801/// Handle a friend type declaration. This works in tandem with 16802/// ActOnTag. 16803/// 16804/// Notes on friend class templates: 16805/// 16806/// We generally treat friend class declarations as if they were 16807/// declaring a class. So, for example, the elaborated type specifier 16808/// in a friend declaration is required to obey the restrictions of a 16809/// class-head (i.e. no typedefs in the scope chain), template 16810/// parameters are required to match up with simple template-ids, &c. 16811/// However, unlike when declaring a template specialization, it's 16812/// okay to refer to a template specialization without an empty 16813/// template parameter declaration, e.g. 16814/// friend class A<T>::B<unsigned>; 16815/// We permit this as a special case; if there are any template 16816/// parameters present at all, require proper matching, i.e. 16817/// template <> template \<class T> friend class A<int>::B; 16818Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16819 MultiTemplateParamsArg TempParams) { 16820 SourceLocation Loc = DS.getBeginLoc(); 16821 16822 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 16822, __extension__ __PRETTY_FUNCTION__))
; 16823 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "clang/lib/Sema/SemaDeclCXX.cpp", 16823, __extension__ __PRETTY_FUNCTION__
))
; 16824 16825 // C++ [class.friend]p3: 16826 // A friend declaration that does not declare a function shall have one of 16827 // the following forms: 16828 // friend elaborated-type-specifier ; 16829 // friend simple-type-specifier ; 16830 // friend typename-specifier ; 16831 // 16832 // Any declaration with a type qualifier does not have that form. (It's 16833 // legal to specify a qualified type as a friend, you just can't write the 16834 // keywords.) 16835 if (DS.getTypeQualifiers()) { 16836 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16837 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16838 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16839 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16840 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16841 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16842 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16843 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16844 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16845 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16846 } 16847 16848 // Try to convert the decl specifier to a type. This works for 16849 // friend templates because ActOnTag never produces a ClassTemplateDecl 16850 // for a TUK_Friend. 16851 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16852 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16853 QualType T = TSI->getType(); 16854 if (TheDeclarator.isInvalidType()) 16855 return nullptr; 16856 16857 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16858 return nullptr; 16859 16860 // This is definitely an error in C++98. It's probably meant to 16861 // be forbidden in C++0x, too, but the specification is just 16862 // poorly written. 16863 // 16864 // The problem is with declarations like the following: 16865 // template <T> friend A<T>::foo; 16866 // where deciding whether a class C is a friend or not now hinges 16867 // on whether there exists an instantiation of A that causes 16868 // 'foo' to equal C. There are restrictions on class-heads 16869 // (which we declare (by fiat) elaborated friend declarations to 16870 // be) that makes this tractable. 16871 // 16872 // FIXME: handle "template <> friend class A<T>;", which 16873 // is possibly well-formed? Who even knows? 16874 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16875 Diag(Loc, diag::err_tagless_friend_type_template) 16876 << DS.getSourceRange(); 16877 return nullptr; 16878 } 16879 16880 // C++98 [class.friend]p1: A friend of a class is a function 16881 // or class that is not a member of the class . . . 16882 // This is fixed in DR77, which just barely didn't make the C++03 16883 // deadline. It's also a very silly restriction that seriously 16884 // affects inner classes and which nobody else seems to implement; 16885 // thus we never diagnose it, not even in -pedantic. 16886 // 16887 // But note that we could warn about it: it's always useless to 16888 // friend one of your own members (it's not, however, worthless to 16889 // friend a member of an arbitrary specialization of your template). 16890 16891 Decl *D; 16892 if (!TempParams.empty()) 16893 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16894 TempParams, 16895 TSI, 16896 DS.getFriendSpecLoc()); 16897 else 16898 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16899 16900 if (!D) 16901 return nullptr; 16902 16903 D->setAccess(AS_public); 16904 CurContext->addDecl(D); 16905 16906 return D; 16907} 16908 16909NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16910 MultiTemplateParamsArg TemplateParams) { 16911 const DeclSpec &DS = D.getDeclSpec(); 16912 16913 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 16913, __extension__ __PRETTY_FUNCTION__))
; 16914 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "clang/lib/Sema/SemaDeclCXX.cpp", 16914, __extension__ __PRETTY_FUNCTION__
))
; 16915 16916 SourceLocation Loc = D.getIdentifierLoc(); 16917 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16918 16919 // C++ [class.friend]p1 16920 // A friend of a class is a function or class.... 16921 // Note that this sees through typedefs, which is intended. 16922 // It *doesn't* see through dependent types, which is correct 16923 // according to [temp.arg.type]p3: 16924 // If a declaration acquires a function type through a 16925 // type dependent on a template-parameter and this causes 16926 // a declaration that does not use the syntactic form of a 16927 // function declarator to have a function type, the program 16928 // is ill-formed. 16929 if (!TInfo->getType()->isFunctionType()) { 16930 Diag(Loc, diag::err_unexpected_friend); 16931 16932 // It might be worthwhile to try to recover by creating an 16933 // appropriate declaration. 16934 return nullptr; 16935 } 16936 16937 // C++ [namespace.memdef]p3 16938 // - If a friend declaration in a non-local class first declares a 16939 // class or function, the friend class or function is a member 16940 // of the innermost enclosing namespace. 16941 // - The name of the friend is not found by simple name lookup 16942 // until a matching declaration is provided in that namespace 16943 // scope (either before or after the class declaration granting 16944 // friendship). 16945 // - If a friend function is called, its name may be found by the 16946 // name lookup that considers functions from namespaces and 16947 // classes associated with the types of the function arguments. 16948 // - When looking for a prior declaration of a class or a function 16949 // declared as a friend, scopes outside the innermost enclosing 16950 // namespace scope are not considered. 16951 16952 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16953 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16954 assert(NameInfo.getName())(static_cast <bool> (NameInfo.getName()) ? void (0) : __assert_fail
("NameInfo.getName()", "clang/lib/Sema/SemaDeclCXX.cpp", 16954
, __extension__ __PRETTY_FUNCTION__))
; 16955 16956 // Check for unexpanded parameter packs. 16957 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16958 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16959 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16960 return nullptr; 16961 16962 // The context we found the declaration in, or in which we should 16963 // create the declaration. 16964 DeclContext *DC; 16965 Scope *DCScope = S; 16966 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16967 ForExternalRedeclaration); 16968 16969 // There are five cases here. 16970 // - There's no scope specifier and we're in a local class. Only look 16971 // for functions declared in the immediately-enclosing block scope. 16972 // We recover from invalid scope qualifiers as if they just weren't there. 16973 FunctionDecl *FunctionContainingLocalClass = nullptr; 16974 if ((SS.isInvalid() || !SS.isSet()) && 16975 (FunctionContainingLocalClass = 16976 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16977 // C++11 [class.friend]p11: 16978 // If a friend declaration appears in a local class and the name 16979 // specified is an unqualified name, a prior declaration is 16980 // looked up without considering scopes that are outside the 16981 // innermost enclosing non-class scope. For a friend function 16982 // declaration, if there is no prior declaration, the program is 16983 // ill-formed. 16984 16985 // Find the innermost enclosing non-class scope. This is the block 16986 // scope containing the local class definition (or for a nested class, 16987 // the outer local class). 16988 DCScope = S->getFnParent(); 16989 16990 // Look up the function name in the scope. 16991 Previous.clear(LookupLocalFriendName); 16992 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16993 16994 if (!Previous.empty()) { 16995 // All possible previous declarations must have the same context: 16996 // either they were declared at block scope or they are members of 16997 // one of the enclosing local classes. 16998 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16999 } else { 17000 // This is ill-formed, but provide the context that we would have 17001 // declared the function in, if we were permitted to, for error recovery. 17002 DC = FunctionContainingLocalClass; 17003 } 17004 adjustContextForLocalExternDecl(DC); 17005 17006 // C++ [class.friend]p6: 17007 // A function can be defined in a friend declaration of a class if and 17008 // only if the class is a non-local class (9.8), the function name is 17009 // unqualified, and the function has namespace scope. 17010 if (D.isFunctionDefinition()) { 17011 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 17012 } 17013 17014 // - There's no scope specifier, in which case we just go to the 17015 // appropriate scope and look for a function or function template 17016 // there as appropriate. 17017 } else if (SS.isInvalid() || !SS.isSet()) { 17018 // C++11 [namespace.memdef]p3: 17019 // If the name in a friend declaration is neither qualified nor 17020 // a template-id and the declaration is a function or an 17021 // elaborated-type-specifier, the lookup to determine whether 17022 // the entity has been previously declared shall not consider 17023 // any scopes outside the innermost enclosing namespace. 17024 bool isTemplateId = 17025 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 17026 17027 // Find the appropriate context according to the above. 17028 DC = CurContext; 17029 17030 // Skip class contexts. If someone can cite chapter and verse 17031 // for this behavior, that would be nice --- it's what GCC and 17032 // EDG do, and it seems like a reasonable intent, but the spec 17033 // really only says that checks for unqualified existing 17034 // declarations should stop at the nearest enclosing namespace, 17035 // not that they should only consider the nearest enclosing 17036 // namespace. 17037 while (DC->isRecord()) 17038 DC = DC->getParent(); 17039 17040 DeclContext *LookupDC = DC->getNonTransparentContext(); 17041 while (true) { 17042 LookupQualifiedName(Previous, LookupDC); 17043 17044 if (!Previous.empty()) { 17045 DC = LookupDC; 17046 break; 17047 } 17048 17049 if (isTemplateId) { 17050 if (isa<TranslationUnitDecl>(LookupDC)) break; 17051 } else { 17052 if (LookupDC->isFileContext()) break; 17053 } 17054 LookupDC = LookupDC->getParent(); 17055 } 17056 17057 DCScope = getScopeForDeclContext(S, DC); 17058 17059 // - There's a non-dependent scope specifier, in which case we 17060 // compute it and do a previous lookup there for a function 17061 // or function template. 17062 } else if (!SS.getScopeRep()->isDependent()) { 17063 DC = computeDeclContext(SS); 17064 if (!DC) return nullptr; 17065 17066 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 17067 17068 LookupQualifiedName(Previous, DC); 17069 17070 // C++ [class.friend]p1: A friend of a class is a function or 17071 // class that is not a member of the class . . . 17072 if (DC->Equals(CurContext)) 17073 Diag(DS.getFriendSpecLoc(), 17074 getLangOpts().CPlusPlus11 ? 17075 diag::warn_cxx98_compat_friend_is_member : 17076 diag::err_friend_is_member); 17077 17078 if (D.isFunctionDefinition()) { 17079 // C++ [class.friend]p6: 17080 // A function can be defined in a friend declaration of a class if and 17081 // only if the class is a non-local class (9.8), the function name is 17082 // unqualified, and the function has namespace scope. 17083 // 17084 // FIXME: We should only do this if the scope specifier names the 17085 // innermost enclosing namespace; otherwise the fixit changes the 17086 // meaning of the code. 17087 SemaDiagnosticBuilder DB 17088 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 17089 17090 DB << SS.getScopeRep(); 17091 if (DC->isFileContext()) 17092 DB << FixItHint::CreateRemoval(SS.getRange()); 17093 SS.clear(); 17094 } 17095 17096 // - There's a scope specifier that does not match any template 17097 // parameter lists, in which case we use some arbitrary context, 17098 // create a method or method template, and wait for instantiation. 17099 // - There's a scope specifier that does match some template 17100 // parameter lists, which we don't handle right now. 17101 } else { 17102 if (D.isFunctionDefinition()) { 17103 // C++ [class.friend]p6: 17104 // A function can be defined in a friend declaration of a class if and 17105 // only if the class is a non-local class (9.8), the function name is 17106 // unqualified, and the function has namespace scope. 17107 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 17108 << SS.getScopeRep(); 17109 } 17110 17111 DC = CurContext; 17112 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"friend declaration not in class?") ? void (0) : __assert_fail
("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17112, __extension__ __PRETTY_FUNCTION__
))
; 17113 } 17114 17115 if (!DC->isRecord()) { 17116 int DiagArg = -1; 17117 switch (D.getName().getKind()) { 17118 case UnqualifiedIdKind::IK_ConstructorTemplateId: 17119 case UnqualifiedIdKind::IK_ConstructorName: 17120 DiagArg = 0; 17121 break; 17122 case UnqualifiedIdKind::IK_DestructorName: 17123 DiagArg = 1; 17124 break; 17125 case UnqualifiedIdKind::IK_ConversionFunctionId: 17126 DiagArg = 2; 17127 break; 17128 case UnqualifiedIdKind::IK_DeductionGuideName: 17129 DiagArg = 3; 17130 break; 17131 case UnqualifiedIdKind::IK_Identifier: 17132 case UnqualifiedIdKind::IK_ImplicitSelfParam: 17133 case UnqualifiedIdKind::IK_LiteralOperatorId: 17134 case UnqualifiedIdKind::IK_OperatorFunctionId: 17135 case UnqualifiedIdKind::IK_TemplateId: 17136 break; 17137 } 17138 // This implies that it has to be an operator or function. 17139 if (DiagArg >= 0) { 17140 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 17141 return nullptr; 17142 } 17143 } 17144 17145 // FIXME: This is an egregious hack to cope with cases where the scope stack 17146 // does not contain the declaration context, i.e., in an out-of-line 17147 // definition of a class. 17148 Scope FakeDCScope(S, Scope::DeclScope, Diags); 17149 if (!DCScope) { 17150 FakeDCScope.setEntity(DC); 17151 DCScope = &FakeDCScope; 17152 } 17153 17154 bool AddToScope = true; 17155 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17156 TemplateParams, AddToScope); 17157 if (!ND) return nullptr; 17158 17159 assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext
) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17159, __extension__ __PRETTY_FUNCTION__
))
; 17160 17161 // If we performed typo correction, we might have added a scope specifier 17162 // and changed the decl context. 17163 DC = ND->getDeclContext(); 17164 17165 // Add the function declaration to the appropriate lookup tables, 17166 // adjusting the redeclarations list as necessary. We don't 17167 // want to do this yet if the friending class is dependent. 17168 // 17169 // Also update the scope-based lookup if the target context's 17170 // lookup context is in lexical scope. 17171 if (!CurContext->isDependentContext()) { 17172 DC = DC->getRedeclContext(); 17173 DC->makeDeclVisibleInContext(ND); 17174 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17175 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17176 } 17177 17178 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17179 D.getIdentifierLoc(), ND, 17180 DS.getFriendSpecLoc()); 17181 FrD->setAccess(AS_public); 17182 CurContext->addDecl(FrD); 17183 17184 if (ND->isInvalidDecl()) { 17185 FrD->setInvalidDecl(); 17186 } else { 17187 if (DC->isRecord()) CheckFriendAccess(ND); 17188 17189 FunctionDecl *FD; 17190 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17191 FD = FTD->getTemplatedDecl(); 17192 else 17193 FD = cast<FunctionDecl>(ND); 17194 17195 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17196 // default argument expression, that declaration shall be a definition 17197 // and shall be the only declaration of the function or function 17198 // template in the translation unit. 17199 if (functionDeclHasDefaultArgument(FD)) { 17200 // We can't look at FD->getPreviousDecl() because it may not have been set 17201 // if we're in a dependent context. If the function is known to be a 17202 // redeclaration, we will have narrowed Previous down to the right decl. 17203 if (D.isRedeclaration()) { 17204 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17205 Diag(Previous.getRepresentativeDecl()->getLocation(), 17206 diag::note_previous_declaration); 17207 } else if (!D.isFunctionDefinition()) 17208 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17209 } 17210 17211 // Mark templated-scope function declarations as unsupported. 17212 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17213 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17214 << SS.getScopeRep() << SS.getRange() 17215 << cast<CXXRecordDecl>(CurContext); 17216 FrD->setUnsupportedFriend(true); 17217 } 17218 } 17219 17220 warnOnReservedIdentifier(ND); 17221 17222 return ND; 17223} 17224 17225void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17226 AdjustDeclIfTemplate(Dcl); 17227 17228 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17229 if (!Fn) { 17230 Diag(DelLoc, diag::err_deleted_non_function); 17231 return; 17232 } 17233 17234 // Deleted function does not have a body. 17235 Fn->setWillHaveBody(false); 17236 17237 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17238 // Don't consider the implicit declaration we generate for explicit 17239 // specializations. FIXME: Do not generate these implicit declarations. 17240 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17241 Prev->getPreviousDecl()) && 17242 !Prev->isDefined()) { 17243 Diag(DelLoc, diag::err_deleted_decl_not_first); 17244 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17245 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17246 : diag::note_previous_declaration); 17247 // We can't recover from this; the declaration might have already 17248 // been used. 17249 Fn->setInvalidDecl(); 17250 return; 17251 } 17252 17253 // To maintain the invariant that functions are only deleted on their first 17254 // declaration, mark the implicitly-instantiated declaration of the 17255 // explicitly-specialized function as deleted instead of marking the 17256 // instantiated redeclaration. 17257 Fn = Fn->getCanonicalDecl(); 17258 } 17259 17260 // dllimport/dllexport cannot be deleted. 17261 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17262 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17263 Fn->setInvalidDecl(); 17264 } 17265 17266 // C++11 [basic.start.main]p3: 17267 // A program that defines main as deleted [...] is ill-formed. 17268 if (Fn->isMain()) 17269 Diag(DelLoc, diag::err_deleted_main); 17270 17271 // C++11 [dcl.fct.def.delete]p4: 17272 // A deleted function is implicitly inline. 17273 Fn->setImplicitlyInline(); 17274 Fn->setDeletedAsWritten(); 17275} 17276 17277void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17278 if (!Dcl || Dcl->isInvalidDecl()) 17279 return; 17280 17281 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17282 if (!FD) { 17283 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17284 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17285 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17286 return; 17287 } 17288 } 17289 17290 Diag(DefaultLoc, diag::err_default_special_members) 17291 << getLangOpts().CPlusPlus20; 17292 return; 17293 } 17294 17295 // Reject if this can't possibly be a defaultable function. 17296 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17297 if (!DefKind && 17298 // A dependent function that doesn't locally look defaultable can 17299 // still instantiate to a defaultable function if it's a constructor 17300 // or assignment operator. 17301 (!FD->isDependentContext() || 17302 (!isa<CXXConstructorDecl>(FD) && 17303 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17304 Diag(DefaultLoc, diag::err_default_special_members) 17305 << getLangOpts().CPlusPlus20; 17306 return; 17307 } 17308 17309 // Issue compatibility warning. We already warned if the operator is 17310 // 'operator<=>' when parsing the '<=>' token. 17311 if (DefKind.isComparison() && 17312 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17313 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17314 ? diag::warn_cxx17_compat_defaulted_comparison 17315 : diag::ext_defaulted_comparison); 17316 } 17317 17318 FD->setDefaulted(); 17319 FD->setExplicitlyDefaulted(); 17320 17321 // Defer checking functions that are defaulted in a dependent context. 17322 if (FD->isDependentContext()) 17323 return; 17324 17325 // Unset that we will have a body for this function. We might not, 17326 // if it turns out to be trivial, and we don't need this marking now 17327 // that we've marked it as defaulted. 17328 FD->setWillHaveBody(false); 17329 17330 if (DefKind.isComparison()) { 17331 // If this comparison's defaulting occurs within the definition of its 17332 // lexical class context, we have to do the checking when complete. 17333 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext())) 17334 if (!RD->isCompleteDefinition()) 17335 return; 17336 } 17337 17338 // If this member fn was defaulted on its first declaration, we will have 17339 // already performed the checking in CheckCompletedCXXClass. Such a 17340 // declaration doesn't trigger an implicit definition. 17341 if (isa<CXXMethodDecl>(FD)) { 17342 const FunctionDecl *Primary = FD; 17343 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17344 // Ask the template instantiation pattern that actually had the 17345 // '= default' on it. 17346 Primary = Pattern; 17347 if (Primary->getCanonicalDecl()->isDefaulted()) 17348 return; 17349 } 17350 17351 if (DefKind.isComparison()) { 17352 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison())) 17353 FD->setInvalidDecl(); 17354 else 17355 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison()); 17356 } else { 17357 auto *MD = cast<CXXMethodDecl>(FD); 17358 17359 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17360 MD->setInvalidDecl(); 17361 else 17362 DefineDefaultedFunction(*this, MD, DefaultLoc); 17363 } 17364} 17365 17366static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17367 for (Stmt *SubStmt : S->children()) { 17368 if (!SubStmt) 17369 continue; 17370 if (isa<ReturnStmt>(SubStmt)) 17371 Self.Diag(SubStmt->getBeginLoc(), 17372 diag::err_return_in_constructor_handler); 17373 if (!isa<Expr>(SubStmt)) 17374 SearchForReturnInStmt(Self, SubStmt); 17375 } 17376} 17377 17378void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17379 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17380 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17381 SearchForReturnInStmt(*this, Handler); 17382 } 17383} 17384 17385void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, 17386 FnBodyKind BodyKind) { 17387 switch (BodyKind) { 17388 case FnBodyKind::Delete: 17389 SetDeclDeleted(D, Loc); 17390 break; 17391 case FnBodyKind::Default: 17392 SetDeclDefaulted(D, Loc); 17393 break; 17394 case FnBodyKind::Other: 17395 llvm_unreachable(::llvm::llvm_unreachable_internal("Parsed function body should be '= delete;' or '= default;'"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17396)
17396 "Parsed function body should be '= delete;' or '= default;'")::llvm::llvm_unreachable_internal("Parsed function body should be '= delete;' or '= default;'"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17396)
; 17397 } 17398} 17399 17400bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17401 const CXXMethodDecl *Old) { 17402 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17403 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17404 17405 if (OldFT->hasExtParameterInfos()) { 17406 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17407 // A parameter of the overriding method should be annotated with noescape 17408 // if the corresponding parameter of the overridden method is annotated. 17409 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17410 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17411 Diag(New->getParamDecl(I)->getLocation(), 17412 diag::warn_overriding_method_missing_noescape); 17413 Diag(Old->getParamDecl(I)->getLocation(), 17414 diag::note_overridden_marked_noescape); 17415 } 17416 } 17417 17418 // Virtual overrides must have the same code_seg. 17419 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17420 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17421 if ((NewCSA || OldCSA) && 17422 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17423 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17424 Diag(Old->getLocation(), diag::note_previous_declaration); 17425 return true; 17426 } 17427 17428 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17429 17430 // If the calling conventions match, everything is fine 17431 if (NewCC == OldCC) 17432 return false; 17433 17434 // If the calling conventions mismatch because the new function is static, 17435 // suppress the calling convention mismatch error; the error about static 17436 // function override (err_static_overrides_virtual from 17437 // Sema::CheckFunctionDeclaration) is more clear. 17438 if (New->getStorageClass() == SC_Static) 17439 return false; 17440 17441 Diag(New->getLocation(), 17442 diag::err_conflicting_overriding_cc_attributes) 17443 << New->getDeclName() << New->getType() << Old->getType(); 17444 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17445 return true; 17446} 17447 17448bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17449 const CXXMethodDecl *Old) { 17450 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17451 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17452 17453 if (Context.hasSameType(NewTy, OldTy) || 17454 NewTy->isDependentType() || OldTy->isDependentType()) 17455 return false; 17456 17457 // Check if the return types are covariant 17458 QualType NewClassTy, OldClassTy; 17459 17460 /// Both types must be pointers or references to classes. 17461 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17462 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17463 NewClassTy = NewPT->getPointeeType(); 17464 OldClassTy = OldPT->getPointeeType(); 17465 } 17466 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17467 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17468 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17469 NewClassTy = NewRT->getPointeeType(); 17470 OldClassTy = OldRT->getPointeeType(); 17471 } 17472 } 17473 } 17474 17475 // The return types aren't either both pointers or references to a class type. 17476 if (NewClassTy.isNull()) { 17477 Diag(New->getLocation(), 17478 diag::err_different_return_type_for_overriding_virtual_function) 17479 << New->getDeclName() << NewTy << OldTy 17480 << New->getReturnTypeSourceRange(); 17481 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17482 << Old->getReturnTypeSourceRange(); 17483 17484 return true; 17485 } 17486 17487 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17488 // C++14 [class.virtual]p8: 17489 // If the class type in the covariant return type of D::f differs from 17490 // that of B::f, the class type in the return type of D::f shall be 17491 // complete at the point of declaration of D::f or shall be the class 17492 // type D. 17493 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17494 if (!RT->isBeingDefined() && 17495 RequireCompleteType(New->getLocation(), NewClassTy, 17496 diag::err_covariant_return_incomplete, 17497 New->getDeclName())) 17498 return true; 17499 } 17500 17501 // Check if the new class derives from the old class. 17502 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17503 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17504 << New->getDeclName() << NewTy << OldTy 17505 << New->getReturnTypeSourceRange(); 17506 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17507 << Old->getReturnTypeSourceRange(); 17508 return true; 17509 } 17510 17511 // Check if we the conversion from derived to base is valid. 17512 if (CheckDerivedToBaseConversion( 17513 NewClassTy, OldClassTy, 17514 diag::err_covariant_return_inaccessible_base, 17515 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17516 New->getLocation(), New->getReturnTypeSourceRange(), 17517 New->getDeclName(), nullptr)) { 17518 // FIXME: this note won't trigger for delayed access control 17519 // diagnostics, and it's impossible to get an undelayed error 17520 // here from access control during the original parse because 17521 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17522 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17523 << Old->getReturnTypeSourceRange(); 17524 return true; 17525 } 17526 } 17527 17528 // The qualifiers of the return types must be the same. 17529 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17530 Diag(New->getLocation(), 17531 diag::err_covariant_return_type_different_qualifications) 17532 << New->getDeclName() << NewTy << OldTy 17533 << New->getReturnTypeSourceRange(); 17534 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17535 << Old->getReturnTypeSourceRange(); 17536 return true; 17537 } 17538 17539 17540 // The new class type must have the same or less qualifiers as the old type. 17541 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17542 Diag(New->getLocation(), 17543 diag::err_covariant_return_type_class_type_more_qualified) 17544 << New->getDeclName() << NewTy << OldTy 17545 << New->getReturnTypeSourceRange(); 17546 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17547 << Old->getReturnTypeSourceRange(); 17548 return true; 17549 } 17550 17551 return false; 17552} 17553 17554/// Mark the given method pure. 17555/// 17556/// \param Method the method to be marked pure. 17557/// 17558/// \param InitRange the source range that covers the "0" initializer. 17559bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17560 SourceLocation EndLoc = InitRange.getEnd(); 17561 if (EndLoc.isValid()) 17562 Method->setRangeEnd(EndLoc); 17563 17564 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17565 Method->setPure(); 17566 return false; 17567 } 17568 17569 if (!Method->isInvalidDecl()) 17570 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17571 << Method->getDeclName() << InitRange; 17572 return true; 17573} 17574 17575void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17576 if (D->getFriendObjectKind()) 17577 Diag(D->getLocation(), diag::err_pure_friend); 17578 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17579 CheckPureMethod(M, ZeroLoc); 17580 else 17581 Diag(D->getLocation(), diag::err_illegal_initializer); 17582} 17583 17584/// Determine whether the given declaration is a global variable or 17585/// static data member. 17586static bool isNonlocalVariable(const Decl *D) { 17587 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17588 return Var->hasGlobalStorage(); 17589 17590 return false; 17591} 17592 17593/// Invoked when we are about to parse an initializer for the declaration 17594/// 'Dcl'. 17595/// 17596/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17597/// static data member of class X, names should be looked up in the scope of 17598/// class X. If the declaration had a scope specifier, a scope will have 17599/// been created and passed in for this purpose. Otherwise, S will be null. 17600void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17601 // If there is no declaration, there was an error parsing it. 17602 if (!D || D->isInvalidDecl()) 17603 return; 17604 17605 // We will always have a nested name specifier here, but this declaration 17606 // might not be out of line if the specifier names the current namespace: 17607 // extern int n; 17608 // int ::n = 0; 17609 if (S && D->isOutOfLine()) 17610 EnterDeclaratorContext(S, D->getDeclContext()); 17611 17612 // If we are parsing the initializer for a static data member, push a 17613 // new expression evaluation context that is associated with this static 17614 // data member. 17615 if (isNonlocalVariable(D)) 17616 PushExpressionEvaluationContext( 17617 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17618} 17619 17620/// Invoked after we are finished parsing an initializer for the declaration D. 17621void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17622 // If there is no declaration, there was an error parsing it. 17623 if (!D || D->isInvalidDecl()) 17624 return; 17625 17626 if (isNonlocalVariable(D)) 17627 PopExpressionEvaluationContext(); 17628 17629 if (S && D->isOutOfLine()) 17630 ExitDeclaratorContext(S); 17631} 17632 17633/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17634/// C++ if/switch/while/for statement. 17635/// e.g: "if (int x = f()) {...}" 17636DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17637 // C++ 6.4p2: 17638 // The declarator shall not specify a function or an array. 17639 // The type-specifier-seq shall not contain typedef and shall not declare a 17640 // new class or enumeration. 17641 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17642, __extension__ __PRETTY_FUNCTION__
))
17642 "Parser allowed 'typedef' as storage class of condition decl.")(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17642, __extension__ __PRETTY_FUNCTION__
))
; 17643 17644 Decl *Dcl = ActOnDeclarator(S, D); 17645 if (!Dcl) 17646 return true; 17647 17648 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17649 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17650 << D.getSourceRange(); 17651 return true; 17652 } 17653 17654 return Dcl; 17655} 17656 17657void Sema::LoadExternalVTableUses() { 17658 if (!ExternalSource) 17659 return; 17660 17661 SmallVector<ExternalVTableUse, 4> VTables; 17662 ExternalSource->ReadUsedVTables(VTables); 17663 SmallVector<VTableUse, 4> NewUses; 17664 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17665 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17666 = VTablesUsed.find(VTables[I].Record); 17667 // Even if a definition wasn't required before, it may be required now. 17668 if (Pos != VTablesUsed.end()) { 17669 if (!Pos->second && VTables[I].DefinitionRequired) 17670 Pos->second = true; 17671 continue; 17672 } 17673 17674 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17675 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17676 } 17677 17678 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17679} 17680 17681void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17682 bool DefinitionRequired) { 17683 // Ignore any vtable uses in unevaluated operands or for classes that do 17684 // not have a vtable. 17685 if (!Class->isDynamicClass() || Class->isDependentContext() || 17686 CurContext->isDependentContext() || isUnevaluatedContext()) 17687 return; 17688 // Do not mark as used if compiling for the device outside of the target 17689 // region. 17690 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17691 !isInOpenMPDeclareTargetContext() && 17692 !isInOpenMPTargetExecutionDirective()) { 17693 if (!DefinitionRequired) 17694 MarkVirtualMembersReferenced(Loc, Class); 17695 return; 17696 } 17697 17698 // Try to insert this class into the map. 17699 LoadExternalVTableUses(); 17700 Class = Class->getCanonicalDecl(); 17701 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17702 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17703 if (!Pos.second) { 17704 // If we already had an entry, check to see if we are promoting this vtable 17705 // to require a definition. If so, we need to reappend to the VTableUses 17706 // list, since we may have already processed the first entry. 17707 if (DefinitionRequired && !Pos.first->second) { 17708 Pos.first->second = true; 17709 } else { 17710 // Otherwise, we can early exit. 17711 return; 17712 } 17713 } else { 17714 // The Microsoft ABI requires that we perform the destructor body 17715 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17716 // the deleting destructor is emitted with the vtable, not with the 17717 // destructor definition as in the Itanium ABI. 17718 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17719 CXXDestructorDecl *DD = Class->getDestructor(); 17720 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17721 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17722 // If this is an out-of-line declaration, marking it referenced will 17723 // not do anything. Manually call CheckDestructor to look up operator 17724 // delete(). 17725 ContextRAII SavedContext(*this, DD); 17726 CheckDestructor(DD); 17727 } else { 17728 MarkFunctionReferenced(Loc, Class->getDestructor()); 17729 } 17730 } 17731 } 17732 } 17733 17734 // Local classes need to have their virtual members marked 17735 // immediately. For all other classes, we mark their virtual members 17736 // at the end of the translation unit. 17737 if (Class->isLocalClass()) 17738 MarkVirtualMembersReferenced(Loc, Class); 17739 else 17740 VTableUses.push_back(std::make_pair(Class, Loc)); 17741} 17742 17743bool Sema::DefineUsedVTables() { 17744 LoadExternalVTableUses(); 17745 if (VTableUses.empty()) 17746 return false; 17747 17748 // Note: The VTableUses vector could grow as a result of marking 17749 // the members of a class as "used", so we check the size each 17750 // time through the loop and prefer indices (which are stable) to 17751 // iterators (which are not). 17752 bool DefinedAnything = false; 17753 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17754 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17755 if (!Class) 17756 continue; 17757 TemplateSpecializationKind ClassTSK = 17758 Class->getTemplateSpecializationKind(); 17759 17760 SourceLocation Loc = VTableUses[I].second; 17761 17762 bool DefineVTable = true; 17763 17764 // If this class has a key function, but that key function is 17765 // defined in another translation unit, we don't need to emit the 17766 // vtable even though we're using it. 17767 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17768 if (KeyFunction && !KeyFunction->hasBody()) { 17769 // The key function is in another translation unit. 17770 DefineVTable = false; 17771 TemplateSpecializationKind TSK = 17772 KeyFunction->getTemplateSpecializationKind(); 17773 assert(TSK != TSK_ExplicitInstantiationDefinition &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17775, __extension__ __PRETTY_FUNCTION__
))
17774 TSK != TSK_ImplicitInstantiation &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17775, __extension__ __PRETTY_FUNCTION__
))
17775 "Instantiations don't have key functions")(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17775, __extension__ __PRETTY_FUNCTION__
))
; 17776 (void)TSK; 17777 } else if (!KeyFunction) { 17778 // If we have a class with no key function that is the subject 17779 // of an explicit instantiation declaration, suppress the 17780 // vtable; it will live with the explicit instantiation 17781 // definition. 17782 bool IsExplicitInstantiationDeclaration = 17783 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17784 for (auto R : Class->redecls()) { 17785 TemplateSpecializationKind TSK 17786 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17787 if (TSK == TSK_ExplicitInstantiationDeclaration) 17788 IsExplicitInstantiationDeclaration = true; 17789 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17790 IsExplicitInstantiationDeclaration = false; 17791 break; 17792 } 17793 } 17794 17795 if (IsExplicitInstantiationDeclaration) 17796 DefineVTable = false; 17797 } 17798 17799 // The exception specifications for all virtual members may be needed even 17800 // if we are not providing an authoritative form of the vtable in this TU. 17801 // We may choose to emit it available_externally anyway. 17802 if (!DefineVTable) { 17803 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17804 continue; 17805 } 17806 17807 // Mark all of the virtual members of this class as referenced, so 17808 // that we can build a vtable. Then, tell the AST consumer that a 17809 // vtable for this class is required. 17810 DefinedAnything = true; 17811 MarkVirtualMembersReferenced(Loc, Class); 17812 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17813 if (VTablesUsed[Canonical]) 17814 Consumer.HandleVTable(Class); 17815 17816 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17817 // no key function or the key function is inlined. Don't warn in C++ ABIs 17818 // that lack key functions, since the user won't be able to make one. 17819 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17820 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 17821 ClassTSK != TSK_ExplicitInstantiationDefinition) { 17822 const FunctionDecl *KeyFunctionDef = nullptr; 17823 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17824 KeyFunctionDef->isInlined())) 17825 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 17826 } 17827 } 17828 VTableUses.clear(); 17829 17830 return DefinedAnything; 17831} 17832 17833void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17834 const CXXRecordDecl *RD) { 17835 for (const auto *I : RD->methods()) 17836 if (I->isVirtual() && !I->isPure()) 17837 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17838} 17839 17840void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17841 const CXXRecordDecl *RD, 17842 bool ConstexprOnly) { 17843 // Mark all functions which will appear in RD's vtable as used. 17844 CXXFinalOverriderMap FinalOverriders; 17845 RD->getFinalOverriders(FinalOverriders); 17846 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17847 E = FinalOverriders.end(); 17848 I != E; ++I) { 17849 for (OverridingMethods::const_iterator OI = I->second.begin(), 17850 OE = I->second.end(); 17851 OI != OE; ++OI) { 17852 assert(OI->second.size() > 0 && "no final overrider")(static_cast <bool> (OI->second.size() > 0 &&
"no final overrider") ? void (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17852, __extension__ __PRETTY_FUNCTION__
))
; 17853 CXXMethodDecl *Overrider = OI->second.front().Method; 17854 17855 // C++ [basic.def.odr]p2: 17856 // [...] A virtual member function is used if it is not pure. [...] 17857 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17858 MarkFunctionReferenced(Loc, Overrider); 17859 } 17860 } 17861 17862 // Only classes that have virtual bases need a VTT. 17863 if (RD->getNumVBases() == 0) 17864 return; 17865 17866 for (const auto &I : RD->bases()) { 17867 const auto *Base = 17868 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17869 if (Base->getNumVBases() == 0) 17870 continue; 17871 MarkVirtualMembersReferenced(Loc, Base); 17872 } 17873} 17874 17875/// SetIvarInitializers - This routine builds initialization ASTs for the 17876/// Objective-C implementation whose ivars need be initialized. 17877void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17878 if (!getLangOpts().CPlusPlus) 17879 return; 17880 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17881 SmallVector<ObjCIvarDecl*, 8> ivars; 17882 CollectIvarsToConstructOrDestruct(OID, ivars); 17883 if (ivars.empty()) 17884 return; 17885 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17886 for (unsigned i = 0; i < ivars.size(); i++) { 17887 FieldDecl *Field = ivars[i]; 17888 if (Field->isInvalidDecl()) 17889 continue; 17890 17891 CXXCtorInitializer *Member; 17892 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17893 InitializationKind InitKind = 17894 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17895 17896 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17897 ExprResult MemberInit = 17898 InitSeq.Perform(*this, InitEntity, InitKind, None); 17899 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17900 // Note, MemberInit could actually come back empty if no initialization 17901 // is required (e.g., because it would call a trivial default constructor) 17902 if (!MemberInit.get() || MemberInit.isInvalid()) 17903 continue; 17904 17905 Member = 17906 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17907 SourceLocation(), 17908 MemberInit.getAs<Expr>(), 17909 SourceLocation()); 17910 AllToInit.push_back(Member); 17911 17912 // Be sure that the destructor is accessible and is marked as referenced. 17913 if (const RecordType *RecordTy = 17914 Context.getBaseElementType(Field->getType()) 17915 ->getAs<RecordType>()) { 17916 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17917 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17918 MarkFunctionReferenced(Field->getLocation(), Destructor); 17919 CheckDestructorAccess(Field->getLocation(), Destructor, 17920 PDiag(diag::err_access_dtor_ivar) 17921 << Context.getBaseElementType(Field->getType())); 17922 } 17923 } 17924 } 17925 ObjCImplementation->setIvarInitializers(Context, 17926 AllToInit.data(), AllToInit.size()); 17927 } 17928} 17929 17930static 17931void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17932 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17933 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17934 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17935 Sema &S) { 17936 if (Ctor->isInvalidDecl()) 17937 return; 17938 17939 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17940 17941 // Target may not be determinable yet, for instance if this is a dependent 17942 // call in an uninstantiated template. 17943 if (Target) { 17944 const FunctionDecl *FNTarget = nullptr; 17945 (void)Target->hasBody(FNTarget); 17946 Target = const_cast<CXXConstructorDecl*>( 17947 cast_or_null<CXXConstructorDecl>(FNTarget)); 17948 } 17949 17950 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17951 // Avoid dereferencing a null pointer here. 17952 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17953 17954 if (!Current.insert(Canonical).second) 17955 return; 17956 17957 // We know that beyond here, we aren't chaining into a cycle. 17958 if (!Target || !Target->isDelegatingConstructor() || 17959 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17960 Valid.insert(Current.begin(), Current.end()); 17961 Current.clear(); 17962 // We've hit a cycle. 17963 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17964 Current.count(TCanonical)) { 17965 // If we haven't diagnosed this cycle yet, do so now. 17966 if (!Invalid.count(TCanonical)) { 17967 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17968 diag::warn_delegating_ctor_cycle) 17969 << Ctor; 17970 17971 // Don't add a note for a function delegating directly to itself. 17972 if (TCanonical != Canonical) 17973 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17974 17975 CXXConstructorDecl *C = Target; 17976 while (C->getCanonicalDecl() != Canonical) { 17977 const FunctionDecl *FNTarget = nullptr; 17978 (void)C->getTargetConstructor()->hasBody(FNTarget); 17979 assert(FNTarget && "Ctor cycle through bodiless function")(static_cast <bool> (FNTarget && "Ctor cycle through bodiless function"
) ? void (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17979, __extension__ __PRETTY_FUNCTION__
))
; 17980 17981 C = const_cast<CXXConstructorDecl*>( 17982 cast<CXXConstructorDecl>(FNTarget)); 17983 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17984 } 17985 } 17986 17987 Invalid.insert(Current.begin(), Current.end()); 17988 Current.clear(); 17989 } else { 17990 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17991 } 17992} 17993 17994 17995void Sema::CheckDelegatingCtorCycles() { 17996 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17997 17998 for (DelegatingCtorDeclsType::iterator 17999 I = DelegatingCtorDecls.begin(ExternalSource), 18000 E = DelegatingCtorDecls.end(); 18001 I != E; ++I) 18002 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 18003 18004 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 18005 (*CI)->setInvalidDecl(); 18006} 18007 18008namespace { 18009 /// AST visitor that finds references to the 'this' expression. 18010 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 18011 Sema &S; 18012 18013 public: 18014 explicit FindCXXThisExpr(Sema &S) : S(S) { } 18015 18016 bool VisitCXXThisExpr(CXXThisExpr *E) { 18017 S.Diag(E->getLocation(), diag::err_this_static_member_func) 18018 << E->isImplicit(); 18019 return false; 18020 } 18021 }; 18022} 18023 18024bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 18025 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18026 if (!TSInfo) 18027 return false; 18028 18029 TypeLoc TL = TSInfo->getTypeLoc(); 18030 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18031 if (!ProtoTL) 18032 return false; 18033 18034 // C++11 [expr.prim.general]p3: 18035 // [The expression this] shall not appear before the optional 18036 // cv-qualifier-seq and it shall not appear within the declaration of a 18037 // static member function (although its type and value category are defined 18038 // within a static member function as they are within a non-static member 18039 // function). [ Note: this is because declaration matching does not occur 18040 // until the complete declarator is known. - end note ] 18041 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18042 FindCXXThisExpr Finder(*this); 18043 18044 // If the return type came after the cv-qualifier-seq, check it now. 18045 if (Proto->hasTrailingReturn() && 18046 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 18047 return true; 18048 18049 // Check the exception specification. 18050 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 18051 return true; 18052 18053 // Check the trailing requires clause 18054 if (Expr *E = Method->getTrailingRequiresClause()) 18055 if (!Finder.TraverseStmt(E)) 18056 return true; 18057 18058 return checkThisInStaticMemberFunctionAttributes(Method); 18059} 18060 18061bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 18062 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18063 if (!TSInfo) 18064 return false; 18065 18066 TypeLoc TL = TSInfo->getTypeLoc(); 18067 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18068 if (!ProtoTL) 18069 return false; 18070 18071 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18072 FindCXXThisExpr Finder(*this); 18073 18074 switch (Proto->getExceptionSpecType()) { 18075 case EST_Unparsed: 18076 case EST_Uninstantiated: 18077 case EST_Unevaluated: 18078 case EST_BasicNoexcept: 18079 case EST_NoThrow: 18080 case EST_DynamicNone: 18081 case EST_MSAny: 18082 case EST_None: 18083 break; 18084 18085 case EST_DependentNoexcept: 18086 case EST_NoexceptFalse: 18087 case EST_NoexceptTrue: 18088 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 18089 return true; 18090 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 18091 18092 case EST_Dynamic: 18093 for (const auto &E : Proto->exceptions()) { 18094 if (!Finder.TraverseType(E)) 18095 return true; 18096 } 18097 break; 18098 } 18099 18100 return false; 18101} 18102 18103bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 18104 FindCXXThisExpr Finder(*this); 18105 18106 // Check attributes. 18107 for (const auto *A : Method->attrs()) { 18108 // FIXME: This should be emitted by tblgen. 18109 Expr *Arg = nullptr; 18110 ArrayRef<Expr *> Args; 18111 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 18112 Arg = G->getArg(); 18113 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 18114 Arg = G->getArg(); 18115 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 18116 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 18117 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 18118 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 18119 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 18120 Arg = ETLF->getSuccessValue(); 18121 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 18122 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 18123 Arg = STLF->getSuccessValue(); 18124 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 18125 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 18126 Arg = LR->getArg(); 18127 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 18128 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 18129 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 18130 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18131 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 18132 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18133 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 18134 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18135 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 18136 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18137 18138 if (Arg && !Finder.TraverseStmt(Arg)) 18139 return true; 18140 18141 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 18142 if (!Finder.TraverseStmt(Args[I])) 18143 return true; 18144 } 18145 } 18146 18147 return false; 18148} 18149 18150void Sema::checkExceptionSpecification( 18151 bool IsTopLevel, ExceptionSpecificationType EST, 18152 ArrayRef<ParsedType> DynamicExceptions, 18153 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 18154 SmallVectorImpl<QualType> &Exceptions, 18155 FunctionProtoType::ExceptionSpecInfo &ESI) { 18156 Exceptions.clear(); 18157 ESI.Type = EST; 18158 if (EST == EST_Dynamic) { 18159 Exceptions.reserve(DynamicExceptions.size()); 18160 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 18161 // FIXME: Preserve type source info. 18162 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 18163 18164 if (IsTopLevel) { 18165 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 18166 collectUnexpandedParameterPacks(ET, Unexpanded); 18167 if (!Unexpanded.empty()) { 18168 DiagnoseUnexpandedParameterPacks( 18169 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18170 Unexpanded); 18171 continue; 18172 } 18173 } 18174 18175 // Check that the type is valid for an exception spec, and 18176 // drop it if not. 18177 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18178 Exceptions.push_back(ET); 18179 } 18180 ESI.Exceptions = Exceptions; 18181 return; 18182 } 18183 18184 if (isComputedNoexcept(EST)) { 18185 assert((NoexceptExpr->isTypeDependent() ||(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18188, __extension__ __PRETTY_FUNCTION__
))
18186 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18188, __extension__ __PRETTY_FUNCTION__
))
18187 Context.BoolTy) &&(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18188, __extension__ __PRETTY_FUNCTION__
))
18188 "Parser should have made sure that the expression is boolean")(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18188, __extension__ __PRETTY_FUNCTION__
))
; 18189 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18190 ESI.Type = EST_BasicNoexcept; 18191 return; 18192 } 18193 18194 ESI.NoexceptExpr = NoexceptExpr; 18195 return; 18196 } 18197} 18198 18199void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18200 ExceptionSpecificationType EST, 18201 SourceRange SpecificationRange, 18202 ArrayRef<ParsedType> DynamicExceptions, 18203 ArrayRef<SourceRange> DynamicExceptionRanges, 18204 Expr *NoexceptExpr) { 18205 if (!MethodD) 18206 return; 18207 18208 // Dig out the method we're referring to. 18209 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18210 MethodD = FunTmpl->getTemplatedDecl(); 18211 18212 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18213 if (!Method) 18214 return; 18215 18216 // Check the exception specification. 18217 llvm::SmallVector<QualType, 4> Exceptions; 18218 FunctionProtoType::ExceptionSpecInfo ESI; 18219 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18220 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18221 ESI); 18222 18223 // Update the exception specification on the function type. 18224 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18225 18226 if (Method->isStatic()) 18227 checkThisInStaticMemberFunctionExceptionSpec(Method); 18228 18229 if (Method->isVirtual()) { 18230 // Check overrides, which we previously had to delay. 18231 for (const CXXMethodDecl *O : Method->overridden_methods()) 18232 CheckOverridingFunctionExceptionSpec(Method, O); 18233 } 18234} 18235 18236/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18237/// 18238MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18239 SourceLocation DeclStart, Declarator &D, 18240 Expr *BitWidth, 18241 InClassInitStyle InitStyle, 18242 AccessSpecifier AS, 18243 const ParsedAttr &MSPropertyAttr) { 18244 IdentifierInfo *II = D.getIdentifier(); 18245 if (!II) { 18246 Diag(DeclStart, diag::err_anonymous_property); 18247 return nullptr; 18248 } 18249 SourceLocation Loc = D.getIdentifierLoc(); 18250 18251 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18252 QualType T = TInfo->getType(); 18253 if (getLangOpts().CPlusPlus) { 18254 CheckExtraCXXDefaultArguments(D); 18255 18256 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18257 UPPC_DataMemberType)) { 18258 D.setInvalidType(); 18259 T = Context.IntTy; 18260 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18261 } 18262 } 18263 18264 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18265 18266 if (D.getDeclSpec().isInlineSpecified()) 18267 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18268 << getLangOpts().CPlusPlus17; 18269 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18270 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18271 diag::err_invalid_thread) 18272 << DeclSpec::getSpecifierName(TSCS); 18273 18274 // Check to see if this name was declared as a member previously 18275 NamedDecl *PrevDecl = nullptr; 18276 LookupResult Previous(*this, II, Loc, LookupMemberName, 18277 ForVisibleRedeclaration); 18278 LookupName(Previous, S); 18279 switch (Previous.getResultKind()) { 18280 case LookupResult::Found: 18281 case LookupResult::FoundUnresolvedValue: 18282 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18283 break; 18284 18285 case LookupResult::FoundOverloaded: 18286 PrevDecl = Previous.getRepresentativeDecl(); 18287 break; 18288 18289 case LookupResult::NotFound: 18290 case LookupResult::NotFoundInCurrentInstantiation: 18291 case LookupResult::Ambiguous: 18292 break; 18293 } 18294 18295 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18296 // Maybe we will complain about the shadowed template parameter. 18297 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18298 // Just pretend that we didn't see the previous declaration. 18299 PrevDecl = nullptr; 18300 } 18301 18302 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18303 PrevDecl = nullptr; 18304 18305 SourceLocation TSSL = D.getBeginLoc(); 18306 MSPropertyDecl *NewPD = 18307 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18308 MSPropertyAttr.getPropertyDataGetter(), 18309 MSPropertyAttr.getPropertyDataSetter()); 18310 ProcessDeclAttributes(TUScope, NewPD, D); 18311 NewPD->setAccess(AS); 18312 18313 if (NewPD->isInvalidDecl()) 18314 Record->setInvalidDecl(); 18315 18316 if (D.getDeclSpec().isModulePrivateSpecified()) 18317 NewPD->setModulePrivate(); 18318 18319 if (NewPD->isInvalidDecl() && PrevDecl) { 18320 // Don't introduce NewFD into scope; there's already something 18321 // with the same name in the same scope. 18322 } else if (II) { 18323 PushOnScopeChains(NewPD, S); 18324 } else 18325 Record->addDecl(NewPD); 18326 18327 return NewPD; 18328} 18329 18330void Sema::ActOnStartFunctionDeclarationDeclarator( 18331 Declarator &Declarator, unsigned TemplateParameterDepth) { 18332 auto &Info = InventedParameterInfos.emplace_back(); 18333 TemplateParameterList *ExplicitParams = nullptr; 18334 ArrayRef<TemplateParameterList *> ExplicitLists = 18335 Declarator.getTemplateParameterLists(); 18336 if (!ExplicitLists.empty()) { 18337 bool IsMemberSpecialization, IsInvalid; 18338 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18339 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18340 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18341 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18342 /*SuppressDiagnostic=*/true); 18343 } 18344 if (ExplicitParams) { 18345 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18346 llvm::append_range(Info.TemplateParams, *ExplicitParams); 18347 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18348 } else { 18349 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18350 Info.NumExplicitTemplateParams = 0; 18351 } 18352} 18353 18354void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18355 auto &FSI = InventedParameterInfos.back(); 18356 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18357 if (FSI.NumExplicitTemplateParams != 0) { 18358 TemplateParameterList *ExplicitParams = 18359 Declarator.getTemplateParameterLists().back(); 18360 Declarator.setInventedTemplateParameterList( 18361 TemplateParameterList::Create( 18362 Context, ExplicitParams->getTemplateLoc(), 18363 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18364 ExplicitParams->getRAngleLoc(), 18365 ExplicitParams->getRequiresClause())); 18366 } else { 18367 Declarator.setInventedTemplateParameterList( 18368 TemplateParameterList::Create( 18369 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18370 SourceLocation(), /*RequiresClause=*/nullptr)); 18371 } 18372 } 18373 InventedParameterInfos.pop_back(); 18374}