Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 5533, column 56
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 -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-15-025533-4418-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp

/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/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/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include <map>
46#include <set>
47
48using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// CheckDefaultArgumentVisitor
52//===----------------------------------------------------------------------===//
53
54namespace {
55/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56/// the default argument of a parameter to determine whether it
57/// contains any ill-formed subexpressions. For example, this will
58/// diagnose the use of local variables or parameters within the
59/// default argument expression.
60class CheckDefaultArgumentVisitor
61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62 Sema &S;
63 const Expr *DefaultArg;
64
65public:
66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67 : S(S), DefaultArg(DefaultArg) {}
68
69 bool VisitExpr(const Expr *Node);
70 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72 bool VisitLambdaExpr(const LambdaExpr *Lambda);
73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74};
75
76/// VisitExpr - Visit all of the children of this expression.
77bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78 bool IsInvalid = false;
79 for (const Stmt *SubStmt : Node->children())
80 IsInvalid |= Visit(SubStmt);
81 return IsInvalid;
82}
83
84/// VisitDeclRefExpr - Visit a reference to a declaration, to
85/// determine whether this declaration can be used in the default
86/// argument expression.
87bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88 const NamedDecl *Decl = DRE->getDecl();
89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90 // C++ [dcl.fct.default]p9:
91 // [...] parameters of a function shall not be used in default
92 // argument expressions, even if they are not evaluated. [...]
93 //
94 // C++17 [dcl.fct.default]p9 (by CWG 2082):
95 // [...] A parameter shall not appear as a potentially-evaluated
96 // expression in a default argument. [...]
97 //
98 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99 return S.Diag(DRE->getBeginLoc(),
100 diag::err_param_default_argument_references_param)
101 << Param->getDeclName() << DefaultArg->getSourceRange();
102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p7:
104 // Local variables shall not be used in default argument
105 // expressions.
106 //
107 // C++17 [dcl.fct.default]p7 (by CWG 2082):
108 // A local variable shall not appear as a potentially-evaluated
109 // expression in a default argument.
110 //
111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112 // Note: A local variable cannot be odr-used (6.3) in a default argument.
113 //
114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_local)
117 << VDecl->getDeclName() << DefaultArg->getSourceRange();
118 }
119
120 return false;
121}
122
123/// VisitCXXThisExpr - Visit a C++ "this" expression.
124bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125 // C++ [dcl.fct.default]p8:
126 // The keyword this shall not be used in a default argument of a
127 // member function.
128 return S.Diag(ThisE->getBeginLoc(),
129 diag::err_param_default_argument_references_this)
130 << ThisE->getSourceRange();
131}
132
133bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134 const PseudoObjectExpr *POE) {
135 bool Invalid = false;
136 for (const Expr *E : POE->semantics()) {
137 // Look through bindings.
138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139 E = OVE->getSourceExpr();
140 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 140, __PRETTY_FUNCTION__))
;
141 }
142
143 Invalid |= Visit(E);
144 }
145 return Invalid;
146}
147
148bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149 // C++11 [expr.lambda.prim]p13:
150 // A lambda-expression appearing in a default argument shall not
151 // implicitly or explicitly capture any entity.
152 if (Lambda->capture_begin() == Lambda->capture_end())
153 return false;
154
155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156}
157} // namespace
158
159void
160Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161 const CXXMethodDecl *Method) {
162 // If we have an MSAny spec already, don't bother.
163 if (!Method || ComputedEST == EST_MSAny)
164 return;
165
166 const FunctionProtoType *Proto
167 = Method->getType()->getAs<FunctionProtoType>();
168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169 if (!Proto)
170 return;
171
172 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
174 // If we have a throw-all spec at this point, ignore the function.
175 if (ComputedEST == EST_None)
176 return;
177
178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179 EST = EST_BasicNoexcept;
180
181 switch (EST) {
182 case EST_Unparsed:
183 case EST_Uninstantiated:
184 case EST_Unevaluated:
185 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 185)
;
186
187 // If this function can throw any exceptions, make a note of that.
188 case EST_MSAny:
189 case EST_None:
190 // FIXME: Whichever we see last of MSAny and None determines our result.
191 // We should make a consistent, order-independent choice here.
192 ClearExceptions();
193 ComputedEST = EST;
194 return;
195 case EST_NoexceptFalse:
196 ClearExceptions();
197 ComputedEST = EST_None;
198 return;
199 // FIXME: If the call to this decl is using any of its default arguments, we
200 // need to search them for potentially-throwing calls.
201 // If this function has a basic noexcept, it doesn't affect the outcome.
202 case EST_BasicNoexcept:
203 case EST_NoexceptTrue:
204 case EST_NoThrow:
205 return;
206 // If we're still at noexcept(true) and there's a throw() callee,
207 // change to that specification.
208 case EST_DynamicNone:
209 if (ComputedEST == EST_BasicNoexcept)
210 ComputedEST = EST_DynamicNone;
211 return;
212 case EST_DependentNoexcept:
213 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
214 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
;
215 case EST_Dynamic:
216 break;
217 }
218 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 218, __PRETTY_FUNCTION__))
;
219 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __PRETTY_FUNCTION__))
220 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __PRETTY_FUNCTION__))
;
221 ComputedEST = EST_Dynamic;
222 // Record the exceptions in this function's exception specification.
223 for (const auto &E : Proto->exceptions())
224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225 Exceptions.push_back(E);
226}
227
228void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229 if (!S || ComputedEST == EST_MSAny)
230 return;
231
232 // FIXME:
233 //
234 // C++0x [except.spec]p14:
235 // [An] implicit exception-specification specifies the type-id T if and
236 // only if T is allowed by the exception-specification of a function directly
237 // invoked by f's implicit definition; f shall allow all exceptions if any
238 // function it directly invokes allows all exceptions, and f shall allow no
239 // exceptions if every function it directly invokes allows no exceptions.
240 //
241 // Note in particular that if an implicit exception-specification is generated
242 // for a function containing a throw-expression, that specification can still
243 // be noexcept(true).
244 //
245 // Note also that 'directly invoked' is not defined in the standard, and there
246 // is no indication that we should only consider potentially-evaluated calls.
247 //
248 // Ultimately we should implement the intent of the standard: the exception
249 // specification should be the set of exceptions which can be thrown by the
250 // implicit definition. For now, we assume that any non-nothrow expression can
251 // throw any exception.
252
253 if (Self->canThrow(S))
254 ComputedEST = EST_None;
255}
256
257ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258 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_RValue));
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)
385 OpaqueValueExpr(EqualLoc,
386 Param->getType().getNonReferenceType(),
387 VK_RValue));
388}
389
390/// CheckExtraCXXDefaultArguments - Check for any extra default
391/// arguments in the declarator, which is not a function declaration
392/// or definition and therefore is not permitted to have default
393/// arguments. This routine should be invoked for every declarator
394/// that is not a function declaration or definition.
395void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396 // C++ [dcl.fct.default]p3
397 // A default argument expression shall be specified only in the
398 // parameter-declaration-clause of a function declaration or in a
399 // template-parameter (14.1). It shall not be specified for a
400 // parameter pack. If it is specified in a
401 // parameter-declaration-clause, it shall not occur within a
402 // declarator or abstract-declarator of a parameter-declaration.
403 bool MightBeFunction = D.isFunctionDeclarationContext();
404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405 DeclaratorChunk &chunk = D.getTypeObject(i);
406 if (chunk.Kind == DeclaratorChunk::Function) {
407 if (MightBeFunction) {
408 // This is a function declaration. It can have default arguments, but
409 // keep looking in case its return type is a function type with default
410 // arguments.
411 MightBeFunction = false;
412 continue;
413 }
414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415 ++argIdx) {
416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417 if (Param->hasUnparsedDefaultArg()) {
418 std::unique_ptr<CachedTokens> Toks =
419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420 SourceRange SR;
421 if (Toks->size() > 1)
422 SR = SourceRange((*Toks)[1].getLocation(),
423 Toks->back().getLocation());
424 else
425 SR = UnparsedDefaultArgLocs[Param];
426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427 << SR;
428 } else if (Param->getDefaultArg()) {
429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430 << Param->getDefaultArg()->getSourceRange();
431 Param->setDefaultArg(nullptr);
432 }
433 }
434 } else if (chunk.Kind != DeclaratorChunk::Paren) {
435 MightBeFunction = false;
436 }
437 }
438}
439
440static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443 });
444}
445
446/// MergeCXXFunctionDecl - Merge two declarations of the same C++
447/// function, once we already know that they have the same
448/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449/// error, false otherwise.
450bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451 Scope *S) {
452 bool Invalid = false;
453
454 // The declaration context corresponding to the scope is the semantic
455 // parent, unless this is a local function declaration, in which case
456 // it is that surrounding function.
457 DeclContext *ScopeDC = New->isLocalExternDecl()
458 ? New->getLexicalDeclContext()
459 : New->getDeclContext();
460
461 // Find the previous declaration for the purpose of default arguments.
462 FunctionDecl *PrevForDefaultArgs = Old;
463 for (/**/; PrevForDefaultArgs;
464 // Don't bother looking back past the latest decl if this is a local
465 // extern declaration; nothing else could work.
466 PrevForDefaultArgs = New->isLocalExternDecl()
467 ? nullptr
468 : PrevForDefaultArgs->getPreviousDecl()) {
469 // Ignore hidden declarations.
470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471 continue;
472
473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474 !New->isCXXClassMember()) {
475 // Ignore default arguments of old decl if they are not in
476 // the same scope and this is not an out-of-line definition of
477 // a member function.
478 continue;
479 }
480
481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482 // If only one of these is a local function declaration, then they are
483 // declared in different scopes, even though isDeclInScope may think
484 // they're in the same scope. (If both are local, the scope check is
485 // sufficient, and if neither is local, then they are in the same scope.)
486 continue;
487 }
488
489 // We found the right previous declaration.
490 break;
491 }
492
493 // C++ [dcl.fct.default]p4:
494 // For non-template functions, default arguments can be added in
495 // later declarations of a function in the same
496 // scope. Declarations in different scopes have completely
497 // distinct sets of default arguments. That is, declarations in
498 // inner scopes do not acquire default arguments from
499 // declarations in outer scopes, and vice versa. In a given
500 // function declaration, all parameters subsequent to a
501 // parameter with a default argument shall have default
502 // arguments supplied in this or previous declarations. A
503 // default argument shall not be redefined by a later
504 // declaration (not even to the same value).
505 //
506 // C++ [dcl.fct.default]p6:
507 // Except for member functions of class templates, the default arguments
508 // in a member function definition that appears outside of the class
509 // definition are added to the set of default arguments provided by the
510 // member function declaration in the class definition.
511 for (unsigned p = 0, NumParams = PrevForDefaultArgs
512 ? PrevForDefaultArgs->getNumParams()
513 : 0;
514 p < NumParams; ++p) {
515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516 ParmVarDecl *NewParam = New->getParamDecl(p);
517
518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519 bool NewParamHasDfl = NewParam->hasDefaultArg();
520
521 if (OldParamHasDfl && NewParamHasDfl) {
522 unsigned DiagDefaultParamID =
523 diag::err_param_default_argument_redefinition;
524
525 // MSVC accepts that default parameters be redefined for member functions
526 // of template class. The new default parameter's value is ignored.
527 Invalid = true;
528 if (getLangOpts().MicrosoftExt) {
529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530 if (MD && MD->getParent()->getDescribedClassTemplate()) {
531 // Merge the old default argument into the new parameter.
532 NewParam->setHasInheritedDefaultArg();
533 if (OldParam->hasUninstantiatedDefaultArg())
534 NewParam->setUninstantiatedDefaultArg(
535 OldParam->getUninstantiatedDefaultArg());
536 else
537 NewParam->setDefaultArg(OldParam->getInit());
538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539 Invalid = false;
540 }
541 }
542
543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544 // hint here. Alternatively, we could walk the type-source information
545 // for NewParam to find the last source location in the type... but it
546 // isn't worth the effort right now. This is the kind of test case that
547 // is hard to get right:
548 // int f(int);
549 // void g(int (*fp)(int) = f);
550 // void g(int (*fp)(int) = &f);
551 Diag(NewParam->getLocation(), DiagDefaultParamID)
552 << NewParam->getDefaultArgRange();
553
554 // Look for the function declaration where the default argument was
555 // actually written, which may be a declaration prior to Old.
556 for (auto Older = PrevForDefaultArgs;
557 OldParam->hasInheritedDefaultArg(); /**/) {
558 Older = Older->getPreviousDecl();
559 OldParam = Older->getParamDecl(p);
560 }
561
562 Diag(OldParam->getLocation(), diag::note_previous_definition)
563 << OldParam->getDefaultArgRange();
564 } else if (OldParamHasDfl) {
565 // Merge the old default argument into the new parameter unless the new
566 // function is a friend declaration in a template class. In the latter
567 // case the default arguments will be inherited when the friend
568 // declaration will be instantiated.
569 if (New->getFriendObjectKind() == Decl::FOK_None ||
570 !New->getLexicalDeclContext()->isDependentContext()) {
571 // It's important to use getInit() here; getDefaultArg()
572 // strips off any top-level ExprWithCleanups.
573 NewParam->setHasInheritedDefaultArg();
574 if (OldParam->hasUnparsedDefaultArg())
575 NewParam->setUnparsedDefaultArg();
576 else if (OldParam->hasUninstantiatedDefaultArg())
577 NewParam->setUninstantiatedDefaultArg(
578 OldParam->getUninstantiatedDefaultArg());
579 else
580 NewParam->setDefaultArg(OldParam->getInit());
581 }
582 } else if (NewParamHasDfl) {
583 if (New->getDescribedFunctionTemplate()) {
584 // Paragraph 4, quoted above, only applies to non-template functions.
585 Diag(NewParam->getLocation(),
586 diag::err_param_default_argument_template_redecl)
587 << NewParam->getDefaultArgRange();
588 Diag(PrevForDefaultArgs->getLocation(),
589 diag::note_template_prev_declaration)
590 << false;
591 } else if (New->getTemplateSpecializationKind()
592 != TSK_ImplicitInstantiation &&
593 New->getTemplateSpecializationKind() != TSK_Undeclared) {
594 // C++ [temp.expr.spec]p21:
595 // Default function arguments shall not be specified in a declaration
596 // or a definition for one of the following explicit specializations:
597 // - the explicit specialization of a function template;
598 // - the explicit specialization of a member function template;
599 // - the explicit specialization of a member function of a class
600 // template where the class template specialization to which the
601 // member function specialization belongs is implicitly
602 // instantiated.
603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605 << New->getDeclName()
606 << NewParam->getDefaultArgRange();
607 } else if (New->getDeclContext()->isDependentContext()) {
608 // C++ [dcl.fct.default]p6 (DR217):
609 // Default arguments for a member function of a class template shall
610 // be specified on the initial declaration of the member function
611 // within the class template.
612 //
613 // Reading the tea leaves a bit in DR217 and its reference to DR205
614 // leads me to the conclusion that one cannot add default function
615 // arguments for an out-of-line definition of a member function of a
616 // dependent type.
617 int WhichKind = 2;
618 if (CXXRecordDecl *Record
619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620 if (Record->getDescribedClassTemplate())
621 WhichKind = 0;
622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623 WhichKind = 1;
624 else
625 WhichKind = 2;
626 }
627
628 Diag(NewParam->getLocation(),
629 diag::err_param_default_argument_member_template_redecl)
630 << WhichKind
631 << NewParam->getDefaultArgRange();
632 }
633 }
634 }
635
636 // DR1344: If a default argument is added outside a class definition and that
637 // default argument makes the function a special member function, the program
638 // is ill-formed. This can only happen for constructors.
639 if (isa<CXXConstructorDecl>(New) &&
640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643 if (NewSM != OldSM) {
644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645 assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 645, __PRETTY_FUNCTION__))
;
646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647 << NewParam->getDefaultArgRange() << NewSM;
648 Diag(Old->getLocation(), diag::note_previous_declaration);
649 }
650 }
651
652 const FunctionDecl *Def;
653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654 // template has a constexpr specifier then all its declarations shall
655 // contain the constexpr specifier.
656 if (New->getConstexprKind() != Old->getConstexprKind()) {
657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658 << New << static_cast<int>(New->getConstexprKind())
659 << static_cast<int>(Old->getConstexprKind());
660 Diag(Old->getLocation(), diag::note_previous_declaration);
661 Invalid = true;
662 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
663 Old->isDefined(Def) &&
664 // If a friend function is inlined but does not have 'inline'
665 // specifier, it is a definition. Do not report attribute conflict
666 // in this case, redefinition will be diagnosed later.
667 (New->isInlineSpecified() ||
668 New->getFriendObjectKind() == Decl::FOK_None)) {
669 // C++11 [dcl.fcn.spec]p4:
670 // If the definition of a function appears in a translation unit before its
671 // first declaration as inline, the program is ill-formed.
672 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
673 Diag(Def->getLocation(), diag::note_previous_definition);
674 Invalid = true;
675 }
676
677 // C++17 [temp.deduct.guide]p3:
678 // Two deduction guide declarations in the same translation unit
679 // for the same class template shall not have equivalent
680 // parameter-declaration-clauses.
681 if (isa<CXXDeductionGuideDecl>(New) &&
682 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
683 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
684 Diag(Old->getLocation(), diag::note_previous_declaration);
685 }
686
687 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
688 // argument expression, that declaration shall be a definition and shall be
689 // the only declaration of the function or function template in the
690 // translation unit.
691 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
692 functionDeclHasDefaultArgument(Old)) {
693 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
694 Diag(Old->getLocation(), diag::note_previous_declaration);
695 Invalid = true;
696 }
697
698 // C++11 [temp.friend]p4 (DR329):
699 // When a function is defined in a friend function declaration in a class
700 // template, the function is instantiated when the function is odr-used.
701 // The same restrictions on multiple declarations and definitions that
702 // apply to non-template function declarations and definitions also apply
703 // to these implicit definitions.
704 const FunctionDecl *OldDefinition = nullptr;
705 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
706 Old->isDefined(OldDefinition, true))
707 CheckForFunctionRedefinition(New, OldDefinition);
708
709 return Invalid;
710}
711
712NamedDecl *
713Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
714 MultiTemplateParamsArg TemplateParamLists) {
715 assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 715, __PRETTY_FUNCTION__))
;
716 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
717
718 // The syntax only allows a decomposition declarator as a simple-declaration,
719 // a for-range-declaration, or a condition in Clang, but we parse it in more
720 // cases than that.
721 if (!D.mayHaveDecompositionDeclarator()) {
722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
723 << Decomp.getSourceRange();
724 return nullptr;
725 }
726
727 if (!TemplateParamLists.empty()) {
728 // FIXME: There's no rule against this, but there are also no rules that
729 // would actually make it usable, so we reject it for now.
730 Diag(TemplateParamLists.front()->getTemplateLoc(),
731 diag::err_decomp_decl_template);
732 return nullptr;
733 }
734
735 Diag(Decomp.getLSquareLoc(),
736 !getLangOpts().CPlusPlus17
737 ? diag::ext_decomp_decl
738 : D.getContext() == DeclaratorContext::Condition
739 ? diag::ext_decomp_decl_cond
740 : diag::warn_cxx14_compat_decomp_decl)
741 << Decomp.getSourceRange();
742
743 // The semantic context is always just the current context.
744 DeclContext *const DC = CurContext;
745
746 // C++17 [dcl.dcl]/8:
747 // The decl-specifier-seq shall contain only the type-specifier auto
748 // and cv-qualifiers.
749 // C++2a [dcl.dcl]/8:
750 // If decl-specifier-seq contains any decl-specifier other than static,
751 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
752 auto &DS = D.getDeclSpec();
753 {
754 SmallVector<StringRef, 8> BadSpecifiers;
755 SmallVector<SourceLocation, 8> BadSpecifierLocs;
756 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
757 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
758 if (auto SCS = DS.getStorageClassSpec()) {
759 if (SCS == DeclSpec::SCS_static) {
760 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
761 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762 } else {
763 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
764 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
765 }
766 }
767 if (auto TSCS = DS.getThreadStorageClassSpec()) {
768 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
769 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
770 }
771 if (DS.hasConstexprSpecifier()) {
772 BadSpecifiers.push_back(
773 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
774 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
775 }
776 if (DS.isInlineSpecified()) {
777 BadSpecifiers.push_back("inline");
778 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
779 }
780 if (!BadSpecifiers.empty()) {
781 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
782 Err << (int)BadSpecifiers.size()
783 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
784 // Don't add FixItHints to remove the specifiers; we do still respect
785 // them when building the underlying variable.
786 for (auto Loc : BadSpecifierLocs)
787 Err << SourceRange(Loc, Loc);
788 } else if (!CPlusPlus20Specifiers.empty()) {
789 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
790 getLangOpts().CPlusPlus20
791 ? diag::warn_cxx17_compat_decomp_decl_spec
792 : diag::ext_decomp_decl_spec);
793 Warn << (int)CPlusPlus20Specifiers.size()
794 << llvm::join(CPlusPlus20Specifiers.begin(),
795 CPlusPlus20Specifiers.end(), " ");
796 for (auto Loc : CPlusPlus20SpecifierLocs)
797 Warn << SourceRange(Loc, Loc);
798 }
799 // We can't recover from it being declared as a typedef.
800 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
801 return nullptr;
802 }
803
804 // C++2a [dcl.struct.bind]p1:
805 // A cv that includes volatile is deprecated
806 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
807 getLangOpts().CPlusPlus20)
808 Diag(DS.getVolatileSpecLoc(),
809 diag::warn_deprecated_volatile_structured_binding);
810
811 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
812 QualType R = TInfo->getType();
813
814 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
815 UPPC_DeclarationType))
816 D.setInvalidType();
817
818 // The syntax only allows a single ref-qualifier prior to the decomposition
819 // declarator. No other declarator chunks are permitted. Also check the type
820 // specifier here.
821 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
822 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
823 (D.getNumTypeObjects() == 1 &&
824 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
825 Diag(Decomp.getLSquareLoc(),
826 (D.hasGroupingParens() ||
827 (D.getNumTypeObjects() &&
828 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
829 ? diag::err_decomp_decl_parens
830 : diag::err_decomp_decl_type)
831 << R;
832
833 // In most cases, there's no actual problem with an explicitly-specified
834 // type, but a function type won't work here, and ActOnVariableDeclarator
835 // shouldn't be called for such a type.
836 if (R->isFunctionType())
837 D.setInvalidType();
838 }
839
840 // Build the BindingDecls.
841 SmallVector<BindingDecl*, 8> Bindings;
842
843 // Build the BindingDecls.
844 for (auto &B : D.getDecompositionDeclarator().bindings()) {
845 // Check for name conflicts.
846 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848 ForVisibleRedeclaration);
849 LookupName(Previous, S,
850 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
851
852 // It's not permitted to shadow a template parameter name.
853 if (Previous.isSingleResult() &&
854 Previous.getFoundDecl()->isTemplateParameter()) {
855 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
856 Previous.getFoundDecl());
857 Previous.clear();
858 }
859
860 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
861 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
862 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
863 /*AllowInlineNamespace*/false);
864 if (!Previous.empty()) {
865 auto *Old = Previous.getRepresentativeDecl();
866 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
867 Diag(Old->getLocation(), diag::note_previous_definition);
868 }
869
870 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
871 PushOnScopeChains(BD, S, true);
872 Bindings.push_back(BD);
873 ParsingInitForAutoVars.insert(BD);
874 }
875
876 // There are no prior lookup results for the variable itself, because it
877 // is unnamed.
878 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
879 Decomp.getLSquareLoc());
880 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
881 ForVisibleRedeclaration);
882
883 // Build the variable that holds the non-decomposed object.
884 bool AddToScope = true;
885 NamedDecl *New =
886 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
887 MultiTemplateParamsArg(), AddToScope, Bindings);
888 if (AddToScope) {
889 S->AddDecl(New);
890 CurContext->addHiddenDecl(New);
891 }
892
893 if (isInOpenMPDeclareTargetContext())
894 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
895
896 return New;
897}
898
899static bool checkSimpleDecomposition(
900 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
901 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
902 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
903 if ((int64_t)Bindings.size() != NumElems) {
904 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
905 << DecompType << (unsigned)Bindings.size()
906 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U)) << NumElems.toString(10)
907 << (NumElems < Bindings.size());
908 return true;
909 }
910
911 unsigned I = 0;
912 for (auto *B : Bindings) {
913 SourceLocation Loc = B->getLocation();
914 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
915 if (E.isInvalid())
916 return true;
917 E = GetInit(Loc, E.get(), I++);
918 if (E.isInvalid())
919 return true;
920 B->setBinding(ElemType, E.get());
921 }
922
923 return false;
924}
925
926static bool checkArrayLikeDecomposition(Sema &S,
927 ArrayRef<BindingDecl *> Bindings,
928 ValueDecl *Src, QualType DecompType,
929 const llvm::APSInt &NumElems,
930 QualType ElemType) {
931 return checkSimpleDecomposition(
932 S, Bindings, Src, DecompType, NumElems, ElemType,
933 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
934 ExprResult E = S.ActOnIntegerConstant(Loc, I);
935 if (E.isInvalid())
936 return ExprError();
937 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
938 });
939}
940
941static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
942 ValueDecl *Src, QualType DecompType,
943 const ConstantArrayType *CAT) {
944 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
945 llvm::APSInt(CAT->getSize()),
946 CAT->getElementType());
947}
948
949static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
950 ValueDecl *Src, QualType DecompType,
951 const VectorType *VT) {
952 return checkArrayLikeDecomposition(
953 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
954 S.Context.getQualifiedType(VT->getElementType(),
955 DecompType.getQualifiers()));
956}
957
958static bool checkComplexDecomposition(Sema &S,
959 ArrayRef<BindingDecl *> Bindings,
960 ValueDecl *Src, QualType DecompType,
961 const ComplexType *CT) {
962 return checkSimpleDecomposition(
963 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
964 S.Context.getQualifiedType(CT->getElementType(),
965 DecompType.getQualifiers()),
966 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
967 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
968 });
969}
970
971static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
972 TemplateArgumentListInfo &Args) {
973 SmallString<128> SS;
974 llvm::raw_svector_ostream OS(SS);
975 bool First = true;
976 for (auto &Arg : Args.arguments()) {
977 if (!First)
978 OS << ", ";
979 Arg.getArgument().print(PrintingPolicy, OS);
980 First = false;
981 }
982 return std::string(OS.str());
983}
984
985static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
986 SourceLocation Loc, StringRef Trait,
987 TemplateArgumentListInfo &Args,
988 unsigned DiagID) {
989 auto DiagnoseMissing = [&] {
990 if (DiagID)
991 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
992 Args);
993 return true;
994 };
995
996 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
997 NamespaceDecl *Std = S.getStdNamespace();
998 if (!Std)
999 return DiagnoseMissing();
1000
1001 // Look up the trait itself, within namespace std. We can diagnose various
1002 // problems with this lookup even if we've been asked to not diagnose a
1003 // missing specialization, because this can only fail if the user has been
1004 // declaring their own names in namespace std or we don't support the
1005 // standard library implementation in use.
1006 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1007 Loc, Sema::LookupOrdinaryName);
1008 if (!S.LookupQualifiedName(Result, Std))
1009 return DiagnoseMissing();
1010 if (Result.isAmbiguous())
1011 return true;
1012
1013 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1014 if (!TraitTD) {
1015 Result.suppressDiagnostics();
1016 NamedDecl *Found = *Result.begin();
1017 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1018 S.Diag(Found->getLocation(), diag::note_declared_at);
1019 return true;
1020 }
1021
1022 // Build the template-id.
1023 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1024 if (TraitTy.isNull())
1025 return true;
1026 if (!S.isCompleteType(Loc, TraitTy)) {
1027 if (DiagID)
1028 S.RequireCompleteType(
1029 Loc, TraitTy, DiagID,
1030 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1031 return true;
1032 }
1033
1034 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1035 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1035, __PRETTY_FUNCTION__))
;
1036
1037 // Look up the member of the trait type.
1038 S.LookupQualifiedName(TraitMemberLookup, RD);
1039 return TraitMemberLookup.isAmbiguous();
1040}
1041
1042static TemplateArgumentLoc
1043getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1044 uint64_t I) {
1045 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1046 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1047}
1048
1049static TemplateArgumentLoc
1050getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1051 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1052}
1053
1054namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1055
1056static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1057 llvm::APSInt &Size) {
1058 EnterExpressionEvaluationContext ContextRAII(
1059 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1060
1061 DeclarationName Value = S.PP.getIdentifierInfo("value");
1062 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1063
1064 // Form template argument list for tuple_size<T>.
1065 TemplateArgumentListInfo Args(Loc, Loc);
1066 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1067
1068 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1069 // it's not tuple-like.
1070 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1071 R.empty())
1072 return IsTupleLike::NotTupleLike;
1073
1074 // If we get this far, we've committed to the tuple interpretation, but
1075 // we can still fail if there actually isn't a usable ::value.
1076
1077 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1078 LookupResult &R;
1079 TemplateArgumentListInfo &Args;
1080 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1081 : R(R), Args(Args) {}
1082 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1083 SourceLocation Loc) override {
1084 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1085 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1086 }
1087 } Diagnoser(R, Args);
1088
1089 ExprResult E =
1090 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1091 if (E.isInvalid())
1092 return IsTupleLike::Error;
1093
1094 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1095 if (E.isInvalid())
1096 return IsTupleLike::Error;
1097
1098 return IsTupleLike::TupleLike;
1099}
1100
1101/// \return std::tuple_element<I, T>::type.
1102static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1103 unsigned I, QualType T) {
1104 // Form template argument list for tuple_element<I, T>.
1105 TemplateArgumentListInfo Args(Loc, Loc);
1106 Args.addArgument(
1107 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1108 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1109
1110 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1111 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1112 if (lookupStdTypeTraitMember(
1113 S, R, Loc, "tuple_element", Args,
1114 diag::err_decomp_decl_std_tuple_element_not_specialized))
1115 return QualType();
1116
1117 auto *TD = R.getAsSingle<TypeDecl>();
1118 if (!TD) {
1119 R.suppressDiagnostics();
1120 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1121 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1122 if (!R.empty())
1123 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1124 return QualType();
1125 }
1126
1127 return S.Context.getTypeDeclType(TD);
1128}
1129
1130namespace {
1131struct InitializingBinding {
1132 Sema &S;
1133 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1134 Sema::CodeSynthesisContext Ctx;
1135 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1136 Ctx.PointOfInstantiation = BD->getLocation();
1137 Ctx.Entity = BD;
1138 S.pushCodeSynthesisContext(Ctx);
1139 }
1140 ~InitializingBinding() {
1141 S.popCodeSynthesisContext();
1142 }
1143};
1144}
1145
1146static bool checkTupleLikeDecomposition(Sema &S,
1147 ArrayRef<BindingDecl *> Bindings,
1148 VarDecl *Src, QualType DecompType,
1149 const llvm::APSInt &TupleSize) {
1150 if ((int64_t)Bindings.size() != TupleSize) {
1151 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1152 << DecompType << (unsigned)Bindings.size()
1153 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1154 << TupleSize.toString(10) << (TupleSize < Bindings.size());
1155 return true;
1156 }
1157
1158 if (Bindings.empty())
1159 return false;
1160
1161 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1162
1163 // [dcl.decomp]p3:
1164 // The unqualified-id get is looked up in the scope of E by class member
1165 // access lookup ...
1166 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1167 bool UseMemberGet = false;
1168 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1169 if (auto *RD = DecompType->getAsCXXRecordDecl())
1170 S.LookupQualifiedName(MemberGet, RD);
1171 if (MemberGet.isAmbiguous())
1172 return true;
1173 // ... and if that finds at least one declaration that is a function
1174 // template whose first template parameter is a non-type parameter ...
1175 for (NamedDecl *D : MemberGet) {
1176 if (FunctionTemplateDecl *FTD =
1177 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1178 TemplateParameterList *TPL = FTD->getTemplateParameters();
1179 if (TPL->size() != 0 &&
1180 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1181 // ... the initializer is e.get<i>().
1182 UseMemberGet = true;
1183 break;
1184 }
1185 }
1186 }
1187 }
1188
1189 unsigned I = 0;
1190 for (auto *B : Bindings) {
1191 InitializingBinding InitContext(S, B);
1192 SourceLocation Loc = B->getLocation();
1193
1194 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1195 if (E.isInvalid())
1196 return true;
1197
1198 // e is an lvalue if the type of the entity is an lvalue reference and
1199 // an xvalue otherwise
1200 if (!Src->getType()->isLValueReferenceType())
1201 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1202 E.get(), nullptr, VK_XValue,
1203 FPOptionsOverride());
1204
1205 TemplateArgumentListInfo Args(Loc, Loc);
1206 Args.addArgument(
1207 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1208
1209 if (UseMemberGet) {
1210 // if [lookup of member get] finds at least one declaration, the
1211 // initializer is e.get<i-1>().
1212 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1213 CXXScopeSpec(), SourceLocation(), nullptr,
1214 MemberGet, &Args, nullptr);
1215 if (E.isInvalid())
1216 return true;
1217
1218 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1219 } else {
1220 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1221 // in the associated namespaces.
1222 Expr *Get = UnresolvedLookupExpr::Create(
1223 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1224 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1225 UnresolvedSetIterator(), UnresolvedSetIterator());
1226
1227 Expr *Arg = E.get();
1228 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1229 }
1230 if (E.isInvalid())
1231 return true;
1232 Expr *Init = E.get();
1233
1234 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1235 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1236 if (T.isNull())
1237 return true;
1238
1239 // each vi is a variable of type "reference to T" initialized with the
1240 // initializer, where the reference is an lvalue reference if the
1241 // initializer is an lvalue and an rvalue reference otherwise
1242 QualType RefType =
1243 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1244 if (RefType.isNull())
1245 return true;
1246 auto *RefVD = VarDecl::Create(
1247 S.Context, Src->getDeclContext(), Loc, Loc,
1248 B->getDeclName().getAsIdentifierInfo(), RefType,
1249 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1250 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1251 RefVD->setTSCSpec(Src->getTSCSpec());
1252 RefVD->setImplicit();
1253 if (Src->isInlineSpecified())
1254 RefVD->setInlineSpecified();
1255 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1256
1257 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1258 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1259 InitializationSequence Seq(S, Entity, Kind, Init);
1260 E = Seq.Perform(S, Entity, Kind, Init);
1261 if (E.isInvalid())
1262 return true;
1263 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1264 if (E.isInvalid())
1265 return true;
1266 RefVD->setInit(E.get());
1267 S.CheckCompleteVariableDeclaration(RefVD);
1268
1269 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1270 DeclarationNameInfo(B->getDeclName(), Loc),
1271 RefVD);
1272 if (E.isInvalid())
1273 return true;
1274
1275 B->setBinding(T, E.get());
1276 I++;
1277 }
1278
1279 return false;
1280}
1281
1282/// Find the base class to decompose in a built-in decomposition of a class type.
1283/// This base class search is, unfortunately, not quite like any other that we
1284/// perform anywhere else in C++.
1285static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1286 const CXXRecordDecl *RD,
1287 CXXCastPath &BasePath) {
1288 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1289 CXXBasePath &Path) {
1290 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1291 };
1292
1293 const CXXRecordDecl *ClassWithFields = nullptr;
1294 AccessSpecifier AS = AS_public;
1295 if (RD->hasDirectFields())
1296 // [dcl.decomp]p4:
1297 // Otherwise, all of E's non-static data members shall be public direct
1298 // members of E ...
1299 ClassWithFields = RD;
1300 else {
1301 // ... or of ...
1302 CXXBasePaths Paths;
1303 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1304 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1305 // If no classes have fields, just decompose RD itself. (This will work
1306 // if and only if zero bindings were provided.)
1307 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1308 }
1309
1310 CXXBasePath *BestPath = nullptr;
1311 for (auto &P : Paths) {
1312 if (!BestPath)
1313 BestPath = &P;
1314 else if (!S.Context.hasSameType(P.back().Base->getType(),
1315 BestPath->back().Base->getType())) {
1316 // ... the same ...
1317 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1318 << false << RD << BestPath->back().Base->getType()
1319 << P.back().Base->getType();
1320 return DeclAccessPair();
1321 } else if (P.Access < BestPath->Access) {
1322 BestPath = &P;
1323 }
1324 }
1325
1326 // ... unambiguous ...
1327 QualType BaseType = BestPath->back().Base->getType();
1328 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1329 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1330 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1331 return DeclAccessPair();
1332 }
1333
1334 // ... [accessible, implied by other rules] base class of E.
1335 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1336 *BestPath, diag::err_decomp_decl_inaccessible_base);
1337 AS = BestPath->Access;
1338
1339 ClassWithFields = BaseType->getAsCXXRecordDecl();
1340 S.BuildBasePathArray(Paths, BasePath);
1341 }
1342
1343 // The above search did not check whether the selected class itself has base
1344 // classes with fields, so check that now.
1345 CXXBasePaths Paths;
1346 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1347 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1348 << (ClassWithFields == RD) << RD << ClassWithFields
1349 << Paths.front().back().Base->getType();
1350 return DeclAccessPair();
1351 }
1352
1353 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1354}
1355
1356static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1357 ValueDecl *Src, QualType DecompType,
1358 const CXXRecordDecl *OrigRD) {
1359 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1360 diag::err_incomplete_type))
1361 return true;
1362
1363 CXXCastPath BasePath;
1364 DeclAccessPair BasePair =
1365 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1366 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1367 if (!RD)
1368 return true;
1369 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1370 DecompType.getQualifiers());
1371
1372 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1373 unsigned NumFields =
1374 std::count_if(RD->field_begin(), RD->field_end(),
1375 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1376 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1376, __PRETTY_FUNCTION__))
;
1377 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1378 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1379 << (NumFields < Bindings.size());
1380 return true;
1381 };
1382
1383 // all of E's non-static data members shall be [...] well-formed
1384 // when named as e.name in the context of the structured binding,
1385 // E shall not have an anonymous union member, ...
1386 unsigned I = 0;
1387 for (auto *FD : RD->fields()) {
1388 if (FD->isUnnamedBitfield())
1389 continue;
1390
1391 // All the non-static data members are required to be nameable, so they
1392 // must all have names.
1393 if (!FD->getDeclName()) {
1394 if (RD->isLambda()) {
1395 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1396 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1397 return true;
1398 }
1399
1400 if (FD->isAnonymousStructOrUnion()) {
1401 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1402 << DecompType << FD->getType()->isUnionType();
1403 S.Diag(FD->getLocation(), diag::note_declared_at);
1404 return true;
1405 }
1406
1407 // FIXME: Are there any other ways we could have an anonymous member?
1408 }
1409
1410 // We have a real field to bind.
1411 if (I >= Bindings.size())
1412 return DiagnoseBadNumberOfBindings();
1413 auto *B = Bindings[I++];
1414 SourceLocation Loc = B->getLocation();
1415
1416 // The field must be accessible in the context of the structured binding.
1417 // We already checked that the base class is accessible.
1418 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1419 // const_cast here.
1420 S.CheckStructuredBindingMemberAccess(
1421 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1422 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1423 BasePair.getAccess(), FD->getAccess())));
1424
1425 // Initialize the binding to Src.FD.
1426 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1427 if (E.isInvalid())
1428 return true;
1429 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1430 VK_LValue, &BasePath);
1431 if (E.isInvalid())
1432 return true;
1433 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1434 CXXScopeSpec(), FD,
1435 DeclAccessPair::make(FD, FD->getAccess()),
1436 DeclarationNameInfo(FD->getDeclName(), Loc));
1437 if (E.isInvalid())
1438 return true;
1439
1440 // If the type of the member is T, the referenced type is cv T, where cv is
1441 // the cv-qualification of the decomposition expression.
1442 //
1443 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1444 // 'const' to the type of the field.
1445 Qualifiers Q = DecompType.getQualifiers();
1446 if (FD->isMutable())
1447 Q.removeConst();
1448 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1449 }
1450
1451 if (I != Bindings.size())
1452 return DiagnoseBadNumberOfBindings();
1453
1454 return false;
1455}
1456
1457void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1458 QualType DecompType = DD->getType();
1459
1460 // If the type of the decomposition is dependent, then so is the type of
1461 // each binding.
1462 if (DecompType->isDependentType()) {
1463 for (auto *B : DD->bindings())
1464 B->setType(Context.DependentTy);
1465 return;
1466 }
1467
1468 DecompType = DecompType.getNonReferenceType();
1469 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1470
1471 // C++1z [dcl.decomp]/2:
1472 // If E is an array type [...]
1473 // As an extension, we also support decomposition of built-in complex and
1474 // vector types.
1475 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1476 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1477 DD->setInvalidDecl();
1478 return;
1479 }
1480 if (auto *VT = DecompType->getAs<VectorType>()) {
1481 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1482 DD->setInvalidDecl();
1483 return;
1484 }
1485 if (auto *CT = DecompType->getAs<ComplexType>()) {
1486 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1487 DD->setInvalidDecl();
1488 return;
1489 }
1490
1491 // C++1z [dcl.decomp]/3:
1492 // if the expression std::tuple_size<E>::value is a well-formed integral
1493 // constant expression, [...]
1494 llvm::APSInt TupleSize(32);
1495 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1496 case IsTupleLike::Error:
1497 DD->setInvalidDecl();
1498 return;
1499
1500 case IsTupleLike::TupleLike:
1501 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1502 DD->setInvalidDecl();
1503 return;
1504
1505 case IsTupleLike::NotTupleLike:
1506 break;
1507 }
1508
1509 // C++1z [dcl.dcl]/8:
1510 // [E shall be of array or non-union class type]
1511 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1512 if (!RD || RD->isUnion()) {
1513 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1514 << DD << !RD << DecompType;
1515 DD->setInvalidDecl();
1516 return;
1517 }
1518
1519 // C++1z [dcl.decomp]/4:
1520 // all of E's non-static data members shall be [...] direct members of
1521 // E or of the same unambiguous public base class of E, ...
1522 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1523 DD->setInvalidDecl();
1524}
1525
1526/// Merge the exception specifications of two variable declarations.
1527///
1528/// This is called when there's a redeclaration of a VarDecl. The function
1529/// checks if the redeclaration might have an exception specification and
1530/// validates compatibility and merges the specs if necessary.
1531void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1532 // Shortcut if exceptions are disabled.
1533 if (!getLangOpts().CXXExceptions)
1534 return;
1535
1536 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1537, __PRETTY_FUNCTION__))
1537 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1537, __PRETTY_FUNCTION__))
;
1538
1539 QualType NewType = New->getType();
1540 QualType OldType = Old->getType();
1541
1542 // We're only interested in pointers and references to functions, as well
1543 // as pointers to member functions.
1544 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1545 NewType = R->getPointeeType();
1546 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1547 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1548 NewType = P->getPointeeType();
1549 OldType = OldType->castAs<PointerType>()->getPointeeType();
1550 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1551 NewType = M->getPointeeType();
1552 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1553 }
1554
1555 if (!NewType->isFunctionProtoType())
1556 return;
1557
1558 // There's lots of special cases for functions. For function pointers, system
1559 // libraries are hopefully not as broken so that we don't need these
1560 // workarounds.
1561 if (CheckEquivalentExceptionSpec(
1562 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1563 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1564 New->setInvalidDecl();
1565 }
1566}
1567
1568/// CheckCXXDefaultArguments - Verify that the default arguments for a
1569/// function declaration are well-formed according to C++
1570/// [dcl.fct.default].
1571void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1572 unsigned NumParams = FD->getNumParams();
1573 unsigned ParamIdx = 0;
1574
1575 // This checking doesn't make sense for explicit specializations; their
1576 // default arguments are determined by the declaration we're specializing,
1577 // not by FD.
1578 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1579 return;
1580 if (auto *FTD = FD->getDescribedFunctionTemplate())
1581 if (FTD->isMemberSpecialization())
1582 return;
1583
1584 // Find first parameter with a default argument
1585 for (; ParamIdx < NumParams; ++ParamIdx) {
1586 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1587 if (Param->hasDefaultArg())
1588 break;
1589 }
1590
1591 // C++20 [dcl.fct.default]p4:
1592 // In a given function declaration, each parameter subsequent to a parameter
1593 // with a default argument shall have a default argument supplied in this or
1594 // a previous declaration, unless the parameter was expanded from a
1595 // parameter pack, or shall be a function parameter pack.
1596 for (; ParamIdx < NumParams; ++ParamIdx) {
1597 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1598 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1599 !(CurrentInstantiationScope &&
1600 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1601 if (Param->isInvalidDecl())
1602 /* We already complained about this parameter. */;
1603 else if (Param->getIdentifier())
1604 Diag(Param->getLocation(),
1605 diag::err_param_default_argument_missing_name)
1606 << Param->getIdentifier();
1607 else
1608 Diag(Param->getLocation(),
1609 diag::err_param_default_argument_missing);
1610 }
1611 }
1612}
1613
1614/// Check that the given type is a literal type. Issue a diagnostic if not,
1615/// if Kind is Diagnose.
1616/// \return \c true if a problem has been found (and optionally diagnosed).
1617template <typename... Ts>
1618static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1619 SourceLocation Loc, QualType T, unsigned DiagID,
1620 Ts &&...DiagArgs) {
1621 if (T->isDependentType())
1622 return false;
1623
1624 switch (Kind) {
1625 case Sema::CheckConstexprKind::Diagnose:
1626 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1627 std::forward<Ts>(DiagArgs)...);
1628
1629 case Sema::CheckConstexprKind::CheckValid:
1630 return !T->isLiteralType(SemaRef.Context);
1631 }
1632
1633 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1633)
;
1634}
1635
1636/// Determine whether a destructor cannot be constexpr due to
1637static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1638 const CXXDestructorDecl *DD,
1639 Sema::CheckConstexprKind Kind) {
1640 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1641 const CXXRecordDecl *RD =
1642 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1643 if (!RD || RD->hasConstexprDestructor())
1644 return true;
1645
1646 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1647 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1648 << static_cast<int>(DD->getConstexprKind()) << !FD
1649 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1650 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1651 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1652 }
1653 return false;
1654 };
1655
1656 const CXXRecordDecl *RD = DD->getParent();
1657 for (const CXXBaseSpecifier &B : RD->bases())
1658 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1659 return false;
1660 for (const FieldDecl *FD : RD->fields())
1661 if (!Check(FD->getLocation(), FD->getType(), FD))
1662 return false;
1663 return true;
1664}
1665
1666/// Check whether a function's parameter types are all literal types. If so,
1667/// return true. If not, produce a suitable diagnostic and return false.
1668static bool CheckConstexprParameterTypes(Sema &SemaRef,
1669 const FunctionDecl *FD,
1670 Sema::CheckConstexprKind Kind) {
1671 unsigned ArgIndex = 0;
1672 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1673 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1674 e = FT->param_type_end();
1675 i != e; ++i, ++ArgIndex) {
1676 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1677 SourceLocation ParamLoc = PD->getLocation();
1678 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1679 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1680 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1681 FD->isConsteval()))
1682 return false;
1683 }
1684 return true;
1685}
1686
1687/// Check whether a function's return type is a literal type. If so, return
1688/// true. If not, produce a suitable diagnostic and return false.
1689static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1690 Sema::CheckConstexprKind Kind) {
1691 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1692 diag::err_constexpr_non_literal_return,
1693 FD->isConsteval()))
1694 return false;
1695 return true;
1696}
1697
1698/// Get diagnostic %select index for tag kind for
1699/// record diagnostic message.
1700/// WARNING: Indexes apply to particular diagnostics only!
1701///
1702/// \returns diagnostic %select index.
1703static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1704 switch (Tag) {
1705 case TTK_Struct: return 0;
1706 case TTK_Interface: return 1;
1707 case TTK_Class: return 2;
1708 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1708)
;
1709 }
1710}
1711
1712static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1713 Stmt *Body,
1714 Sema::CheckConstexprKind Kind);
1715
1716// Check whether a function declaration satisfies the requirements of a
1717// constexpr function definition or a constexpr constructor definition. If so,
1718// return true. If not, produce appropriate diagnostics (unless asked not to by
1719// Kind) and return false.
1720//
1721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1722bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1723 CheckConstexprKind Kind) {
1724 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1725 if (MD && MD->isInstance()) {
1726 // C++11 [dcl.constexpr]p4:
1727 // The definition of a constexpr constructor shall satisfy the following
1728 // constraints:
1729 // - the class shall not have any virtual base classes;
1730 //
1731 // FIXME: This only applies to constructors and destructors, not arbitrary
1732 // member functions.
1733 const CXXRecordDecl *RD = MD->getParent();
1734 if (RD->getNumVBases()) {
1735 if (Kind == CheckConstexprKind::CheckValid)
1736 return false;
1737
1738 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1739 << isa<CXXConstructorDecl>(NewFD)
1740 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1741 for (const auto &I : RD->vbases())
1742 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1743 << I.getSourceRange();
1744 return false;
1745 }
1746 }
1747
1748 if (!isa<CXXConstructorDecl>(NewFD)) {
1749 // C++11 [dcl.constexpr]p3:
1750 // The definition of a constexpr function shall satisfy the following
1751 // constraints:
1752 // - it shall not be virtual; (removed in C++20)
1753 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1754 if (Method && Method->isVirtual()) {
1755 if (getLangOpts().CPlusPlus20) {
1756 if (Kind == CheckConstexprKind::Diagnose)
1757 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1758 } else {
1759 if (Kind == CheckConstexprKind::CheckValid)
1760 return false;
1761
1762 Method = Method->getCanonicalDecl();
1763 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1764
1765 // If it's not obvious why this function is virtual, find an overridden
1766 // function which uses the 'virtual' keyword.
1767 const CXXMethodDecl *WrittenVirtual = Method;
1768 while (!WrittenVirtual->isVirtualAsWritten())
1769 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1770 if (WrittenVirtual != Method)
1771 Diag(WrittenVirtual->getLocation(),
1772 diag::note_overridden_virtual_function);
1773 return false;
1774 }
1775 }
1776
1777 // - its return type shall be a literal type;
1778 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1779 return false;
1780 }
1781
1782 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1783 // A destructor can be constexpr only if the defaulted destructor could be;
1784 // we don't need to check the members and bases if we already know they all
1785 // have constexpr destructors.
1786 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1787 if (Kind == CheckConstexprKind::CheckValid)
1788 return false;
1789 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1790 return false;
1791 }
1792 }
1793
1794 // - each of its parameter types shall be a literal type;
1795 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1796 return false;
1797
1798 Stmt *Body = NewFD->getBody();
1799 assert(Body &&((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
1800 "CheckConstexprFunctionDefinition called on function with no body")((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
;
1801 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1802}
1803
1804/// Check the given declaration statement is legal within a constexpr function
1805/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1806///
1807/// \return true if the body is OK (maybe only as an extension), false if we
1808/// have diagnosed a problem.
1809static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1810 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1811 Sema::CheckConstexprKind Kind) {
1812 // C++11 [dcl.constexpr]p3 and p4:
1813 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1814 // contain only
1815 for (const auto *DclIt : DS->decls()) {
1816 switch (DclIt->getKind()) {
1817 case Decl::StaticAssert:
1818 case Decl::Using:
1819 case Decl::UsingShadow:
1820 case Decl::UsingDirective:
1821 case Decl::UnresolvedUsingTypename:
1822 case Decl::UnresolvedUsingValue:
1823 // - static_assert-declarations
1824 // - using-declarations,
1825 // - using-directives,
1826 continue;
1827
1828 case Decl::Typedef:
1829 case Decl::TypeAlias: {
1830 // - typedef declarations and alias-declarations that do not define
1831 // classes or enumerations,
1832 const auto *TN = cast<TypedefNameDecl>(DclIt);
1833 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1834 // Don't allow variably-modified types in constexpr functions.
1835 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1836 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1837 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1838 << TL.getSourceRange() << TL.getType()
1839 << isa<CXXConstructorDecl>(Dcl);
1840 }
1841 return false;
1842 }
1843 continue;
1844 }
1845
1846 case Decl::Enum:
1847 case Decl::CXXRecord:
1848 // C++1y allows types to be defined, not just declared.
1849 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1850 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851 SemaRef.Diag(DS->getBeginLoc(),
1852 SemaRef.getLangOpts().CPlusPlus14
1853 ? diag::warn_cxx11_compat_constexpr_type_definition
1854 : diag::ext_constexpr_type_definition)
1855 << isa<CXXConstructorDecl>(Dcl);
1856 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1857 return false;
1858 }
1859 }
1860 continue;
1861
1862 case Decl::EnumConstant:
1863 case Decl::IndirectField:
1864 case Decl::ParmVar:
1865 // These can only appear with other declarations which are banned in
1866 // C++11 and permitted in C++1y, so ignore them.
1867 continue;
1868
1869 case Decl::Var:
1870 case Decl::Decomposition: {
1871 // C++1y [dcl.constexpr]p3 allows anything except:
1872 // a definition of a variable of non-literal type or of static or
1873 // thread storage duration or [before C++2a] for which no
1874 // initialization is performed.
1875 const auto *VD = cast<VarDecl>(DclIt);
1876 if (VD->isThisDeclarationADefinition()) {
1877 if (VD->isStaticLocal()) {
1878 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879 SemaRef.Diag(VD->getLocation(),
1880 diag::err_constexpr_local_var_static)
1881 << isa<CXXConstructorDecl>(Dcl)
1882 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1883 }
1884 return false;
1885 }
1886 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1887 diag::err_constexpr_local_var_non_literal_type,
1888 isa<CXXConstructorDecl>(Dcl)))
1889 return false;
1890 if (!VD->getType()->isDependentType() &&
1891 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1892 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1893 SemaRef.Diag(
1894 VD->getLocation(),
1895 SemaRef.getLangOpts().CPlusPlus20
1896 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1897 : diag::ext_constexpr_local_var_no_init)
1898 << isa<CXXConstructorDecl>(Dcl);
1899 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1900 return false;
1901 }
1902 continue;
1903 }
1904 }
1905 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1906 SemaRef.Diag(VD->getLocation(),
1907 SemaRef.getLangOpts().CPlusPlus14
1908 ? diag::warn_cxx11_compat_constexpr_local_var
1909 : diag::ext_constexpr_local_var)
1910 << isa<CXXConstructorDecl>(Dcl);
1911 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1912 return false;
1913 }
1914 continue;
1915 }
1916
1917 case Decl::NamespaceAlias:
1918 case Decl::Function:
1919 // These are disallowed in C++11 and permitted in C++1y. Allow them
1920 // everywhere as an extension.
1921 if (!Cxx1yLoc.isValid())
1922 Cxx1yLoc = DS->getBeginLoc();
1923 continue;
1924
1925 default:
1926 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1927 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1928 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1929 }
1930 return false;
1931 }
1932 }
1933
1934 return true;
1935}
1936
1937/// Check that the given field is initialized within a constexpr constructor.
1938///
1939/// \param Dcl The constexpr constructor being checked.
1940/// \param Field The field being checked. This may be a member of an anonymous
1941/// struct or union nested within the class being checked.
1942/// \param Inits All declarations, including anonymous struct/union members and
1943/// indirect members, for which any initialization was provided.
1944/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1945/// multiple notes for different members to the same error.
1946/// \param Kind Whether we're diagnosing a constructor as written or determining
1947/// whether the formal requirements are satisfied.
1948/// \return \c false if we're checking for validity and the constructor does
1949/// not satisfy the requirements on a constexpr constructor.
1950static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1951 const FunctionDecl *Dcl,
1952 FieldDecl *Field,
1953 llvm::SmallSet<Decl*, 16> &Inits,
1954 bool &Diagnosed,
1955 Sema::CheckConstexprKind Kind) {
1956 // In C++20 onwards, there's nothing to check for validity.
1957 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1958 SemaRef.getLangOpts().CPlusPlus20)
1959 return true;
1960
1961 if (Field->isInvalidDecl())
1962 return true;
1963
1964 if (Field->isUnnamedBitfield())
1965 return true;
1966
1967 // Anonymous unions with no variant members and empty anonymous structs do not
1968 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1969 // indirect fields don't need initializing.
1970 if (Field->isAnonymousStructOrUnion() &&
1971 (Field->getType()->isUnionType()
1972 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1973 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1974 return true;
1975
1976 if (!Inits.count(Field)) {
1977 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1978 if (!Diagnosed) {
1979 SemaRef.Diag(Dcl->getLocation(),
1980 SemaRef.getLangOpts().CPlusPlus20
1981 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1982 : diag::ext_constexpr_ctor_missing_init);
1983 Diagnosed = true;
1984 }
1985 SemaRef.Diag(Field->getLocation(),
1986 diag::note_constexpr_ctor_missing_init);
1987 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1988 return false;
1989 }
1990 } else if (Field->isAnonymousStructOrUnion()) {
1991 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1992 for (auto *I : RD->fields())
1993 // If an anonymous union contains an anonymous struct of which any member
1994 // is initialized, all members must be initialized.
1995 if (!RD->isUnion() || Inits.count(I))
1996 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1997 Kind))
1998 return false;
1999 }
2000 return true;
2001}
2002
2003/// Check the provided statement is allowed in a constexpr function
2004/// definition.
2005static bool
2006CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2007 SmallVectorImpl<SourceLocation> &ReturnStmts,
2008 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2009 Sema::CheckConstexprKind Kind) {
2010 // - its function-body shall be [...] a compound-statement that contains only
2011 switch (S->getStmtClass()) {
2012 case Stmt::NullStmtClass:
2013 // - null statements,
2014 return true;
2015
2016 case Stmt::DeclStmtClass:
2017 // - static_assert-declarations
2018 // - using-declarations,
2019 // - using-directives,
2020 // - typedef declarations and alias-declarations that do not define
2021 // classes or enumerations,
2022 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2023 return false;
2024 return true;
2025
2026 case Stmt::ReturnStmtClass:
2027 // - and exactly one return statement;
2028 if (isa<CXXConstructorDecl>(Dcl)) {
2029 // C++1y allows return statements in constexpr constructors.
2030 if (!Cxx1yLoc.isValid())
2031 Cxx1yLoc = S->getBeginLoc();
2032 return true;
2033 }
2034
2035 ReturnStmts.push_back(S->getBeginLoc());
2036 return true;
2037
2038 case Stmt::CompoundStmtClass: {
2039 // C++1y allows compound-statements.
2040 if (!Cxx1yLoc.isValid())
2041 Cxx1yLoc = S->getBeginLoc();
2042
2043 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2044 for (auto *BodyIt : CompStmt->body()) {
2045 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2046 Cxx1yLoc, Cxx2aLoc, Kind))
2047 return false;
2048 }
2049 return true;
2050 }
2051
2052 case Stmt::AttributedStmtClass:
2053 if (!Cxx1yLoc.isValid())
2054 Cxx1yLoc = S->getBeginLoc();
2055 return true;
2056
2057 case Stmt::IfStmtClass: {
2058 // C++1y allows if-statements.
2059 if (!Cxx1yLoc.isValid())
2060 Cxx1yLoc = S->getBeginLoc();
2061
2062 IfStmt *If = cast<IfStmt>(S);
2063 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2064 Cxx1yLoc, Cxx2aLoc, Kind))
2065 return false;
2066 if (If->getElse() &&
2067 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2068 Cxx1yLoc, Cxx2aLoc, Kind))
2069 return false;
2070 return true;
2071 }
2072
2073 case Stmt::WhileStmtClass:
2074 case Stmt::DoStmtClass:
2075 case Stmt::ForStmtClass:
2076 case Stmt::CXXForRangeStmtClass:
2077 case Stmt::ContinueStmtClass:
2078 // C++1y allows all of these. We don't allow them as extensions in C++11,
2079 // because they don't make sense without variable mutation.
2080 if (!SemaRef.getLangOpts().CPlusPlus14)
2081 break;
2082 if (!Cxx1yLoc.isValid())
2083 Cxx1yLoc = S->getBeginLoc();
2084 for (Stmt *SubStmt : S->children())
2085 if (SubStmt &&
2086 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2087 Cxx1yLoc, Cxx2aLoc, Kind))
2088 return false;
2089 return true;
2090
2091 case Stmt::SwitchStmtClass:
2092 case Stmt::CaseStmtClass:
2093 case Stmt::DefaultStmtClass:
2094 case Stmt::BreakStmtClass:
2095 // C++1y allows switch-statements, and since they don't need variable
2096 // mutation, we can reasonably allow them in C++11 as an extension.
2097 if (!Cxx1yLoc.isValid())
2098 Cxx1yLoc = S->getBeginLoc();
2099 for (Stmt *SubStmt : S->children())
2100 if (SubStmt &&
2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2102 Cxx1yLoc, Cxx2aLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::GCCAsmStmtClass:
2107 case Stmt::MSAsmStmtClass:
2108 // C++2a allows inline assembly statements.
2109 case Stmt::CXXTryStmtClass:
2110 if (Cxx2aLoc.isInvalid())
2111 Cxx2aLoc = S->getBeginLoc();
2112 for (Stmt *SubStmt : S->children()) {
2113 if (SubStmt &&
2114 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2115 Cxx1yLoc, Cxx2aLoc, Kind))
2116 return false;
2117 }
2118 return true;
2119
2120 case Stmt::CXXCatchStmtClass:
2121 // Do not bother checking the language mode (already covered by the
2122 // try block check).
2123 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2124 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2125 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2126 return false;
2127 return true;
2128
2129 default:
2130 if (!isa<Expr>(S))
2131 break;
2132
2133 // C++1y allows expression-statements.
2134 if (!Cxx1yLoc.isValid())
2135 Cxx1yLoc = S->getBeginLoc();
2136 return true;
2137 }
2138
2139 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2140 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2141 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2142 }
2143 return false;
2144}
2145
2146/// Check the body for the given constexpr function declaration only contains
2147/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2148///
2149/// \return true if the body is OK, false if we have found or diagnosed a
2150/// problem.
2151static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2152 Stmt *Body,
2153 Sema::CheckConstexprKind Kind) {
2154 SmallVector<SourceLocation, 4> ReturnStmts;
2155
2156 if (isa<CXXTryStmt>(Body)) {
2157 // C++11 [dcl.constexpr]p3:
2158 // The definition of a constexpr function shall satisfy the following
2159 // constraints: [...]
2160 // - its function-body shall be = delete, = default, or a
2161 // compound-statement
2162 //
2163 // C++11 [dcl.constexpr]p4:
2164 // In the definition of a constexpr constructor, [...]
2165 // - its function-body shall not be a function-try-block;
2166 //
2167 // This restriction is lifted in C++2a, as long as inner statements also
2168 // apply the general constexpr rules.
2169 switch (Kind) {
2170 case Sema::CheckConstexprKind::CheckValid:
2171 if (!SemaRef.getLangOpts().CPlusPlus20)
2172 return false;
2173 break;
2174
2175 case Sema::CheckConstexprKind::Diagnose:
2176 SemaRef.Diag(Body->getBeginLoc(),
2177 !SemaRef.getLangOpts().CPlusPlus20
2178 ? diag::ext_constexpr_function_try_block_cxx20
2179 : diag::warn_cxx17_compat_constexpr_function_try_block)
2180 << isa<CXXConstructorDecl>(Dcl);
2181 break;
2182 }
2183 }
2184
2185 // - its function-body shall be [...] a compound-statement that contains only
2186 // [... list of cases ...]
2187 //
2188 // Note that walking the children here is enough to properly check for
2189 // CompoundStmt and CXXTryStmt body.
2190 SourceLocation Cxx1yLoc, Cxx2aLoc;
2191 for (Stmt *SubStmt : Body->children()) {
2192 if (SubStmt &&
2193 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2194 Cxx1yLoc, Cxx2aLoc, Kind))
2195 return false;
2196 }
2197
2198 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2199 // If this is only valid as an extension, report that we don't satisfy the
2200 // constraints of the current language.
2201 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2202 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2203 return false;
2204 } else if (Cxx2aLoc.isValid()) {
2205 SemaRef.Diag(Cxx2aLoc,
2206 SemaRef.getLangOpts().CPlusPlus20
2207 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2208 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2209 << isa<CXXConstructorDecl>(Dcl);
2210 } else if (Cxx1yLoc.isValid()) {
2211 SemaRef.Diag(Cxx1yLoc,
2212 SemaRef.getLangOpts().CPlusPlus14
2213 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2214 : diag::ext_constexpr_body_invalid_stmt)
2215 << isa<CXXConstructorDecl>(Dcl);
2216 }
2217
2218 if (const CXXConstructorDecl *Constructor
2219 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2220 const CXXRecordDecl *RD = Constructor->getParent();
2221 // DR1359:
2222 // - every non-variant non-static data member and base class sub-object
2223 // shall be initialized;
2224 // DR1460:
2225 // - if the class is a union having variant members, exactly one of them
2226 // shall be initialized;
2227 if (RD->isUnion()) {
2228 if (Constructor->getNumCtorInitializers() == 0 &&
2229 RD->hasVariantMembers()) {
2230 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2231 SemaRef.Diag(
2232 Dcl->getLocation(),
2233 SemaRef.getLangOpts().CPlusPlus20
2234 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2235 : diag::ext_constexpr_union_ctor_no_init);
2236 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2237 return false;
2238 }
2239 }
2240 } else if (!Constructor->isDependentContext() &&
2241 !Constructor->isDelegatingConstructor()) {
2242 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2242, __PRETTY_FUNCTION__))
;
2243
2244 // Skip detailed checking if we have enough initializers, and we would
2245 // allow at most one initializer per member.
2246 bool AnyAnonStructUnionMembers = false;
2247 unsigned Fields = 0;
2248 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2249 E = RD->field_end(); I != E; ++I, ++Fields) {
2250 if (I->isAnonymousStructOrUnion()) {
2251 AnyAnonStructUnionMembers = true;
2252 break;
2253 }
2254 }
2255 // DR1460:
2256 // - if the class is a union-like class, but is not a union, for each of
2257 // its anonymous union members having variant members, exactly one of
2258 // them shall be initialized;
2259 if (AnyAnonStructUnionMembers ||
2260 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2261 // Check initialization of non-static data members. Base classes are
2262 // always initialized so do not need to be checked. Dependent bases
2263 // might not have initializers in the member initializer list.
2264 llvm::SmallSet<Decl*, 16> Inits;
2265 for (const auto *I: Constructor->inits()) {
2266 if (FieldDecl *FD = I->getMember())
2267 Inits.insert(FD);
2268 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2269 Inits.insert(ID->chain_begin(), ID->chain_end());
2270 }
2271
2272 bool Diagnosed = false;
2273 for (auto *I : RD->fields())
2274 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2275 Kind))
2276 return false;
2277 }
2278 }
2279 } else {
2280 if (ReturnStmts.empty()) {
2281 // C++1y doesn't require constexpr functions to contain a 'return'
2282 // statement. We still do, unless the return type might be void, because
2283 // otherwise if there's no return statement, the function cannot
2284 // be used in a core constant expression.
2285 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2286 (Dcl->getReturnType()->isVoidType() ||
2287 Dcl->getReturnType()->isDependentType());
2288 switch (Kind) {
2289 case Sema::CheckConstexprKind::Diagnose:
2290 SemaRef.Diag(Dcl->getLocation(),
2291 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2292 : diag::err_constexpr_body_no_return)
2293 << Dcl->isConsteval();
2294 if (!OK)
2295 return false;
2296 break;
2297
2298 case Sema::CheckConstexprKind::CheckValid:
2299 // The formal requirements don't include this rule in C++14, even
2300 // though the "must be able to produce a constant expression" rules
2301 // still imply it in some cases.
2302 if (!SemaRef.getLangOpts().CPlusPlus14)
2303 return false;
2304 break;
2305 }
2306 } else if (ReturnStmts.size() > 1) {
2307 switch (Kind) {
2308 case Sema::CheckConstexprKind::Diagnose:
2309 SemaRef.Diag(
2310 ReturnStmts.back(),
2311 SemaRef.getLangOpts().CPlusPlus14
2312 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2313 : diag::ext_constexpr_body_multiple_return);
2314 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2315 SemaRef.Diag(ReturnStmts[I],
2316 diag::note_constexpr_body_previous_return);
2317 break;
2318
2319 case Sema::CheckConstexprKind::CheckValid:
2320 if (!SemaRef.getLangOpts().CPlusPlus14)
2321 return false;
2322 break;
2323 }
2324 }
2325 }
2326
2327 // C++11 [dcl.constexpr]p5:
2328 // if no function argument values exist such that the function invocation
2329 // substitution would produce a constant expression, the program is
2330 // ill-formed; no diagnostic required.
2331 // C++11 [dcl.constexpr]p3:
2332 // - every constructor call and implicit conversion used in initializing the
2333 // return value shall be one of those allowed in a constant expression.
2334 // C++11 [dcl.constexpr]p4:
2335 // - every constructor involved in initializing non-static data members and
2336 // base class sub-objects shall be a constexpr constructor.
2337 //
2338 // Note that this rule is distinct from the "requirements for a constexpr
2339 // function", so is not checked in CheckValid mode.
2340 SmallVector<PartialDiagnosticAt, 8> Diags;
2341 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2342 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2343 SemaRef.Diag(Dcl->getLocation(),
2344 diag::ext_constexpr_function_never_constant_expr)
2345 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2346 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2347 SemaRef.Diag(Diags[I].first, Diags[I].second);
2348 // Don't return false here: we allow this for compatibility in
2349 // system headers.
2350 }
2351
2352 return true;
2353}
2354
2355/// Get the class that is directly named by the current context. This is the
2356/// class for which an unqualified-id in this scope could name a constructor
2357/// or destructor.
2358///
2359/// If the scope specifier denotes a class, this will be that class.
2360/// If the scope specifier is empty, this will be the class whose
2361/// member-specification we are currently within. Otherwise, there
2362/// is no such class.
2363CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2364 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2364, __PRETTY_FUNCTION__))
;
2365
2366 if (SS && SS->isInvalid())
2367 return nullptr;
2368
2369 if (SS && SS->isNotEmpty()) {
2370 DeclContext *DC = computeDeclContext(*SS, true);
2371 return dyn_cast_or_null<CXXRecordDecl>(DC);
2372 }
2373
2374 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2375}
2376
2377/// isCurrentClassName - Determine whether the identifier II is the
2378/// name of the class type currently being defined. In the case of
2379/// nested classes, this will only return true if II is the name of
2380/// the innermost class.
2381bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2382 const CXXScopeSpec *SS) {
2383 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2384 return CurDecl && &II == CurDecl->getIdentifier();
2385}
2386
2387/// Determine whether the identifier II is a typo for the name of
2388/// the class type currently being defined. If so, update it to the identifier
2389/// that should have been used.
2390bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2391 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2391, __PRETTY_FUNCTION__))
;
2392
2393 if (!getLangOpts().SpellChecking)
2394 return false;
2395
2396 CXXRecordDecl *CurDecl;
2397 if (SS && SS->isSet() && !SS->isInvalid()) {
2398 DeclContext *DC = computeDeclContext(*SS, true);
2399 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2400 } else
2401 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2402
2403 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2404 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2405 < II->getLength()) {
2406 II = CurDecl->getIdentifier();
2407 return true;
2408 }
2409
2410 return false;
2411}
2412
2413/// Determine whether the given class is a base class of the given
2414/// class, including looking at dependent bases.
2415static bool findCircularInheritance(const CXXRecordDecl *Class,
2416 const CXXRecordDecl *Current) {
2417 SmallVector<const CXXRecordDecl*, 8> Queue;
2418
2419 Class = Class->getCanonicalDecl();
2420 while (true) {
2421 for (const auto &I : Current->bases()) {
2422 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2423 if (!Base)
2424 continue;
2425
2426 Base = Base->getDefinition();
2427 if (!Base)
2428 continue;
2429
2430 if (Base->getCanonicalDecl() == Class)
2431 return true;
2432
2433 Queue.push_back(Base);
2434 }
2435
2436 if (Queue.empty())
2437 return false;
2438
2439 Current = Queue.pop_back_val();
2440 }
2441
2442 return false;
2443}
2444
2445/// Check the validity of a C++ base class specifier.
2446///
2447/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2448/// and returns NULL otherwise.
2449CXXBaseSpecifier *
2450Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2451 SourceRange SpecifierRange,
2452 bool Virtual, AccessSpecifier Access,
2453 TypeSourceInfo *TInfo,
2454 SourceLocation EllipsisLoc) {
2455 QualType BaseType = TInfo->getType();
2456 if (BaseType->containsErrors()) {
2457 // Already emitted a diagnostic when parsing the error type.
2458 return nullptr;
2459 }
2460 // C++ [class.union]p1:
2461 // A union shall not have base classes.
2462 if (Class->isUnion()) {
2463 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2464 << SpecifierRange;
2465 return nullptr;
2466 }
2467
2468 if (EllipsisLoc.isValid() &&
2469 !TInfo->getType()->containsUnexpandedParameterPack()) {
2470 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2471 << TInfo->getTypeLoc().getSourceRange();
2472 EllipsisLoc = SourceLocation();
2473 }
2474
2475 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2476
2477 if (BaseType->isDependentType()) {
2478 // Make sure that we don't have circular inheritance among our dependent
2479 // bases. For non-dependent bases, the check for completeness below handles
2480 // this.
2481 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2482 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2483 ((BaseDecl = BaseDecl->getDefinition()) &&
2484 findCircularInheritance(Class, BaseDecl))) {
2485 Diag(BaseLoc, diag::err_circular_inheritance)
2486 << BaseType << Context.getTypeDeclType(Class);
2487
2488 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2489 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2490 << BaseType;
2491
2492 return nullptr;
2493 }
2494 }
2495
2496 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2497 Class->getTagKind() == TTK_Class,
2498 Access, TInfo, EllipsisLoc);
2499 }
2500
2501 // Base specifiers must be record types.
2502 if (!BaseType->isRecordType()) {
2503 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2504 return nullptr;
2505 }
2506
2507 // C++ [class.union]p1:
2508 // A union shall not be used as a base class.
2509 if (BaseType->isUnionType()) {
2510 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2511 return nullptr;
2512 }
2513
2514 // For the MS ABI, propagate DLL attributes to base class templates.
2515 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2516 if (Attr *ClassAttr = getDLLAttr(Class)) {
2517 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2518 BaseType->getAsCXXRecordDecl())) {
2519 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2520 BaseLoc);
2521 }
2522 }
2523 }
2524
2525 // C++ [class.derived]p2:
2526 // The class-name in a base-specifier shall not be an incompletely
2527 // defined class.
2528 if (RequireCompleteType(BaseLoc, BaseType,
2529 diag::err_incomplete_base_class, SpecifierRange)) {
2530 Class->setInvalidDecl();
2531 return nullptr;
2532 }
2533
2534 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2535 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2536 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2536, __PRETTY_FUNCTION__))
;
2537 BaseDecl = BaseDecl->getDefinition();
2538 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2538, __PRETTY_FUNCTION__))
;
2539 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2540 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2540, __PRETTY_FUNCTION__))
;
2541
2542 // Microsoft docs say:
2543 // "If a base-class has a code_seg attribute, derived classes must have the
2544 // same attribute."
2545 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2546 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2547 if ((DerivedCSA || BaseCSA) &&
2548 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2549 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2550 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2551 << CXXBaseDecl;
2552 return nullptr;
2553 }
2554
2555 // A class which contains a flexible array member is not suitable for use as a
2556 // base class:
2557 // - If the layout determines that a base comes before another base,
2558 // the flexible array member would index into the subsequent base.
2559 // - If the layout determines that base comes before the derived class,
2560 // the flexible array member would index into the derived class.
2561 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2562 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2563 << CXXBaseDecl->getDeclName();
2564 return nullptr;
2565 }
2566
2567 // C++ [class]p3:
2568 // If a class is marked final and it appears as a base-type-specifier in
2569 // base-clause, the program is ill-formed.
2570 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2571 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2572 << CXXBaseDecl->getDeclName()
2573 << FA->isSpelledAsSealed();
2574 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2575 << CXXBaseDecl->getDeclName() << FA->getRange();
2576 return nullptr;
2577 }
2578
2579 if (BaseDecl->isInvalidDecl())
2580 Class->setInvalidDecl();
2581
2582 // Create the base specifier.
2583 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2584 Class->getTagKind() == TTK_Class,
2585 Access, TInfo, EllipsisLoc);
2586}
2587
2588/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2589/// one entry in the base class list of a class specifier, for
2590/// example:
2591/// class foo : public bar, virtual private baz {
2592/// 'public bar' and 'virtual private baz' are each base-specifiers.
2593BaseResult
2594Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2595 ParsedAttributes &Attributes,
2596 bool Virtual, AccessSpecifier Access,
2597 ParsedType basetype, SourceLocation BaseLoc,
2598 SourceLocation EllipsisLoc) {
2599 if (!classdecl)
2600 return true;
2601
2602 AdjustDeclIfTemplate(classdecl);
2603 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2604 if (!Class)
2605 return true;
2606
2607 // We haven't yet attached the base specifiers.
2608 Class->setIsParsingBaseSpecifiers();
2609
2610 // We do not support any C++11 attributes on base-specifiers yet.
2611 // Diagnose any attributes we see.
2612 for (const ParsedAttr &AL : Attributes) {
2613 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2614 continue;
2615 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2616 ? (unsigned)diag::warn_unknown_attribute_ignored
2617 : (unsigned)diag::err_base_specifier_attribute)
2618 << AL << AL.getRange();
2619 }
2620
2621 TypeSourceInfo *TInfo = nullptr;
2622 GetTypeFromParser(basetype, &TInfo);
2623
2624 if (EllipsisLoc.isInvalid() &&
2625 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2626 UPPC_BaseType))
2627 return true;
2628
2629 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2630 Virtual, Access, TInfo,
2631 EllipsisLoc))
2632 return BaseSpec;
2633 else
2634 Class->setInvalidDecl();
2635
2636 return true;
2637}
2638
2639/// Use small set to collect indirect bases. As this is only used
2640/// locally, there's no need to abstract the small size parameter.
2641typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2642
2643/// Recursively add the bases of Type. Don't add Type itself.
2644static void
2645NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2646 const QualType &Type)
2647{
2648 // Even though the incoming type is a base, it might not be
2649 // a class -- it could be a template parm, for instance.
2650 if (auto Rec = Type->getAs<RecordType>()) {
2651 auto Decl = Rec->getAsCXXRecordDecl();
2652
2653 // Iterate over its bases.
2654 for (const auto &BaseSpec : Decl->bases()) {
2655 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2656 .getUnqualifiedType();
2657 if (Set.insert(Base).second)
2658 // If we've not already seen it, recurse.
2659 NoteIndirectBases(Context, Set, Base);
2660 }
2661 }
2662}
2663
2664/// Performs the actual work of attaching the given base class
2665/// specifiers to a C++ class.
2666bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2667 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2668 if (Bases.empty())
2669 return false;
2670
2671 // Used to keep track of which base types we have already seen, so
2672 // that we can properly diagnose redundant direct base types. Note
2673 // that the key is always the unqualified canonical type of the base
2674 // class.
2675 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2676
2677 // Used to track indirect bases so we can see if a direct base is
2678 // ambiguous.
2679 IndirectBaseSet IndirectBaseTypes;
2680
2681 // Copy non-redundant base specifiers into permanent storage.
2682 unsigned NumGoodBases = 0;
2683 bool Invalid = false;
2684 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2685 QualType NewBaseType
2686 = Context.getCanonicalType(Bases[idx]->getType());
2687 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2688
2689 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2690 if (KnownBase) {
2691 // C++ [class.mi]p3:
2692 // A class shall not be specified as a direct base class of a
2693 // derived class more than once.
2694 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2695 << KnownBase->getType() << Bases[idx]->getSourceRange();
2696
2697 // Delete the duplicate base class specifier; we're going to
2698 // overwrite its pointer later.
2699 Context.Deallocate(Bases[idx]);
2700
2701 Invalid = true;
2702 } else {
2703 // Okay, add this new base class.
2704 KnownBase = Bases[idx];
2705 Bases[NumGoodBases++] = Bases[idx];
2706
2707 // Note this base's direct & indirect bases, if there could be ambiguity.
2708 if (Bases.size() > 1)
2709 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2710
2711 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2712 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2713 if (Class->isInterface() &&
2714 (!RD->isInterfaceLike() ||
2715 KnownBase->getAccessSpecifier() != AS_public)) {
2716 // The Microsoft extension __interface does not permit bases that
2717 // are not themselves public interfaces.
2718 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2719 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2720 << RD->getSourceRange();
2721 Invalid = true;
2722 }
2723 if (RD->hasAttr<WeakAttr>())
2724 Class->addAttr(WeakAttr::CreateImplicit(Context));
2725 }
2726 }
2727 }
2728
2729 // Attach the remaining base class specifiers to the derived class.
2730 Class->setBases(Bases.data(), NumGoodBases);
2731
2732 // Check that the only base classes that are duplicate are virtual.
2733 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2734 // Check whether this direct base is inaccessible due to ambiguity.
2735 QualType BaseType = Bases[idx]->getType();
2736
2737 // Skip all dependent types in templates being used as base specifiers.
2738 // Checks below assume that the base specifier is a CXXRecord.
2739 if (BaseType->isDependentType())
2740 continue;
2741
2742 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2743 .getUnqualifiedType();
2744
2745 if (IndirectBaseTypes.count(CanonicalBase)) {
2746 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2747 /*DetectVirtual=*/true);
2748 bool found
2749 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2750 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2750, __PRETTY_FUNCTION__))
;
2751 (void)found;
2752
2753 if (Paths.isAmbiguous(CanonicalBase))
2754 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2755 << BaseType << getAmbiguousPathsDisplayString(Paths)
2756 << Bases[idx]->getSourceRange();
2757 else
2758 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2758, __PRETTY_FUNCTION__))
;
2759 }
2760
2761 // Delete the base class specifier, since its data has been copied
2762 // into the CXXRecordDecl.
2763 Context.Deallocate(Bases[idx]);
2764 }
2765
2766 return Invalid;
2767}
2768
2769/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2770/// class, after checking whether there are any duplicate base
2771/// classes.
2772void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2773 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2774 if (!ClassDecl || Bases.empty())
2775 return;
2776
2777 AdjustDeclIfTemplate(ClassDecl);
2778 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2779}
2780
2781/// Determine whether the type \p Derived is a C++ class that is
2782/// derived from the type \p Base.
2783bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2784 if (!getLangOpts().CPlusPlus)
2785 return false;
2786
2787 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2788 if (!DerivedRD)
2789 return false;
2790
2791 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2792 if (!BaseRD)
2793 return false;
2794
2795 // If either the base or the derived type is invalid, don't try to
2796 // check whether one is derived from the other.
2797 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2798 return false;
2799
2800 // FIXME: In a modules build, do we need the entire path to be visible for us
2801 // to be able to use the inheritance relationship?
2802 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2803 return false;
2804
2805 return DerivedRD->isDerivedFrom(BaseRD);
2806}
2807
2808/// Determine whether the type \p Derived is a C++ class that is
2809/// derived from the type \p Base.
2810bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2811 CXXBasePaths &Paths) {
2812 if (!getLangOpts().CPlusPlus)
2813 return false;
2814
2815 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2816 if (!DerivedRD)
2817 return false;
2818
2819 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2820 if (!BaseRD)
2821 return false;
2822
2823 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2824 return false;
2825
2826 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2827}
2828
2829static void BuildBasePathArray(const CXXBasePath &Path,
2830 CXXCastPath &BasePathArray) {
2831 // We first go backward and check if we have a virtual base.
2832 // FIXME: It would be better if CXXBasePath had the base specifier for
2833 // the nearest virtual base.
2834 unsigned Start = 0;
2835 for (unsigned I = Path.size(); I != 0; --I) {
2836 if (Path[I - 1].Base->isVirtual()) {
2837 Start = I - 1;
2838 break;
2839 }
2840 }
2841
2842 // Now add all bases.
2843 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2844 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2845}
2846
2847
2848void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2849 CXXCastPath &BasePathArray) {
2850 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2850, __PRETTY_FUNCTION__))
;
2851 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2851, __PRETTY_FUNCTION__))
;
2852 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2853}
2854/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2855/// conversion (where Derived and Base are class types) is
2856/// well-formed, meaning that the conversion is unambiguous (and
2857/// that all of the base classes are accessible). Returns true
2858/// and emits a diagnostic if the code is ill-formed, returns false
2859/// otherwise. Loc is the location where this routine should point to
2860/// if there is an error, and Range is the source range to highlight
2861/// if there is an error.
2862///
2863/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2864/// diagnostic for the respective type of error will be suppressed, but the
2865/// check for ill-formed code will still be performed.
2866bool
2867Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2868 unsigned InaccessibleBaseID,
2869 unsigned AmbiguousBaseConvID,
2870 SourceLocation Loc, SourceRange Range,
2871 DeclarationName Name,
2872 CXXCastPath *BasePath,
2873 bool IgnoreAccess) {
2874 // First, determine whether the path from Derived to Base is
2875 // ambiguous. This is slightly more expensive than checking whether
2876 // the Derived to Base conversion exists, because here we need to
2877 // explore multiple paths to determine if there is an ambiguity.
2878 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2879 /*DetectVirtual=*/false);
2880 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2881 if (!DerivationOkay)
2882 return true;
2883
2884 const CXXBasePath *Path = nullptr;
2885 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2886 Path = &Paths.front();
2887
2888 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2889 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2890 // user to access such bases.
2891 if (!Path && getLangOpts().MSVCCompat) {
2892 for (const CXXBasePath &PossiblePath : Paths) {
2893 if (PossiblePath.size() == 1) {
2894 Path = &PossiblePath;
2895 if (AmbiguousBaseConvID)
2896 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2897 << Base << Derived << Range;
2898 break;
2899 }
2900 }
2901 }
2902
2903 if (Path) {
2904 if (!IgnoreAccess) {
2905 // Check that the base class can be accessed.
2906 switch (
2907 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2908 case AR_inaccessible:
2909 return true;
2910 case AR_accessible:
2911 case AR_dependent:
2912 case AR_delayed:
2913 break;
2914 }
2915 }
2916
2917 // Build a base path if necessary.
2918 if (BasePath)
2919 ::BuildBasePathArray(*Path, *BasePath);
2920 return false;
2921 }
2922
2923 if (AmbiguousBaseConvID) {
2924 // We know that the derived-to-base conversion is ambiguous, and
2925 // we're going to produce a diagnostic. Perform the derived-to-base
2926 // search just one more time to compute all of the possible paths so
2927 // that we can print them out. This is more expensive than any of
2928 // the previous derived-to-base checks we've done, but at this point
2929 // performance isn't as much of an issue.
2930 Paths.clear();
2931 Paths.setRecordingPaths(true);
2932 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2933 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2933, __PRETTY_FUNCTION__))
;
2934 (void)StillOkay;
2935
2936 // Build up a textual representation of the ambiguous paths, e.g.,
2937 // D -> B -> A, that will be used to illustrate the ambiguous
2938 // conversions in the diagnostic. We only print one of the paths
2939 // to each base class subobject.
2940 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2941
2942 Diag(Loc, AmbiguousBaseConvID)
2943 << Derived << Base << PathDisplayStr << Range << Name;
2944 }
2945 return true;
2946}
2947
2948bool
2949Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2950 SourceLocation Loc, SourceRange Range,
2951 CXXCastPath *BasePath,
2952 bool IgnoreAccess) {
2953 return CheckDerivedToBaseConversion(
2954 Derived, Base, diag::err_upcast_to_inaccessible_base,
2955 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2956 BasePath, IgnoreAccess);
2957}
2958
2959
2960/// Builds a string representing ambiguous paths from a
2961/// specific derived class to different subobjects of the same base
2962/// class.
2963///
2964/// This function builds a string that can be used in error messages
2965/// to show the different paths that one can take through the
2966/// inheritance hierarchy to go from the derived class to different
2967/// subobjects of a base class. The result looks something like this:
2968/// @code
2969/// struct D -> struct B -> struct A
2970/// struct D -> struct C -> struct A
2971/// @endcode
2972std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2973 std::string PathDisplayStr;
2974 std::set<unsigned> DisplayedPaths;
2975 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2976 Path != Paths.end(); ++Path) {
2977 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2978 // We haven't displayed a path to this particular base
2979 // class subobject yet.
2980 PathDisplayStr += "\n ";
2981 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2982 for (CXXBasePath::const_iterator Element = Path->begin();
2983 Element != Path->end(); ++Element)
2984 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2985 }
2986 }
2987
2988 return PathDisplayStr;
2989}
2990
2991//===----------------------------------------------------------------------===//
2992// C++ class member Handling
2993//===----------------------------------------------------------------------===//
2994
2995/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2996bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2997 SourceLocation ColonLoc,
2998 const ParsedAttributesView &Attrs) {
2999 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 2999, __PRETTY_FUNCTION__))
;
3000 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3001 ASLoc, ColonLoc);
3002 CurContext->addHiddenDecl(ASDecl);
3003 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3004}
3005
3006/// CheckOverrideControl - Check C++11 override control semantics.
3007void Sema::CheckOverrideControl(NamedDecl *D) {
3008 if (D->isInvalidDecl())
3009 return;
3010
3011 // We only care about "override" and "final" declarations.
3012 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3013 return;
3014
3015 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3016
3017 // We can't check dependent instance methods.
3018 if (MD && MD->isInstance() &&
3019 (MD->getParent()->hasAnyDependentBases() ||
3020 MD->getType()->isDependentType()))
3021 return;
3022
3023 if (MD && !MD->isVirtual()) {
3024 // If we have a non-virtual method, check if if hides a virtual method.
3025 // (In that case, it's most likely the method has the wrong type.)
3026 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3027 FindHiddenVirtualMethods(MD, OverloadedMethods);
3028
3029 if (!OverloadedMethods.empty()) {
3030 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3031 Diag(OA->getLocation(),
3032 diag::override_keyword_hides_virtual_member_function)
3033 << "override" << (OverloadedMethods.size() > 1);
3034 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3035 Diag(FA->getLocation(),
3036 diag::override_keyword_hides_virtual_member_function)
3037 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3038 << (OverloadedMethods.size() > 1);
3039 }
3040 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3041 MD->setInvalidDecl();
3042 return;
3043 }
3044 // Fall through into the general case diagnostic.
3045 // FIXME: We might want to attempt typo correction here.
3046 }
3047
3048 if (!MD || !MD->isVirtual()) {
3049 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3050 Diag(OA->getLocation(),
3051 diag::override_keyword_only_allowed_on_virtual_member_functions)
3052 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3053 D->dropAttr<OverrideAttr>();
3054 }
3055 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3056 Diag(FA->getLocation(),
3057 diag::override_keyword_only_allowed_on_virtual_member_functions)
3058 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3059 << FixItHint::CreateRemoval(FA->getLocation());
3060 D->dropAttr<FinalAttr>();
3061 }
3062 return;
3063 }
3064
3065 // C++11 [class.virtual]p5:
3066 // If a function is marked with the virt-specifier override and
3067 // does not override a member function of a base class, the program is
3068 // ill-formed.
3069 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3070 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3071 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3072 << MD->getDeclName();
3073}
3074
3075void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3076 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3077 return;
3078 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3079 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3080 return;
3081
3082 SourceLocation Loc = MD->getLocation();
3083 SourceLocation SpellingLoc = Loc;
3084 if (getSourceManager().isMacroArgExpansion(Loc))
3085 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3086 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3087 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3088 return;
3089
3090 if (MD->size_overridden_methods() > 0) {
3091 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3092 unsigned DiagID =
3093 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3094 ? DiagInconsistent
3095 : DiagSuggest;
3096 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3097 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3098 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3099 };
3100 if (isa<CXXDestructorDecl>(MD))
3101 EmitDiag(
3102 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3103 diag::warn_suggest_destructor_marked_not_override_overriding);
3104 else
3105 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3106 diag::warn_suggest_function_marked_not_override_overriding);
3107 }
3108}
3109
3110/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3111/// function overrides a virtual member function marked 'final', according to
3112/// C++11 [class.virtual]p4.
3113bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3114 const CXXMethodDecl *Old) {
3115 FinalAttr *FA = Old->getAttr<FinalAttr>();
3116 if (!FA)
3117 return false;
3118
3119 Diag(New->getLocation(), diag::err_final_function_overridden)
3120 << New->getDeclName()
3121 << FA->isSpelledAsSealed();
3122 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3123 return true;
3124}
3125
3126static bool InitializationHasSideEffects(const FieldDecl &FD) {
3127 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3128 // FIXME: Destruction of ObjC lifetime types has side-effects.
3129 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3130 return !RD->isCompleteDefinition() ||
3131 !RD->hasTrivialDefaultConstructor() ||
3132 !RD->hasTrivialDestructor();
3133 return false;
3134}
3135
3136static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3137 ParsedAttributesView::const_iterator Itr =
3138 llvm::find_if(list, [](const ParsedAttr &AL) {
3139 return AL.isDeclspecPropertyAttribute();
3140 });
3141 if (Itr != list.end())
3142 return &*Itr;
3143 return nullptr;
3144}
3145
3146// Check if there is a field shadowing.
3147void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3148 DeclarationName FieldName,
3149 const CXXRecordDecl *RD,
3150 bool DeclIsField) {
3151 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3152 return;
3153
3154 // To record a shadowed field in a base
3155 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3156 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3157 CXXBasePath &Path) {
3158 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3159 // Record an ambiguous path directly
3160 if (Bases.find(Base) != Bases.end())
3161 return true;
3162 for (const auto Field : Base->lookup(FieldName)) {
3163 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3164 Field->getAccess() != AS_private) {
3165 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3165, __PRETTY_FUNCTION__))
;
3166 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3166, __PRETTY_FUNCTION__))
;
3167 Bases[Base] = Field;
3168 return true;
3169 }
3170 }
3171 return false;
3172 };
3173
3174 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3175 /*DetectVirtual=*/true);
3176 if (!RD->lookupInBases(FieldShadowed, Paths))
3177 return;
3178
3179 for (const auto &P : Paths) {
3180 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3181 auto It = Bases.find(Base);
3182 // Skip duplicated bases
3183 if (It == Bases.end())
3184 continue;
3185 auto BaseField = It->second;
3186 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3186, __PRETTY_FUNCTION__))
;
3187 if (AS_none !=
3188 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3189 Diag(Loc, diag::warn_shadow_field)
3190 << FieldName << RD << Base << DeclIsField;
3191 Diag(BaseField->getLocation(), diag::note_shadow_field);
3192 Bases.erase(It);
3193 }
3194 }
3195}
3196
3197/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3198/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3199/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3200/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3201/// present (but parsing it has been deferred).
3202NamedDecl *
3203Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3204 MultiTemplateParamsArg TemplateParameterLists,
3205 Expr *BW, const VirtSpecifiers &VS,
3206 InClassInitStyle InitStyle) {
3207 const DeclSpec &DS = D.getDeclSpec();
3208 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3209 DeclarationName Name = NameInfo.getName();
3210 SourceLocation Loc = NameInfo.getLoc();
3211
3212 // For anonymous bitfields, the location should point to the type.
3213 if (Loc.isInvalid())
3214 Loc = D.getBeginLoc();
3215
3216 Expr *BitWidth = static_cast<Expr*>(BW);
3217
3218 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3218, __PRETTY_FUNCTION__))
;
3219 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3219, __PRETTY_FUNCTION__))
;
3220
3221 bool isFunc = D.isDeclarationOfFunction();
3222 const ParsedAttr *MSPropertyAttr =
3223 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3224
3225 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3226 // The Microsoft extension __interface only permits public member functions
3227 // and prohibits constructors, destructors, operators, non-public member
3228 // functions, static methods and data members.
3229 unsigned InvalidDecl;
3230 bool ShowDeclName = true;
3231 if (!isFunc &&
3232 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3233 InvalidDecl = 0;
3234 else if (!isFunc)
3235 InvalidDecl = 1;
3236 else if (AS != AS_public)
3237 InvalidDecl = 2;
3238 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3239 InvalidDecl = 3;
3240 else switch (Name.getNameKind()) {
3241 case DeclarationName::CXXConstructorName:
3242 InvalidDecl = 4;
3243 ShowDeclName = false;
3244 break;
3245
3246 case DeclarationName::CXXDestructorName:
3247 InvalidDecl = 5;
3248 ShowDeclName = false;
3249 break;
3250
3251 case DeclarationName::CXXOperatorName:
3252 case DeclarationName::CXXConversionFunctionName:
3253 InvalidDecl = 6;
3254 break;
3255
3256 default:
3257 InvalidDecl = 0;
3258 break;
3259 }
3260
3261 if (InvalidDecl) {
3262 if (ShowDeclName)
3263 Diag(Loc, diag::err_invalid_member_in_interface)
3264 << (InvalidDecl-1) << Name;
3265 else
3266 Diag(Loc, diag::err_invalid_member_in_interface)
3267 << (InvalidDecl-1) << "";
3268 return nullptr;
3269 }
3270 }
3271
3272 // C++ 9.2p6: A member shall not be declared to have automatic storage
3273 // duration (auto, register) or with the extern storage-class-specifier.
3274 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3275 // data members and cannot be applied to names declared const or static,
3276 // and cannot be applied to reference members.
3277 switch (DS.getStorageClassSpec()) {
3278 case DeclSpec::SCS_unspecified:
3279 case DeclSpec::SCS_typedef:
3280 case DeclSpec::SCS_static:
3281 break;
3282 case DeclSpec::SCS_mutable:
3283 if (isFunc) {
3284 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3285
3286 // FIXME: It would be nicer if the keyword was ignored only for this
3287 // declarator. Otherwise we could get follow-up errors.
3288 D.getMutableDeclSpec().ClearStorageClassSpecs();
3289 }
3290 break;
3291 default:
3292 Diag(DS.getStorageClassSpecLoc(),
3293 diag::err_storageclass_invalid_for_member);
3294 D.getMutableDeclSpec().ClearStorageClassSpecs();
3295 break;
3296 }
3297
3298 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3299 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3300 !isFunc);
3301
3302 if (DS.hasConstexprSpecifier() && isInstField) {
3303 SemaDiagnosticBuilder B =
3304 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3305 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3306 if (InitStyle == ICIS_NoInit) {
3307 B << 0 << 0;
3308 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3309 B << FixItHint::CreateRemoval(ConstexprLoc);
3310 else {
3311 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3312 D.getMutableDeclSpec().ClearConstexprSpec();
3313 const char *PrevSpec;
3314 unsigned DiagID;
3315 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3316 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3317 (void)Failed;
3318 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3318, __PRETTY_FUNCTION__))
;
3319 }
3320 } else {
3321 B << 1;
3322 const char *PrevSpec;
3323 unsigned DiagID;
3324 if (D.getMutableDeclSpec().SetStorageClassSpec(
3325 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3326 Context.getPrintingPolicy())) {
3327 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3328, __PRETTY_FUNCTION__))
3328 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3328, __PRETTY_FUNCTION__))
;
3329 B << 1;
3330 } else {
3331 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3332 isInstField = false;
3333 }
3334 }
3335 }
3336
3337 NamedDecl *Member;
3338 if (isInstField) {
3339 CXXScopeSpec &SS = D.getCXXScopeSpec();
3340
3341 // Data members must have identifiers for names.
3342 if (!Name.isIdentifier()) {
3343 Diag(Loc, diag::err_bad_variable_name)
3344 << Name;
3345 return nullptr;
3346 }
3347
3348 IdentifierInfo *II = Name.getAsIdentifierInfo();
3349
3350 // Member field could not be with "template" keyword.
3351 // So TemplateParameterLists should be empty in this case.
3352 if (TemplateParameterLists.size()) {
3353 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3354 if (TemplateParams->size()) {
3355 // There is no such thing as a member field template.
3356 Diag(D.getIdentifierLoc(), diag::err_template_member)
3357 << II
3358 << SourceRange(TemplateParams->getTemplateLoc(),
3359 TemplateParams->getRAngleLoc());
3360 } else {
3361 // There is an extraneous 'template<>' for this member.
3362 Diag(TemplateParams->getTemplateLoc(),
3363 diag::err_template_member_noparams)
3364 << II
3365 << SourceRange(TemplateParams->getTemplateLoc(),
3366 TemplateParams->getRAngleLoc());
3367 }
3368 return nullptr;
3369 }
3370
3371 if (SS.isSet() && !SS.isInvalid()) {
3372 // The user provided a superfluous scope specifier inside a class
3373 // definition:
3374 //
3375 // class X {
3376 // int X::member;
3377 // };
3378 if (DeclContext *DC = computeDeclContext(SS, false))
3379 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3380 D.getName().getKind() ==
3381 UnqualifiedIdKind::IK_TemplateId);
3382 else
3383 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3384 << Name << SS.getRange();
3385
3386 SS.clear();
3387 }
3388
3389 if (MSPropertyAttr) {
3390 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3391 BitWidth, InitStyle, AS, *MSPropertyAttr);
3392 if (!Member)
3393 return nullptr;
3394 isInstField = false;
3395 } else {
3396 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3397 BitWidth, InitStyle, AS);
3398 if (!Member)
3399 return nullptr;
3400 }
3401
3402 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3403 } else {
3404 Member = HandleDeclarator(S, D, TemplateParameterLists);
3405 if (!Member)
3406 return nullptr;
3407
3408 // Non-instance-fields can't have a bitfield.
3409 if (BitWidth) {
3410 if (Member->isInvalidDecl()) {
3411 // don't emit another diagnostic.
3412 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3413 // C++ 9.6p3: A bit-field shall not be a static member.
3414 // "static member 'A' cannot be a bit-field"
3415 Diag(Loc, diag::err_static_not_bitfield)
3416 << Name << BitWidth->getSourceRange();
3417 } else if (isa<TypedefDecl>(Member)) {
3418 // "typedef member 'x' cannot be a bit-field"
3419 Diag(Loc, diag::err_typedef_not_bitfield)
3420 << Name << BitWidth->getSourceRange();
3421 } else {
3422 // A function typedef ("typedef int f(); f a;").
3423 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3424 Diag(Loc, diag::err_not_integral_type_bitfield)
3425 << Name << cast<ValueDecl>(Member)->getType()
3426 << BitWidth->getSourceRange();
3427 }
3428
3429 BitWidth = nullptr;
3430 Member->setInvalidDecl();
3431 }
3432
3433 NamedDecl *NonTemplateMember = Member;
3434 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3435 NonTemplateMember = FunTmpl->getTemplatedDecl();
3436 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3437 NonTemplateMember = VarTmpl->getTemplatedDecl();
3438
3439 Member->setAccess(AS);
3440
3441 // If we have declared a member function template or static data member
3442 // template, set the access of the templated declaration as well.
3443 if (NonTemplateMember != Member)
3444 NonTemplateMember->setAccess(AS);
3445
3446 // C++ [temp.deduct.guide]p3:
3447 // A deduction guide [...] for a member class template [shall be
3448 // declared] with the same access [as the template].
3449 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3450 auto *TD = DG->getDeducedTemplate();
3451 // Access specifiers are only meaningful if both the template and the
3452 // deduction guide are from the same scope.
3453 if (AS != TD->getAccess() &&
3454 TD->getDeclContext()->getRedeclContext()->Equals(
3455 DG->getDeclContext()->getRedeclContext())) {
3456 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3457 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3458 << TD->getAccess();
3459 const AccessSpecDecl *LastAccessSpec = nullptr;
3460 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3461 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3462 LastAccessSpec = AccessSpec;
3463 }
3464 assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier"
) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3464, __PRETTY_FUNCTION__))
;
3465 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3466 << AS;
3467 }
3468 }
3469 }
3470
3471 if (VS.isOverrideSpecified())
3472 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3473 AttributeCommonInfo::AS_Keyword));
3474 if (VS.isFinalSpecified())
3475 Member->addAttr(FinalAttr::Create(
3476 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3477 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3478
3479 if (VS.getLastLocation().isValid()) {
3480 // Update the end location of a method that has a virt-specifiers.
3481 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3482 MD->setRangeEnd(VS.getLastLocation());
3483 }
3484
3485 CheckOverrideControl(Member);
3486
3487 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3487, __PRETTY_FUNCTION__))
;
3488
3489 if (isInstField) {
3490 FieldDecl *FD = cast<FieldDecl>(Member);
3491 FieldCollector->Add(FD);
3492
3493 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3494 // Remember all explicit private FieldDecls that have a name, no side
3495 // effects and are not part of a dependent type declaration.
3496 if (!FD->isImplicit() && FD->getDeclName() &&
3497 FD->getAccess() == AS_private &&
3498 !FD->hasAttr<UnusedAttr>() &&
3499 !FD->getParent()->isDependentContext() &&
3500 !InitializationHasSideEffects(*FD))
3501 UnusedPrivateFields.insert(FD);
3502 }
3503 }
3504
3505 return Member;
3506}
3507
3508namespace {
3509 class UninitializedFieldVisitor
3510 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3511 Sema &S;
3512 // List of Decls to generate a warning on. Also remove Decls that become
3513 // initialized.
3514 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3515 // List of base classes of the record. Classes are removed after their
3516 // initializers.
3517 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3518 // Vector of decls to be removed from the Decl set prior to visiting the
3519 // nodes. These Decls may have been initialized in the prior initializer.
3520 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3521 // If non-null, add a note to the warning pointing back to the constructor.
3522 const CXXConstructorDecl *Constructor;
3523 // Variables to hold state when processing an initializer list. When
3524 // InitList is true, special case initialization of FieldDecls matching
3525 // InitListFieldDecl.
3526 bool InitList;
3527 FieldDecl *InitListFieldDecl;
3528 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3529
3530 public:
3531 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3532 UninitializedFieldVisitor(Sema &S,
3533 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3534 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3535 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3536 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3537
3538 // Returns true if the use of ME is not an uninitialized use.
3539 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3540 bool CheckReferenceOnly) {
3541 llvm::SmallVector<FieldDecl*, 4> Fields;
3542 bool ReferenceField = false;
3543 while (ME) {
3544 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3545 if (!FD)
3546 return false;
3547 Fields.push_back(FD);
3548 if (FD->getType()->isReferenceType())
3549 ReferenceField = true;
3550 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3551 }
3552
3553 // Binding a reference to an uninitialized field is not an
3554 // uninitialized use.
3555 if (CheckReferenceOnly && !ReferenceField)
3556 return true;
3557
3558 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3559 // Discard the first field since it is the field decl that is being
3560 // initialized.
3561 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3562 UsedFieldIndex.push_back((*I)->getFieldIndex());
3563 }
3564
3565 for (auto UsedIter = UsedFieldIndex.begin(),
3566 UsedEnd = UsedFieldIndex.end(),
3567 OrigIter = InitFieldIndex.begin(),
3568 OrigEnd = InitFieldIndex.end();
3569 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3570 if (*UsedIter < *OrigIter)
3571 return true;
3572 if (*UsedIter > *OrigIter)
3573 break;
3574 }
3575
3576 return false;
3577 }
3578
3579 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3580 bool AddressOf) {
3581 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3582 return;
3583
3584 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3585 // or union.
3586 MemberExpr *FieldME = ME;
3587
3588 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3589
3590 Expr *Base = ME;
3591 while (MemberExpr *SubME =
3592 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3593
3594 if (isa<VarDecl>(SubME->getMemberDecl()))
3595 return;
3596
3597 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3598 if (!FD->isAnonymousStructOrUnion())
3599 FieldME = SubME;
3600
3601 if (!FieldME->getType().isPODType(S.Context))
3602 AllPODFields = false;
3603
3604 Base = SubME->getBase();
3605 }
3606
3607 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3608 Visit(Base);
3609 return;
3610 }
3611
3612 if (AddressOf && AllPODFields)
3613 return;
3614
3615 ValueDecl* FoundVD = FieldME->getMemberDecl();
3616
3617 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3618 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3619 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3620 }
3621
3622 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3623 QualType T = BaseCast->getType();
3624 if (T->isPointerType() &&
3625 BaseClasses.count(T->getPointeeType())) {
3626 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3627 << T->getPointeeType() << FoundVD;
3628 }
3629 }
3630 }
3631
3632 if (!Decls.count(FoundVD))
3633 return;
3634
3635 const bool IsReference = FoundVD->getType()->isReferenceType();
3636
3637 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3638 // Special checking for initializer lists.
3639 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3640 return;
3641 }
3642 } else {
3643 // Prevent double warnings on use of unbounded references.
3644 if (CheckReferenceOnly && !IsReference)
3645 return;
3646 }
3647
3648 unsigned diag = IsReference
3649 ? diag::warn_reference_field_is_uninit
3650 : diag::warn_field_is_uninit;
3651 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3652 if (Constructor)
3653 S.Diag(Constructor->getLocation(),
3654 diag::note_uninit_in_this_constructor)
3655 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3656
3657 }
3658
3659 void HandleValue(Expr *E, bool AddressOf) {
3660 E = E->IgnoreParens();
3661
3662 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3663 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3664 AddressOf /*AddressOf*/);
3665 return;
3666 }
3667
3668 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3669 Visit(CO->getCond());
3670 HandleValue(CO->getTrueExpr(), AddressOf);
3671 HandleValue(CO->getFalseExpr(), AddressOf);
3672 return;
3673 }
3674
3675 if (BinaryConditionalOperator *BCO =
3676 dyn_cast<BinaryConditionalOperator>(E)) {
3677 Visit(BCO->getCond());
3678 HandleValue(BCO->getFalseExpr(), AddressOf);
3679 return;
3680 }
3681
3682 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3683 HandleValue(OVE->getSourceExpr(), AddressOf);
3684 return;
3685 }
3686
3687 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3688 switch (BO->getOpcode()) {
3689 default:
3690 break;
3691 case(BO_PtrMemD):
3692 case(BO_PtrMemI):
3693 HandleValue(BO->getLHS(), AddressOf);
3694 Visit(BO->getRHS());
3695 return;
3696 case(BO_Comma):
3697 Visit(BO->getLHS());
3698 HandleValue(BO->getRHS(), AddressOf);
3699 return;
3700 }
3701 }
3702
3703 Visit(E);
3704 }
3705
3706 void CheckInitListExpr(InitListExpr *ILE) {
3707 InitFieldIndex.push_back(0);
3708 for (auto Child : ILE->children()) {
3709 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3710 CheckInitListExpr(SubList);
3711 } else {
3712 Visit(Child);
3713 }
3714 ++InitFieldIndex.back();
3715 }
3716 InitFieldIndex.pop_back();
3717 }
3718
3719 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3720 FieldDecl *Field, const Type *BaseClass) {
3721 // Remove Decls that may have been initialized in the previous
3722 // initializer.
3723 for (ValueDecl* VD : DeclsToRemove)
3724 Decls.erase(VD);
3725 DeclsToRemove.clear();
3726
3727 Constructor = FieldConstructor;
3728 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3729
3730 if (ILE && Field) {
3731 InitList = true;
3732 InitListFieldDecl = Field;
3733 InitFieldIndex.clear();
3734 CheckInitListExpr(ILE);
3735 } else {
3736 InitList = false;
3737 Visit(E);
3738 }
3739
3740 if (Field)
3741 Decls.erase(Field);
3742 if (BaseClass)
3743 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3744 }
3745
3746 void VisitMemberExpr(MemberExpr *ME) {
3747 // All uses of unbounded reference fields will warn.
3748 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3749 }
3750
3751 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3752 if (E->getCastKind() == CK_LValueToRValue) {
3753 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3754 return;
3755 }
3756
3757 Inherited::VisitImplicitCastExpr(E);
3758 }
3759
3760 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3761 if (E->getConstructor()->isCopyConstructor()) {
3762 Expr *ArgExpr = E->getArg(0);
3763 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3764 if (ILE->getNumInits() == 1)
3765 ArgExpr = ILE->getInit(0);
3766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3767 if (ICE->getCastKind() == CK_NoOp)
3768 ArgExpr = ICE->getSubExpr();
3769 HandleValue(ArgExpr, false /*AddressOf*/);
3770 return;
3771 }
3772 Inherited::VisitCXXConstructExpr(E);
3773 }
3774
3775 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3776 Expr *Callee = E->getCallee();
3777 if (isa<MemberExpr>(Callee)) {
3778 HandleValue(Callee, false /*AddressOf*/);
3779 for (auto Arg : E->arguments())
3780 Visit(Arg);
3781 return;
3782 }
3783
3784 Inherited::VisitCXXMemberCallExpr(E);
3785 }
3786
3787 void VisitCallExpr(CallExpr *E) {
3788 // Treat std::move as a use.
3789 if (E->isCallToStdMove()) {
3790 HandleValue(E->getArg(0), /*AddressOf=*/false);
3791 return;
3792 }
3793
3794 Inherited::VisitCallExpr(E);
3795 }
3796
3797 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3798 Expr *Callee = E->getCallee();
3799
3800 if (isa<UnresolvedLookupExpr>(Callee))
3801 return Inherited::VisitCXXOperatorCallExpr(E);
3802
3803 Visit(Callee);
3804 for (auto Arg : E->arguments())
3805 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3806 }
3807
3808 void VisitBinaryOperator(BinaryOperator *E) {
3809 // If a field assignment is detected, remove the field from the
3810 // uninitiailized field set.
3811 if (E->getOpcode() == BO_Assign)
3812 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3813 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3814 if (!FD->getType()->isReferenceType())
3815 DeclsToRemove.push_back(FD);
3816
3817 if (E->isCompoundAssignmentOp()) {
3818 HandleValue(E->getLHS(), false /*AddressOf*/);
3819 Visit(E->getRHS());
3820 return;
3821 }
3822
3823 Inherited::VisitBinaryOperator(E);
3824 }
3825
3826 void VisitUnaryOperator(UnaryOperator *E) {
3827 if (E->isIncrementDecrementOp()) {
3828 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3829 return;
3830 }
3831 if (E->getOpcode() == UO_AddrOf) {
3832 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3833 HandleValue(ME->getBase(), true /*AddressOf*/);
3834 return;
3835 }
3836 }
3837
3838 Inherited::VisitUnaryOperator(E);
3839 }
3840 };
3841
3842 // Diagnose value-uses of fields to initialize themselves, e.g.
3843 // foo(foo)
3844 // where foo is not also a parameter to the constructor.
3845 // Also diagnose across field uninitialized use such as
3846 // x(y), y(x)
3847 // TODO: implement -Wuninitialized and fold this into that framework.
3848 static void DiagnoseUninitializedFields(
3849 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3850
3851 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3852 Constructor->getLocation())) {
3853 return;
3854 }
3855
3856 if (Constructor->isInvalidDecl())
3857 return;
3858
3859 const CXXRecordDecl *RD = Constructor->getParent();
3860
3861 if (RD->isDependentContext())
3862 return;
3863
3864 // Holds fields that are uninitialized.
3865 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3866
3867 // At the beginning, all fields are uninitialized.
3868 for (auto *I : RD->decls()) {
3869 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3870 UninitializedFields.insert(FD);
3871 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3872 UninitializedFields.insert(IFD->getAnonField());
3873 }
3874 }
3875
3876 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3877 for (auto I : RD->bases())
3878 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3879
3880 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3881 return;
3882
3883 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3884 UninitializedFields,
3885 UninitializedBaseClasses);
3886
3887 for (const auto *FieldInit : Constructor->inits()) {
3888 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3889 break;
3890
3891 Expr *InitExpr = FieldInit->getInit();
3892 if (!InitExpr)
3893 continue;
3894
3895 if (CXXDefaultInitExpr *Default =
3896 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3897 InitExpr = Default->getExpr();
3898 if (!InitExpr)
3899 continue;
3900 // In class initializers will point to the constructor.
3901 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3902 FieldInit->getAnyMember(),
3903 FieldInit->getBaseClass());
3904 } else {
3905 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3906 FieldInit->getAnyMember(),
3907 FieldInit->getBaseClass());
3908 }
3909 }
3910 }
3911} // namespace
3912
3913/// Enter a new C++ default initializer scope. After calling this, the
3914/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3915/// parsing or instantiating the initializer failed.
3916void Sema::ActOnStartCXXInClassMemberInitializer() {
3917 // Create a synthetic function scope to represent the call to the constructor
3918 // that notionally surrounds a use of this initializer.
3919 PushFunctionScope();
3920}
3921
3922void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3923 if (!D.isFunctionDeclarator())
3924 return;
3925 auto &FTI = D.getFunctionTypeInfo();
3926 if (!FTI.Params)
3927 return;
3928 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3929 FTI.NumParams)) {
3930 auto *ParamDecl = cast<NamedDecl>(Param.Param);
3931 if (ParamDecl->getDeclName())
3932 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3933 }
3934}
3935
3936ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3937 return ActOnRequiresClause(ConstraintExpr);
3938}
3939
3940ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3941 if (ConstraintExpr.isInvalid())
3942 return ExprError();
3943
3944 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3945 if (ConstraintExpr.isInvalid())
3946 return ExprError();
3947
3948 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3949 UPPC_RequiresClause))
3950 return ExprError();
3951
3952 return ConstraintExpr;
3953}
3954
3955/// This is invoked after parsing an in-class initializer for a
3956/// non-static C++ class member, and after instantiating an in-class initializer
3957/// in a class template. Such actions are deferred until the class is complete.
3958void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3959 SourceLocation InitLoc,
3960 Expr *InitExpr) {
3961 // Pop the notional constructor scope we created earlier.
3962 PopFunctionScopeInfo(nullptr, D);
3963
3964 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3965 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3966, __PRETTY_FUNCTION__))
3966 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 3966, __PRETTY_FUNCTION__))
;
3967
3968 if (!InitExpr) {
3969 D->setInvalidDecl();
3970 if (FD)
3971 FD->removeInClassInitializer();
3972 return;
3973 }
3974
3975 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3976 FD->setInvalidDecl();
3977 FD->removeInClassInitializer();
3978 return;
3979 }
3980
3981 ExprResult Init = InitExpr;
3982 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3983 InitializedEntity Entity =
3984 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3985 InitializationKind Kind =
3986 FD->getInClassInitStyle() == ICIS_ListInit
3987 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3988 InitExpr->getBeginLoc(),
3989 InitExpr->getEndLoc())
3990 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3991 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3992 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3993 if (Init.isInvalid()) {
3994 FD->setInvalidDecl();
3995 return;
3996 }
3997 }
3998
3999 // C++11 [class.base.init]p7:
4000 // The initialization of each base and member constitutes a
4001 // full-expression.
4002 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4003 if (Init.isInvalid()) {
4004 FD->setInvalidDecl();
4005 return;
4006 }
4007
4008 InitExpr = Init.get();
4009
4010 FD->setInClassInitializer(InitExpr);
4011}
4012
4013/// Find the direct and/or virtual base specifiers that
4014/// correspond to the given base type, for use in base initialization
4015/// within a constructor.
4016static bool FindBaseInitializer(Sema &SemaRef,
4017 CXXRecordDecl *ClassDecl,
4018 QualType BaseType,
4019 const CXXBaseSpecifier *&DirectBaseSpec,
4020 const CXXBaseSpecifier *&VirtualBaseSpec) {
4021 // First, check for a direct base class.
4022 DirectBaseSpec = nullptr;
4023 for (const auto &Base : ClassDecl->bases()) {
4024 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4025 // We found a direct base of this type. That's what we're
4026 // initializing.
4027 DirectBaseSpec = &Base;
4028 break;
4029 }
4030 }
4031
4032 // Check for a virtual base class.
4033 // FIXME: We might be able to short-circuit this if we know in advance that
4034 // there are no virtual bases.
4035 VirtualBaseSpec = nullptr;
4036 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4037 // We haven't found a base yet; search the class hierarchy for a
4038 // virtual base class.
4039 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4040 /*DetectVirtual=*/false);
4041 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4042 SemaRef.Context.getTypeDeclType(ClassDecl),
4043 BaseType, Paths)) {
4044 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4045 Path != Paths.end(); ++Path) {
4046 if (Path->back().Base->isVirtual()) {
4047 VirtualBaseSpec = Path->back().Base;
4048 break;
4049 }
4050 }
4051 }
4052 }
4053
4054 return DirectBaseSpec || VirtualBaseSpec;
4055}
4056
4057/// Handle a C++ member initializer using braced-init-list syntax.
4058MemInitResult
4059Sema::ActOnMemInitializer(Decl *ConstructorD,
4060 Scope *S,
4061 CXXScopeSpec &SS,
4062 IdentifierInfo *MemberOrBase,
4063 ParsedType TemplateTypeTy,
4064 const DeclSpec &DS,
4065 SourceLocation IdLoc,
4066 Expr *InitList,
4067 SourceLocation EllipsisLoc) {
4068 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4069 DS, IdLoc, InitList,
4070 EllipsisLoc);
4071}
4072
4073/// Handle a C++ member initializer using parentheses syntax.
4074MemInitResult
4075Sema::ActOnMemInitializer(Decl *ConstructorD,
4076 Scope *S,
4077 CXXScopeSpec &SS,
4078 IdentifierInfo *MemberOrBase,
4079 ParsedType TemplateTypeTy,
4080 const DeclSpec &DS,
4081 SourceLocation IdLoc,
4082 SourceLocation LParenLoc,
4083 ArrayRef<Expr *> Args,
4084 SourceLocation RParenLoc,
4085 SourceLocation EllipsisLoc) {
4086 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4087 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4088 DS, IdLoc, List, EllipsisLoc);
4089}
4090
4091namespace {
4092
4093// Callback to only accept typo corrections that can be a valid C++ member
4094// intializer: either a non-static field member or a base class.
4095class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4096public:
4097 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4098 : ClassDecl(ClassDecl) {}
4099
4100 bool ValidateCandidate(const TypoCorrection &candidate) override {
4101 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4102 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4103 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4104 return isa<TypeDecl>(ND);
4105 }
4106 return false;
4107 }
4108
4109 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4110 return std::make_unique<MemInitializerValidatorCCC>(*this);
4111 }
4112
4113private:
4114 CXXRecordDecl *ClassDecl;
4115};
4116
4117}
4118
4119ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4120 CXXScopeSpec &SS,
4121 ParsedType TemplateTypeTy,
4122 IdentifierInfo *MemberOrBase) {
4123 if (SS.getScopeRep() || TemplateTypeTy)
4124 return nullptr;
4125 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4126 if (Result.empty())
4127 return nullptr;
4128 ValueDecl *Member;
4129 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4130 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4131 return Member;
4132 return nullptr;
4133}
4134
4135/// Handle a C++ member initializer.
4136MemInitResult
4137Sema::BuildMemInitializer(Decl *ConstructorD,
4138 Scope *S,
4139 CXXScopeSpec &SS,
4140 IdentifierInfo *MemberOrBase,
4141 ParsedType TemplateTypeTy,
4142 const DeclSpec &DS,
4143 SourceLocation IdLoc,
4144 Expr *Init,
4145 SourceLocation EllipsisLoc) {
4146 ExprResult Res = CorrectDelayedTyposInExpr(Init);
4147 if (!Res.isUsable())
4148 return true;
4149 Init = Res.get();
4150
4151 if (!ConstructorD)
4152 return true;
4153
4154 AdjustDeclIfTemplate(ConstructorD);
4155
4156 CXXConstructorDecl *Constructor
4157 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4158 if (!Constructor) {
4159 // The user wrote a constructor initializer on a function that is
4160 // not a C++ constructor. Ignore the error for now, because we may
4161 // have more member initializers coming; we'll diagnose it just
4162 // once in ActOnMemInitializers.
4163 return true;
4164 }
4165
4166 CXXRecordDecl *ClassDecl = Constructor->getParent();
4167
4168 // C++ [class.base.init]p2:
4169 // Names in a mem-initializer-id are looked up in the scope of the
4170 // constructor's class and, if not found in that scope, are looked
4171 // up in the scope containing the constructor's definition.
4172 // [Note: if the constructor's class contains a member with the
4173 // same name as a direct or virtual base class of the class, a
4174 // mem-initializer-id naming the member or base class and composed
4175 // of a single identifier refers to the class member. A
4176 // mem-initializer-id for the hidden base class may be specified
4177 // using a qualified name. ]
4178
4179 // Look for a member, first.
4180 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4181 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4182 if (EllipsisLoc.isValid())
4183 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4184 << MemberOrBase
4185 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4186
4187 return BuildMemberInitializer(Member, Init, IdLoc);
4188 }
4189 // It didn't name a member, so see if it names a class.
4190 QualType BaseType;
4191 TypeSourceInfo *TInfo = nullptr;
4192
4193 if (TemplateTypeTy) {
4194 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4195 if (BaseType.isNull())
4196 return true;
4197 } else if (DS.getTypeSpecType() == TST_decltype) {
4198 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4199 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4200 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4201 return true;
4202 } else {
4203 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4204 LookupParsedName(R, S, &SS);
4205
4206 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4207 if (!TyD) {
4208 if (R.isAmbiguous()) return true;
4209
4210 // We don't want access-control diagnostics here.
4211 R.suppressDiagnostics();
4212
4213 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4214 bool NotUnknownSpecialization = false;
4215 DeclContext *DC = computeDeclContext(SS, false);
4216 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4217 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4218
4219 if (!NotUnknownSpecialization) {
4220 // When the scope specifier can refer to a member of an unknown
4221 // specialization, we take it as a type name.
4222 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4223 SS.getWithLocInContext(Context),
4224 *MemberOrBase, IdLoc);
4225 if (BaseType.isNull())
4226 return true;
4227
4228 TInfo = Context.CreateTypeSourceInfo(BaseType);
4229 DependentNameTypeLoc TL =
4230 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4231 if (!TL.isNull()) {
4232 TL.setNameLoc(IdLoc);
4233 TL.setElaboratedKeywordLoc(SourceLocation());
4234 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4235 }
4236
4237 R.clear();
4238 R.setLookupName(MemberOrBase);
4239 }
4240 }
4241
4242 // If no results were found, try to correct typos.
4243 TypoCorrection Corr;
4244 MemInitializerValidatorCCC CCC(ClassDecl);
4245 if (R.empty() && BaseType.isNull() &&
4246 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4247 CCC, CTK_ErrorRecovery, ClassDecl))) {
4248 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4249 // We have found a non-static data member with a similar
4250 // name to what was typed; complain and initialize that
4251 // member.
4252 diagnoseTypo(Corr,
4253 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4254 << MemberOrBase << true);
4255 return BuildMemberInitializer(Member, Init, IdLoc);
4256 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4257 const CXXBaseSpecifier *DirectBaseSpec;
4258 const CXXBaseSpecifier *VirtualBaseSpec;
4259 if (FindBaseInitializer(*this, ClassDecl,
4260 Context.getTypeDeclType(Type),
4261 DirectBaseSpec, VirtualBaseSpec)) {
4262 // We have found a direct or virtual base class with a
4263 // similar name to what was typed; complain and initialize
4264 // that base class.
4265 diagnoseTypo(Corr,
4266 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4267 << MemberOrBase << false,
4268 PDiag() /*Suppress note, we provide our own.*/);
4269
4270 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4271 : VirtualBaseSpec;
4272 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4273 << BaseSpec->getType() << BaseSpec->getSourceRange();
4274
4275 TyD = Type;
4276 }
4277 }
4278 }
4279
4280 if (!TyD && BaseType.isNull()) {
4281 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4282 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4283 return true;
4284 }
4285 }
4286
4287 if (BaseType.isNull()) {
4288 BaseType = Context.getTypeDeclType(TyD);
4289 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4290 if (SS.isSet()) {
4291 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4292 BaseType);
4293 TInfo = Context.CreateTypeSourceInfo(BaseType);
4294 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4295 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4296 TL.setElaboratedKeywordLoc(SourceLocation());
4297 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4298 }
4299 }
4300 }
4301
4302 if (!TInfo)
4303 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4304
4305 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4306}
4307
4308MemInitResult
4309Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4310 SourceLocation IdLoc) {
4311 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4312 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4313 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4314, __PRETTY_FUNCTION__))
4314 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4314, __PRETTY_FUNCTION__))
;
4315
4316 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4317 return true;
4318
4319 if (Member->isInvalidDecl())
4320 return true;
4321
4322 MultiExprArg Args;
4323 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4324 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4325 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4326 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4327 } else {
4328 // Template instantiation doesn't reconstruct ParenListExprs for us.
4329 Args = Init;
4330 }
4331
4332 SourceRange InitRange = Init->getSourceRange();
4333
4334 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4335 // Can't check initialization for a member of dependent type or when
4336 // any of the arguments are type-dependent expressions.
4337 DiscardCleanupsInEvaluationContext();
4338 } else {
4339 bool InitList = false;
4340 if (isa<InitListExpr>(Init)) {
4341 InitList = true;
4342 Args = Init;
4343 }
4344
4345 // Initialize the member.
4346 InitializedEntity MemberEntity =
4347 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4348 : InitializedEntity::InitializeMember(IndirectMember,
4349 nullptr);
4350 InitializationKind Kind =
4351 InitList ? InitializationKind::CreateDirectList(
4352 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4353 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4354 InitRange.getEnd());
4355
4356 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4357 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4358 nullptr);
4359 if (MemberInit.isInvalid())
4360 return true;
4361
4362 // C++11 [class.base.init]p7:
4363 // The initialization of each base and member constitutes a
4364 // full-expression.
4365 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4366 /*DiscardedValue*/ false);
4367 if (MemberInit.isInvalid())
4368 return true;
4369
4370 Init = MemberInit.get();
4371 }
4372
4373 if (DirectMember) {
4374 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4375 InitRange.getBegin(), Init,
4376 InitRange.getEnd());
4377 } else {
4378 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4379 InitRange.getBegin(), Init,
4380 InitRange.getEnd());
4381 }
4382}
4383
4384MemInitResult
4385Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4386 CXXRecordDecl *ClassDecl) {
4387 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4388 if (!LangOpts.CPlusPlus11)
4389 return Diag(NameLoc, diag::err_delegating_ctor)
4390 << TInfo->getTypeLoc().getLocalSourceRange();
4391 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4392
4393 bool InitList = true;
4394 MultiExprArg Args = Init;
4395 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4396 InitList = false;
4397 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4398 }
4399
4400 SourceRange InitRange = Init->getSourceRange();
4401 // Initialize the object.
4402 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4403 QualType(ClassDecl->getTypeForDecl(), 0));
4404 InitializationKind Kind =
4405 InitList ? InitializationKind::CreateDirectList(
4406 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4407 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4408 InitRange.getEnd());
4409 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4410 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4411 Args, nullptr);
4412 if (DelegationInit.isInvalid())
4413 return true;
4414
4415 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4416, __PRETTY_FUNCTION__))
4416 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4416, __PRETTY_FUNCTION__))
;
4417
4418 // C++11 [class.base.init]p7:
4419 // The initialization of each base and member constitutes a
4420 // full-expression.
4421 DelegationInit = ActOnFinishFullExpr(
4422 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4423 if (DelegationInit.isInvalid())
4424 return true;
4425
4426 // If we are in a dependent context, template instantiation will
4427 // perform this type-checking again. Just save the arguments that we
4428 // received in a ParenListExpr.
4429 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4430 // of the information that we have about the base
4431 // initializer. However, deconstructing the ASTs is a dicey process,
4432 // and this approach is far more likely to get the corner cases right.
4433 if (CurContext->isDependentContext())
4434 DelegationInit = Init;
4435
4436 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4437 DelegationInit.getAs<Expr>(),
4438 InitRange.getEnd());
4439}
4440
4441MemInitResult
4442Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4443 Expr *Init, CXXRecordDecl *ClassDecl,
4444 SourceLocation EllipsisLoc) {
4445 SourceLocation BaseLoc
4446 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4447
4448 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4449 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4450 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4451
4452 // C++ [class.base.init]p2:
4453 // [...] Unless the mem-initializer-id names a nonstatic data
4454 // member of the constructor's class or a direct or virtual base
4455 // of that class, the mem-initializer is ill-formed. A
4456 // mem-initializer-list can initialize a base class using any
4457 // name that denotes that base class type.
4458 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4459
4460 SourceRange InitRange = Init->getSourceRange();
4461 if (EllipsisLoc.isValid()) {
4462 // This is a pack expansion.
4463 if (!BaseType->containsUnexpandedParameterPack()) {
4464 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4465 << SourceRange(BaseLoc, InitRange.getEnd());
4466
4467 EllipsisLoc = SourceLocation();
4468 }
4469 } else {
4470 // Check for any unexpanded parameter packs.
4471 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4472 return true;
4473
4474 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4475 return true;
4476 }
4477
4478 // Check for direct and virtual base classes.
4479 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4480 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4481 if (!Dependent) {
4482 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4483 BaseType))
4484 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4485
4486 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4487 VirtualBaseSpec);
4488
4489 // C++ [base.class.init]p2:
4490 // Unless the mem-initializer-id names a nonstatic data member of the
4491 // constructor's class or a direct or virtual base of that class, the
4492 // mem-initializer is ill-formed.
4493 if (!DirectBaseSpec && !VirtualBaseSpec) {
4494 // If the class has any dependent bases, then it's possible that
4495 // one of those types will resolve to the same type as
4496 // BaseType. Therefore, just treat this as a dependent base
4497 // class initialization. FIXME: Should we try to check the
4498 // initialization anyway? It seems odd.
4499 if (ClassDecl->hasAnyDependentBases())
4500 Dependent = true;
4501 else
4502 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4503 << BaseType << Context.getTypeDeclType(ClassDecl)
4504 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4505 }
4506 }
4507
4508 if (Dependent) {
4509 DiscardCleanupsInEvaluationContext();
4510
4511 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4512 /*IsVirtual=*/false,
4513 InitRange.getBegin(), Init,
4514 InitRange.getEnd(), EllipsisLoc);
4515 }
4516
4517 // C++ [base.class.init]p2:
4518 // If a mem-initializer-id is ambiguous because it designates both
4519 // a direct non-virtual base class and an inherited virtual base
4520 // class, the mem-initializer is ill-formed.
4521 if (DirectBaseSpec && VirtualBaseSpec)
4522 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4523 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4524
4525 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4526 if (!BaseSpec)
4527 BaseSpec = VirtualBaseSpec;
4528
4529 // Initialize the base.
4530 bool InitList = true;
4531 MultiExprArg Args = Init;
4532 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4533 InitList = false;
4534 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4535 }
4536
4537 InitializedEntity BaseEntity =
4538 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4539 InitializationKind Kind =
4540 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4541 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4542 InitRange.getEnd());
4543 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4544 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4545 if (BaseInit.isInvalid())
4546 return true;
4547
4548 // C++11 [class.base.init]p7:
4549 // The initialization of each base and member constitutes a
4550 // full-expression.
4551 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4552 /*DiscardedValue*/ false);
4553 if (BaseInit.isInvalid())
4554 return true;
4555
4556 // If we are in a dependent context, template instantiation will
4557 // perform this type-checking again. Just save the arguments that we
4558 // received in a ParenListExpr.
4559 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4560 // of the information that we have about the base
4561 // initializer. However, deconstructing the ASTs is a dicey process,
4562 // and this approach is far more likely to get the corner cases right.
4563 if (CurContext->isDependentContext())
4564 BaseInit = Init;
4565
4566 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4567 BaseSpec->isVirtual(),
4568 InitRange.getBegin(),
4569 BaseInit.getAs<Expr>(),
4570 InitRange.getEnd(), EllipsisLoc);
4571}
4572
4573// Create a static_cast\<T&&>(expr).
4574static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4575 if (T.isNull()) T = E->getType();
4576 QualType TargetType = SemaRef.BuildReferenceType(
4577 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4578 SourceLocation ExprLoc = E->getBeginLoc();
4579 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4580 TargetType, ExprLoc);
4581
4582 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4583 SourceRange(ExprLoc, ExprLoc),
4584 E->getSourceRange()).get();
4585}
4586
4587/// ImplicitInitializerKind - How an implicit base or member initializer should
4588/// initialize its base or member.
4589enum ImplicitInitializerKind {
4590 IIK_Default,
4591 IIK_Copy,
4592 IIK_Move,
4593 IIK_Inherit
4594};
4595
4596static bool
4597BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4598 ImplicitInitializerKind ImplicitInitKind,
4599 CXXBaseSpecifier *BaseSpec,
4600 bool IsInheritedVirtualBase,
4601 CXXCtorInitializer *&CXXBaseInit) {
4602 InitializedEntity InitEntity
4603 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4604 IsInheritedVirtualBase);
4605
4606 ExprResult BaseInit;
4607
4608 switch (ImplicitInitKind) {
4609 case IIK_Inherit:
4610 case IIK_Default: {
4611 InitializationKind InitKind
4612 = InitializationKind::CreateDefault(Constructor->getLocation());
4613 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4614 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4615 break;
4616 }
4617
4618 case IIK_Move:
4619 case IIK_Copy: {
4620 bool Moving = ImplicitInitKind == IIK_Move;
4621 ParmVarDecl *Param = Constructor->getParamDecl(0);
4622 QualType ParamType = Param->getType().getNonReferenceType();
4623
4624 Expr *CopyCtorArg =
4625 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4626 SourceLocation(), Param, false,
4627 Constructor->getLocation(), ParamType,
4628 VK_LValue, nullptr);
4629
4630 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4631
4632 // Cast to the base class to avoid ambiguities.
4633 QualType ArgTy =
4634 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4635 ParamType.getQualifiers());
4636
4637 if (Moving) {
4638 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4639 }
4640
4641 CXXCastPath BasePath;
4642 BasePath.push_back(BaseSpec);
4643 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4644 CK_UncheckedDerivedToBase,
4645 Moving ? VK_XValue : VK_LValue,
4646 &BasePath).get();
4647
4648 InitializationKind InitKind
4649 = InitializationKind::CreateDirect(Constructor->getLocation(),
4650 SourceLocation(), SourceLocation());
4651 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4652 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4653 break;
4654 }
4655 }
4656
4657 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4658 if (BaseInit.isInvalid())
4659 return true;
4660
4661 CXXBaseInit =
4662 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4663 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4664 SourceLocation()),
4665 BaseSpec->isVirtual(),
4666 SourceLocation(),
4667 BaseInit.getAs<Expr>(),
4668 SourceLocation(),
4669 SourceLocation());
4670
4671 return false;
4672}
4673
4674static bool RefersToRValueRef(Expr *MemRef) {
4675 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4676 return Referenced->getType()->isRValueReferenceType();
4677}
4678
4679static bool
4680BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4681 ImplicitInitializerKind ImplicitInitKind,
4682 FieldDecl *Field, IndirectFieldDecl *Indirect,
4683 CXXCtorInitializer *&CXXMemberInit) {
4684 if (Field->isInvalidDecl())
4685 return true;
4686
4687 SourceLocation Loc = Constructor->getLocation();
4688
4689 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4690 bool Moving = ImplicitInitKind == IIK_Move;
4691 ParmVarDecl *Param = Constructor->getParamDecl(0);
4692 QualType ParamType = Param->getType().getNonReferenceType();
4693
4694 // Suppress copying zero-width bitfields.
4695 if (Field->isZeroLengthBitField(SemaRef.Context))
4696 return false;
4697
4698 Expr *MemberExprBase =
4699 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4700 SourceLocation(), Param, false,
4701 Loc, ParamType, VK_LValue, nullptr);
4702
4703 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4704
4705 if (Moving) {
4706 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4707 }
4708
4709 // Build a reference to this field within the parameter.
4710 CXXScopeSpec SS;
4711 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4712 Sema::LookupMemberName);
4713 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4714 : cast<ValueDecl>(Field), AS_public);
4715 MemberLookup.resolveKind();
4716 ExprResult CtorArg
4717 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4718 ParamType, Loc,
4719 /*IsArrow=*/false,
4720 SS,
4721 /*TemplateKWLoc=*/SourceLocation(),
4722 /*FirstQualifierInScope=*/nullptr,
4723 MemberLookup,
4724 /*TemplateArgs=*/nullptr,
4725 /*S*/nullptr);
4726 if (CtorArg.isInvalid())
4727 return true;
4728
4729 // C++11 [class.copy]p15:
4730 // - if a member m has rvalue reference type T&&, it is direct-initialized
4731 // with static_cast<T&&>(x.m);
4732 if (RefersToRValueRef(CtorArg.get())) {
4733 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4734 }
4735
4736 InitializedEntity Entity =
4737 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4738 /*Implicit*/ true)
4739 : InitializedEntity::InitializeMember(Field, nullptr,
4740 /*Implicit*/ true);
4741
4742 // Direct-initialize to use the copy constructor.
4743 InitializationKind InitKind =
4744 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4745
4746 Expr *CtorArgE = CtorArg.getAs<Expr>();
4747 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4748 ExprResult MemberInit =
4749 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4750 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4751 if (MemberInit.isInvalid())
4752 return true;
4753
4754 if (Indirect)
4755 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4756 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4757 else
4758 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4759 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4760 return false;
4761 }
4762
4763 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4764, __PRETTY_FUNCTION__))
4764 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4764, __PRETTY_FUNCTION__))
;
4765
4766 QualType FieldBaseElementType =
4767 SemaRef.Context.getBaseElementType(Field->getType());
4768
4769 if (FieldBaseElementType->isRecordType()) {
4770 InitializedEntity InitEntity =
4771 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4772 /*Implicit*/ true)
4773 : InitializedEntity::InitializeMember(Field, nullptr,
4774 /*Implicit*/ true);
4775 InitializationKind InitKind =
4776 InitializationKind::CreateDefault(Loc);
4777
4778 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4779 ExprResult MemberInit =
4780 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4781
4782 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4783 if (MemberInit.isInvalid())
4784 return true;
4785
4786 if (Indirect)
4787 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4788 Indirect, Loc,
4789 Loc,
4790 MemberInit.get(),
4791 Loc);
4792 else
4793 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4794 Field, Loc, Loc,
4795 MemberInit.get(),
4796 Loc);
4797 return false;
4798 }
4799
4800 if (!Field->getParent()->isUnion()) {
4801 if (FieldBaseElementType->isReferenceType()) {
4802 SemaRef.Diag(Constructor->getLocation(),
4803 diag::err_uninitialized_member_in_ctor)
4804 << (int)Constructor->isImplicit()
4805 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4806 << 0 << Field->getDeclName();
4807 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4808 return true;
4809 }
4810
4811 if (FieldBaseElementType.isConstQualified()) {
4812 SemaRef.Diag(Constructor->getLocation(),
4813 diag::err_uninitialized_member_in_ctor)
4814 << (int)Constructor->isImplicit()
4815 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4816 << 1 << Field->getDeclName();
4817 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4818 return true;
4819 }
4820 }
4821
4822 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4823 // ARC and Weak:
4824 // Default-initialize Objective-C pointers to NULL.
4825 CXXMemberInit
4826 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4827 Loc, Loc,
4828 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4829 Loc);
4830 return false;
4831 }
4832
4833 // Nothing to initialize.
4834 CXXMemberInit = nullptr;
4835 return false;
4836}
4837
4838namespace {
4839struct BaseAndFieldInfo {
4840 Sema &S;
4841 CXXConstructorDecl *Ctor;
4842 bool AnyErrorsInInits;
4843 ImplicitInitializerKind IIK;
4844 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4845 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4846 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4847
4848 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4849 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4850 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4851 if (Ctor->getInheritedConstructor())
4852 IIK = IIK_Inherit;
4853 else if (Generated && Ctor->isCopyConstructor())
4854 IIK = IIK_Copy;
4855 else if (Generated && Ctor->isMoveConstructor())
4856 IIK = IIK_Move;
4857 else
4858 IIK = IIK_Default;
4859 }
4860
4861 bool isImplicitCopyOrMove() const {
4862 switch (IIK) {
4863 case IIK_Copy:
4864 case IIK_Move:
4865 return true;
4866
4867 case IIK_Default:
4868 case IIK_Inherit:
4869 return false;
4870 }
4871
4872 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 4872)
;
4873 }
4874
4875 bool addFieldInitializer(CXXCtorInitializer *Init) {
4876 AllToInit.push_back(Init);
4877
4878 // Check whether this initializer makes the field "used".
4879 if (Init->getInit()->HasSideEffects(S.Context))
4880 S.UnusedPrivateFields.remove(Init->getAnyMember());
4881
4882 return false;
4883 }
4884
4885 bool isInactiveUnionMember(FieldDecl *Field) {
4886 RecordDecl *Record = Field->getParent();
4887 if (!Record->isUnion())
4888 return false;
4889
4890 if (FieldDecl *Active =
4891 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4892 return Active != Field->getCanonicalDecl();
4893
4894 // In an implicit copy or move constructor, ignore any in-class initializer.
4895 if (isImplicitCopyOrMove())
4896 return true;
4897
4898 // If there's no explicit initialization, the field is active only if it
4899 // has an in-class initializer...
4900 if (Field->hasInClassInitializer())
4901 return false;
4902 // ... or it's an anonymous struct or union whose class has an in-class
4903 // initializer.
4904 if (!Field->isAnonymousStructOrUnion())
4905 return true;
4906 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4907 return !FieldRD->hasInClassInitializer();
4908 }
4909
4910 /// Determine whether the given field is, or is within, a union member
4911 /// that is inactive (because there was an initializer given for a different
4912 /// member of the union, or because the union was not initialized at all).
4913 bool isWithinInactiveUnionMember(FieldDecl *Field,
4914 IndirectFieldDecl *Indirect) {
4915 if (!Indirect)
4916 return isInactiveUnionMember(Field);
4917
4918 for (auto *C : Indirect->chain()) {
4919 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4920 if (Field && isInactiveUnionMember(Field))
4921 return true;
4922 }
4923 return false;
4924 }
4925};
4926}
4927
4928/// Determine whether the given type is an incomplete or zero-lenfgth
4929/// array type.
4930static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4931 if (T->isIncompleteArrayType())
4932 return true;
4933
4934 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4935 if (!ArrayT->getSize())
4936 return true;
4937
4938 T = ArrayT->getElementType();
4939 }
4940
4941 return false;
4942}
4943
4944static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4945 FieldDecl *Field,
4946 IndirectFieldDecl *Indirect = nullptr) {
4947 if (Field->isInvalidDecl())
4948 return false;
4949
4950 // Overwhelmingly common case: we have a direct initializer for this field.
4951 if (CXXCtorInitializer *Init =
4952 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4953 return Info.addFieldInitializer(Init);
4954
4955 // C++11 [class.base.init]p8:
4956 // if the entity is a non-static data member that has a
4957 // brace-or-equal-initializer and either
4958 // -- the constructor's class is a union and no other variant member of that
4959 // union is designated by a mem-initializer-id or
4960 // -- the constructor's class is not a union, and, if the entity is a member
4961 // of an anonymous union, no other member of that union is designated by
4962 // a mem-initializer-id,
4963 // the entity is initialized as specified in [dcl.init].
4964 //
4965 // We also apply the same rules to handle anonymous structs within anonymous
4966 // unions.
4967 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4968 return false;
4969
4970 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4971 ExprResult DIE =
4972 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4973 if (DIE.isInvalid())
4974 return true;
4975
4976 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4977 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4978
4979 CXXCtorInitializer *Init;
4980 if (Indirect)
4981 Init = new (SemaRef.Context)
4982 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4983 SourceLocation(), DIE.get(), SourceLocation());
4984 else
4985 Init = new (SemaRef.Context)
4986 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4987 SourceLocation(), DIE.get(), SourceLocation());
4988 return Info.addFieldInitializer(Init);
4989 }
4990
4991 // Don't initialize incomplete or zero-length arrays.
4992 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4993 return false;
4994
4995 // Don't try to build an implicit initializer if there were semantic
4996 // errors in any of the initializers (and therefore we might be
4997 // missing some that the user actually wrote).
4998 if (Info.AnyErrorsInInits)
4999 return false;
5000
5001 CXXCtorInitializer *Init = nullptr;
5002 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5003 Indirect, Init))
5004 return true;
5005
5006 if (!Init)
5007 return false;
5008
5009 return Info.addFieldInitializer(Init);
5010}
5011
5012bool
5013Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5014 CXXCtorInitializer *Initializer) {
5015 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5015, __PRETTY_FUNCTION__))
;
5016 Constructor->setNumCtorInitializers(1);
5017 CXXCtorInitializer **initializer =
5018 new (Context) CXXCtorInitializer*[1];
5019 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5020 Constructor->setCtorInitializers(initializer);
5021
5022 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5023 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5024 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5025 }
5026
5027 DelegatingCtorDecls.push_back(Constructor);
5028
5029 DiagnoseUninitializedFields(*this, Constructor);
5030
5031 return false;
5032}
5033
5034bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5035 ArrayRef<CXXCtorInitializer *> Initializers) {
5036 if (Constructor->isDependentContext()) {
5037 // Just store the initializers as written, they will be checked during
5038 // instantiation.
5039 if (!Initializers.empty()) {
5040 Constructor->setNumCtorInitializers(Initializers.size());
5041 CXXCtorInitializer **baseOrMemberInitializers =
5042 new (Context) CXXCtorInitializer*[Initializers.size()];
5043 memcpy(baseOrMemberInitializers, Initializers.data(),
5044 Initializers.size() * sizeof(CXXCtorInitializer*));
5045 Constructor->setCtorInitializers(baseOrMemberInitializers);
5046 }
5047
5048 // Let template instantiation know whether we had errors.
5049 if (AnyErrors)
5050 Constructor->setInvalidDecl();
5051
5052 return false;
5053 }
5054
5055 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5056
5057 // We need to build the initializer AST according to order of construction
5058 // and not what user specified in the Initializers list.
5059 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5060 if (!ClassDecl)
5061 return true;
5062
5063 bool HadError = false;
5064
5065 for (unsigned i = 0; i < Initializers.size(); i++) {
5066 CXXCtorInitializer *Member = Initializers[i];
5067
5068 if (Member->isBaseInitializer())
5069 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5070 else {
5071 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5072
5073 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5074 for (auto *C : F->chain()) {
5075 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5076 if (FD && FD->getParent()->isUnion())
5077 Info.ActiveUnionMember.insert(std::make_pair(
5078 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5079 }
5080 } else if (FieldDecl *FD = Member->getMember()) {
5081 if (FD->getParent()->isUnion())
5082 Info.ActiveUnionMember.insert(std::make_pair(
5083 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5084 }
5085 }
5086 }
5087
5088 // Keep track of the direct virtual bases.
5089 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5090 for (auto &I : ClassDecl->bases()) {
5091 if (I.isVirtual())
5092 DirectVBases.insert(&I);
5093 }
5094
5095 // Push virtual bases before others.
5096 for (auto &VBase : ClassDecl->vbases()) {
5097 if (CXXCtorInitializer *Value
5098 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5099 // [class.base.init]p7, per DR257:
5100 // A mem-initializer where the mem-initializer-id names a virtual base
5101 // class is ignored during execution of a constructor of any class that
5102 // is not the most derived class.
5103 if (ClassDecl->isAbstract()) {
5104 // FIXME: Provide a fixit to remove the base specifier. This requires
5105 // tracking the location of the associated comma for a base specifier.
5106 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5107 << VBase.getType() << ClassDecl;
5108 DiagnoseAbstractType(ClassDecl);
5109 }
5110
5111 Info.AllToInit.push_back(Value);
5112 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5113 // [class.base.init]p8, per DR257:
5114 // If a given [...] base class is not named by a mem-initializer-id
5115 // [...] and the entity is not a virtual base class of an abstract
5116 // class, then [...] the entity is default-initialized.
5117 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5118 CXXCtorInitializer *CXXBaseInit;
5119 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5120 &VBase, IsInheritedVirtualBase,
5121 CXXBaseInit)) {
5122 HadError = true;
5123 continue;
5124 }
5125
5126 Info.AllToInit.push_back(CXXBaseInit);
5127 }
5128 }
5129
5130 // Non-virtual bases.
5131 for (auto &Base : ClassDecl->bases()) {
5132 // Virtuals are in the virtual base list and already constructed.
5133 if (Base.isVirtual())
5134 continue;
5135
5136 if (CXXCtorInitializer *Value
5137 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5138 Info.AllToInit.push_back(Value);
5139 } else if (!AnyErrors) {
5140 CXXCtorInitializer *CXXBaseInit;
5141 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5142 &Base, /*IsInheritedVirtualBase=*/false,
5143 CXXBaseInit)) {
5144 HadError = true;
5145 continue;
5146 }
5147
5148 Info.AllToInit.push_back(CXXBaseInit);
5149 }
5150 }
5151
5152 // Fields.
5153 for (auto *Mem : ClassDecl->decls()) {
5154 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5155 // C++ [class.bit]p2:
5156 // A declaration for a bit-field that omits the identifier declares an
5157 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5158 // initialized.
5159 if (F->isUnnamedBitfield())
5160 continue;
5161
5162 // If we're not generating the implicit copy/move constructor, then we'll
5163 // handle anonymous struct/union fields based on their individual
5164 // indirect fields.
5165 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5166 continue;
5167
5168 if (CollectFieldInitializer(*this, Info, F))
5169 HadError = true;
5170 continue;
5171 }
5172
5173 // Beyond this point, we only consider default initialization.
5174 if (Info.isImplicitCopyOrMove())
5175 continue;
5176
5177 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5178 if (F->getType()->isIncompleteArrayType()) {
5179 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5180, __PRETTY_FUNCTION__))
5180 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5180, __PRETTY_FUNCTION__))
;
5181 continue;
5182 }
5183
5184 // Initialize each field of an anonymous struct individually.
5185 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5186 HadError = true;
5187
5188 continue;
5189 }
5190 }
5191
5192 unsigned NumInitializers = Info.AllToInit.size();
5193 if (NumInitializers > 0) {
5194 Constructor->setNumCtorInitializers(NumInitializers);
5195 CXXCtorInitializer **baseOrMemberInitializers =
5196 new (Context) CXXCtorInitializer*[NumInitializers];
5197 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5198 NumInitializers * sizeof(CXXCtorInitializer*));
5199 Constructor->setCtorInitializers(baseOrMemberInitializers);
5200
5201 // Constructors implicitly reference the base and member
5202 // destructors.
5203 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5204 Constructor->getParent());
5205 }
5206
5207 return HadError;
5208}
5209
5210static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5211 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5212 const RecordDecl *RD = RT->getDecl();
5213 if (RD->isAnonymousStructOrUnion()) {
5214 for (auto *Field : RD->fields())
5215 PopulateKeysForFields(Field, IdealInits);
5216 return;
5217 }
5218 }
5219 IdealInits.push_back(Field->getCanonicalDecl());
5220}
5221
5222static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5223 return Context.getCanonicalType(BaseType).getTypePtr();
5224}
5225
5226static const void *GetKeyForMember(ASTContext &Context,
5227 CXXCtorInitializer *Member) {
5228 if (!Member->isAnyMemberInitializer())
5229 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5230
5231 return Member->getAnyMember()->getCanonicalDecl();
5232}
5233
5234static void DiagnoseBaseOrMemInitializerOrder(
5235 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5236 ArrayRef<CXXCtorInitializer *> Inits) {
5237 if (Constructor->getDeclContext()->isDependentContext())
5238 return;
5239
5240 // Don't check initializers order unless the warning is enabled at the
5241 // location of at least one initializer.
5242 bool ShouldCheckOrder = false;
5243 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5244 CXXCtorInitializer *Init = Inits[InitIndex];
5245 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5246 Init->getSourceLocation())) {
5247 ShouldCheckOrder = true;
5248 break;
5249 }
5250 }
5251 if (!ShouldCheckOrder)
5252 return;
5253
5254 // Build the list of bases and members in the order that they'll
5255 // actually be initialized. The explicit initializers should be in
5256 // this same order but may be missing things.
5257 SmallVector<const void*, 32> IdealInitKeys;
5258
5259 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5260
5261 // 1. Virtual bases.
5262 for (const auto &VBase : ClassDecl->vbases())
5263 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5264
5265 // 2. Non-virtual bases.
5266 for (const auto &Base : ClassDecl->bases()) {
5267 if (Base.isVirtual())
5268 continue;
5269 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5270 }
5271
5272 // 3. Direct fields.
5273 for (auto *Field : ClassDecl->fields()) {
5274 if (Field->isUnnamedBitfield())
5275 continue;
5276
5277 PopulateKeysForFields(Field, IdealInitKeys);
5278 }
5279
5280 unsigned NumIdealInits = IdealInitKeys.size();
5281 unsigned IdealIndex = 0;
5282
5283 CXXCtorInitializer *PrevInit = nullptr;
5284 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5285 CXXCtorInitializer *Init = Inits[InitIndex];
5286 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5287
5288 // Scan forward to try to find this initializer in the idealized
5289 // initializers list.
5290 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5291 if (InitKey == IdealInitKeys[IdealIndex])
5292 break;
5293
5294 // If we didn't find this initializer, it must be because we
5295 // scanned past it on a previous iteration. That can only
5296 // happen if we're out of order; emit a warning.
5297 if (IdealIndex == NumIdealInits && PrevInit) {
5298 Sema::SemaDiagnosticBuilder D =
5299 SemaRef.Diag(PrevInit->getSourceLocation(),
5300 diag::warn_initializer_out_of_order);
5301
5302 if (PrevInit->isAnyMemberInitializer())
5303 D << 0 << PrevInit->getAnyMember()->getDeclName();
5304 else
5305 D << 1 << PrevInit->getTypeSourceInfo()->getType();
5306
5307 if (Init->isAnyMemberInitializer())
5308 D << 0 << Init->getAnyMember()->getDeclName();
5309 else
5310 D << 1 << Init->getTypeSourceInfo()->getType();
5311
5312 // Move back to the initializer's location in the ideal list.
5313 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5314 if (InitKey == IdealInitKeys[IdealIndex])
5315 break;
5316
5317 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5318, __PRETTY_FUNCTION__))
5318 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5318, __PRETTY_FUNCTION__))
;
5319 }
5320
5321 PrevInit = Init;
5322 }
5323}
5324
5325namespace {
5326bool CheckRedundantInit(Sema &S,
5327 CXXCtorInitializer *Init,
5328 CXXCtorInitializer *&PrevInit) {
5329 if (!PrevInit) {
5330 PrevInit = Init;
5331 return false;
5332 }
5333
5334 if (FieldDecl *Field = Init->getAnyMember())
5335 S.Diag(Init->getSourceLocation(),
5336 diag::err_multiple_mem_initialization)
5337 << Field->getDeclName()
5338 << Init->getSourceRange();
5339 else {
5340 const Type *BaseClass = Init->getBaseClass();
5341 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5341, __PRETTY_FUNCTION__))
;
5342 S.Diag(Init->getSourceLocation(),
5343 diag::err_multiple_base_initialization)
5344 << QualType(BaseClass, 0)
5345 << Init->getSourceRange();
5346 }
5347 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5348 << 0 << PrevInit->getSourceRange();
5349
5350 return true;
5351}
5352
5353typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5354typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5355
5356bool CheckRedundantUnionInit(Sema &S,
5357 CXXCtorInitializer *Init,
5358 RedundantUnionMap &Unions) {
5359 FieldDecl *Field = Init->getAnyMember();
5360 RecordDecl *Parent = Field->getParent();
5361 NamedDecl *Child = Field;
5362
5363 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5364 if (Parent->isUnion()) {
5365 UnionEntry &En = Unions[Parent];
5366 if (En.first && En.first != Child) {
5367 S.Diag(Init->getSourceLocation(),
5368 diag::err_multiple_mem_union_initialization)
5369 << Field->getDeclName()
5370 << Init->getSourceRange();
5371 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5372 << 0 << En.second->getSourceRange();
5373 return true;
5374 }
5375 if (!En.first) {
5376 En.first = Child;
5377 En.second = Init;
5378 }
5379 if (!Parent->isAnonymousStructOrUnion())
5380 return false;
5381 }
5382
5383 Child = Parent;
5384 Parent = cast<RecordDecl>(Parent->getDeclContext());
5385 }
5386
5387 return false;
5388}
5389}
5390
5391/// ActOnMemInitializers - Handle the member initializers for a constructor.
5392void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5393 SourceLocation ColonLoc,
5394 ArrayRef<CXXCtorInitializer*> MemInits,
5395 bool AnyErrors) {
5396 if (!ConstructorDecl)
5397 return;
5398
5399 AdjustDeclIfTemplate(ConstructorDecl);
5400
5401 CXXConstructorDecl *Constructor
5402 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5403
5404 if (!Constructor) {
5405 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5406 return;
5407 }
5408
5409 // Mapping for the duplicate initializers check.
5410 // For member initializers, this is keyed with a FieldDecl*.
5411 // For base initializers, this is keyed with a Type*.
5412 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5413
5414 // Mapping for the inconsistent anonymous-union initializers check.
5415 RedundantUnionMap MemberUnions;
5416
5417 bool HadError = false;
5418 for (unsigned i = 0; i < MemInits.size(); i++) {
5419 CXXCtorInitializer *Init = MemInits[i];
5420
5421 // Set the source order index.
5422 Init->setSourceOrder(i);
5423
5424 if (Init->isAnyMemberInitializer()) {
5425 const void *Key = GetKeyForMember(Context, Init);
5426 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5427 CheckRedundantUnionInit(*this, Init, MemberUnions))
5428 HadError = true;
5429 } else if (Init->isBaseInitializer()) {
5430 const void *Key = GetKeyForMember(Context, Init);
5431 if (CheckRedundantInit(*this, Init, Members[Key]))
5432 HadError = true;
5433 } else {
5434 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5434, __PRETTY_FUNCTION__))
;
5435 // This must be the only initializer
5436 if (MemInits.size() != 1) {
5437 Diag(Init->getSourceLocation(),
5438 diag::err_delegating_initializer_alone)
5439 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5440 // We will treat this as being the only initializer.
5441 }
5442 SetDelegatingInitializer(Constructor, MemInits[i]);
5443 // Return immediately as the initializer is set.
5444 return;
5445 }
5446 }
5447
5448 if (HadError)
5449 return;
5450
5451 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5452
5453 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5454
5455 DiagnoseUninitializedFields(*this, Constructor);
5456}
5457
5458void
5459Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5460 CXXRecordDecl *ClassDecl) {
5461 // Ignore dependent contexts. Also ignore unions, since their members never
5462 // have destructors implicitly called.
5463 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
18
Assuming the condition is false
19
Calling 'TagDecl::isUnion'
22
Returning from 'TagDecl::isUnion'
23
Taking false branch
5464 return;
5465
5466 // FIXME: all the access-control diagnostics are positioned on the
5467 // field/base declaration. That's probably good; that said, the
5468 // user might reasonably want to know why the destructor is being
5469 // emitted, and we currently don't say.
5470
5471 // Non-static data members.
5472 for (auto *Field : ClassDecl->fields()) {
5473 if (Field->isInvalidDecl())
5474 continue;
5475
5476 // Don't destroy incomplete or zero-length arrays.
5477 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5478 continue;
5479
5480 QualType FieldType = Context.getBaseElementType(Field->getType());
5481
5482 const RecordType* RT = FieldType->getAs<RecordType>();
5483 if (!RT)
5484 continue;
5485
5486 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5487 if (FieldClassDecl->isInvalidDecl())
5488 continue;
5489 if (FieldClassDecl->hasIrrelevantDestructor())
5490 continue;
5491 // The destructor for an implicit anonymous union member is never invoked.
5492 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5493 continue;
5494
5495 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5496 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5496, __PRETTY_FUNCTION__))
;
5497 CheckDestructorAccess(Field->getLocation(), Dtor,
5498 PDiag(diag::err_access_dtor_field)
5499 << Field->getDeclName()
5500 << FieldType);
5501
5502 MarkFunctionReferenced(Location, Dtor);
5503 DiagnoseUseOfDecl(Dtor, Location);
5504 }
5505
5506 // We only potentially invoke the destructors of potentially constructed
5507 // subobjects.
5508 bool VisitVirtualBases = !ClassDecl->isAbstract();
24
Assuming the condition is false
5509
5510 // If the destructor exists and has already been marked used in the MS ABI,
5511 // then virtual base destructors have already been checked and marked used.
5512 // Skip checking them again to avoid duplicate diagnostics.
5513 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
25
Taking true branch
5514 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5515 if (Dtor && Dtor->isUsed())
26
Assuming 'Dtor' is null
5516 VisitVirtualBases = false;
5517 }
5518
5519 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5520
5521 // Bases.
5522 for (const auto &Base : ClassDecl->bases()) {
27
Assuming '__begin1' is not equal to '__end1'
5523 // Bases are always records in a well-formed non-dependent class.
5524 const RecordType *RT = Base.getType()->getAs<RecordType>();
28
Assuming the object is not a 'RecordType'
29
'RT' initialized to a null pointer value
5525
5526 // Remember direct virtual bases.
5527 if (Base.isVirtual()) {
30
Assuming the condition is false
31
Taking false branch
5528 if (!VisitVirtualBases)
5529 continue;
5530 DirectVirtualBases.insert(RT);
5531 }
5532
5533 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
32
Called C++ object pointer is null
5534 // If our base class is invalid, we probably can't get its dtor anyway.
5535 if (BaseClassDecl->isInvalidDecl())
5536 continue;
5537 if (BaseClassDecl->hasIrrelevantDestructor())
5538 continue;
5539
5540 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5541 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5541, __PRETTY_FUNCTION__))
;
5542
5543 // FIXME: caret should be on the start of the class name
5544 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5545 PDiag(diag::err_access_dtor_base)
5546 << Base.getType() << Base.getSourceRange(),
5547 Context.getTypeDeclType(ClassDecl));
5548
5549 MarkFunctionReferenced(Location, Dtor);
5550 DiagnoseUseOfDecl(Dtor, Location);
5551 }
5552
5553 if (VisitVirtualBases)
5554 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5555 &DirectVirtualBases);
5556}
5557
5558void Sema::MarkVirtualBaseDestructorsReferenced(
5559 SourceLocation Location, CXXRecordDecl *ClassDecl,
5560 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5561 // Virtual bases.
5562 for (const auto &VBase : ClassDecl->vbases()) {
5563 // Bases are always records in a well-formed non-dependent class.
5564 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5565
5566 // Ignore already visited direct virtual bases.
5567 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5568 continue;
5569
5570 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5571 // If our base class is invalid, we probably can't get its dtor anyway.
5572 if (BaseClassDecl->isInvalidDecl())
5573 continue;
5574 if (BaseClassDecl->hasIrrelevantDestructor())
5575 continue;
5576
5577 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5578 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5578, __PRETTY_FUNCTION__))
;
5579 if (CheckDestructorAccess(
5580 ClassDecl->getLocation(), Dtor,
5581 PDiag(diag::err_access_dtor_vbase)
5582 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5583 Context.getTypeDeclType(ClassDecl)) ==
5584 AR_accessible) {
5585 CheckDerivedToBaseConversion(
5586 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5587 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5588 SourceRange(), DeclarationName(), nullptr);
5589 }
5590
5591 MarkFunctionReferenced(Location, Dtor);
5592 DiagnoseUseOfDecl(Dtor, Location);
5593 }
5594}
5595
5596void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5597 if (!CDtorDecl)
5598 return;
5599
5600 if (CXXConstructorDecl *Constructor
5601 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5602 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5603 DiagnoseUninitializedFields(*this, Constructor);
5604 }
5605}
5606
5607bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5608 if (!getLangOpts().CPlusPlus)
5609 return false;
5610
5611 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5612 if (!RD)
5613 return false;
5614
5615 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5616 // class template specialization here, but doing so breaks a lot of code.
5617
5618 // We can't answer whether something is abstract until it has a
5619 // definition. If it's currently being defined, we'll walk back
5620 // over all the declarations when we have a full definition.
5621 const CXXRecordDecl *Def = RD->getDefinition();
5622 if (!Def || Def->isBeingDefined())
5623 return false;
5624
5625 return RD->isAbstract();
5626}
5627
5628bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5629 TypeDiagnoser &Diagnoser) {
5630 if (!isAbstractType(Loc, T))
5631 return false;
5632
5633 T = Context.getBaseElementType(T);
5634 Diagnoser.diagnose(*this, Loc, T);
5635 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5636 return true;
5637}
5638
5639void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5640 // Check if we've already emitted the list of pure virtual functions
5641 // for this class.
5642 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5643 return;
5644
5645 // If the diagnostic is suppressed, don't emit the notes. We're only
5646 // going to emit them once, so try to attach them to a diagnostic we're
5647 // actually going to show.
5648 if (Diags.isLastDiagnosticIgnored())
5649 return;
5650
5651 CXXFinalOverriderMap FinalOverriders;
5652 RD->getFinalOverriders(FinalOverriders);
5653
5654 // Keep a set of seen pure methods so we won't diagnose the same method
5655 // more than once.
5656 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5657
5658 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5659 MEnd = FinalOverriders.end();
5660 M != MEnd;
5661 ++M) {
5662 for (OverridingMethods::iterator SO = M->second.begin(),
5663 SOEnd = M->second.end();
5664 SO != SOEnd; ++SO) {
5665 // C++ [class.abstract]p4:
5666 // A class is abstract if it contains or inherits at least one
5667 // pure virtual function for which the final overrider is pure
5668 // virtual.
5669
5670 //
5671 if (SO->second.size() != 1)
5672 continue;
5673
5674 if (!SO->second.front().Method->isPure())
5675 continue;
5676
5677 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5678 continue;
5679
5680 Diag(SO->second.front().Method->getLocation(),
5681 diag::note_pure_virtual_function)
5682 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5683 }
5684 }
5685
5686 if (!PureVirtualClassDiagSet)
5687 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5688 PureVirtualClassDiagSet->insert(RD);
5689}
5690
5691namespace {
5692struct AbstractUsageInfo {
5693 Sema &S;
5694 CXXRecordDecl *Record;
5695 CanQualType AbstractType;
5696 bool Invalid;
5697
5698 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5699 : S(S), Record(Record),
5700 AbstractType(S.Context.getCanonicalType(
5701 S.Context.getTypeDeclType(Record))),
5702 Invalid(false) {}
5703
5704 void DiagnoseAbstractType() {
5705 if (Invalid) return;
5706 S.DiagnoseAbstractType(Record);
5707 Invalid = true;
5708 }
5709
5710 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5711};
5712
5713struct CheckAbstractUsage {
5714 AbstractUsageInfo &Info;
5715 const NamedDecl *Ctx;
5716
5717 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5718 : Info(Info), Ctx(Ctx) {}
5719
5720 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5721 switch (TL.getTypeLocClass()) {
5722#define ABSTRACT_TYPELOC(CLASS, PARENT)
5723#define TYPELOC(CLASS, PARENT) \
5724 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5725#include "clang/AST/TypeLocNodes.def"
5726 }
5727 }
5728
5729 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5730 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5731 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5732 if (!TL.getParam(I))
5733 continue;
5734
5735 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5736 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5737 }
5738 }
5739
5740 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5741 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5742 }
5743
5744 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5745 // Visit the type parameters from a permissive context.
5746 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5747 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5748 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5749 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5750 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5751 // TODO: other template argument types?
5752 }
5753 }
5754
5755 // Visit pointee types from a permissive context.
5756#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5757 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5758 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5759 }
5760 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5761 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5762 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5763 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5764 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5765
5766 /// Handle all the types we haven't given a more specific
5767 /// implementation for above.
5768 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5769 // Every other kind of type that we haven't called out already
5770 // that has an inner type is either (1) sugar or (2) contains that
5771 // inner type in some way as a subobject.
5772 if (TypeLoc Next = TL.getNextTypeLoc())
5773 return Visit(Next, Sel);
5774
5775 // If there's no inner type and we're in a permissive context,
5776 // don't diagnose.
5777 if (Sel == Sema::AbstractNone) return;
5778
5779 // Check whether the type matches the abstract type.
5780 QualType T = TL.getType();
5781 if (T->isArrayType()) {
5782 Sel = Sema::AbstractArrayType;
5783 T = Info.S.Context.getBaseElementType(T);
5784 }
5785 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5786 if (CT != Info.AbstractType) return;
5787
5788 // It matched; do some magic.
5789 if (Sel == Sema::AbstractArrayType) {
5790 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5791 << T << TL.getSourceRange();
5792 } else {
5793 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5794 << Sel << T << TL.getSourceRange();
5795 }
5796 Info.DiagnoseAbstractType();
5797 }
5798};
5799
5800void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5801 Sema::AbstractDiagSelID Sel) {
5802 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5803}
5804
5805}
5806
5807/// Check for invalid uses of an abstract type in a method declaration.
5808static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5809 CXXMethodDecl *MD) {
5810 // No need to do the check on definitions, which require that
5811 // the return/param types be complete.
5812 if (MD->doesThisDeclarationHaveABody())
5813 return;
5814
5815 // For safety's sake, just ignore it if we don't have type source
5816 // information. This should never happen for non-implicit methods,
5817 // but...
5818 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5819 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5820}
5821
5822/// Check for invalid uses of an abstract type within a class definition.
5823static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5824 CXXRecordDecl *RD) {
5825 for (auto *D : RD->decls()) {
5826 if (D->isImplicit()) continue;
5827
5828 // Methods and method templates.
5829 if (isa<CXXMethodDecl>(D)) {
5830 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5831 } else if (isa<FunctionTemplateDecl>(D)) {
5832 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5833 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5834
5835 // Fields and static variables.
5836 } else if (isa<FieldDecl>(D)) {
5837 FieldDecl *FD = cast<FieldDecl>(D);
5838 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5839 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5840 } else if (isa<VarDecl>(D)) {
5841 VarDecl *VD = cast<VarDecl>(D);
5842 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5843 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5844
5845 // Nested classes and class templates.
5846 } else if (isa<CXXRecordDecl>(D)) {
5847 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5848 } else if (isa<ClassTemplateDecl>(D)) {
5849 CheckAbstractClassUsage(Info,
5850 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5851 }
5852 }
5853}
5854
5855static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5856 Attr *ClassAttr = getDLLAttr(Class);
5857 if (!ClassAttr)
5858 return;
5859
5860 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 5860, __PRETTY_FUNCTION__))
;
5861
5862 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5863
5864 if (TSK == TSK_ExplicitInstantiationDeclaration)
5865 // Don't go any further if this is just an explicit instantiation
5866 // declaration.
5867 return;
5868
5869 // Add a context note to explain how we got to any diagnostics produced below.
5870 struct MarkingClassDllexported {
5871 Sema &S;
5872 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5873 SourceLocation AttrLoc)
5874 : S(S) {
5875 Sema::CodeSynthesisContext Ctx;
5876 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5877 Ctx.PointOfInstantiation = AttrLoc;
5878 Ctx.Entity = Class;
5879 S.pushCodeSynthesisContext(Ctx);
5880 }
5881 ~MarkingClassDllexported() {
5882 S.popCodeSynthesisContext();
5883 }
5884 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5885
5886 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5887 S.MarkVTableUsed(Class->getLocation(), Class, true);
5888
5889 for (Decl *Member : Class->decls()) {
5890 // Defined static variables that are members of an exported base
5891 // class must be marked export too.
5892 auto *VD = dyn_cast<VarDecl>(Member);
5893 if (VD && Member->getAttr<DLLExportAttr>() &&
5894 VD->getStorageClass() == SC_Static &&
5895 TSK == TSK_ImplicitInstantiation)
5896 S.MarkVariableReferenced(VD->getLocation(), VD);
5897
5898 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5899 if (!MD)
5900 continue;
5901
5902 if (Member->getAttr<DLLExportAttr>()) {
5903 if (MD->isUserProvided()) {
5904 // Instantiate non-default class member functions ...
5905
5906 // .. except for certain kinds of template specializations.
5907 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5908 continue;
5909
5910 S.MarkFunctionReferenced(Class->getLocation(), MD);
5911
5912 // The function will be passed to the consumer when its definition is
5913 // encountered.
5914 } else if (MD->isExplicitlyDefaulted()) {
5915 // Synthesize and instantiate explicitly defaulted methods.
5916 S.MarkFunctionReferenced(Class->getLocation(), MD);
5917
5918 if (TSK != TSK_ExplicitInstantiationDefinition) {
5919 // Except for explicit instantiation defs, we will not see the
5920 // definition again later, so pass it to the consumer now.
5921 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5922 }
5923 } else if (!MD->isTrivial() ||
5924 MD->isCopyAssignmentOperator() ||
5925 MD->isMoveAssignmentOperator()) {
5926 // Synthesize and instantiate non-trivial implicit methods, and the copy
5927 // and move assignment operators. The latter are exported even if they
5928 // are trivial, because the address of an operator can be taken and
5929 // should compare equal across libraries.
5930 S.MarkFunctionReferenced(Class->getLocation(), MD);
5931
5932 // There is no later point when we will see the definition of this
5933 // function, so pass it to the consumer now.
5934 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5935 }
5936 }
5937 }
5938}
5939
5940static void checkForMultipleExportedDefaultConstructors(Sema &S,
5941 CXXRecordDecl *Class) {
5942 // Only the MS ABI has default constructor closures, so we don't need to do
5943 // this semantic checking anywhere else.
5944 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5945 return;
5946
5947 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5948 for (Decl *Member : Class->decls()) {
5949 // Look for exported default constructors.
5950 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5951 if (!CD || !CD->isDefaultConstructor())
5952 continue;
5953 auto *Attr = CD->getAttr<DLLExportAttr>();
5954 if (!Attr)
5955 continue;
5956
5957 // If the class is non-dependent, mark the default arguments as ODR-used so
5958 // that we can properly codegen the constructor closure.
5959 if (!Class->isDependentContext()) {
5960 for (ParmVarDecl *PD : CD->parameters()) {
5961 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5962 S.DiscardCleanupsInEvaluationContext();
5963 }
5964 }
5965
5966 if (LastExportedDefaultCtor) {
5967 S.Diag(LastExportedDefaultCtor->getLocation(),
5968 diag::err_attribute_dll_ambiguous_default_ctor)
5969 << Class;
5970 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5971 << CD->getDeclName();
5972 return;
5973 }
5974 LastExportedDefaultCtor = CD;
5975 }
5976}
5977
5978static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5979 CXXRecordDecl *Class) {
5980 bool ErrorReported = false;
5981 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5982 ClassTemplateDecl *TD) {
5983 if (ErrorReported)
5984 return;
5985 S.Diag(TD->getLocation(),
5986 diag::err_cuda_device_builtin_surftex_cls_template)
5987 << /*surface*/ 0 << TD;
5988 ErrorReported = true;
5989 };
5990
5991 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5992 if (!TD) {
5993 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5994 if (!SD) {
5995 S.Diag(Class->getLocation(),
5996 diag::err_cuda_device_builtin_surftex_ref_decl)
5997 << /*surface*/ 0 << Class;
5998 S.Diag(Class->getLocation(),
5999 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6000 << Class;
6001 return;
6002 }
6003 TD = SD->getSpecializedTemplate();
6004 }
6005
6006 TemplateParameterList *Params = TD->getTemplateParameters();
6007 unsigned N = Params->size();
6008
6009 if (N != 2) {
6010 reportIllegalClassTemplate(S, TD);
6011 S.Diag(TD->getLocation(),
6012 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6013 << TD << 2;
6014 }
6015 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6016 reportIllegalClassTemplate(S, TD);
6017 S.Diag(TD->getLocation(),
6018 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6019 << TD << /*1st*/ 0 << /*type*/ 0;
6020 }
6021 if (N > 1) {
6022 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6023 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6024 reportIllegalClassTemplate(S, TD);
6025 S.Diag(TD->getLocation(),
6026 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6027 << TD << /*2nd*/ 1 << /*integer*/ 1;
6028 }
6029 }
6030}
6031
6032static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6033 CXXRecordDecl *Class) {
6034 bool ErrorReported = false;
6035 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6036 ClassTemplateDecl *TD) {
6037 if (ErrorReported)
6038 return;
6039 S.Diag(TD->getLocation(),
6040 diag::err_cuda_device_builtin_surftex_cls_template)
6041 << /*texture*/ 1 << TD;
6042 ErrorReported = true;
6043 };
6044
6045 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6046 if (!TD) {
6047 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6048 if (!SD) {
6049 S.Diag(Class->getLocation(),
6050 diag::err_cuda_device_builtin_surftex_ref_decl)
6051 << /*texture*/ 1 << Class;
6052 S.Diag(Class->getLocation(),
6053 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6054 << Class;
6055 return;
6056 }
6057 TD = SD->getSpecializedTemplate();
6058 }
6059
6060 TemplateParameterList *Params = TD->getTemplateParameters();
6061 unsigned N = Params->size();
6062
6063 if (N != 3) {
6064 reportIllegalClassTemplate(S, TD);
6065 S.Diag(TD->getLocation(),
6066 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6067 << TD << 3;
6068 }
6069 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6070 reportIllegalClassTemplate(S, TD);
6071 S.Diag(TD->getLocation(),
6072 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6073 << TD << /*1st*/ 0 << /*type*/ 0;
6074 }
6075 if (N > 1) {
6076 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6077 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6078 reportIllegalClassTemplate(S, TD);
6079 S.Diag(TD->getLocation(),
6080 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6081 << TD << /*2nd*/ 1 << /*integer*/ 1;
6082 }
6083 }
6084 if (N > 2) {
6085 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6086 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6087 reportIllegalClassTemplate(S, TD);
6088 S.Diag(TD->getLocation(),
6089 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6090 << TD << /*3rd*/ 2 << /*integer*/ 1;
6091 }
6092 }
6093}
6094
6095void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6096 // Mark any compiler-generated routines with the implicit code_seg attribute.
6097 for (auto *Method : Class->methods()) {
6098 if (Method->isUserProvided())
6099 continue;
6100 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6101 Method->addAttr(A);
6102 }
6103}
6104
6105/// Check class-level dllimport/dllexport attribute.
6106void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6107 Attr *ClassAttr = getDLLAttr(Class);
6108
6109 // MSVC inherits DLL attributes to partial class template specializations.
6110 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6111 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6112 if (Attr *TemplateAttr =
6113 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6114 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6115 A->setInherited(true);
6116 ClassAttr = A;
6117 }
6118 }
6119 }
6120
6121 if (!ClassAttr)
6122 return;
6123
6124 if (!Class->isExternallyVisible()) {
6125 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6126 << Class << ClassAttr;
6127 return;
6128 }
6129
6130 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6131 !ClassAttr->isInherited()) {
6132 // Diagnose dll attributes on members of class with dll attribute.
6133 for (Decl *Member : Class->decls()) {
6134 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6135 continue;
6136 InheritableAttr *MemberAttr = getDLLAttr(Member);
6137 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6138 continue;
6139
6140 Diag(MemberAttr->getLocation(),
6141 diag::err_attribute_dll_member_of_dll_class)
6142 << MemberAttr << ClassAttr;
6143 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6144 Member->setInvalidDecl();
6145 }
6146 }
6147
6148 if (Class->getDescribedClassTemplate())
6149 // Don't inherit dll attribute until the template is instantiated.
6150 return;
6151
6152 // The class is either imported or exported.
6153 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6154
6155 // Check if this was a dllimport attribute propagated from a derived class to
6156 // a base class template specialization. We don't apply these attributes to
6157 // static data members.
6158 const bool PropagatedImport =
6159 !ClassExported &&
6160 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6161
6162 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6163
6164 // Ignore explicit dllexport on explicit class template instantiation
6165 // declarations, except in MinGW mode.
6166 if (ClassExported && !ClassAttr->isInherited() &&
6167 TSK == TSK_ExplicitInstantiationDeclaration &&
6168 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6169 Class->dropAttr<DLLExportAttr>();
6170 return;
6171 }
6172
6173 // Force declaration of implicit members so they can inherit the attribute.
6174 ForceDeclarationOfImplicitMembers(Class);
6175
6176 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6177 // seem to be true in practice?
6178
6179 for (Decl *Member : Class->decls()) {
6180 VarDecl *VD = dyn_cast<VarDecl>(Member);
6181 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6182
6183 // Only methods and static fields inherit the attributes.
6184 if (!VD && !MD)
6185 continue;
6186
6187 if (MD) {
6188 // Don't process deleted methods.
6189 if (MD->isDeleted())
6190 continue;
6191
6192 if (MD->isInlined()) {
6193 // MinGW does not import or export inline methods. But do it for
6194 // template instantiations.
6195 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6196 TSK != TSK_ExplicitInstantiationDeclaration &&
6197 TSK != TSK_ExplicitInstantiationDefinition)
6198 continue;
6199
6200 // MSVC versions before 2015 don't export the move assignment operators
6201 // and move constructor, so don't attempt to import/export them if
6202 // we have a definition.
6203 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6204 if ((MD->isMoveAssignmentOperator() ||
6205 (Ctor && Ctor->isMoveConstructor())) &&
6206 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6207 continue;
6208
6209 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6210 // operator is exported anyway.
6211 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6212 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6213 continue;
6214 }
6215 }
6216
6217 // Don't apply dllimport attributes to static data members of class template
6218 // instantiations when the attribute is propagated from a derived class.
6219 if (VD && PropagatedImport)
6220 continue;
6221
6222 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6223 continue;
6224
6225 if (!getDLLAttr(Member)) {
6226 InheritableAttr *NewAttr = nullptr;
6227
6228 // Do not export/import inline function when -fno-dllexport-inlines is
6229 // passed. But add attribute for later local static var check.
6230 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6231 TSK != TSK_ExplicitInstantiationDeclaration &&
6232 TSK != TSK_ExplicitInstantiationDefinition) {
6233 if (ClassExported) {
6234 NewAttr = ::new (getASTContext())
6235 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6236 } else {
6237 NewAttr = ::new (getASTContext())
6238 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6239 }
6240 } else {
6241 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6242 }
6243
6244 NewAttr->setInherited(true);
6245 Member->addAttr(NewAttr);
6246
6247 if (MD) {
6248 // Propagate DLLAttr to friend re-declarations of MD that have already
6249 // been constructed.
6250 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6251 FD = FD->getPreviousDecl()) {
6252 if (FD->getFriendObjectKind() == Decl::FOK_None)
6253 continue;
6254 assert(!getDLLAttr(FD) &&((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 6255, __PRETTY_FUNCTION__))
6255 "friend re-decl should not already have a DLLAttr")((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 6255, __PRETTY_FUNCTION__))
;
6256 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6257 NewAttr->setInherited(true);
6258 FD->addAttr(NewAttr);
6259 }
6260 }
6261 }
6262 }
6263
6264 if (ClassExported)
6265 DelayedDllExportClasses.push_back(Class);
6266}
6267
6268/// Perform propagation of DLL attributes from a derived class to a
6269/// templated base class for MS compatibility.
6270void Sema::propagateDLLAttrToBaseClassTemplate(
6271 CXXRecordDecl *Class, Attr *ClassAttr,
6272 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6273 if (getDLLAttr(
6274 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6275 // If the base class template has a DLL attribute, don't try to change it.
6276 return;
6277 }
6278
6279 auto TSK = BaseTemplateSpec->getSpecializationKind();
6280 if (!getDLLAttr(BaseTemplateSpec) &&
6281 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6282 TSK == TSK_ImplicitInstantiation)) {
6283 // The template hasn't been instantiated yet (or it has, but only as an
6284 // explicit instantiation declaration or implicit instantiation, which means
6285 // we haven't codegenned any members yet), so propagate the attribute.
6286 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6287 NewAttr->setInherited(true);
6288 BaseTemplateSpec->addAttr(NewAttr);
6289
6290 // If this was an import, mark that we propagated it from a derived class to
6291 // a base class template specialization.
6292 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6293 ImportAttr->setPropagatedToBaseTemplate();
6294
6295 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6296 // needs to be run again to work see the new attribute. Otherwise this will
6297 // get run whenever the template is instantiated.
6298 if (TSK != TSK_Undeclared)
6299 checkClassLevelDLLAttribute(BaseTemplateSpec);
6300
6301 return;
6302 }
6303
6304 if (getDLLAttr(BaseTemplateSpec)) {
6305 // The template has already been specialized or instantiated with an
6306 // attribute, explicitly or through propagation. We should not try to change
6307 // it.
6308 return;
6309 }
6310
6311 // The template was previously instantiated or explicitly specialized without
6312 // a dll attribute, It's too late for us to add an attribute, so warn that
6313 // this is unsupported.
6314 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6315 << BaseTemplateSpec->isExplicitSpecialization();
6316 Diag(ClassAttr->getLocation(), diag::note_attribute);
6317 if (BaseTemplateSpec->isExplicitSpecialization()) {
6318 Diag(BaseTemplateSpec->getLocation(),
6319 diag::note_template_class_explicit_specialization_was_here)
6320 << BaseTemplateSpec;
6321 } else {
6322 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6323 diag::note_template_class_instantiation_was_here)
6324 << BaseTemplateSpec;
6325 }
6326}
6327
6328/// Determine the kind of defaulting that would be done for a given function.
6329///
6330/// If the function is both a default constructor and a copy / move constructor
6331/// (due to having a default argument for the first parameter), this picks
6332/// CXXDefaultConstructor.
6333///
6334/// FIXME: Check that case is properly handled by all callers.
6335Sema::DefaultedFunctionKind
6336Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6337 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6338 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6339 if (Ctor->isDefaultConstructor())
6340 return Sema::CXXDefaultConstructor;
6341
6342 if (Ctor->isCopyConstructor())
6343 return Sema::CXXCopyConstructor;
6344
6345 if (Ctor->isMoveConstructor())
6346 return Sema::CXXMoveConstructor;
6347 }
6348
6349 if (MD->isCopyAssignmentOperator())
6350 return Sema::CXXCopyAssignment;
6351
6352 if (MD->isMoveAssignmentOperator())
6353 return Sema::CXXMoveAssignment;
6354
6355 if (isa<CXXDestructorDecl>(FD))
6356 return Sema::CXXDestructor;
6357 }
6358
6359 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6360 case OO_EqualEqual:
6361 return DefaultedComparisonKind::Equal;
6362
6363 case OO_ExclaimEqual:
6364 return DefaultedComparisonKind::NotEqual;
6365
6366 case OO_Spaceship:
6367 // No point allowing this if <=> doesn't exist in the current language mode.
6368 if (!getLangOpts().CPlusPlus20)
6369 break;
6370 return DefaultedComparisonKind::ThreeWay;
6371
6372 case OO_Less:
6373 case OO_LessEqual:
6374 case OO_Greater:
6375 case OO_GreaterEqual:
6376 // No point allowing this if <=> doesn't exist in the current language mode.
6377 if (!getLangOpts().CPlusPlus20)
6378 break;
6379 return DefaultedComparisonKind::Relational;
6380
6381 default:
6382 break;
6383 }
6384
6385 // Not defaultable.
6386 return DefaultedFunctionKind();
6387}
6388
6389static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6390 SourceLocation DefaultLoc) {
6391 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6392 if (DFK.isComparison())
4
Taking false branch
6393 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6394
6395 switch (DFK.asSpecialMember()) {
5
Control jumps to 'case CXXDestructor:' at line 6406
6396 case Sema::CXXDefaultConstructor:
6397 S.DefineImplicitDefaultConstructor(DefaultLoc,
6398 cast<CXXConstructorDecl>(FD));
6399 break;
6400 case Sema::CXXCopyConstructor:
6401 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6402 break;
6403 case Sema::CXXCopyAssignment:
6404 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6405 break;
6406 case Sema::CXXDestructor:
6407 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6
'FD' is a 'CXXDestructorDecl'
7
Calling 'Sema::DefineImplicitDestructor'
6408 break;
6409 case Sema::CXXMoveConstructor:
6410 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6411 break;
6412 case Sema::CXXMoveAssignment:
6413 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6414 break;
6415 case Sema::CXXInvalid:
6416 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 6416)
;
6417 }
6418}
6419
6420/// Determine whether a type is permitted to be passed or returned in
6421/// registers, per C++ [class.temporary]p3.
6422static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6423 TargetInfo::CallingConvKind CCK) {
6424 if (D->isDependentType() || D->isInvalidDecl())
6425 return false;
6426
6427 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6428 // The PS4 platform ABI follows the behavior of Clang 3.2.
6429 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6430 return !D->hasNonTrivialDestructorForCall() &&
6431 !D->hasNonTrivialCopyConstructorForCall();
6432
6433 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6434 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6435 bool DtorIsTrivialForCall = false;
6436
6437 // If a class has at least one non-deleted, trivial copy constructor, it
6438 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6439 //
6440 // Note: This permits classes with non-trivial copy or move ctors to be
6441 // passed in registers, so long as they *also* have a trivial copy ctor,
6442 // which is non-conforming.
6443 if (D->needsImplicitCopyConstructor()) {
6444 if (!D->defaultedCopyConstructorIsDeleted()) {
6445 if (D->hasTrivialCopyConstructor())
6446 CopyCtorIsTrivial = true;
6447 if (D->hasTrivialCopyConstructorForCall())
6448 CopyCtorIsTrivialForCall = true;
6449 }
6450 } else {
6451 for (const CXXConstructorDecl *CD : D->ctors()) {
6452 if (CD->isCopyConstructor() && !CD->isDeleted()) {
6453 if (CD->isTrivial())
6454 CopyCtorIsTrivial = true;
6455 if (CD->isTrivialForCall())
6456 CopyCtorIsTrivialForCall = true;
6457 }
6458 }
6459 }
6460
6461 if (D->needsImplicitDestructor()) {
6462 if (!D->defaultedDestructorIsDeleted() &&
6463 D->hasTrivialDestructorForCall())
6464 DtorIsTrivialForCall = true;
6465 } else if (const auto *DD = D->getDestructor()) {
6466 if (!DD->isDeleted() && DD->isTrivialForCall())
6467 DtorIsTrivialForCall = true;
6468 }
6469
6470 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6471 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6472 return true;
6473
6474 // If a class has a destructor, we'd really like to pass it indirectly
6475 // because it allows us to elide copies. Unfortunately, MSVC makes that
6476 // impossible for small types, which it will pass in a single register or
6477 // stack slot. Most objects with dtors are large-ish, so handle that early.
6478 // We can't call out all large objects as being indirect because there are
6479 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6480 // how we pass large POD types.
6481
6482 // Note: This permits small classes with nontrivial destructors to be
6483 // passed in registers, which is non-conforming.
6484 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6485 uint64_t TypeSize = isAArch64 ? 128 : 64;
6486
6487 if (CopyCtorIsTrivial &&
6488 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6489 return true;
6490 return false;
6491 }
6492
6493 // Per C++ [class.temporary]p3, the relevant condition is:
6494 // each copy constructor, move constructor, and destructor of X is
6495 // either trivial or deleted, and X has at least one non-deleted copy
6496 // or move constructor
6497 bool HasNonDeletedCopyOrMove = false;
6498
6499 if (D->needsImplicitCopyConstructor() &&
6500 !D->defaultedCopyConstructorIsDeleted()) {
6501 if (!D->hasTrivialCopyConstructorForCall())
6502 return false;
6503 HasNonDeletedCopyOrMove = true;
6504 }
6505
6506 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6507 !D->defaultedMoveConstructorIsDeleted()) {
6508 if (!D->hasTrivialMoveConstructorForCall())
6509 return false;
6510 HasNonDeletedCopyOrMove = true;
6511 }
6512
6513 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6514 !D->hasTrivialDestructorForCall())
6515 return false;
6516
6517 for (const CXXMethodDecl *MD : D->methods()) {
6518 if (MD->isDeleted())
6519 continue;
6520
6521 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6522 if (CD && CD->isCopyOrMoveConstructor())
6523 HasNonDeletedCopyOrMove = true;
6524 else if (!isa<CXXDestructorDecl>(MD))
6525 continue;
6526
6527 if (!MD->isTrivialForCall())
6528 return false;
6529 }
6530
6531 return HasNonDeletedCopyOrMove;
6532}
6533
6534/// Report an error regarding overriding, along with any relevant
6535/// overridden methods.
6536///
6537/// \param DiagID the primary error to report.
6538/// \param MD the overriding method.
6539static bool
6540ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6541 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6542 bool IssuedDiagnostic = false;
6543 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6544 if (Report(O)) {
6545 if (!IssuedDiagnostic) {
6546 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6547 IssuedDiagnostic = true;
6548 }
6549 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6550 }
6551 }
6552 return IssuedDiagnostic;
6553}
6554
6555/// Perform semantic checks on a class definition that has been
6556/// completing, introducing implicitly-declared members, checking for
6557/// abstract types, etc.
6558///
6559/// \param S The scope in which the class was parsed. Null if we didn't just
6560/// parse a class definition.
6561/// \param Record The completed class.
6562void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6563 if (!Record)
6564 return;
6565
6566 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6567 AbstractUsageInfo Info(*this, Record);
6568 CheckAbstractClassUsage(Info, Record);
6569 }
6570
6571 // If this is not an aggregate type and has no user-declared constructor,
6572 // complain about any non-static data members of reference or const scalar
6573 // type, since they will never get initializers.
6574 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6575 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6576 !Record->isLambda()) {
6577 bool Complained = false;
6578 for (const auto *F : Record->fields()) {
6579 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6580 continue;
6581
6582 if (F->getType()->isReferenceType() ||
6583 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6584 if (!Complained) {
6585 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6586 << Record->getTagKind() << Record;
6587 Complained = true;
6588 }
6589
6590 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6591 << F->getType()->isReferenceType()
6592 << F->getDeclName();
6593 }
6594 }
6595 }
6596
6597 if (Record->getIdentifier()) {
6598 // C++ [class.mem]p13:
6599 // If T is the name of a class, then each of the following shall have a
6600 // name different from T:
6601 // - every member of every anonymous union that is a member of class T.
6602 //
6603 // C++ [class.mem]p14:
6604 // In addition, if class T has a user-declared constructor (12.1), every
6605 // non-static data member of class T shall have a name different from T.
6606 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6607 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6608 ++I) {
6609 NamedDecl *D = (*I)->getUnderlyingDecl();
6610 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6611 Record->hasUserDeclaredConstructor()) ||
6612 isa<IndirectFieldDecl>(D)) {
6613 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6614 << D->getDeclName();
6615 break;
6616 }
6617 }
6618 }
6619
6620 // Warn if the class has virtual methods but non-virtual public destructor.
6621 if (Record->isPolymorphic() && !Record->isDependentType()) {
6622 CXXDestructorDecl *dtor = Record->getDestructor();
6623 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6624 !Record->hasAttr<FinalAttr>())
6625 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6626 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6627 }
6628
6629 if (Record->isAbstract()) {
6630 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6631 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6632 << FA->isSpelledAsSealed();
6633 DiagnoseAbstractType(Record);
6634 }
6635 }
6636
6637 // Warn if the class has a final destructor but is not itself marked final.
6638 if (!Record->hasAttr<FinalAttr>()) {
6639 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6640 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6641 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6642 << FA->isSpelledAsSealed()
6643 << FixItHint::CreateInsertion(
6644 getLocForEndOfToken(Record->getLocation()),
6645 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6646 Diag(Record->getLocation(),
6647 diag::note_final_dtor_non_final_class_silence)
6648 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6649 }
6650 }
6651 }
6652
6653 // See if trivial_abi has to be dropped.
6654 if (Record->hasAttr<TrivialABIAttr>())
6655 checkIllFormedTrivialABIStruct(*Record);
6656
6657 // Set HasTrivialSpecialMemberForCall if the record has attribute
6658 // "trivial_abi".
6659 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6660
6661 if (HasTrivialABI)
6662 Record->setHasTrivialSpecialMemberForCall();
6663
6664 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6665 // We check these last because they can depend on the properties of the
6666 // primary comparison functions (==, <=>).
6667 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6668
6669 // Perform checks that can't be done until we know all the properties of a
6670 // member function (whether it's defaulted, deleted, virtual, overriding,
6671 // ...).
6672 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6673 // A static function cannot override anything.
6674 if (MD->getStorageClass() == SC_Static) {
6675 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6676 [](const CXXMethodDecl *) { return true; }))
6677 return;
6678 }
6679
6680 // A deleted function cannot override a non-deleted function and vice
6681 // versa.
6682 if (ReportOverrides(*this,
6683 MD->isDeleted() ? diag::err_deleted_override
6684 : diag::err_non_deleted_override,
6685 MD, [&](const CXXMethodDecl *V) {
6686 return MD->isDeleted() != V->isDeleted();
6687 })) {
6688 if (MD->isDefaulted() && MD->isDeleted())
6689 // Explain why this defaulted function was deleted.
6690 DiagnoseDeletedDefaultedFunction(MD);
6691 return;
6692 }
6693
6694 // A consteval function cannot override a non-consteval function and vice
6695 // versa.
6696 if (ReportOverrides(*this,
6697 MD->isConsteval() ? diag::err_consteval_override
6698 : diag::err_non_consteval_override,
6699 MD, [&](const CXXMethodDecl *V) {
6700 return MD->isConsteval() != V->isConsteval();
6701 })) {
6702 if (MD->isDefaulted() && MD->isDeleted())
6703 // Explain why this defaulted function was deleted.
6704 DiagnoseDeletedDefaultedFunction(MD);
6705 return;
6706 }
6707 };
6708
6709 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6710 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6711 return false;
6712
6713 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6714 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6715 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6716 DefaultedSecondaryComparisons.push_back(FD);
6717 return true;
6718 }
6719
6720 CheckExplicitlyDefaultedFunction(S, FD);
6721 return false;
6722 };
6723
6724 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6725 // Check whether the explicitly-defaulted members are valid.
6726 bool Incomplete = CheckForDefaultedFunction(M);
6727
6728 // Skip the rest of the checks for a member of a dependent class.
6729 if (Record->isDependentType())
6730 return;
6731
6732 // For an explicitly defaulted or deleted special member, we defer
6733 // determining triviality until the class is complete. That time is now!
6734 CXXSpecialMember CSM = getSpecialMember(M);
6735 if (!M->isImplicit() && !M->isUserProvided()) {
6736 if (CSM != CXXInvalid) {
6737 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6738 // Inform the class that we've finished declaring this member.
6739 Record->finishedDefaultedOrDeletedMember(M);
6740 M->setTrivialForCall(
6741 HasTrivialABI ||
6742 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6743 Record->setTrivialForCallFlags(M);
6744 }
6745 }
6746
6747 // Set triviality for the purpose of calls if this is a user-provided
6748 // copy/move constructor or destructor.
6749 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6750 CSM == CXXDestructor) && M->isUserProvided()) {
6751 M->setTrivialForCall(HasTrivialABI);
6752 Record->setTrivialForCallFlags(M);
6753 }
6754
6755 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6756 M->hasAttr<DLLExportAttr>()) {
6757 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6758 M->isTrivial() &&
6759 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6760 CSM == CXXDestructor))
6761 M->dropAttr<DLLExportAttr>();
6762
6763 if (M->hasAttr<DLLExportAttr>()) {
6764 // Define after any fields with in-class initializers have been parsed.
6765 DelayedDllExportMemberFunctions.push_back(M);
6766 }
6767 }
6768
6769 // Define defaulted constexpr virtual functions that override a base class
6770 // function right away.
6771 // FIXME: We can defer doing this until the vtable is marked as used.
6772 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6773 DefineDefaultedFunction(*this, M, M->getLocation());
6774
6775 if (!Incomplete)
6776 CheckCompletedMemberFunction(M);
6777 };
6778
6779 // Check the destructor before any other member function. We need to
6780 // determine whether it's trivial in order to determine whether the claas
6781 // type is a literal type, which is a prerequisite for determining whether
6782 // other special member functions are valid and whether they're implicitly
6783 // 'constexpr'.
6784 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6785 CompleteMemberFunction(Dtor);
6786
6787 bool HasMethodWithOverrideControl = false,
6788 HasOverridingMethodWithoutOverrideControl = false;
6789 for (auto *D : Record->decls()) {
6790 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6791 // FIXME: We could do this check for dependent types with non-dependent
6792 // bases.
6793 if (!Record->isDependentType()) {
6794 // See if a method overloads virtual methods in a base
6795 // class without overriding any.
6796 if (!M->isStatic())
6797 DiagnoseHiddenVirtualMethods(M);
6798 if (M->hasAttr<OverrideAttr>())
6799 HasMethodWithOverrideControl = true;
6800 else if (M->size_overridden_methods() > 0)
6801 HasOverridingMethodWithoutOverrideControl = true;
6802 }
6803
6804 if (!isa<CXXDestructorDecl>(M))
6805 CompleteMemberFunction(M);
6806 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6807 CheckForDefaultedFunction(
6808 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6809 }
6810 }
6811
6812 if (HasOverridingMethodWithoutOverrideControl) {
6813 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6814 for (auto *M : Record->methods())
6815 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6816 }
6817
6818 // Check the defaulted secondary comparisons after any other member functions.
6819 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6820 CheckExplicitlyDefaultedFunction(S, FD);
6821
6822 // If this is a member function, we deferred checking it until now.
6823 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6824 CheckCompletedMemberFunction(MD);
6825 }
6826
6827 // ms_struct is a request to use the same ABI rules as MSVC. Check
6828 // whether this class uses any C++ features that are implemented
6829 // completely differently in MSVC, and if so, emit a diagnostic.
6830 // That diagnostic defaults to an error, but we allow projects to
6831 // map it down to a warning (or ignore it). It's a fairly common
6832 // practice among users of the ms_struct pragma to mass-annotate
6833 // headers, sweeping up a bunch of types that the project doesn't
6834 // really rely on MSVC-compatible layout for. We must therefore
6835 // support "ms_struct except for C++ stuff" as a secondary ABI.
6836 // Don't emit this diagnostic if the feature was enabled as a
6837 // language option (as opposed to via a pragma or attribute), as
6838 // the option -mms-bitfields otherwise essentially makes it impossible
6839 // to build C++ code, unless this diagnostic is turned off.
6840 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6841 (Record->isPolymorphic() || Record->getNumBases())) {
6842 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6843 }
6844
6845 checkClassLevelDLLAttribute(Record);
6846 checkClassLevelCodeSegAttribute(Record);
6847
6848 bool ClangABICompat4 =
6849 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6850 TargetInfo::CallingConvKind CCK =
6851 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6852 bool CanPass = canPassInRegisters(*this, Record, CCK);
6853
6854 // Do not change ArgPassingRestrictions if it has already been set to
6855 // APK_CanNeverPassInRegs.
6856 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6857 Record->setArgPassingRestrictions(CanPass
6858 ? RecordDecl::APK_CanPassInRegs
6859 : RecordDecl::APK_CannotPassInRegs);
6860
6861 // If canPassInRegisters returns true despite the record having a non-trivial
6862 // destructor, the record is destructed in the callee. This happens only when
6863 // the record or one of its subobjects has a field annotated with trivial_abi
6864 // or a field qualified with ObjC __strong/__weak.
6865 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6866 Record->setParamDestroyedInCallee(true);
6867 else if (Record->hasNonTrivialDestructor())
6868 Record->setParamDestroyedInCallee(CanPass);
6869
6870 if (getLangOpts().ForceEmitVTables) {
6871 // If we want to emit all the vtables, we need to mark it as used. This
6872 // is especially required for cases like vtable assumption loads.
6873 MarkVTableUsed(Record->getInnerLocStart(), Record);
6874 }
6875
6876 if (getLangOpts().CUDA) {
6877 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6878 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6879 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6880 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6881 }
6882}
6883
6884/// Look up the special member function that would be called by a special
6885/// member function for a subobject of class type.
6886///
6887/// \param Class The class type of the subobject.
6888/// \param CSM The kind of special member function.
6889/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6890/// \param ConstRHS True if this is a copy operation with a const object
6891/// on its RHS, that is, if the argument to the outer special member
6892/// function is 'const' and this is not a field marked 'mutable'.
6893static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6894 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6895 unsigned FieldQuals, bool ConstRHS) {
6896 unsigned LHSQuals = 0;
6897 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6898 LHSQuals = FieldQuals;
6899
6900 unsigned RHSQuals = FieldQuals;
6901 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6902 RHSQuals = 0;
6903 else if (ConstRHS)
6904 RHSQuals |= Qualifiers::Const;
6905
6906 return S.LookupSpecialMember(Class, CSM,
6907 RHSQuals & Qualifiers::Const,
6908 RHSQuals & Qualifiers::Volatile,
6909 false,
6910 LHSQuals & Qualifiers::Const,
6911 LHSQuals & Qualifiers::Volatile);
6912}
6913
6914class Sema::InheritedConstructorInfo {
6915 Sema &S;
6916 SourceLocation UseLoc;
6917
6918 /// A mapping from the base classes through which the constructor was
6919 /// inherited to the using shadow declaration in that base class (or a null
6920 /// pointer if the constructor was declared in that base class).
6921 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6922 InheritedFromBases;
6923
6924public:
6925 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6926 ConstructorUsingShadowDecl *Shadow)
6927 : S(S), UseLoc(UseLoc) {
6928 bool DiagnosedMultipleConstructedBases = false;
6929 CXXRecordDecl *ConstructedBase = nullptr;
6930 UsingDecl *ConstructedBaseUsing = nullptr;
6931
6932 // Find the set of such base class subobjects and check that there's a
6933 // unique constructed subobject.
6934 for (auto *D : Shadow->redecls()) {
6935 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6936 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6937 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6938
6939 InheritedFromBases.insert(
6940 std::make_pair(DNominatedBase->getCanonicalDecl(),
6941 DShadow->getNominatedBaseClassShadowDecl()));
6942 if (DShadow->constructsVirtualBase())
6943 InheritedFromBases.insert(
6944 std::make_pair(DConstructedBase->getCanonicalDecl(),
6945 DShadow->getConstructedBaseClassShadowDecl()));
6946 else
6947 assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void>
(0) : __assert_fail ("DNominatedBase == DConstructedBase", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 6947, __PRETTY_FUNCTION__))
;
6948
6949 // [class.inhctor.init]p2:
6950 // If the constructor was inherited from multiple base class subobjects
6951 // of type B, the program is ill-formed.
6952 if (!ConstructedBase) {
6953 ConstructedBase = DConstructedBase;
6954 ConstructedBaseUsing = D->getUsingDecl();
6955 } else if (ConstructedBase != DConstructedBase &&
6956 !Shadow->isInvalidDecl()) {
6957 if (!DiagnosedMultipleConstructedBases) {
6958 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6959 << Shadow->getTargetDecl();
6960 S.Diag(ConstructedBaseUsing->getLocation(),
6961 diag::note_ambiguous_inherited_constructor_using)
6962 << ConstructedBase;
6963 DiagnosedMultipleConstructedBases = true;
6964 }
6965 S.Diag(D->getUsingDecl()->getLocation(),
6966 diag::note_ambiguous_inherited_constructor_using)
6967 << DConstructedBase;
6968 }
6969 }
6970
6971 if (DiagnosedMultipleConstructedBases)
6972 Shadow->setInvalidDecl();
6973 }
6974
6975 /// Find the constructor to use for inherited construction of a base class,
6976 /// and whether that base class constructor inherits the constructor from a
6977 /// virtual base class (in which case it won't actually invoke it).
6978 std::pair<CXXConstructorDecl *, bool>
6979 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6980 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6981 if (It == InheritedFromBases.end())
6982 return std::make_pair(nullptr, false);
6983
6984 // This is an intermediary class.
6985 if (It->second)
6986 return std::make_pair(
6987 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6988 It->second->constructsVirtualBase());
6989
6990 // This is the base class from which the constructor was inherited.
6991 return std::make_pair(Ctor, false);
6992 }
6993};
6994
6995/// Is the special member function which would be selected to perform the
6996/// specified operation on the specified class type a constexpr constructor?
6997static bool
6998specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6999 Sema::CXXSpecialMember CSM, unsigned Quals,
7000 bool ConstRHS,
7001 CXXConstructorDecl *InheritedCtor = nullptr,
7002 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7003 // If we're inheriting a constructor, see if we need to call it for this base
7004 // class.
7005 if (InheritedCtor) {
7006 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7006, __PRETTY_FUNCTION__))
;
7007 auto BaseCtor =
7008 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7009 if (BaseCtor)
7010 return BaseCtor->isConstexpr();
7011 }
7012
7013 if (CSM == Sema::CXXDefaultConstructor)
7014 return ClassDecl->hasConstexprDefaultConstructor();
7015 if (CSM == Sema::CXXDestructor)
7016 return ClassDecl->hasConstexprDestructor();
7017
7018 Sema::SpecialMemberOverloadResult SMOR =
7019 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7020 if (!SMOR.getMethod())
7021 // A constructor we wouldn't select can't be "involved in initializing"
7022 // anything.
7023 return true;
7024 return SMOR.getMethod()->isConstexpr();
7025}
7026
7027/// Determine whether the specified special member function would be constexpr
7028/// if it were implicitly defined.
7029static bool defaultedSpecialMemberIsConstexpr(
7030 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7031 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7032 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7033 if (!S.getLangOpts().CPlusPlus11)
7034 return false;
7035
7036 // C++11 [dcl.constexpr]p4:
7037 // In the definition of a constexpr constructor [...]
7038 bool Ctor = true;
7039 switch (CSM) {
7040 case Sema::CXXDefaultConstructor:
7041 if (Inherited)
7042 break;
7043 // Since default constructor lookup is essentially trivial (and cannot
7044 // involve, for instance, template instantiation), we compute whether a
7045 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7046 //
7047 // This is important for performance; we need to know whether the default
7048 // constructor is constexpr to determine whether the type is a literal type.
7049 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7050
7051 case Sema::CXXCopyConstructor:
7052 case Sema::CXXMoveConstructor:
7053 // For copy or move constructors, we need to perform overload resolution.
7054 break;
7055
7056 case Sema::CXXCopyAssignment:
7057 case Sema::CXXMoveAssignment:
7058 if (!S.getLangOpts().CPlusPlus14)
7059 return false;
7060 // In C++1y, we need to perform overload resolution.
7061 Ctor = false;
7062 break;
7063
7064 case Sema::CXXDestructor:
7065 return ClassDecl->defaultedDestructorIsConstexpr();
7066
7067 case Sema::CXXInvalid:
7068 return false;
7069 }
7070
7071 // -- if the class is a non-empty union, or for each non-empty anonymous
7072 // union member of a non-union class, exactly one non-static data member
7073 // shall be initialized; [DR1359]
7074 //
7075 // If we squint, this is guaranteed, since exactly one non-static data member
7076 // will be initialized (if the constructor isn't deleted), we just don't know
7077 // which one.
7078 if (Ctor && ClassDecl->isUnion())
7079 return CSM == Sema::CXXDefaultConstructor
7080 ? ClassDecl->hasInClassInitializer() ||
7081 !ClassDecl->hasVariantMembers()
7082 : true;
7083
7084 // -- the class shall not have any virtual base classes;
7085 if (Ctor && ClassDecl->getNumVBases())
7086 return false;
7087
7088 // C++1y [class.copy]p26:
7089 // -- [the class] is a literal type, and
7090 if (!Ctor && !ClassDecl->isLiteral())
7091 return false;
7092
7093 // -- every constructor involved in initializing [...] base class
7094 // sub-objects shall be a constexpr constructor;
7095 // -- the assignment operator selected to copy/move each direct base
7096 // class is a constexpr function, and
7097 for (const auto &B : ClassDecl->bases()) {
7098 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7099 if (!BaseType) continue;
7100
7101 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7102 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7103 InheritedCtor, Inherited))
7104 return false;
7105 }
7106
7107 // -- every constructor involved in initializing non-static data members
7108 // [...] shall be a constexpr constructor;
7109 // -- every non-static data member and base class sub-object shall be
7110 // initialized
7111 // -- for each non-static data member of X that is of class type (or array
7112 // thereof), the assignment operator selected to copy/move that member is
7113 // a constexpr function
7114 for (const auto *F : ClassDecl->fields()) {
7115 if (F->isInvalidDecl())
7116 continue;
7117 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7118 continue;
7119 QualType BaseType = S.Context.getBaseElementType(F->getType());
7120 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7121 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7122 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7123 BaseType.getCVRQualifiers(),
7124 ConstArg && !F->isMutable()))
7125 return false;
7126 } else if (CSM == Sema::CXXDefaultConstructor) {
7127 return false;
7128 }
7129 }
7130
7131 // All OK, it's constexpr!
7132 return true;
7133}
7134
7135namespace {
7136/// RAII object to register a defaulted function as having its exception
7137/// specification computed.
7138struct ComputingExceptionSpec {
7139 Sema &S;
7140
7141 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7142 : S(S) {
7143 Sema::CodeSynthesisContext Ctx;
7144 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7145 Ctx.PointOfInstantiation = Loc;
7146 Ctx.Entity = FD;
7147 S.pushCodeSynthesisContext(Ctx);
7148 }
7149 ~ComputingExceptionSpec() {
7150 S.popCodeSynthesisContext();
7151 }
7152};
7153}
7154
7155static Sema::ImplicitExceptionSpecification
7156ComputeDefaultedSpecialMemberExceptionSpec(
7157 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7158 Sema::InheritedConstructorInfo *ICI);
7159
7160static Sema::ImplicitExceptionSpecification
7161ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7162 FunctionDecl *FD,
7163 Sema::DefaultedComparisonKind DCK);
7164
7165static Sema::ImplicitExceptionSpecification
7166computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7167 auto DFK = S.getDefaultedFunctionKind(FD);
7168 if (DFK.isSpecialMember())
7169 return ComputeDefaultedSpecialMemberExceptionSpec(
7170 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7171 if (DFK.isComparison())
7172 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7173 DFK.asComparison());
7174
7175 auto *CD = cast<CXXConstructorDecl>(FD);
7176 assert(CD->getInheritedConstructor() &&((CD->getInheritedConstructor() && "only defaulted functions and inherited constructors have implicit "
"exception specs") ? static_cast<void> (0) : __assert_fail
("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7178, __PRETTY_FUNCTION__))
7177 "only defaulted functions and inherited constructors have implicit "((CD->getInheritedConstructor() && "only defaulted functions and inherited constructors have implicit "
"exception specs") ? static_cast<void> (0) : __assert_fail
("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7178, __PRETTY_FUNCTION__))
7178 "exception specs")((CD->getInheritedConstructor() && "only defaulted functions and inherited constructors have implicit "
"exception specs") ? static_cast<void> (0) : __assert_fail
("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7178, __PRETTY_FUNCTION__))
;
7179 Sema::InheritedConstructorInfo ICI(
7180 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7181 return ComputeDefaultedSpecialMemberExceptionSpec(
7182 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7183}
7184
7185static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7186 CXXMethodDecl *MD) {
7187 FunctionProtoType::ExtProtoInfo EPI;
7188
7189 // Build an exception specification pointing back at this member.
7190 EPI.ExceptionSpec.Type = EST_Unevaluated;
7191 EPI.ExceptionSpec.SourceDecl = MD;
7192
7193 // Set the calling convention to the default for C++ instance methods.
7194 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7195 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7196 /*IsCXXMethod=*/true));
7197 return EPI;
7198}
7199
7200void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7201 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7202 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7203 return;
7204
7205 // Evaluate the exception specification.
7206 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7207 auto ESI = IES.getExceptionSpec();
7208
7209 // Update the type of the special member to use it.
7210 UpdateExceptionSpec(FD, ESI);
7211}
7212
7213void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7214 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted")((FD->isExplicitlyDefaulted() && "not explicitly-defaulted"
) ? static_cast<void> (0) : __assert_fail ("FD->isExplicitlyDefaulted() && \"not explicitly-defaulted\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7214, __PRETTY_FUNCTION__))
;
7215
7216 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7217 if (!DefKind) {
7218 assert(FD->getDeclContext()->isDependentContext())((FD->getDeclContext()->isDependentContext()) ? static_cast
<void> (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7218, __PRETTY_FUNCTION__))
;
7219 return;
7220 }
7221
7222 if (DefKind.isSpecialMember()
7223 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7224 DefKind.asSpecialMember())
7225 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7226 FD->setInvalidDecl();
7227}
7228
7229bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7230 CXXSpecialMember CSM) {
7231 CXXRecordDecl *RD = MD->getParent();
7232
7233 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7234, __PRETTY_FUNCTION__))
7234 "not an explicitly-defaulted special member")((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7234, __PRETTY_FUNCTION__))
;
7235
7236 // Defer all checking for special members of a dependent type.
7237 if (RD->isDependentType())
7238 return false;
7239
7240 // Whether this was the first-declared instance of the constructor.
7241 // This affects whether we implicitly add an exception spec and constexpr.
7242 bool First = MD == MD->getCanonicalDecl();
7243
7244 bool HadError = false;
7245
7246 // C++11 [dcl.fct.def.default]p1:
7247 // A function that is explicitly defaulted shall
7248 // -- be a special member function [...] (checked elsewhere),
7249 // -- have the same type (except for ref-qualifiers, and except that a
7250 // copy operation can take a non-const reference) as an implicit
7251 // declaration, and
7252 // -- not have default arguments.
7253 // C++2a changes the second bullet to instead delete the function if it's
7254 // defaulted on its first declaration, unless it's "an assignment operator,
7255 // and its return type differs or its parameter type is not a reference".
7256 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7257 bool ShouldDeleteForTypeMismatch = false;
7258 unsigned ExpectedParams = 1;
7259 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7260 ExpectedParams = 0;
7261 if (MD->getNumParams() != ExpectedParams) {
7262 // This checks for default arguments: a copy or move constructor with a
7263 // default argument is classified as a default constructor, and assignment
7264 // operations and destructors can't have default arguments.
7265 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7266 << CSM << MD->getSourceRange();
7267 HadError = true;
7268 } else if (MD->isVariadic()) {
7269 if (DeleteOnTypeMismatch)
7270 ShouldDeleteForTypeMismatch = true;
7271 else {
7272 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7273 << CSM << MD->getSourceRange();
7274 HadError = true;
7275 }
7276 }
7277
7278 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7279
7280 bool CanHaveConstParam = false;
7281 if (CSM == CXXCopyConstructor)
7282 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7283 else if (CSM == CXXCopyAssignment)
7284 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7285
7286 QualType ReturnType = Context.VoidTy;
7287 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7288 // Check for return type matching.
7289 ReturnType = Type->getReturnType();
7290
7291 QualType DeclType = Context.getTypeDeclType(RD);
7292 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7293 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7294
7295 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7296 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7297 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7298 HadError = true;
7299 }
7300
7301 // A defaulted special member cannot have cv-qualifiers.
7302 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7303 if (DeleteOnTypeMismatch)
7304 ShouldDeleteForTypeMismatch = true;
7305 else {
7306 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7307 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7308 HadError = true;
7309 }
7310 }
7311 }
7312
7313 // Check for parameter type matching.
7314 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7315 bool HasConstParam = false;
7316 if (ExpectedParams && ArgType->isReferenceType()) {
7317 // Argument must be reference to possibly-const T.
7318 QualType ReferentType = ArgType->getPointeeType();
7319 HasConstParam = ReferentType.isConstQualified();
7320
7321 if (ReferentType.isVolatileQualified()) {
7322 if (DeleteOnTypeMismatch)
7323 ShouldDeleteForTypeMismatch = true;
7324 else {
7325 Diag(MD->getLocation(),
7326 diag::err_defaulted_special_member_volatile_param) << CSM;
7327 HadError = true;
7328 }
7329 }
7330
7331 if (HasConstParam && !CanHaveConstParam) {
7332 if (DeleteOnTypeMismatch)
7333 ShouldDeleteForTypeMismatch = true;
7334 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7335 Diag(MD->getLocation(),
7336 diag::err_defaulted_special_member_copy_const_param)
7337 << (CSM == CXXCopyAssignment);
7338 // FIXME: Explain why this special member can't be const.
7339 HadError = true;
7340 } else {
7341 Diag(MD->getLocation(),
7342 diag::err_defaulted_special_member_move_const_param)
7343 << (CSM == CXXMoveAssignment);
7344 HadError = true;
7345 }
7346 }
7347 } else if (ExpectedParams) {
7348 // A copy assignment operator can take its argument by value, but a
7349 // defaulted one cannot.
7350 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")((CSM == CXXCopyAssignment && "unexpected non-ref argument"
) ? static_cast<void> (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7350, __PRETTY_FUNCTION__))
;
7351 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7352 HadError = true;
7353 }
7354
7355 // C++11 [dcl.fct.def.default]p2:
7356 // An explicitly-defaulted function may be declared constexpr only if it
7357 // would have been implicitly declared as constexpr,
7358 // Do not apply this rule to members of class templates, since core issue 1358
7359 // makes such functions always instantiate to constexpr functions. For
7360 // functions which cannot be constexpr (for non-constructors in C++11 and for
7361 // destructors in C++14 and C++17), this is checked elsewhere.
7362 //
7363 // FIXME: This should not apply if the member is deleted.
7364 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7365 HasConstParam);
7366 if ((getLangOpts().CPlusPlus20 ||
7367 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7368 : isa<CXXConstructorDecl>(MD))) &&
7369 MD->isConstexpr() && !Constexpr &&
7370 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7371 Diag(MD->getBeginLoc(), MD->isConsteval()
7372 ? diag::err_incorrect_defaulted_consteval
7373 : diag::err_incorrect_defaulted_constexpr)
7374 << CSM;
7375 // FIXME: Explain why the special member can't be constexpr.
7376 HadError = true;
7377 }
7378
7379 if (First) {
7380 // C++2a [dcl.fct.def.default]p3:
7381 // If a function is explicitly defaulted on its first declaration, it is
7382 // implicitly considered to be constexpr if the implicit declaration
7383 // would be.
7384 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7385 ? ConstexprSpecKind::Consteval
7386 : ConstexprSpecKind::Constexpr)
7387 : ConstexprSpecKind::Unspecified);
7388
7389 if (!Type->hasExceptionSpec()) {
7390 // C++2a [except.spec]p3:
7391 // If a declaration of a function does not have a noexcept-specifier
7392 // [and] is defaulted on its first declaration, [...] the exception
7393 // specification is as specified below
7394 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7395 EPI.ExceptionSpec.Type = EST_Unevaluated;
7396 EPI.ExceptionSpec.SourceDecl = MD;
7397 MD->setType(Context.getFunctionType(ReturnType,
7398 llvm::makeArrayRef(&ArgType,
7399 ExpectedParams),
7400 EPI));
7401 }
7402 }
7403
7404 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7405 if (First) {
7406 SetDeclDeleted(MD, MD->getLocation());
7407 if (!inTemplateInstantiation() && !HadError) {
7408 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7409 if (ShouldDeleteForTypeMismatch) {
7410 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7411 } else {
7412 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7413 }
7414 }
7415 if (ShouldDeleteForTypeMismatch && !HadError) {
7416 Diag(MD->getLocation(),
7417 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7418 }
7419 } else {
7420 // C++11 [dcl.fct.def.default]p4:
7421 // [For a] user-provided explicitly-defaulted function [...] if such a
7422 // function is implicitly defined as deleted, the program is ill-formed.
7423 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7424 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")((!ShouldDeleteForTypeMismatch && "deleted non-first decl"
) ? static_cast<void> (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7424, __PRETTY_FUNCTION__))
;
7425 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7426 HadError = true;
7427 }
7428 }
7429
7430 return HadError;
7431}
7432
7433namespace {
7434/// Helper class for building and checking a defaulted comparison.
7435///
7436/// Defaulted functions are built in two phases:
7437///
7438/// * First, the set of operations that the function will perform are
7439/// identified, and some of them are checked. If any of the checked
7440/// operations is invalid in certain ways, the comparison function is
7441/// defined as deleted and no body is built.
7442/// * Then, if the function is not defined as deleted, the body is built.
7443///
7444/// This is accomplished by performing two visitation steps over the eventual
7445/// body of the function.
7446template<typename Derived, typename ResultList, typename Result,
7447 typename Subobject>
7448class DefaultedComparisonVisitor {
7449public:
7450 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7451
7452 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7453 DefaultedComparisonKind DCK)
7454 : S(S), RD(RD), FD(FD), DCK(DCK) {
7455 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7456 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7457 // UnresolvedSet to avoid this copy.
7458 Fns.assign(Info->getUnqualifiedLookups().begin(),
7459 Info->getUnqualifiedLookups().end());
7460 }
7461 }
7462
7463 ResultList visit() {
7464 // The type of an lvalue naming a parameter of this function.
7465 QualType ParamLvalType =
7466 FD->getParamDecl(0)->getType().getNonReferenceType();
7467
7468 ResultList Results;
7469
7470 switch (DCK) {
7471 case DefaultedComparisonKind::None:
7472 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7472)
;
7473
7474 case DefaultedComparisonKind::Equal:
7475 case DefaultedComparisonKind::ThreeWay:
7476 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7477 return Results;
7478
7479 case DefaultedComparisonKind::NotEqual:
7480 case DefaultedComparisonKind::Relational:
7481 Results.add(getDerived().visitExpandedSubobject(
7482 ParamLvalType, getDerived().getCompleteObject()));
7483 return Results;
7484 }
7485 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7485)
;
7486 }
7487
7488protected:
7489 Derived &getDerived() { return static_cast<Derived&>(*this); }
7490
7491 /// Visit the expanded list of subobjects of the given type, as specified in
7492 /// C++2a [class.compare.default].
7493 ///
7494 /// \return \c true if the ResultList object said we're done, \c false if not.
7495 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7496 Qualifiers Quals) {
7497 // C++2a [class.compare.default]p4:
7498 // The direct base class subobjects of C
7499 for (CXXBaseSpecifier &Base : Record->bases())
7500 if (Results.add(getDerived().visitSubobject(
7501 S.Context.getQualifiedType(Base.getType(), Quals),
7502 getDerived().getBase(&Base))))
7503 return true;
7504
7505 // followed by the non-static data members of C
7506 for (FieldDecl *Field : Record->fields()) {
7507 // Recursively expand anonymous structs.
7508 if (Field->isAnonymousStructOrUnion()) {
7509 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7510 Quals))
7511 return true;
7512 continue;
7513 }
7514
7515 // Figure out the type of an lvalue denoting this field.
7516 Qualifiers FieldQuals = Quals;
7517 if (Field->isMutable())
7518 FieldQuals.removeConst();
7519 QualType FieldType =
7520 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7521
7522 if (Results.add(getDerived().visitSubobject(
7523 FieldType, getDerived().getField(Field))))
7524 return true;
7525 }
7526
7527 // form a list of subobjects.
7528 return false;
7529 }
7530
7531 Result visitSubobject(QualType Type, Subobject Subobj) {
7532 // In that list, any subobject of array type is recursively expanded
7533 const ArrayType *AT = S.Context.getAsArrayType(Type);
7534 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7535 return getDerived().visitSubobjectArray(CAT->getElementType(),
7536 CAT->getSize(), Subobj);
7537 return getDerived().visitExpandedSubobject(Type, Subobj);
7538 }
7539
7540 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7541 Subobject Subobj) {
7542 return getDerived().visitSubobject(Type, Subobj);
7543 }
7544
7545protected:
7546 Sema &S;
7547 CXXRecordDecl *RD;
7548 FunctionDecl *FD;
7549 DefaultedComparisonKind DCK;
7550 UnresolvedSet<16> Fns;
7551};
7552
7553/// Information about a defaulted comparison, as determined by
7554/// DefaultedComparisonAnalyzer.
7555struct DefaultedComparisonInfo {
7556 bool Deleted = false;
7557 bool Constexpr = true;
7558 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7559
7560 static DefaultedComparisonInfo deleted() {
7561 DefaultedComparisonInfo Deleted;
7562 Deleted.Deleted = true;
7563 return Deleted;
7564 }
7565
7566 bool add(const DefaultedComparisonInfo &R) {
7567 Deleted |= R.Deleted;
7568 Constexpr &= R.Constexpr;
7569 Category = commonComparisonType(Category, R.Category);
7570 return Deleted;
7571 }
7572};
7573
7574/// An element in the expanded list of subobjects of a defaulted comparison, as
7575/// specified in C++2a [class.compare.default]p4.
7576struct DefaultedComparisonSubobject {
7577 enum { CompleteObject, Member, Base } Kind;
7578 NamedDecl *Decl;
7579 SourceLocation Loc;
7580};
7581
7582/// A visitor over the notional body of a defaulted comparison that determines
7583/// whether that body would be deleted or constexpr.
7584class DefaultedComparisonAnalyzer
7585 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7586 DefaultedComparisonInfo,
7587 DefaultedComparisonInfo,
7588 DefaultedComparisonSubobject> {
7589public:
7590 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7591
7592private:
7593 DiagnosticKind Diagnose;
7594
7595public:
7596 using Base = DefaultedComparisonVisitor;
7597 using Result = DefaultedComparisonInfo;
7598 using Subobject = DefaultedComparisonSubobject;
7599
7600 friend Base;
7601
7602 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7603 DefaultedComparisonKind DCK,
7604 DiagnosticKind Diagnose = NoDiagnostics)
7605 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7606
7607 Result visit() {
7608 if ((DCK == DefaultedComparisonKind::Equal ||
7609 DCK == DefaultedComparisonKind::ThreeWay) &&
7610 RD->hasVariantMembers()) {
7611 // C++2a [class.compare.default]p2 [P2002R0]:
7612 // A defaulted comparison operator function for class C is defined as
7613 // deleted if [...] C has variant members.
7614 if (Diagnose == ExplainDeleted) {
7615 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7616 << FD << RD->isUnion() << RD;
7617 }
7618 return Result::deleted();
7619 }
7620
7621 return Base::visit();
7622 }
7623
7624private:
7625 Subobject getCompleteObject() {
7626 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7627 }
7628
7629 Subobject getBase(CXXBaseSpecifier *Base) {
7630 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7631 Base->getBaseTypeLoc()};
7632 }
7633
7634 Subobject getField(FieldDecl *Field) {
7635 return Subobject{Subobject::Member, Field, Field->getLocation()};
7636 }
7637
7638 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7639 // C++2a [class.compare.default]p2 [P2002R0]:
7640 // A defaulted <=> or == operator function for class C is defined as
7641 // deleted if any non-static data member of C is of reference type
7642 if (Type->isReferenceType()) {
7643 if (Diagnose == ExplainDeleted) {
7644 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7645 << FD << RD;
7646 }
7647 return Result::deleted();
7648 }
7649
7650 // [...] Let xi be an lvalue denoting the ith element [...]
7651 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7652 Expr *Args[] = {&Xi, &Xi};
7653
7654 // All operators start by trying to apply that same operator recursively.
7655 OverloadedOperatorKind OO = FD->getOverloadedOperator();
7656 assert(OO != OO_None && "not an overloaded operator!")((OO != OO_None && "not an overloaded operator!") ? static_cast
<void> (0) : __assert_fail ("OO != OO_None && \"not an overloaded operator!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7656, __PRETTY_FUNCTION__))
;
7657 return visitBinaryOperator(OO, Args, Subobj);
7658 }
7659
7660 Result
7661 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7662 Subobject Subobj,
7663 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7664 // Note that there is no need to consider rewritten candidates here if
7665 // we've already found there is no viable 'operator<=>' candidate (and are
7666 // considering synthesizing a '<=>' from '==' and '<').
7667 OverloadCandidateSet CandidateSet(
7668 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7669 OverloadCandidateSet::OperatorRewriteInfo(
7670 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7671
7672 /// C++2a [class.compare.default]p1 [P2002R0]:
7673 /// [...] the defaulted function itself is never a candidate for overload
7674 /// resolution [...]
7675 CandidateSet.exclude(FD);
7676
7677 if (Args[0]->getType()->isOverloadableType())
7678 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7679 else {
7680 // FIXME: We determine whether this is a valid expression by checking to
7681 // see if there's a viable builtin operator candidate for it. That isn't
7682 // really what the rules ask us to do, but should give the right results.
7683 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7684 }
7685
7686 Result R;
7687
7688 OverloadCandidateSet::iterator Best;
7689 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7690 case OR_Success: {
7691 // C++2a [class.compare.secondary]p2 [P2002R0]:
7692 // The operator function [...] is defined as deleted if [...] the
7693 // candidate selected by overload resolution is not a rewritten
7694 // candidate.
7695 if ((DCK == DefaultedComparisonKind::NotEqual ||
7696 DCK == DefaultedComparisonKind::Relational) &&
7697 !Best->RewriteKind) {
7698 if (Diagnose == ExplainDeleted) {
7699 S.Diag(Best->Function->getLocation(),
7700 diag::note_defaulted_comparison_not_rewritten_callee)
7701 << FD;
7702 }
7703 return Result::deleted();
7704 }
7705
7706 // Throughout C++2a [class.compare]: if overload resolution does not
7707 // result in a usable function, the candidate function is defined as
7708 // deleted. This requires that we selected an accessible function.
7709 //
7710 // Note that this only considers the access of the function when named
7711 // within the type of the subobject, and not the access path for any
7712 // derived-to-base conversion.
7713 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7714 if (ArgClass && Best->FoundDecl.getDecl() &&
7715 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7716 QualType ObjectType = Subobj.Kind == Subobject::Member
7717 ? Args[0]->getType()
7718 : S.Context.getRecordType(RD);
7719 if (!S.isMemberAccessibleForDeletion(
7720 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7721 Diagnose == ExplainDeleted
7722 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7723 << FD << Subobj.Kind << Subobj.Decl
7724 : S.PDiag()))
7725 return Result::deleted();
7726 }
7727
7728 // C++2a [class.compare.default]p3 [P2002R0]:
7729 // A defaulted comparison function is constexpr-compatible if [...]
7730 // no overlod resolution performed [...] results in a non-constexpr
7731 // function.
7732 if (FunctionDecl *BestFD = Best->Function) {
7733 assert(!BestFD->isDeleted() && "wrong overload resolution result")((!BestFD->isDeleted() && "wrong overload resolution result"
) ? static_cast<void> (0) : __assert_fail ("!BestFD->isDeleted() && \"wrong overload resolution result\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7733, __PRETTY_FUNCTION__))
;
7734 // If it's not constexpr, explain why not.
7735 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7736 if (Subobj.Kind != Subobject::CompleteObject)
7737 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7738 << Subobj.Kind << Subobj.Decl;
7739 S.Diag(BestFD->getLocation(),
7740 diag::note_defaulted_comparison_not_constexpr_here);
7741 // Bail out after explaining; we don't want any more notes.
7742 return Result::deleted();
7743 }
7744 R.Constexpr &= BestFD->isConstexpr();
7745 }
7746
7747 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7748 if (auto *BestFD = Best->Function) {
7749 // If any callee has an undeduced return type, deduce it now.
7750 // FIXME: It's not clear how a failure here should be handled. For
7751 // now, we produce an eager diagnostic, because that is forward
7752 // compatible with most (all?) other reasonable options.
7753 if (BestFD->getReturnType()->isUndeducedType() &&
7754 S.DeduceReturnType(BestFD, FD->getLocation(),
7755 /*Diagnose=*/false)) {
7756 // Don't produce a duplicate error when asked to explain why the
7757 // comparison is deleted: we diagnosed that when initially checking
7758 // the defaulted operator.
7759 if (Diagnose == NoDiagnostics) {
7760 S.Diag(
7761 FD->getLocation(),
7762 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7763 << Subobj.Kind << Subobj.Decl;
7764 S.Diag(
7765 Subobj.Loc,
7766 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7767 << Subobj.Kind << Subobj.Decl;
7768 S.Diag(BestFD->getLocation(),
7769 diag::note_defaulted_comparison_cannot_deduce_callee)
7770 << Subobj.Kind << Subobj.Decl;
7771 }
7772 return Result::deleted();
7773 }
7774 if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7775 BestFD->getCallResultType())) {
7776 R.Category = Info->Kind;
7777 } else {
7778 if (Diagnose == ExplainDeleted) {
7779 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7780 << Subobj.Kind << Subobj.Decl
7781 << BestFD->getCallResultType().withoutLocalFastQualifiers();
7782 S.Diag(BestFD->getLocation(),
7783 diag::note_defaulted_comparison_cannot_deduce_callee)
7784 << Subobj.Kind << Subobj.Decl;
7785 }
7786 return Result::deleted();
7787 }
7788 } else {
7789 Optional<ComparisonCategoryType> Cat =
7790 getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7791 assert(Cat && "no category for builtin comparison?")((Cat && "no category for builtin comparison?") ? static_cast
<void> (0) : __assert_fail ("Cat && \"no category for builtin comparison?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7791, __PRETTY_FUNCTION__))
;
7792 R.Category = *Cat;
7793 }
7794 }
7795
7796 // Note that we might be rewriting to a different operator. That call is
7797 // not considered until we come to actually build the comparison function.
7798 break;
7799 }
7800
7801 case OR_Ambiguous:
7802 if (Diagnose == ExplainDeleted) {
7803 unsigned Kind = 0;
7804 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7805 Kind = OO == OO_EqualEqual ? 1 : 2;
7806 CandidateSet.NoteCandidates(
7807 PartialDiagnosticAt(
7808 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7809 << FD << Kind << Subobj.Kind << Subobj.Decl),
7810 S, OCD_AmbiguousCandidates, Args);
7811 }
7812 R = Result::deleted();
7813 break;
7814
7815 case OR_Deleted:
7816 if (Diagnose == ExplainDeleted) {
7817 if ((DCK == DefaultedComparisonKind::NotEqual ||
7818 DCK == DefaultedComparisonKind::Relational) &&
7819 !Best->RewriteKind) {
7820 S.Diag(Best->Function->getLocation(),
7821 diag::note_defaulted_comparison_not_rewritten_callee)
7822 << FD;
7823 } else {
7824 S.Diag(Subobj.Loc,
7825 diag::note_defaulted_comparison_calls_deleted)
7826 << FD << Subobj.Kind << Subobj.Decl;
7827 S.NoteDeletedFunction(Best->Function);
7828 }
7829 }
7830 R = Result::deleted();
7831 break;
7832
7833 case OR_No_Viable_Function:
7834 // If there's no usable candidate, we're done unless we can rewrite a
7835 // '<=>' in terms of '==' and '<'.
7836 if (OO == OO_Spaceship &&
7837 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7838 // For any kind of comparison category return type, we need a usable
7839 // '==' and a usable '<'.
7840 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7841 &CandidateSet)))
7842 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7843 break;
7844 }
7845
7846 if (Diagnose == ExplainDeleted) {
7847 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7848 << FD << Subobj.Kind << Subobj.Decl;
7849
7850 // For a three-way comparison, list both the candidates for the
7851 // original operator and the candidates for the synthesized operator.
7852 if (SpaceshipCandidates) {
7853 SpaceshipCandidates->NoteCandidates(
7854 S, Args,
7855 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7856 Args, FD->getLocation()));
7857 S.Diag(Subobj.Loc,
7858 diag::note_defaulted_comparison_no_viable_function_synthesized)
7859 << (OO == OO_EqualEqual ? 0 : 1);
7860 }
7861
7862 CandidateSet.NoteCandidates(
7863 S, Args,
7864 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7865 FD->getLocation()));
7866 }
7867 R = Result::deleted();
7868 break;
7869 }
7870
7871 return R;
7872 }
7873};
7874
7875/// A list of statements.
7876struct StmtListResult {
7877 bool IsInvalid = false;
7878 llvm::SmallVector<Stmt*, 16> Stmts;
7879
7880 bool add(const StmtResult &S) {
7881 IsInvalid |= S.isInvalid();
7882 if (IsInvalid)
7883 return true;
7884 Stmts.push_back(S.get());
7885 return false;
7886 }
7887};
7888
7889/// A visitor over the notional body of a defaulted comparison that synthesizes
7890/// the actual body.
7891class DefaultedComparisonSynthesizer
7892 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7893 StmtListResult, StmtResult,
7894 std::pair<ExprResult, ExprResult>> {
7895 SourceLocation Loc;
7896 unsigned ArrayDepth = 0;
7897
7898public:
7899 using Base = DefaultedComparisonVisitor;
7900 using ExprPair = std::pair<ExprResult, ExprResult>;
7901
7902 friend Base;
7903
7904 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7905 DefaultedComparisonKind DCK,
7906 SourceLocation BodyLoc)
7907 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7908
7909 /// Build a suitable function body for this defaulted comparison operator.
7910 StmtResult build() {
7911 Sema::CompoundScopeRAII CompoundScope(S);
7912
7913 StmtListResult Stmts = visit();
7914 if (Stmts.IsInvalid)
7915 return StmtError();
7916
7917 ExprResult RetVal;
7918 switch (DCK) {
7919 case DefaultedComparisonKind::None:
7920 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 7920)
;
7921
7922 case DefaultedComparisonKind::Equal: {
7923 // C++2a [class.eq]p3:
7924 // [...] compar[e] the corresponding elements [...] until the first
7925 // index i where xi == yi yields [...] false. If no such index exists,
7926 // V is true. Otherwise, V is false.
7927 //
7928 // Join the comparisons with '&&'s and return the result. Use a right
7929 // fold (traversing the conditions right-to-left), because that
7930 // short-circuits more naturally.
7931 auto OldStmts = std::move(Stmts.Stmts);
7932 Stmts.Stmts.clear();
7933 ExprResult CmpSoFar;
7934 // Finish a particular comparison chain.
7935 auto FinishCmp = [&] {
7936 if (Expr *Prior = CmpSoFar.get()) {
7937 // Convert the last expression to 'return ...;'
7938 if (RetVal.isUnset() && Stmts.Stmts.empty())
7939 RetVal = CmpSoFar;
7940 // Convert any prior comparison to 'if (!(...)) return false;'
7941 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7942 return true;
7943 CmpSoFar = ExprResult();
7944 }
7945 return false;
7946 };
7947 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7948 Expr *E = dyn_cast<Expr>(EAsStmt);
7949 if (!E) {
7950 // Found an array comparison.
7951 if (FinishCmp() || Stmts.add(EAsStmt))
7952 return StmtError();
7953 continue;
7954 }
7955
7956 if (CmpSoFar.isUnset()) {
7957 CmpSoFar = E;
7958 continue;
7959 }
7960 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7961 if (CmpSoFar.isInvalid())
7962 return StmtError();
7963 }
7964 if (FinishCmp())
7965 return StmtError();
7966 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7967 // If no such index exists, V is true.
7968 if (RetVal.isUnset())
7969 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7970 break;
7971 }
7972
7973 case DefaultedComparisonKind::ThreeWay: {
7974 // Per C++2a [class.spaceship]p3, as a fallback add:
7975 // return static_cast<R>(std::strong_ordering::equal);
7976 QualType StrongOrdering = S.CheckComparisonCategoryType(
7977 ComparisonCategoryType::StrongOrdering, Loc,
7978 Sema::ComparisonCategoryUsage::DefaultedOperator);
7979 if (StrongOrdering.isNull())
7980 return StmtError();
7981 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7982 .getValueInfo(ComparisonCategoryResult::Equal)
7983 ->VD;
7984 RetVal = getDecl(EqualVD);
7985 if (RetVal.isInvalid())
7986 return StmtError();
7987 RetVal = buildStaticCastToR(RetVal.get());
7988 break;
7989 }
7990
7991 case DefaultedComparisonKind::NotEqual:
7992 case DefaultedComparisonKind::Relational:
7993 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7994 break;
7995 }
7996
7997 // Build the final return statement.
7998 if (RetVal.isInvalid())
7999 return StmtError();
8000 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8001 if (ReturnStmt.isInvalid())
8002 return StmtError();
8003 Stmts.Stmts.push_back(ReturnStmt.get());
8004
8005 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8006 }
8007
8008private:
8009 ExprResult getDecl(ValueDecl *VD) {
8010 return S.BuildDeclarationNameExpr(
8011 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8012 }
8013
8014 ExprResult getParam(unsigned I) {
8015 ParmVarDecl *PD = FD->getParamDecl(I);
8016 return getDecl(PD);
8017 }
8018
8019 ExprPair getCompleteObject() {
8020 unsigned Param = 0;
8021 ExprResult LHS;
8022 if (isa<CXXMethodDecl>(FD)) {
8023 // LHS is '*this'.
8024 LHS = S.ActOnCXXThis(Loc);
8025 if (!LHS.isInvalid())
8026 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8027 } else {
8028 LHS = getParam(Param++);
8029 }
8030 ExprResult RHS = getParam(Param++);
8031 assert(Param == FD->getNumParams())((Param == FD->getNumParams()) ? static_cast<void> (
0) : __assert_fail ("Param == FD->getNumParams()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8031, __PRETTY_FUNCTION__))
;
8032 return {LHS, RHS};
8033 }
8034
8035 ExprPair getBase(CXXBaseSpecifier *Base) {
8036 ExprPair Obj = getCompleteObject();
8037 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8038 return {ExprError(), ExprError()};
8039 CXXCastPath Path = {Base};
8040 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8041 CK_DerivedToBase, VK_LValue, &Path),
8042 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8043 CK_DerivedToBase, VK_LValue, &Path)};
8044 }
8045
8046 ExprPair getField(FieldDecl *Field) {
8047 ExprPair Obj = getCompleteObject();
8048 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8049 return {ExprError(), ExprError()};
8050
8051 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8052 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8053 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8054 CXXScopeSpec(), Field, Found, NameInfo),
8055 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8056 CXXScopeSpec(), Field, Found, NameInfo)};
8057 }
8058
8059 // FIXME: When expanding a subobject, register a note in the code synthesis
8060 // stack to say which subobject we're comparing.
8061
8062 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8063 if (Cond.isInvalid())
8064 return StmtError();
8065
8066 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8067 if (NotCond.isInvalid())
8068 return StmtError();
8069
8070 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8071 assert(!False.isInvalid() && "should never fail")((!False.isInvalid() && "should never fail") ? static_cast
<void> (0) : __assert_fail ("!False.isInvalid() && \"should never fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8071, __PRETTY_FUNCTION__))
;
8072 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8073 if (ReturnFalse.isInvalid())
8074 return StmtError();
8075
8076 return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8077 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8078 Sema::ConditionKind::Boolean),
8079 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8080 }
8081
8082 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8083 ExprPair Subobj) {
8084 QualType SizeType = S.Context.getSizeType();
8085 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8086
8087 // Build 'size_t i$n = 0'.
8088 IdentifierInfo *IterationVarName = nullptr;
8089 {
8090 SmallString<8> Str;
8091 llvm::raw_svector_ostream OS(Str);
8092 OS << "i" << ArrayDepth;
8093 IterationVarName = &S.Context.Idents.get(OS.str());
8094 }
8095 VarDecl *IterationVar = VarDecl::Create(
8096 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8097 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8098 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8099 IterationVar->setInit(
8100 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8101 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8102
8103 auto IterRef = [&] {
8104 ExprResult Ref = S.BuildDeclarationNameExpr(
8105 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8106 IterationVar);
8107 assert(!Ref.isInvalid() && "can't reference our own variable?")((!Ref.isInvalid() && "can't reference our own variable?"
) ? static_cast<void> (0) : __assert_fail ("!Ref.isInvalid() && \"can't reference our own variable?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8107, __PRETTY_FUNCTION__))
;
8108 return Ref.get();
8109 };
8110
8111 // Build 'i$n != Size'.
8112 ExprResult Cond = S.CreateBuiltinBinOp(
8113 Loc, BO_NE, IterRef(),
8114 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8115 assert(!Cond.isInvalid() && "should never fail")((!Cond.isInvalid() && "should never fail") ? static_cast
<void> (0) : __assert_fail ("!Cond.isInvalid() && \"should never fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8115, __PRETTY_FUNCTION__))
;
8116
8117 // Build '++i$n'.
8118 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8119 assert(!Inc.isInvalid() && "should never fail")((!Inc.isInvalid() && "should never fail") ? static_cast
<void> (0) : __assert_fail ("!Inc.isInvalid() && \"should never fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8119, __PRETTY_FUNCTION__))
;
8120
8121 // Build 'a[i$n]' and 'b[i$n]'.
8122 auto Index = [&](ExprResult E) {
8123 if (E.isInvalid())
8124 return ExprError();
8125 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8126 };
8127 Subobj.first = Index(Subobj.first);
8128 Subobj.second = Index(Subobj.second);
8129
8130 // Compare the array elements.
8131 ++ArrayDepth;
8132 StmtResult Substmt = visitSubobject(Type, Subobj);
8133 --ArrayDepth;
8134
8135 if (Substmt.isInvalid())
8136 return StmtError();
8137
8138 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8139 // For outer levels or for an 'operator<=>' we already have a suitable
8140 // statement that returns as necessary.
8141 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8142 assert(DCK == DefaultedComparisonKind::Equal &&((DCK == DefaultedComparisonKind::Equal && "should have non-expression statement"
) ? static_cast<void> (0) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8143, __PRETTY_FUNCTION__))
8143 "should have non-expression statement")((DCK == DefaultedComparisonKind::Equal && "should have non-expression statement"
) ? static_cast<void> (0) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8143, __PRETTY_FUNCTION__))
;
8144 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8145 if (Substmt.isInvalid())
8146 return StmtError();
8147 }
8148
8149 // Build 'for (...) ...'
8150 return S.ActOnForStmt(Loc, Loc, Init,
8151 S.ActOnCondition(nullptr, Loc, Cond.get(),
8152 Sema::ConditionKind::Boolean),
8153 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8154 Substmt.get());
8155 }
8156
8157 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8158 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8159 return StmtError();
8160
8161 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8162 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8163 ExprResult Op;
8164 if (Type->isOverloadableType())
8165 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8166 Obj.second.get(), /*PerformADL=*/true,
8167 /*AllowRewrittenCandidates=*/true, FD);
8168 else
8169 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8170 if (Op.isInvalid())
8171 return StmtError();
8172
8173 switch (DCK) {
8174 case DefaultedComparisonKind::None:
8175 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8175)
;
8176
8177 case DefaultedComparisonKind::Equal:
8178 // Per C++2a [class.eq]p2, each comparison is individually contextually
8179 // converted to bool.
8180 Op = S.PerformContextuallyConvertToBool(Op.get());
8181 if (Op.isInvalid())
8182 return StmtError();
8183 return Op.get();
8184
8185 case DefaultedComparisonKind::ThreeWay: {
8186 // Per C++2a [class.spaceship]p3, form:
8187 // if (R cmp = static_cast<R>(op); cmp != 0)
8188 // return cmp;
8189 QualType R = FD->getReturnType();
8190 Op = buildStaticCastToR(Op.get());
8191 if (Op.isInvalid())
8192 return StmtError();
8193
8194 // R cmp = ...;
8195 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8196 VarDecl *VD =
8197 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8198 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8199 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8200 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8201
8202 // cmp != 0
8203 ExprResult VDRef = getDecl(VD);
8204 if (VDRef.isInvalid())
8205 return StmtError();
8206 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8207 Expr *Zero =
8208 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8209 ExprResult Comp;
8210 if (VDRef.get()->getType()->isOverloadableType())
8211 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8212 true, FD);
8213 else
8214 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8215 if (Comp.isInvalid())
8216 return StmtError();
8217 Sema::ConditionResult Cond = S.ActOnCondition(
8218 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8219 if (Cond.isInvalid())
8220 return StmtError();
8221
8222 // return cmp;
8223 VDRef = getDecl(VD);
8224 if (VDRef.isInvalid())
8225 return StmtError();
8226 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8227 if (ReturnStmt.isInvalid())
8228 return StmtError();
8229
8230 // if (...)
8231 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8232 ReturnStmt.get(),
8233 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8234 }
8235
8236 case DefaultedComparisonKind::NotEqual:
8237 case DefaultedComparisonKind::Relational:
8238 // C++2a [class.compare.secondary]p2:
8239 // Otherwise, the operator function yields x @ y.
8240 return Op.get();
8241 }
8242 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8242)
;
8243 }
8244
8245 /// Build "static_cast<R>(E)".
8246 ExprResult buildStaticCastToR(Expr *E) {
8247 QualType R = FD->getReturnType();
8248 assert(!R->isUndeducedType() && "type should have been deduced already")((!R->isUndeducedType() && "type should have been deduced already"
) ? static_cast<void> (0) : __assert_fail ("!R->isUndeducedType() && \"type should have been deduced already\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8248, __PRETTY_FUNCTION__))
;
8249
8250 // Don't bother forming a no-op cast in the common case.
8251 if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8252 return E;
8253 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8254 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8255 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8256 }
8257};
8258}
8259
8260/// Perform the unqualified lookups that might be needed to form a defaulted
8261/// comparison function for the given operator.
8262static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8263 UnresolvedSetImpl &Operators,
8264 OverloadedOperatorKind Op) {
8265 auto Lookup = [&](OverloadedOperatorKind OO) {
8266 Self.LookupOverloadedOperatorName(OO, S, Operators);
8267 };
8268
8269 // Every defaulted operator looks up itself.
8270 Lookup(Op);
8271 // ... and the rewritten form of itself, if any.
8272 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8273 Lookup(ExtraOp);
8274
8275 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8276 // synthesize a three-way comparison from '<' and '=='. In a dependent
8277 // context, we also need to look up '==' in case we implicitly declare a
8278 // defaulted 'operator=='.
8279 if (Op == OO_Spaceship) {
8280 Lookup(OO_ExclaimEqual);
8281 Lookup(OO_Less);
8282 Lookup(OO_EqualEqual);
8283 }
8284}
8285
8286bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8287 DefaultedComparisonKind DCK) {
8288 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison")((DCK != DefaultedComparisonKind::None && "not a defaulted comparison"
) ? static_cast<void> (0) : __assert_fail ("DCK != DefaultedComparisonKind::None && \"not a defaulted comparison\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8288, __PRETTY_FUNCTION__))
;
8289
8290 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8291 assert(RD && "defaulted comparison is not defaulted in a class")((RD && "defaulted comparison is not defaulted in a class"
) ? static_cast<void> (0) : __assert_fail ("RD && \"defaulted comparison is not defaulted in a class\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8291, __PRETTY_FUNCTION__))
;
8292
8293 // Perform any unqualified lookups we're going to need to default this
8294 // function.
8295 if (S) {
8296 UnresolvedSet<32> Operators;
8297 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8298 FD->getOverloadedOperator());
8299 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8300 Context, Operators.pairs()));
8301 }
8302
8303 // C++2a [class.compare.default]p1:
8304 // A defaulted comparison operator function for some class C shall be a
8305 // non-template function declared in the member-specification of C that is
8306 // -- a non-static const member of C having one parameter of type
8307 // const C&, or
8308 // -- a friend of C having two parameters of type const C& or two
8309 // parameters of type C.
8310 QualType ExpectedParmType1 = Context.getRecordType(RD);
8311 QualType ExpectedParmType2 =
8312 Context.getLValueReferenceType(ExpectedParmType1.withConst());
8313 if (isa<CXXMethodDecl>(FD))
8314 ExpectedParmType1 = ExpectedParmType2;
8315 for (const ParmVarDecl *Param : FD->parameters()) {
8316 if (!Param->getType()->isDependentType() &&
8317 !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8318 !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8319 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8320 // corresponding defaulted 'operator<=>' already.
8321 if (!FD->isImplicit()) {
8322 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8323 << (int)DCK << Param->getType() << ExpectedParmType1
8324 << !isa<CXXMethodDecl>(FD)
8325 << ExpectedParmType2 << Param->getSourceRange();
8326 }
8327 return true;
8328 }
8329 }
8330 if (FD->getNumParams() == 2 &&
8331 !Context.hasSameType(FD->getParamDecl(0)->getType(),
8332 FD->getParamDecl(1)->getType())) {
8333 if (!FD->isImplicit()) {
8334 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8335 << (int)DCK
8336 << FD->getParamDecl(0)->getType()
8337 << FD->getParamDecl(0)->getSourceRange()
8338 << FD->getParamDecl(1)->getType()
8339 << FD->getParamDecl(1)->getSourceRange();
8340 }
8341 return true;
8342 }
8343
8344 // ... non-static const member ...
8345 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8346 assert(!MD->isStatic() && "comparison function cannot be a static member")((!MD->isStatic() && "comparison function cannot be a static member"
) ? static_cast<void> (0) : __assert_fail ("!MD->isStatic() && \"comparison function cannot be a static member\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8346, __PRETTY_FUNCTION__))
;
8347 if (!MD->isConst()) {
8348 SourceLocation InsertLoc;
8349 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8350 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8351 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8352 // corresponding defaulted 'operator<=>' already.
8353 if (!MD->isImplicit()) {
8354 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8355 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8356 }
8357
8358 // Add the 'const' to the type to recover.
8359 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8360 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8361 EPI.TypeQuals.addConst();
8362 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8363 FPT->getParamTypes(), EPI));
8364 }
8365 } else {
8366 // A non-member function declared in a class must be a friend.
8367 assert(FD->getFriendObjectKind() && "expected a friend declaration")((FD->getFriendObjectKind() && "expected a friend declaration"
) ? static_cast<void> (0) : __assert_fail ("FD->getFriendObjectKind() && \"expected a friend declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8367, __PRETTY_FUNCTION__))
;
8368 }
8369
8370 // C++2a [class.eq]p1, [class.rel]p1:
8371 // A [defaulted comparison other than <=>] shall have a declared return
8372 // type bool.
8373 if (DCK != DefaultedComparisonKind::ThreeWay &&
8374 !FD->getDeclaredReturnType()->isDependentType() &&
8375 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8376 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8377 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8378 << FD->getReturnTypeSourceRange();
8379 return true;
8380 }
8381 // C++2a [class.spaceship]p2 [P2002R0]:
8382 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8383 // R shall not contain a placeholder type.
8384 if (DCK == DefaultedComparisonKind::ThreeWay &&
8385 FD->getDeclaredReturnType()->getContainedDeducedType() &&
8386 !Context.hasSameType(FD->getDeclaredReturnType(),
8387 Context.getAutoDeductType())) {
8388 Diag(FD->getLocation(),
8389 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8390 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8391 << FD->getReturnTypeSourceRange();
8392 return true;
8393 }
8394
8395 // For a defaulted function in a dependent class, defer all remaining checks
8396 // until instantiation.
8397 if (RD->isDependentType())
8398 return false;
8399
8400 // Determine whether the function should be defined as deleted.
8401 DefaultedComparisonInfo Info =
8402 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8403
8404 bool First = FD == FD->getCanonicalDecl();
8405
8406 // If we want to delete the function, then do so; there's nothing else to
8407 // check in that case.
8408 if (Info.Deleted) {
8409 if (!First) {
8410 // C++11 [dcl.fct.def.default]p4:
8411 // [For a] user-provided explicitly-defaulted function [...] if such a
8412 // function is implicitly defined as deleted, the program is ill-formed.
8413 //
8414 // This is really just a consequence of the general rule that you can
8415 // only delete a function on its first declaration.
8416 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8417 << FD->isImplicit() << (int)DCK;
8418 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8419 DefaultedComparisonAnalyzer::ExplainDeleted)
8420 .visit();
8421 return true;
8422 }
8423
8424 SetDeclDeleted(FD, FD->getLocation());
8425 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8426 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8427 << (int)DCK;
8428 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8429 DefaultedComparisonAnalyzer::ExplainDeleted)
8430 .visit();
8431 }
8432 return false;
8433 }
8434
8435 // C++2a [class.spaceship]p2:
8436 // The return type is deduced as the common comparison type of R0, R1, ...
8437 if (DCK == DefaultedComparisonKind::ThreeWay &&
8438 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8439 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8440 if (RetLoc.isInvalid())
8441 RetLoc = FD->getBeginLoc();
8442 // FIXME: Should we really care whether we have the complete type and the
8443 // 'enumerator' constants here? A forward declaration seems sufficient.
8444 QualType Cat = CheckComparisonCategoryType(
8445 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8446 if (Cat.isNull())
8447 return true;
8448 Context.adjustDeducedFunctionResultType(
8449 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8450 }
8451
8452 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8453 // An explicitly-defaulted function that is not defined as deleted may be
8454 // declared constexpr or consteval only if it is constexpr-compatible.
8455 // C++2a [class.compare.default]p3 [P2002R0]:
8456 // A defaulted comparison function is constexpr-compatible if it satisfies
8457 // the requirements for a constexpr function [...]
8458 // The only relevant requirements are that the parameter and return types are
8459 // literal types. The remaining conditions are checked by the analyzer.
8460 if (FD->isConstexpr()) {
8461 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8462 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8463 !Info.Constexpr) {
8464 Diag(FD->getBeginLoc(),
8465 diag::err_incorrect_defaulted_comparison_constexpr)
8466 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8467 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8468 DefaultedComparisonAnalyzer::ExplainConstexpr)
8469 .visit();
8470 }
8471 }
8472
8473 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8474 // If a constexpr-compatible function is explicitly defaulted on its first
8475 // declaration, it is implicitly considered to be constexpr.
8476 // FIXME: Only applying this to the first declaration seems problematic, as
8477 // simple reorderings can affect the meaning of the program.
8478 if (First && !FD->isConstexpr() && Info.Constexpr)
8479 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8480
8481 // C++2a [except.spec]p3:
8482 // If a declaration of a function does not have a noexcept-specifier
8483 // [and] is defaulted on its first declaration, [...] the exception
8484 // specification is as specified below
8485 if (FD->getExceptionSpecType() == EST_None) {
8486 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8487 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8488 EPI.ExceptionSpec.Type = EST_Unevaluated;
8489 EPI.ExceptionSpec.SourceDecl = FD;
8490 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8491 FPT->getParamTypes(), EPI));
8492 }
8493
8494 return false;
8495}
8496
8497void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8498 FunctionDecl *Spaceship) {
8499 Sema::CodeSynthesisContext Ctx;
8500 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8501 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8502 Ctx.Entity = Spaceship;
8503 pushCodeSynthesisContext(Ctx);
8504
8505 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8506 EqualEqual->setImplicit();
8507
8508 popCodeSynthesisContext();
8509}
8510
8511void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8512 DefaultedComparisonKind DCK) {
8513 assert(FD->isDefaulted() && !FD->isDeleted() &&((FD->isDefaulted() && !FD->isDeleted() &&
!FD->doesThisDeclarationHaveABody()) ? static_cast<void
> (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8514, __PRETTY_FUNCTION__))
8514 !FD->doesThisDeclarationHaveABody())((FD->isDefaulted() && !FD->isDeleted() &&
!FD->doesThisDeclarationHaveABody()) ? static_cast<void
> (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8514, __PRETTY_FUNCTION__))
;
8515 if (FD->willHaveBody() || FD->isInvalidDecl())
8516 return;
8517
8518 SynthesizedFunctionScope Scope(*this, FD);
8519
8520 // Add a context note for diagnostics produced after this point.
8521 Scope.addContextNote(UseLoc);
8522
8523 {
8524 // Build and set up the function body.
8525 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8526 SourceLocation BodyLoc =
8527 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8528 StmtResult Body =
8529 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8530 if (Body.isInvalid()) {
8531 FD->setInvalidDecl();
8532 return;
8533 }
8534 FD->setBody(Body.get());
8535 FD->markUsed(Context);
8536 }
8537
8538 // The exception specification is needed because we are defining the
8539 // function. Note that this will reuse the body we just built.
8540 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8541
8542 if (ASTMutationListener *L = getASTMutationListener())
8543 L->CompletedImplicitDefinition(FD);
8544}
8545
8546static Sema::ImplicitExceptionSpecification
8547ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8548 FunctionDecl *FD,
8549 Sema::DefaultedComparisonKind DCK) {
8550 ComputingExceptionSpec CES(S, FD, Loc);
8551 Sema::ImplicitExceptionSpecification ExceptSpec(S);
8552
8553 if (FD->isInvalidDecl())
8554 return ExceptSpec;
8555
8556 // The common case is that we just defined the comparison function. In that
8557 // case, just look at whether the body can throw.
8558 if (FD->hasBody()) {
8559 ExceptSpec.CalledStmt(FD->getBody());
8560 } else {
8561 // Otherwise, build a body so we can check it. This should ideally only
8562 // happen when we're not actually marking the function referenced. (This is
8563 // only really important for efficiency: we don't want to build and throw
8564 // away bodies for comparison functions more than we strictly need to.)
8565
8566 // Pretend to synthesize the function body in an unevaluated context.
8567 // Note that we can't actually just go ahead and define the function here:
8568 // we are not permitted to mark its callees as referenced.
8569 Sema::SynthesizedFunctionScope Scope(S, FD);
8570 EnterExpressionEvaluationContext Context(
8571 S, Sema::ExpressionEvaluationContext::Unevaluated);
8572
8573 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8574 SourceLocation BodyLoc =
8575 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8576 StmtResult Body =
8577 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8578 if (!Body.isInvalid())
8579 ExceptSpec.CalledStmt(Body.get());
8580
8581 // FIXME: Can we hold onto this body and just transform it to potentially
8582 // evaluated when we're asked to define the function rather than rebuilding
8583 // it? Either that, or we should only build the bits of the body that we
8584 // need (the expressions, not the statements).
8585 }
8586
8587 return ExceptSpec;
8588}
8589
8590void Sema::CheckDelayedMemberExceptionSpecs() {
8591 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8592 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8593
8594 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8595 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8596
8597 // Perform any deferred checking of exception specifications for virtual
8598 // destructors.
8599 for (auto &Check : Overriding)
8600 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8601
8602 // Perform any deferred checking of exception specifications for befriended
8603 // special members.
8604 for (auto &Check : Equivalent)
8605 CheckEquivalentExceptionSpec(Check.second, Check.first);
8606}
8607
8608namespace {
8609/// CRTP base class for visiting operations performed by a special member
8610/// function (or inherited constructor).
8611template<typename Derived>
8612struct SpecialMemberVisitor {
8613 Sema &S;
8614 CXXMethodDecl *MD;
8615 Sema::CXXSpecialMember CSM;
8616 Sema::InheritedConstructorInfo *ICI;
8617
8618 // Properties of the special member, computed for convenience.
8619 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8620
8621 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8622 Sema::InheritedConstructorInfo *ICI)
8623 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8624 switch (CSM) {
8625 case Sema::CXXDefaultConstructor:
8626 case Sema::CXXCopyConstructor:
8627 case Sema::CXXMoveConstructor:
8628 IsConstructor = true;
8629 break;
8630 case Sema::CXXCopyAssignment:
8631 case Sema::CXXMoveAssignment:
8632 IsAssignment = true;
8633 break;
8634 case Sema::CXXDestructor:
8635 break;
8636 case Sema::CXXInvalid:
8637 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8637)
;
8638 }
8639
8640 if (MD->getNumParams()) {
8641 if (const ReferenceType *RT =
8642 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8643 ConstArg = RT->getPointeeType().isConstQualified();
8644 }
8645 }
8646
8647 Derived &getDerived() { return static_cast<Derived&>(*this); }
8648
8649 /// Is this a "move" special member?
8650 bool isMove() const {
8651 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8652 }
8653
8654 /// Look up the corresponding special member in the given class.
8655 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8656 unsigned Quals, bool IsMutable) {
8657 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8658 ConstArg && !IsMutable);
8659 }
8660
8661 /// Look up the constructor for the specified base class to see if it's
8662 /// overridden due to this being an inherited constructor.
8663 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8664 if (!ICI)
8665 return {};
8666 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 8666, __PRETTY_FUNCTION__))
;
8667 auto *BaseCtor =
8668 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8669 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8670 return MD;
8671 return {};
8672 }
8673
8674 /// A base or member subobject.
8675 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8676
8677 /// Get the location to use for a subobject in diagnostics.
8678 static SourceLocation getSubobjectLoc(Subobject Subobj) {
8679 // FIXME: For an indirect virtual base, the direct base leading to
8680 // the indirect virtual base would be a more useful choice.
8681 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8682 return B->getBaseTypeLoc();
8683 else
8684 return Subobj.get<FieldDecl*>()->getLocation();
8685 }
8686
8687 enum BasesToVisit {
8688 /// Visit all non-virtual (direct) bases.
8689 VisitNonVirtualBases,
8690 /// Visit all direct bases, virtual or not.
8691 VisitDirectBases,
8692 /// Visit all non-virtual bases, and all virtual bases if the class
8693 /// is not abstract.
8694 VisitPotentiallyConstructedBases,
8695 /// Visit all direct or virtual bases.
8696 VisitAllBases
8697 };
8698
8699 // Visit the bases and members of the class.
8700 bool visit(BasesToVisit Bases) {
8701 CXXRecordDecl *RD = MD->getParent();
8702
8703 if (Bases == VisitPotentiallyConstructedBases)
8704 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8705
8706 for (auto &B : RD->bases())
8707 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8708 getDerived().visitBase(&B))
8709 return true;
8710
8711 if (Bases == VisitAllBases)
8712 for (auto &B : RD->vbases())
8713 if (getDerived().visitBase(&B))
8714 return true;
8715
8716 for (auto *F : RD->fields())
8717 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8718 getDerived().visitField(F))
8719 return true;
8720
8721 return false;
8722 }
8723};
8724}
8725
8726namespace {
8727struct SpecialMemberDeletionInfo
8728 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8729 bool Diagnose;
8730
8731 SourceLocation Loc;
8732
8733 bool AllFieldsAreConst;
8734
8735 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8736 Sema::CXXSpecialMember CSM,
8737 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8738 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8739 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8740
8741 bool inUnion() const { return MD->getParent()->isUnion(); }
8742
8743 Sema::CXXSpecialMember getEffectiveCSM() {
8744 return ICI ? Sema::CXXInvalid : CSM;
8745 }
8746
8747 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8748
8749 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8750 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8751
8752 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8753 bool shouldDeleteForField(FieldDecl *FD);
8754 bool shouldDeleteForAllConstMembers();
8755
8756 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8757 unsigned Quals);
8758 bool shouldDeleteForSubobjectCall(Subobject Subobj,
8759 Sema::SpecialMemberOverloadResult SMOR,
8760 bool IsDtorCallInCtor);
8761
8762 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8763};
8764}
8765
8766/// Is the given special member inaccessible when used on the given
8767/// sub-object.
8768bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8769 CXXMethodDecl *target) {
8770 /// If we're operating on a base class, the object type is the
8771 /// type of this special member.
8772 QualType objectTy;
8773 AccessSpecifier access = target->getAccess();
8774 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8775 objectTy = S.Context.getTypeDeclType(MD->getParent());
8776 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8777
8778 // If we're operating on a field, the object type is the type of the field.
8779 } else {
8780 objectTy = S.Context.getTypeDeclType(target->getParent());
8781 }
8782
8783 return S.isMemberAccessibleForDeletion(
8784 target->getParent(), DeclAccessPair::make(target, access), objectTy);
8785}
8786
8787/// Check whether we should delete a special member due to the implicit
8788/// definition containing a call to a special member of a subobject.
8789bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8790 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8791 bool IsDtorCallInCtor) {
8792 CXXMethodDecl *Decl = SMOR.getMethod();
8793 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8794
8795 int DiagKind = -1;
8796
8797 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8798 DiagKind = !Decl ? 0 : 1;
8799 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8800 DiagKind = 2;
8801 else if (!isAccessible(Subobj, Decl))
8802 DiagKind = 3;
8803 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8804 !Decl->isTrivial()) {
8805 // A member of a union must have a trivial corresponding special member.
8806 // As a weird special case, a destructor call from a union's constructor
8807 // must be accessible and non-deleted, but need not be trivial. Such a
8808 // destructor is never actually called, but is semantically checked as
8809 // if it were.
8810 DiagKind = 4;
8811 }
8812
8813 if (DiagKind == -1)
8814 return false;
8815
8816 if (Diagnose) {
8817 if (Field) {
8818 S.Diag(Field->getLocation(),
8819 diag::note_deleted_special_member_class_subobject)
8820 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8821 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8822 } else {
8823 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8824 S.Diag(Base->getBeginLoc(),
8825 diag::note_deleted_special_member_class_subobject)
8826 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8827 << Base->getType() << DiagKind << IsDtorCallInCtor
8828 << /*IsObjCPtr*/false;
8829 }
8830
8831 if (DiagKind == 1)
8832 S.NoteDeletedFunction(Decl);
8833 // FIXME: Explain inaccessibility if DiagKind == 3.
8834 }
8835
8836 return true;
8837}
8838
8839/// Check whether we should delete a special member function due to having a
8840/// direct or virtual base class or non-static data member of class type M.
8841bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8842 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8843 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8844 bool IsMutable = Field && Field->isMutable();
8845
8846 // C++11 [class.ctor]p5:
8847 // -- any direct or virtual base class, or non-static data member with no
8848 // brace-or-equal-initializer, has class type M (or array thereof) and
8849 // either M has no default constructor or overload resolution as applied
8850 // to M's default constructor results in an ambiguity or in a function
8851 // that is deleted or inaccessible
8852 // C++11 [class.copy]p11, C++11 [class.copy]p23:
8853 // -- a direct or virtual base class B that cannot be copied/moved because
8854 // overload resolution, as applied to B's corresponding special member,
8855 // results in an ambiguity or a function that is deleted or inaccessible
8856 // from the defaulted special member
8857 // C++11 [class.dtor]p5:
8858 // -- any direct or virtual base class [...] has a type with a destructor
8859 // that is deleted or inaccessible
8860 if (!(CSM == Sema::CXXDefaultConstructor &&
8861 Field && Field->hasInClassInitializer()) &&
8862 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8863 false))
8864 return true;
8865
8866 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8867 // -- any direct or virtual base class or non-static data member has a
8868 // type with a destructor that is deleted or inaccessible
8869 if (IsConstructor) {
8870 Sema::SpecialMemberOverloadResult SMOR =
8871 S.LookupSpecialMember(Class, Sema::CXXDestructor,
8872 false, false, false, false, false);
8873 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8874 return true;
8875 }
8876
8877 return false;
8878}
8879
8880bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8881 FieldDecl *FD, QualType FieldType) {
8882 // The defaulted special functions are defined as deleted if this is a variant
8883 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8884 // type under ARC.
8885 if (!FieldType.hasNonTrivialObjCLifetime())
8886 return false;
8887
8888 // Don't make the defaulted default constructor defined as deleted if the
8889 // member has an in-class initializer.
8890 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8891 return false;
8892
8893 if (Diagnose) {
8894 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8895 S.Diag(FD->getLocation(),
8896 diag::note_deleted_special_member_class_subobject)
8897 << getEffectiveCSM() << ParentClass << /*IsField*/true
8898 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8899 }
8900
8901 return true;
8902}
8903
8904/// Check whether we should delete a special member function due to the class
8905/// having a particular direct or virtual base class.
8906bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8907 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8908 // If program is correct, BaseClass cannot be null, but if it is, the error
8909 // must be reported elsewhere.
8910 if (!BaseClass)
8911 return false;
8912 // If we have an inheriting constructor, check whether we're calling an
8913 // inherited constructor instead of a default constructor.
8914 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8915 if (auto *BaseCtor = SMOR.getMethod()) {
8916 // Note that we do not check access along this path; other than that,
8917 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8918 // FIXME: Check that the base has a usable destructor! Sink this into
8919 // shouldDeleteForClassSubobject.
8920 if (BaseCtor->isDeleted() && Diagnose) {
8921 S.Diag(Base->getBeginLoc(),
8922 diag::note_deleted_special_member_class_subobject)
8923 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8924 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8925 << /*IsObjCPtr*/false;
8926 S.NoteDeletedFunction(BaseCtor);
8927 }
8928 return BaseCtor->isDeleted();
8929 }
8930 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8931}
8932
8933/// Check whether we should delete a special member function due to the class
8934/// having a particular non-static data member.
8935bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8936 QualType FieldType = S.Context.getBaseElementType(FD->getType());
8937 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8938
8939 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8940 return true;
8941
8942 if (CSM == Sema::CXXDefaultConstructor) {
8943 // For a default constructor, all references must be initialized in-class
8944 // and, if a union, it must have a non-const member.
8945 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8946 if (Diagnose)
8947 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8948 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8949 return true;
8950 }
8951 // C++11 [class.ctor]p5: any non-variant non-static data member of
8952 // const-qualified type (or array thereof) with no
8953 // brace-or-equal-initializer does not have a user-provided default
8954 // constructor.
8955 if (!inUnion() && FieldType.isConstQualified() &&
8956 !FD->hasInClassInitializer() &&
8957 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8958 if (Diagnose)
8959 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8960 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8961 return true;
8962 }
8963
8964 if (inUnion() && !FieldType.isConstQualified())
8965 AllFieldsAreConst = false;
8966 } else if (CSM == Sema::CXXCopyConstructor) {
8967 // For a copy constructor, data members must not be of rvalue reference
8968 // type.
8969 if (FieldType->isRValueReferenceType()) {
8970 if (Diagnose)
8971 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8972 << MD->getParent() << FD << FieldType;
8973 return true;
8974 }
8975 } else if (IsAssignment) {
8976 // For an assignment operator, data members must not be of reference type.
8977 if (FieldType->isReferenceType()) {
8978 if (Diagnose)
8979 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8980 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8981 return true;
8982 }
8983 if (!FieldRecord && FieldType.isConstQualified()) {
8984 // C++11 [class.copy]p23:
8985 // -- a non-static data member of const non-class type (or array thereof)
8986 if (Diagnose)
8987 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8988 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8989 return true;
8990 }
8991 }
8992
8993 if (FieldRecord) {
8994 // Some additional restrictions exist on the variant members.
8995 if (!inUnion() && FieldRecord->isUnion() &&
8996 FieldRecord->isAnonymousStructOrUnion()) {
8997 bool AllVariantFieldsAreConst = true;
8998
8999 // FIXME: Handle anonymous unions declared within anonymous unions.
9000 for (auto *UI : FieldRecord->fields()) {
9001 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9002
9003 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9004 return true;
9005
9006 if (!UnionFieldType.isConstQualified())
9007 AllVariantFieldsAreConst = false;
9008
9009 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9010 if (UnionFieldRecord &&
9011 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9012 UnionFieldType.getCVRQualifiers()))
9013 return true;
9014 }
9015
9016 // At least one member in each anonymous union must be non-const
9017 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9018 !FieldRecord->field_empty()) {
9019 if (Diagnose)
9020 S.Diag(FieldRecord->getLocation(),
9021 diag::note_deleted_default_ctor_all_const)
9022 << !!ICI << MD->getParent() << /*anonymous union*/1;
9023 return true;
9024 }
9025
9026 // Don't check the implicit member of the anonymous union type.
9027 // This is technically non-conformant, but sanity demands it.
9028 return false;
9029 }
9030
9031 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9032 FieldType.getCVRQualifiers()))
9033 return true;
9034 }
9035
9036 return false;
9037}
9038
9039/// C++11 [class.ctor] p5:
9040/// A defaulted default constructor for a class X is defined as deleted if
9041/// X is a union and all of its variant members are of const-qualified type.
9042bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9043 // This is a silly definition, because it gives an empty union a deleted
9044 // default constructor. Don't do that.
9045 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9046 bool AnyFields = false;
9047 for (auto *F : MD->getParent()->fields())
9048 if ((AnyFields = !F->isUnnamedBitfield()))
9049 break;
9050 if (!AnyFields)
9051 return false;
9052 if (Diagnose)
9053 S.Diag(MD->getParent()->getLocation(),
9054 diag::note_deleted_default_ctor_all_const)
9055 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9056 return true;
9057 }
9058 return false;
9059}
9060
9061/// Determine whether a defaulted special member function should be defined as
9062/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9063/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9064bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9065 InheritedConstructorInfo *ICI,
9066 bool Diagnose) {
9067 if (MD->isInvalidDecl())
9068 return false;
9069 CXXRecordDecl *RD = MD->getParent();
9070 assert(!RD->isDependentType() && "do deletion after instantiation")((!RD->isDependentType() && "do deletion after instantiation"
) ? static_cast<void> (0) : __assert_fail ("!RD->isDependentType() && \"do deletion after instantiation\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9070, __PRETTY_FUNCTION__))
;
9071 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9072 return false;
9073
9074 // C++11 [expr.lambda.prim]p19:
9075 // The closure type associated with a lambda-expression has a
9076 // deleted (8.4.3) default constructor and a deleted copy
9077 // assignment operator.
9078 // C++2a adds back these operators if the lambda has no lambda-capture.
9079 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9080 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9081 if (Diagnose)
9082 Diag(RD->getLocation(), diag::note_lambda_decl);
9083 return true;
9084 }
9085
9086 // For an anonymous struct or union, the copy and assignment special members
9087 // will never be used, so skip the check. For an anonymous union declared at
9088 // namespace scope, the constructor and destructor are used.
9089 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9090 RD->isAnonymousStructOrUnion())
9091 return false;
9092
9093 // C++11 [class.copy]p7, p18:
9094 // If the class definition declares a move constructor or move assignment
9095 // operator, an implicitly declared copy constructor or copy assignment
9096 // operator is defined as deleted.
9097 if (MD->isImplicit() &&
9098 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9099 CXXMethodDecl *UserDeclaredMove = nullptr;
9100
9101 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9102 // deletion of the corresponding copy operation, not both copy operations.
9103 // MSVC 2015 has adopted the standards conforming behavior.
9104 bool DeletesOnlyMatchingCopy =
9105 getLangOpts().MSVCCompat &&
9106 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9107
9108 if (RD->hasUserDeclaredMoveConstructor() &&
9109 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9110 if (!Diagnose) return true;
9111
9112 // Find any user-declared move constructor.
9113 for (auto *I : RD->ctors()) {
9114 if (I->isMoveConstructor()) {
9115 UserDeclaredMove = I;
9116 break;
9117 }
9118 }
9119 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9119, __PRETTY_FUNCTION__))
;
9120 } else if (RD->hasUserDeclaredMoveAssignment() &&
9121 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9122 if (!Diagnose) return true;
9123
9124 // Find any user-declared move assignment operator.
9125 for (auto *I : RD->methods()) {
9126 if (I->isMoveAssignmentOperator()) {
9127 UserDeclaredMove = I;
9128 break;
9129 }
9130 }
9131 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9131, __PRETTY_FUNCTION__))
;
9132 }
9133
9134 if (UserDeclaredMove) {
9135 Diag(UserDeclaredMove->getLocation(),
9136 diag::note_deleted_copy_user_declared_move)
9137 << (CSM == CXXCopyAssignment) << RD
9138 << UserDeclaredMove->isMoveAssignmentOperator();
9139 return true;
9140 }
9141 }
9142
9143 // Do access control from the special member function
9144 ContextRAII MethodContext(*this, MD);
9145
9146 // C++11 [class.dtor]p5:
9147 // -- for a virtual destructor, lookup of the non-array deallocation function
9148 // results in an ambiguity or in a function that is deleted or inaccessible
9149 if (CSM == CXXDestructor && MD->isVirtual()) {
9150 FunctionDecl *OperatorDelete = nullptr;
9151 DeclarationName Name =
9152 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9153 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9154 OperatorDelete, /*Diagnose*/false)) {
9155 if (Diagnose)
9156 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9157 return true;
9158 }
9159 }
9160
9161 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9162
9163 // Per DR1611, do not consider virtual bases of constructors of abstract
9164 // classes, since we are not going to construct them.
9165 // Per DR1658, do not consider virtual bases of destructors of abstract
9166 // classes either.
9167 // Per DR2180, for assignment operators we only assign (and thus only
9168 // consider) direct bases.
9169 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9170 : SMI.VisitPotentiallyConstructedBases))
9171 return true;
9172
9173 if (SMI.shouldDeleteForAllConstMembers())
9174 return true;
9175
9176 if (getLangOpts().CUDA) {
9177 // We should delete the special member in CUDA mode if target inference
9178 // failed.
9179 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9180 // is treated as certain special member, which may not reflect what special
9181 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9182 // expects CSM to match MD, therefore recalculate CSM.
9183 assert(ICI || CSM == getSpecialMember(MD))((ICI || CSM == getSpecialMember(MD)) ? static_cast<void>
(0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9183, __PRETTY_FUNCTION__))
;
9184 auto RealCSM = CSM;
9185 if (ICI)
9186 RealCSM = getSpecialMember(MD);
9187
9188 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9189 SMI.ConstArg, Diagnose);
9190 }
9191
9192 return false;
9193}
9194
9195void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9196 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9197 assert(DFK && "not a defaultable function")((DFK && "not a defaultable function") ? static_cast<
void> (0) : __assert_fail ("DFK && \"not a defaultable function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9197, __PRETTY_FUNCTION__))
;
9198 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted")((FD->isDefaulted() && FD->isDeleted() &&
"not defaulted and deleted") ? static_cast<void> (0) :
__assert_fail ("FD->isDefaulted() && FD->isDeleted() && \"not defaulted and deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9198, __PRETTY_FUNCTION__))
;
9199
9200 if (DFK.isSpecialMember()) {
9201 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9202 nullptr, /*Diagnose=*/true);
9203 } else {
9204 DefaultedComparisonAnalyzer(
9205 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9206 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9207 .visit();
9208 }
9209}
9210
9211/// Perform lookup for a special member of the specified kind, and determine
9212/// whether it is trivial. If the triviality can be determined without the
9213/// lookup, skip it. This is intended for use when determining whether a
9214/// special member of a containing object is trivial, and thus does not ever
9215/// perform overload resolution for default constructors.
9216///
9217/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9218/// member that was most likely to be intended to be trivial, if any.
9219///
9220/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9221/// determine whether the special member is trivial.
9222static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9223 Sema::CXXSpecialMember CSM, unsigned Quals,
9224 bool ConstRHS,
9225 Sema::TrivialABIHandling TAH,
9226 CXXMethodDecl **Selected) {
9227 if (Selected)
9228 *Selected = nullptr;
9229
9230 switch (CSM) {
9231 case Sema::CXXInvalid:
9232 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9232)
;
9233
9234 case Sema::CXXDefaultConstructor:
9235 // C++11 [class.ctor]p5:
9236 // A default constructor is trivial if:
9237 // - all the [direct subobjects] have trivial default constructors
9238 //
9239 // Note, no overload resolution is performed in this case.
9240 if (RD->hasTrivialDefaultConstructor())
9241 return true;
9242
9243 if (Selected) {
9244 // If there's a default constructor which could have been trivial, dig it
9245 // out. Otherwise, if there's any user-provided default constructor, point
9246 // to that as an example of why there's not a trivial one.
9247 CXXConstructorDecl *DefCtor = nullptr;
9248 if (RD->needsImplicitDefaultConstructor())
9249 S.DeclareImplicitDefaultConstructor(RD);
9250 for (auto *CI : RD->ctors()) {
9251 if (!CI->isDefaultConstructor())
9252 continue;
9253 DefCtor = CI;
9254 if (!DefCtor->isUserProvided())
9255 break;
9256 }
9257
9258 *Selected = DefCtor;
9259 }
9260
9261 return false;
9262
9263 case Sema::CXXDestructor:
9264 // C++11 [class.dtor]p5:
9265 // A destructor is trivial if:
9266 // - all the direct [subobjects] have trivial destructors
9267 if (RD->hasTrivialDestructor() ||
9268 (TAH == Sema::TAH_ConsiderTrivialABI &&
9269 RD->hasTrivialDestructorForCall()))
9270 return true;
9271
9272 if (Selected) {
9273 if (RD->needsImplicitDestructor())
9274 S.DeclareImplicitDestructor(RD);
9275 *Selected = RD->getDestructor();
9276 }
9277
9278 return false;
9279
9280 case Sema::CXXCopyConstructor:
9281 // C++11 [class.copy]p12:
9282 // A copy constructor is trivial if:
9283 // - the constructor selected to copy each direct [subobject] is trivial
9284 if (RD->hasTrivialCopyConstructor() ||
9285 (TAH == Sema::TAH_ConsiderTrivialABI &&
9286 RD->hasTrivialCopyConstructorForCall())) {
9287 if (Quals == Qualifiers::Const)
9288 // We must either select the trivial copy constructor or reach an
9289 // ambiguity; no need to actually perform overload resolution.
9290 return true;
9291 } else if (!Selected) {
9292 return false;
9293 }
9294 // In C++98, we are not supposed to perform overload resolution here, but we
9295 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9296 // cases like B as having a non-trivial copy constructor:
9297 // struct A { template<typename T> A(T&); };
9298 // struct B { mutable A a; };
9299 goto NeedOverloadResolution;
9300
9301 case Sema::CXXCopyAssignment:
9302 // C++11 [class.copy]p25:
9303 // A copy assignment operator is trivial if:
9304 // - the assignment operator selected to copy each direct [subobject] is
9305 // trivial
9306 if (RD->hasTrivialCopyAssignment()) {
9307 if (Quals == Qualifiers::Const)
9308 return true;
9309 } else if (!Selected) {
9310 return false;
9311 }
9312 // In C++98, we are not supposed to perform overload resolution here, but we
9313 // treat that as a language defect.
9314 goto NeedOverloadResolution;
9315
9316 case Sema::CXXMoveConstructor:
9317 case Sema::CXXMoveAssignment:
9318 NeedOverloadResolution:
9319 Sema::SpecialMemberOverloadResult SMOR =
9320 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9321
9322 // The standard doesn't describe how to behave if the lookup is ambiguous.
9323 // We treat it as not making the member non-trivial, just like the standard
9324 // mandates for the default constructor. This should rarely matter, because
9325 // the member will also be deleted.
9326 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9327 return true;
9328
9329 if (!SMOR.getMethod()) {
9330 assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9331, __PRETTY_FUNCTION__))
9331 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9331, __PRETTY_FUNCTION__))
;
9332 return false;
9333 }
9334
9335 // We deliberately don't check if we found a deleted special member. We're
9336 // not supposed to!
9337 if (Selected)
9338 *Selected = SMOR.getMethod();
9339
9340 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9341 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9342 return SMOR.getMethod()->isTrivialForCall();
9343 return SMOR.getMethod()->isTrivial();
9344 }
9345
9346 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9346)
;
9347}
9348
9349static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9350 for (auto *CI : RD->ctors())
9351 if (!CI->isImplicit())
9352 return CI;
9353
9354 // Look for constructor templates.
9355 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9356 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9357 if (CXXConstructorDecl *CD =
9358 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9359 return CD;
9360 }
9361
9362 return nullptr;
9363}
9364
9365/// The kind of subobject we are checking for triviality. The values of this
9366/// enumeration are used in diagnostics.
9367enum TrivialSubobjectKind {
9368 /// The subobject is a base class.
9369 TSK_BaseClass,
9370 /// The subobject is a non-static data member.
9371 TSK_Field,
9372 /// The object is actually the complete object.
9373 TSK_CompleteObject
9374};
9375
9376/// Check whether the special member selected for a given type would be trivial.
9377static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9378 QualType SubType, bool ConstRHS,
9379 Sema::CXXSpecialMember CSM,
9380 TrivialSubobjectKind Kind,
9381 Sema::TrivialABIHandling TAH, bool Diagnose) {
9382 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9383 if (!SubRD)
9384 return true;
9385
9386 CXXMethodDecl *Selected;
9387 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9388 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9389 return true;
9390
9391 if (Diagnose) {
9392 if (ConstRHS)
9393 SubType.addConst();
9394
9395 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9396 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9397 << Kind << SubType.getUnqualifiedType();
9398 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9399 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9400 } else if (!Selected)
9401 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9402 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9403 else if (Selected->isUserProvided()) {
9404 if (Kind == TSK_CompleteObject)
9405 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9406 << Kind << SubType.getUnqualifiedType() << CSM;
9407 else {
9408 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9409 << Kind << SubType.getUnqualifiedType() << CSM;
9410 S.Diag(Selected->getLocation(), diag::note_declared_at);
9411 }
9412 } else {
9413 if (Kind != TSK_CompleteObject)
9414 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9415 << Kind << SubType.getUnqualifiedType() << CSM;
9416
9417 // Explain why the defaulted or deleted special member isn't trivial.
9418 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9419 Diagnose);
9420 }
9421 }
9422
9423 return false;
9424}
9425
9426/// Check whether the members of a class type allow a special member to be
9427/// trivial.
9428static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9429 Sema::CXXSpecialMember CSM,
9430 bool ConstArg,
9431 Sema::TrivialABIHandling TAH,
9432 bool Diagnose) {
9433 for (const auto *FI : RD->fields()) {
9434 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9435 continue;
9436
9437 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9438
9439 // Pretend anonymous struct or union members are members of this class.
9440 if (FI->isAnonymousStructOrUnion()) {
9441 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9442 CSM, ConstArg, TAH, Diagnose))
9443 return false;
9444 continue;
9445 }
9446
9447 // C++11 [class.ctor]p5:
9448 // A default constructor is trivial if [...]
9449 // -- no non-static data member of its class has a
9450 // brace-or-equal-initializer
9451 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9452 if (Diagnose)
9453 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9454 << FI;
9455 return false;
9456 }
9457
9458 // Objective C ARC 4.3.5:
9459 // [...] nontrivally ownership-qualified types are [...] not trivially
9460 // default constructible, copy constructible, move constructible, copy
9461 // assignable, move assignable, or destructible [...]
9462 if (FieldType.hasNonTrivialObjCLifetime()) {
9463 if (Diagnose)
9464 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9465 << RD << FieldType.getObjCLifetime();
9466 return false;
9467 }
9468
9469 bool ConstRHS = ConstArg && !FI->isMutable();
9470 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9471 CSM, TSK_Field, TAH, Diagnose))
9472 return false;
9473 }
9474
9475 return true;
9476}
9477
9478/// Diagnose why the specified class does not have a trivial special member of
9479/// the given kind.
9480void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9481 QualType Ty = Context.getRecordType(RD);
9482
9483 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9484 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9485 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9486 /*Diagnose*/true);
9487}
9488
9489/// Determine whether a defaulted or deleted special member function is trivial,
9490/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9491/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9492bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9493 TrivialABIHandling TAH, bool Diagnose) {
9494 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")((!MD->isUserProvided() && CSM != CXXInvalid &&
"not special enough") ? static_cast<void> (0) : __assert_fail
("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9494, __PRETTY_FUNCTION__))
;
9495
9496 CXXRecordDecl *RD = MD->getParent();
9497
9498 bool ConstArg = false;
9499
9500 // C++11 [class.copy]p12, p25: [DR1593]
9501 // A [special member] is trivial if [...] its parameter-type-list is
9502 // equivalent to the parameter-type-list of an implicit declaration [...]
9503 switch (CSM) {
9504 case CXXDefaultConstructor:
9505 case CXXDestructor:
9506 // Trivial default constructors and destructors cannot have parameters.
9507 break;
9508
9509 case CXXCopyConstructor:
9510 case CXXCopyAssignment: {
9511 // Trivial copy operations always have const, non-volatile parameter types.
9512 ConstArg = true;
9513 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9514 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9515 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9516 if (Diagnose)
9517 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9518 << Param0->getSourceRange() << Param0->getType()
9519 << Context.getLValueReferenceType(
9520 Context.getRecordType(RD).withConst());
9521 return false;
9522 }
9523 break;
9524 }
9525
9526 case CXXMoveConstructor:
9527 case CXXMoveAssignment: {
9528 // Trivial move operations always have non-cv-qualified parameters.
9529 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9530 const RValueReferenceType *RT =
9531 Param0->getType()->getAs<RValueReferenceType>();
9532 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9533 if (Diagnose)
9534 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9535 << Param0->getSourceRange() << Param0->getType()
9536 << Context.getRValueReferenceType(Context.getRecordType(RD));
9537 return false;
9538 }
9539 break;
9540 }
9541
9542 case CXXInvalid:
9543 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9543)
;
9544 }
9545
9546 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9547 if (Diagnose)
9548 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9549 diag::note_nontrivial_default_arg)
9550 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9551 return false;
9552 }
9553 if (MD->isVariadic()) {
9554 if (Diagnose)
9555 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9556 return false;
9557 }
9558
9559 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9560 // A copy/move [constructor or assignment operator] is trivial if
9561 // -- the [member] selected to copy/move each direct base class subobject
9562 // is trivial
9563 //
9564 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9565 // A [default constructor or destructor] is trivial if
9566 // -- all the direct base classes have trivial [default constructors or
9567 // destructors]
9568 for (const auto &BI : RD->bases())
9569 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9570 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9571 return false;
9572
9573 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9574 // A copy/move [constructor or assignment operator] for a class X is
9575 // trivial if
9576 // -- for each non-static data member of X that is of class type (or array
9577 // thereof), the constructor selected to copy/move that member is
9578 // trivial
9579 //
9580 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9581 // A [default constructor or destructor] is trivial if
9582 // -- for all of the non-static data members of its class that are of class
9583 // type (or array thereof), each such class has a trivial [default
9584 // constructor or destructor]
9585 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9586 return false;
9587
9588 // C++11 [class.dtor]p5:
9589 // A destructor is trivial if [...]
9590 // -- the destructor is not virtual
9591 if (CSM == CXXDestructor && MD->isVirtual()) {
9592 if (Diagnose)
9593 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9594 return false;
9595 }
9596
9597 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9598 // A [special member] for class X is trivial if [...]
9599 // -- class X has no virtual functions and no virtual base classes
9600 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9601 if (!Diagnose)
9602 return false;
9603
9604 if (RD->getNumVBases()) {
9605 // Check for virtual bases. We already know that the corresponding
9606 // member in all bases is trivial, so vbases must all be direct.
9607 CXXBaseSpecifier &BS = *RD->vbases_begin();
9608 assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail
("BS.isVirtual()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9608, __PRETTY_FUNCTION__))
;
9609 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9610 return false;
9611 }
9612
9613 // Must have a virtual method.
9614 for (const auto *MI : RD->methods()) {
9615 if (MI->isVirtual()) {
9616 SourceLocation MLoc = MI->getBeginLoc();
9617 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9618 return false;
9619 }
9620 }
9621
9622 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9622)
;
9623 }
9624
9625 // Looks like it's trivial!
9626 return true;
9627}
9628
9629namespace {
9630struct FindHiddenVirtualMethod {
9631 Sema *S;
9632 CXXMethodDecl *Method;
9633 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9634 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9635
9636private:
9637 /// Check whether any most overridden method from MD in Methods
9638 static bool CheckMostOverridenMethods(
9639 const CXXMethodDecl *MD,
9640 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9641 if (MD->size_overridden_methods() == 0)
9642 return Methods.count(MD->getCanonicalDecl());
9643 for (const CXXMethodDecl *O : MD->overridden_methods())
9644 if (CheckMostOverridenMethods(O, Methods))
9645 return true;
9646 return false;
9647 }
9648
9649public:
9650 /// Member lookup function that determines whether a given C++
9651 /// method overloads virtual methods in a base class without overriding any,
9652 /// to be used with CXXRecordDecl::lookupInBases().
9653 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9654 RecordDecl *BaseRecord =
9655 Specifier->getType()->castAs<RecordType>()->getDecl();
9656
9657 DeclarationName Name = Method->getDeclName();
9658 assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast
<void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 9658, __PRETTY_FUNCTION__))
;
9659
9660 bool foundSameNameMethod = false;
9661 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9662 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9663 Path.Decls = Path.Decls.slice(1)) {
9664 NamedDecl *D = Path.Decls.front();
9665 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9666 MD = MD->getCanonicalDecl();
9667 foundSameNameMethod = true;
9668 // Interested only in hidden virtual methods.
9669 if (!MD->isVirtual())
9670 continue;
9671 // If the method we are checking overrides a method from its base
9672 // don't warn about the other overloaded methods. Clang deviates from
9673 // GCC by only diagnosing overloads of inherited virtual functions that
9674 // do not override any other virtual functions in the base. GCC's
9675 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9676 // function from a base class. These cases may be better served by a
9677 // warning (not specific to virtual functions) on call sites when the
9678 // call would select a different function from the base class, were it
9679 // visible.
9680 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9681 if (!S->IsOverload(Method, MD, false))
9682 return true;
9683 // Collect the overload only if its hidden.
9684 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9685 overloadedMethods.push_back(MD);
9686 }
9687 }
9688
9689 if (foundSameNameMethod)
9690 OverloadedMethods.append(overloadedMethods.begin(),
9691 overloadedMethods.end());
9692 return foundSameNameMethod;
9693 }
9694};
9695} // end anonymous namespace
9696
9697/// Add the most overriden methods from MD to Methods
9698static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9699 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9700 if (MD->size_overridden_methods() == 0)
9701 Methods.insert(MD->getCanonicalDecl());
9702 else
9703 for (const CXXMethodDecl *O : MD->overridden_methods())
9704 AddMostOverridenMethods(O, Methods);
9705}
9706
9707/// Check if a method overloads virtual methods in a base class without
9708/// overriding any.
9709void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9710 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9711 if (!MD->getDeclName().isIdentifier())
9712 return;
9713
9714 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9715 /*bool RecordPaths=*/false,
9716 /*bool DetectVirtual=*/false);
9717 FindHiddenVirtualMethod FHVM;
9718 FHVM.Method = MD;
9719 FHVM.S = this;
9720
9721 // Keep the base methods that were overridden or introduced in the subclass
9722 // by 'using' in a set. A base method not in this set is hidden.
9723 CXXRecordDecl *DC = MD->getParent();
9724 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9725 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9726 NamedDecl *ND = *I;
9727 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9728 ND = shad->getTargetDecl();
9729 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9730 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9731 }
9732
9733 if (DC->lookupInBases(FHVM, Paths))
9734 OverloadedMethods = FHVM.OverloadedMethods;
9735}
9736
9737void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9738 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9739 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9740 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9741 PartialDiagnostic PD = PDiag(
9742 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9743 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9744 Diag(overloadedMD->getLocation(), PD);
9745 }
9746}
9747
9748/// Diagnose methods which overload virtual methods in a base class
9749/// without overriding any.
9750void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9751 if (MD->isInvalidDecl())
9752 return;
9753
9754 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9755 return;
9756
9757 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9758 FindHiddenVirtualMethods(MD, OverloadedMethods);
9759 if (!OverloadedMethods.empty()) {
9760 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9761 << MD << (OverloadedMethods.size() > 1);
9762
9763 NoteHiddenVirtualMethods(MD, OverloadedMethods);
9764 }
9765}
9766
9767void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9768 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9769 // No diagnostics if this is a template instantiation.
9770 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9771 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9772 diag::ext_cannot_use_trivial_abi) << &RD;
9773 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9774 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9775 }
9776 RD.dropAttr<TrivialABIAttr>();
9777 };
9778
9779 // Ill-formed if the copy and move constructors are deleted.
9780 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9781 // If the type is dependent, then assume it might have
9782 // implicit copy or move ctor because we won't know yet at this point.
9783 if (RD.isDependentType())
9784 return true;
9785 if (RD.needsImplicitCopyConstructor() &&
9786 !RD.defaultedCopyConstructorIsDeleted())
9787 return true;
9788 if (RD.needsImplicitMoveConstructor() &&
9789 !RD.defaultedMoveConstructorIsDeleted())
9790 return true;
9791 for (const CXXConstructorDecl *CD : RD.ctors())
9792 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9793 return true;
9794 return false;
9795 };
9796
9797 if (!HasNonDeletedCopyOrMoveConstructor()) {
9798 PrintDiagAndRemoveAttr(0);
9799 return;
9800 }
9801
9802 // Ill-formed if the struct has virtual functions.
9803 if (RD.isPolymorphic()) {
9804 PrintDiagAndRemoveAttr(1);
9805 return;
9806 }
9807
9808 for (const auto &B : RD.bases()) {
9809 // Ill-formed if the base class is non-trivial for the purpose of calls or a
9810 // virtual base.
9811 if (!B.getType()->isDependentType() &&
9812 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9813 PrintDiagAndRemoveAttr(2);
9814 return;
9815 }
9816
9817 if (B.isVirtual()) {
9818 PrintDiagAndRemoveAttr(3);
9819 return;
9820 }
9821 }
9822
9823 for (const auto *FD : RD.fields()) {
9824 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9825 // non-trivial for the purpose of calls.
9826 QualType FT = FD->getType();
9827 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9828 PrintDiagAndRemoveAttr(4);
9829 return;
9830 }
9831
9832 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9833 if (!RT->isDependentType() &&
9834 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9835 PrintDiagAndRemoveAttr(5);
9836 return;
9837 }
9838 }
9839}
9840
9841void Sema::ActOnFinishCXXMemberSpecification(
9842 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9843 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9844 if (!TagDecl)
9845 return;
9846
9847 AdjustDeclIfTemplate(TagDecl);
9848
9849 for (const ParsedAttr &AL : AttrList) {
9850 if (AL.getKind() != ParsedAttr::AT_Visibility)
9851 continue;
9852 AL.setInvalid();
9853 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9854 }
9855
9856 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9857 // strict aliasing violation!
9858 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9859 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9860
9861 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9862}
9863
9864/// Find the equality comparison functions that should be implicitly declared
9865/// in a given class definition, per C++2a [class.compare.default]p3.
9866static void findImplicitlyDeclaredEqualityComparisons(
9867 ASTContext &Ctx, CXXRecordDecl *RD,
9868 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9869 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9870 if (!RD->lookup(EqEq).empty())
9871 // Member operator== explicitly declared: no implicit operator==s.
9872 return;
9873
9874 // Traverse friends looking for an '==' or a '<=>'.
9875 for (FriendDecl *Friend : RD->friends()) {
9876 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9877 if (!FD) continue;
9878
9879 if (FD->getOverloadedOperator() == OO_EqualEqual) {
9880 // Friend operator== explicitly declared: no implicit operator==s.
9881 Spaceships.clear();
9882 return;
9883 }
9884
9885 if (FD->getOverloadedOperator() == OO_Spaceship &&
9886 FD->isExplicitlyDefaulted())
9887 Spaceships.push_back(FD);
9888 }
9889
9890 // Look for members named 'operator<=>'.
9891 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9892 for (NamedDecl *ND : RD->lookup(Cmp)) {
9893 // Note that we could find a non-function here (either a function template
9894 // or a using-declaration). Neither case results in an implicit
9895 // 'operator=='.
9896 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9897 if (FD->isExplicitlyDefaulted())
9898 Spaceships.push_back(FD);
9899 }
9900}
9901
9902/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9903/// special functions, such as the default constructor, copy
9904/// constructor, or destructor, to the given C++ class (C++
9905/// [special]p1). This routine can only be executed just before the
9906/// definition of the class is complete.
9907void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9908 // Don't add implicit special members to templated classes.
9909 // FIXME: This means unqualified lookups for 'operator=' within a class
9910 // template don't work properly.
9911 if (!ClassDecl->isDependentType()) {
9912 if (ClassDecl->needsImplicitDefaultConstructor()) {
9913 ++getASTContext().NumImplicitDefaultConstructors;
9914
9915 if (ClassDecl->hasInheritedConstructor())
9916 DeclareImplicitDefaultConstructor(ClassDecl);
9917 }
9918
9919 if (ClassDecl->needsImplicitCopyConstructor()) {
9920 ++getASTContext().NumImplicitCopyConstructors;
9921
9922 // If the properties or semantics of the copy constructor couldn't be
9923 // determined while the class was being declared, force a declaration
9924 // of it now.
9925 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9926 ClassDecl->hasInheritedConstructor())
9927 DeclareImplicitCopyConstructor(ClassDecl);
9928 // For the MS ABI we need to know whether the copy ctor is deleted. A
9929 // prerequisite for deleting the implicit copy ctor is that the class has
9930 // a move ctor or move assignment that is either user-declared or whose
9931 // semantics are inherited from a subobject. FIXME: We should provide a
9932 // more direct way for CodeGen to ask whether the constructor was deleted.
9933 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9934 (ClassDecl->hasUserDeclaredMoveConstructor() ||
9935 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9936 ClassDecl->hasUserDeclaredMoveAssignment() ||
9937 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9938 DeclareImplicitCopyConstructor(ClassDecl);
9939 }
9940
9941 if (getLangOpts().CPlusPlus11 &&
9942 ClassDecl->needsImplicitMoveConstructor()) {
9943 ++getASTContext().NumImplicitMoveConstructors;
9944
9945 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9946 ClassDecl->hasInheritedConstructor())
9947 DeclareImplicitMoveConstructor(ClassDecl);
9948 }
9949
9950 if (ClassDecl->needsImplicitCopyAssignment()) {
9951 ++getASTContext().NumImplicitCopyAssignmentOperators;
9952
9953 // If we have a dynamic class, then the copy assignment operator may be
9954 // virtual, so we have to declare it immediately. This ensures that, e.g.,
9955 // it shows up in the right place in the vtable and that we diagnose
9956 // problems with the implicit exception specification.
9957 if (ClassDecl->isDynamicClass() ||
9958 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9959 ClassDecl->hasInheritedAssignment())
9960 DeclareImplicitCopyAssignment(ClassDecl);
9961 }
9962
9963 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9964 ++getASTContext().NumImplicitMoveAssignmentOperators;
9965
9966 // Likewise for the move assignment operator.
9967 if (ClassDecl->isDynamicClass() ||
9968 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9969 ClassDecl->hasInheritedAssignment())
9970 DeclareImplicitMoveAssignment(ClassDecl);
9971 }
9972
9973 if (ClassDecl->needsImplicitDestructor()) {
9974 ++getASTContext().NumImplicitDestructors;
9975
9976 // If we have a dynamic class, then the destructor may be virtual, so we
9977 // have to declare the destructor immediately. This ensures that, e.g., it
9978 // shows up in the right place in the vtable and that we diagnose problems
9979 // with the implicit exception specification.
9980 if (ClassDecl->isDynamicClass() ||
9981 ClassDecl->needsOverloadResolutionForDestructor())
9982 DeclareImplicitDestructor(ClassDecl);
9983 }
9984 }
9985
9986 // C++2a [class.compare.default]p3:
9987 // If the member-specification does not explicitly declare any member or
9988 // friend named operator==, an == operator function is declared implicitly
9989 // for each defaulted three-way comparison operator function defined in
9990 // the member-specification
9991 // FIXME: Consider doing this lazily.
9992 // We do this during the initial parse for a class template, not during
9993 // instantiation, so that we can handle unqualified lookups for 'operator=='
9994 // when parsing the template.
9995 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9996 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9997 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9998 DefaultedSpaceships);
9999 for (auto *FD : DefaultedSpaceships)
10000 DeclareImplicitEqualityComparison(ClassDecl, FD);
10001 }
10002}
10003
10004unsigned
10005Sema::ActOnReenterTemplateScope(Decl *D,
10006 llvm::function_ref<Scope *()> EnterScope) {
10007 if (!D)
10008 return 0;
10009 AdjustDeclIfTemplate(D);
10010
10011 // In order to get name lookup right, reenter template scopes in order from
10012 // outermost to innermost.
10013 SmallVector<TemplateParameterList *, 4> ParameterLists;
10014 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10015
10016 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10017 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10018 ParameterLists.push_back(DD->getTemplateParameterList(i));
10019
10020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10021 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10022 ParameterLists.push_back(FTD->getTemplateParameters());
10023 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10024 LookupDC = VD->getDeclContext();
10025
10026 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10027 ParameterLists.push_back(VTD->getTemplateParameters());
10028 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10029 ParameterLists.push_back(PSD->getTemplateParameters());
10030 }
10031 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10032 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10033 ParameterLists.push_back(TD->getTemplateParameterList(i));
10034
10035 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10036 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10037 ParameterLists.push_back(CTD->getTemplateParameters());
10038 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10039 ParameterLists.push_back(PSD->getTemplateParameters());
10040 }
10041 }
10042 // FIXME: Alias declarations and concepts.
10043
10044 unsigned Count = 0;
10045 Scope *InnermostTemplateScope = nullptr;
10046 for (TemplateParameterList *Params : ParameterLists) {
10047 // Ignore explicit specializations; they don't contribute to the template
10048 // depth.
10049 if (Params->size() == 0)
10050 continue;
10051
10052 InnermostTemplateScope = EnterScope();
10053 for (NamedDecl *Param : *Params) {
10054 if (Param->getDeclName()) {
10055 InnermostTemplateScope->AddDecl(Param);
10056 IdResolver.AddDecl(Param);
10057 }
10058 }
10059 ++Count;
10060 }
10061
10062 // Associate the new template scopes with the corresponding entities.
10063 if (InnermostTemplateScope) {
10064 assert(LookupDC && "no enclosing DeclContext for template lookup")((LookupDC && "no enclosing DeclContext for template lookup"
) ? static_cast<void> (0) : __assert_fail ("LookupDC && \"no enclosing DeclContext for template lookup\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 10064, __PRETTY_FUNCTION__))
;
10065 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10066 }
10067
10068 return Count;
10069}
10070
10071void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10072 if (!RecordD) return;
10073 AdjustDeclIfTemplate(RecordD);
10074 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10075 PushDeclContext(S, Record);
10076}
10077
10078void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10079 if (!RecordD) return;
10080 PopDeclContext();
10081}
10082
10083/// This is used to implement the constant expression evaluation part of the
10084/// attribute enable_if extension. There is nothing in standard C++ which would
10085/// require reentering parameters.
10086void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10087 if (!Param)
10088 return;
10089
10090 S->AddDecl(Param);
10091 if (Param->getDeclName())
10092 IdResolver.AddDecl(Param);
10093}
10094
10095/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10096/// parsing a top-level (non-nested) C++ class, and we are now
10097/// parsing those parts of the given Method declaration that could
10098/// not be parsed earlier (C++ [class.mem]p2), such as default
10099/// arguments. This action should enter the scope of the given
10100/// Method declaration as if we had just parsed the qualified method
10101/// name. However, it should not bring the parameters into scope;
10102/// that will be performed by ActOnDelayedCXXMethodParameter.
10103void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10104}
10105
10106/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10107/// C++ method declaration. We're (re-)introducing the given
10108/// function parameter into scope for use in parsing later parts of
10109/// the method declaration. For example, we could see an
10110/// ActOnParamDefaultArgument event for this parameter.
10111void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10112 if (!ParamD)
10113 return;
10114
10115 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10116
10117 S->AddDecl(Param);
10118 if (Param->getDeclName())
10119 IdResolver.AddDecl(Param);
10120}
10121
10122/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10123/// processing the delayed method declaration for Method. The method
10124/// declaration is now considered finished. There may be a separate
10125/// ActOnStartOfFunctionDef action later (not necessarily
10126/// immediately!) for this method, if it was also defined inside the
10127/// class body.
10128void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10129 if (!MethodD)
10130 return;
10131
10132 AdjustDeclIfTemplate(MethodD);
10133
10134 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10135
10136 // Now that we have our default arguments, check the constructor
10137 // again. It could produce additional diagnostics or affect whether
10138 // the class has implicitly-declared destructors, among other
10139 // things.
10140 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10141 CheckConstructor(Constructor);
10142
10143 // Check the default arguments, which we may have added.
10144 if (!Method->isInvalidDecl())
10145 CheckCXXDefaultArguments(Method);
10146}
10147
10148// Emit the given diagnostic for each non-address-space qualifier.
10149// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10150static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10151 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10152 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10153 bool DiagOccured = false;
10154 FTI.MethodQualifiers->forEachQualifier(
10155 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10156 SourceLocation SL) {
10157 // This diagnostic should be emitted on any qualifier except an addr
10158 // space qualifier. However, forEachQualifier currently doesn't visit
10159 // addr space qualifiers, so there's no way to write this condition
10160 // right now; we just diagnose on everything.
10161 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10162 DiagOccured = true;
10163 });
10164 if (DiagOccured)
10165 D.setInvalidType();
10166 }
10167}
10168
10169/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10170/// the well-formedness of the constructor declarator @p D with type @p
10171/// R. If there are any errors in the declarator, this routine will
10172/// emit diagnostics and set the invalid bit to true. In any case, the type
10173/// will be updated to reflect a well-formed type for the constructor and
10174/// returned.
10175QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10176 StorageClass &SC) {
10177 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10178
10179 // C++ [class.ctor]p3:
10180 // A constructor shall not be virtual (10.3) or static (9.4). A
10181 // constructor can be invoked for a const, volatile or const
10182 // volatile object. A constructor shall not be declared const,
10183 // volatile, or const volatile (9.3.2).
10184 if (isVirtual) {
10185 if (!D.isInvalidType())
10186 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10187 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10188 << SourceRange(D.getIdentifierLoc());
10189 D.setInvalidType();
10190 }
10191 if (SC == SC_Static) {
10192 if (!D.isInvalidType())
10193 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10194 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10195 << SourceRange(D.getIdentifierLoc());
10196 D.setInvalidType();
10197 SC = SC_None;
10198 }
10199
10200 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10201 diagnoseIgnoredQualifiers(
10202 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10203 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10204 D.getDeclSpec().getRestrictSpecLoc(),
10205 D.getDeclSpec().getAtomicSpecLoc());
10206 D.setInvalidType();
10207 }
10208
10209 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10210
10211 // C++0x [class.ctor]p4:
10212 // A constructor shall not be declared with a ref-qualifier.
10213 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10214 if (FTI.hasRefQualifier()) {
10215 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10216 << FTI.RefQualifierIsLValueRef
10217 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10218 D.setInvalidType();
10219 }
10220
10221 // Rebuild the function type "R" without any type qualifiers (in
10222 // case any of the errors above fired) and with "void" as the
10223 // return type, since constructors don't have return types.
10224 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10225 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10226 return R;
10227
10228 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10229 EPI.TypeQuals = Qualifiers();
10230 EPI.RefQualifier = RQ_None;
10231
10232 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10233}
10234
10235/// CheckConstructor - Checks a fully-formed constructor for
10236/// well-formedness, issuing any diagnostics required. Returns true if
10237/// the constructor declarator is invalid.
10238void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10239 CXXRecordDecl *ClassDecl
10240 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10241 if (!ClassDecl)
10242 return Constructor->setInvalidDecl();
10243
10244 // C++ [class.copy]p3:
10245 // A declaration of a constructor for a class X is ill-formed if
10246 // its first parameter is of type (optionally cv-qualified) X and
10247 // either there are no other parameters or else all other
10248 // parameters have default arguments.
10249 if (!Constructor->isInvalidDecl() &&
10250 Constructor->hasOneParamOrDefaultArgs() &&
10251 Constructor->getTemplateSpecializationKind() !=
10252 TSK_ImplicitInstantiation) {
10253 QualType ParamType = Constructor->getParamDecl(0)->getType();
10254 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10255 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10256 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10257 const char *ConstRef
10258 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10259 : " const &";
10260 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10261 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10262
10263 // FIXME: Rather that making the constructor invalid, we should endeavor
10264 // to fix the type.
10265 Constructor->setInvalidDecl();
10266 }
10267 }
10268}
10269
10270/// CheckDestructor - Checks a fully-formed destructor definition for
10271/// well-formedness, issuing any diagnostics required. Returns true
10272/// on error.
10273bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10274 CXXRecordDecl *RD = Destructor->getParent();
10275
10276 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10277 SourceLocation Loc;
10278
10279 if (!Destructor->isImplicit())
10280 Loc = Destructor->getLocation();
10281 else
10282 Loc = RD->getLocation();
10283
10284 // If we have a virtual destructor, look up the deallocation function
10285 if (FunctionDecl *OperatorDelete =
10286 FindDeallocationFunctionForDestructor(Loc, RD)) {
10287 Expr *ThisArg = nullptr;
10288
10289 // If the notional 'delete this' expression requires a non-trivial
10290 // conversion from 'this' to the type of a destroying operator delete's
10291 // first parameter, perform that conversion now.
10292 if (OperatorDelete->isDestroyingOperatorDelete()) {
10293 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10294 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10295 // C++ [class.dtor]p13:
10296 // ... as if for the expression 'delete this' appearing in a
10297 // non-virtual destructor of the destructor's class.
10298 ContextRAII SwitchContext(*this, Destructor);
10299 ExprResult This =
10300 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10301 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")((!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? static_cast<void> (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 10301, __PRETTY_FUNCTION__))
;
10302 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10303 if (This.isInvalid()) {
10304 // FIXME: Register this as a context note so that it comes out
10305 // in the right order.
10306 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10307 return true;
10308 }
10309 ThisArg = This.get();
10310 }
10311 }
10312
10313 DiagnoseUseOfDecl(OperatorDelete, Loc);
10314 MarkFunctionReferenced(Loc, OperatorDelete);
10315 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10316 }
10317 }
10318
10319 return false;
10320}
10321
10322/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10323/// the well-formednes of the destructor declarator @p D with type @p
10324/// R. If there are any errors in the declarator, this routine will
10325/// emit diagnostics and set the declarator to invalid. Even if this happens,
10326/// will be updated to reflect a well-formed type for the destructor and
10327/// returned.
10328QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10329 StorageClass& SC) {
10330 // C++ [class.dtor]p1:
10331 // [...] A typedef-name that names a class is a class-name
10332 // (7.1.3); however, a typedef-name that names a class shall not
10333 // be used as the identifier in the declarator for a destructor
10334 // declaration.
10335 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10336 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10337 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10338 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10339 else if (const TemplateSpecializationType *TST =
10340 DeclaratorType->getAs<TemplateSpecializationType>())
10341 if (TST->isTypeAlias())
10342 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10343 << DeclaratorType << 1;
10344
10345 // C++ [class.dtor]p2:
10346 // A destructor is used to destroy objects of its class type. A
10347 // destructor takes no parameters, and no return type can be
10348 // specified for it (not even void). The address of a destructor
10349 // shall not be taken. A destructor shall not be static. A
10350 // destructor can be invoked for a const, volatile or const
10351 // volatile object. A destructor shall not be declared const,
10352 // volatile or const volatile (9.3.2).
10353 if (SC == SC_Static) {
10354 if (!D.isInvalidType())
10355 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10356 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10357 << SourceRange(D.getIdentifierLoc())
10358 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10359
10360 SC = SC_None;
10361 }
10362 if (!D.isInvalidType()) {
10363 // Destructors don't have return types, but the parser will
10364 // happily parse something like:
10365 //
10366 // class X {
10367 // float ~X();
10368 // };
10369 //
10370 // The return type will be eliminated later.
10371 if (D.getDeclSpec().hasTypeSpecifier())
10372 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10373 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10374 << SourceRange(D.getIdentifierLoc());
10375 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10376 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10377 SourceLocation(),
10378 D.getDeclSpec().getConstSpecLoc(),
10379 D.getDeclSpec().getVolatileSpecLoc(),
10380 D.getDeclSpec().getRestrictSpecLoc(),
10381 D.getDeclSpec().getAtomicSpecLoc());
10382 D.setInvalidType();
10383 }
10384 }
10385
10386 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10387
10388 // C++0x [class.dtor]p2:
10389 // A destructor shall not be declared with a ref-qualifier.
10390 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10391 if (FTI.hasRefQualifier()) {
10392 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10393 << FTI.RefQualifierIsLValueRef
10394 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10395 D.setInvalidType();
10396 }
10397
10398 // Make sure we don't have any parameters.
10399 if (FTIHasNonVoidParameters(FTI)) {
10400 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10401
10402 // Delete the parameters.
10403 FTI.freeParams();
10404 D.setInvalidType();
10405 }
10406
10407 // Make sure the destructor isn't variadic.
10408 if (FTI.isVariadic) {
10409 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10410 D.setInvalidType();
10411 }
10412
10413 // Rebuild the function type "R" without any type qualifiers or
10414 // parameters (in case any of the errors above fired) and with
10415 // "void" as the return type, since destructors don't have return
10416 // types.
10417 if (!D.isInvalidType())
10418 return R;
10419
10420 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10421 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10422 EPI.Variadic = false;
10423 EPI.TypeQuals = Qualifiers();
10424 EPI.RefQualifier = RQ_None;
10425 return Context.getFunctionType(Context.VoidTy, None, EPI);
10426}
10427
10428static void extendLeft(SourceRange &R, SourceRange Before) {
10429 if (Before.isInvalid())
10430 return;
10431 R.setBegin(Before.getBegin());
10432 if (R.getEnd().isInvalid())
10433 R.setEnd(Before.getEnd());
10434}
10435
10436static void extendRight(SourceRange &R, SourceRange After) {
10437 if (After.isInvalid())
10438 return;
10439 if (R.getBegin().isInvalid())
10440 R.setBegin(After.getBegin());
10441 R.setEnd(After.getEnd());
10442}
10443
10444/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10445/// well-formednes of the conversion function declarator @p D with
10446/// type @p R. If there are any errors in the declarator, this routine
10447/// will emit diagnostics and return true. Otherwise, it will return
10448/// false. Either way, the type @p R will be updated to reflect a
10449/// well-formed type for the conversion operator.
10450void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10451 StorageClass& SC) {
10452 // C++ [class.conv.fct]p1:
10453 // Neither parameter types nor return type can be specified. The
10454 // type of a conversion function (8.3.5) is "function taking no
10455 // parameter returning conversion-type-id."
10456 if (SC == SC_Static) {
10457 if (!D.isInvalidType())
10458 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10459 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10460 << D.getName().getSourceRange();
10461 D.setInvalidType();
10462 SC = SC_None;
10463 }
10464
10465 TypeSourceInfo *ConvTSI = nullptr;
10466 QualType ConvType =
10467 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10468
10469 const DeclSpec &DS = D.getDeclSpec();
10470 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10471 // Conversion functions don't have return types, but the parser will
10472 // happily parse something like:
10473 //
10474 // class X {
10475 // float operator bool();
10476 // };
10477 //
10478 // The return type will be changed later anyway.
10479 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10480 << SourceRange(DS.getTypeSpecTypeLoc())
10481 << SourceRange(D.getIdentifierLoc());
10482 D.setInvalidType();
10483 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10484 // It's also plausible that the user writes type qualifiers in the wrong
10485 // place, such as:
10486 // struct S { const operator int(); };
10487 // FIXME: we could provide a fixit to move the qualifiers onto the
10488 // conversion type.
10489 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10490 << SourceRange(D.getIdentifierLoc()) << 0;
10491 D.setInvalidType();
10492 }
10493
10494 const auto *Proto = R->castAs<FunctionProtoType>();
10495
10496 // Make sure we don't have any parameters.
10497 if (Proto->getNumParams() > 0) {
10498 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10499
10500 // Delete the parameters.
10501 D.getFunctionTypeInfo().freeParams();
10502 D.setInvalidType();
10503 } else if (Proto->isVariadic()) {
10504 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10505 D.setInvalidType();
10506 }
10507
10508 // Diagnose "&operator bool()" and other such nonsense. This
10509 // is actually a gcc extension which we don't support.
10510 if (Proto->getReturnType() != ConvType) {
10511 bool NeedsTypedef = false;
10512 SourceRange Before, After;
10513
10514 // Walk the chunks and extract information on them for our diagnostic.
10515 bool PastFunctionChunk = false;
10516 for (auto &Chunk : D.type_objects()) {
10517 switch (Chunk.Kind) {
10518 case DeclaratorChunk::Function:
10519 if (!PastFunctionChunk) {
10520 if (Chunk.Fun.HasTrailingReturnType) {
10521 TypeSourceInfo *TRT = nullptr;
10522 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10523 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10524 }
10525 PastFunctionChunk = true;
10526 break;
10527 }
10528 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10529 case DeclaratorChunk::Array:
10530 NeedsTypedef = true;
10531 extendRight(After, Chunk.getSourceRange());
10532 break;
10533
10534 case DeclaratorChunk::Pointer:
10535 case DeclaratorChunk::BlockPointer:
10536 case DeclaratorChunk::Reference:
10537 case DeclaratorChunk::MemberPointer:
10538 case DeclaratorChunk::Pipe:
10539 extendLeft(Before, Chunk.getSourceRange());
10540 break;
10541
10542 case DeclaratorChunk::Paren:
10543 extendLeft(Before, Chunk.Loc);
10544 extendRight(After, Chunk.EndLoc);
10545 break;
10546 }
10547 }
10548
10549 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10550 After.isValid() ? After.getBegin() :
10551 D.getIdentifierLoc();
10552 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10553 DB << Before << After;
10554
10555 if (!NeedsTypedef) {
10556 DB << /*don't need a typedef*/0;
10557
10558 // If we can provide a correct fix-it hint, do so.
10559 if (After.isInvalid() && ConvTSI) {
10560 SourceLocation InsertLoc =
10561 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10562 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10563 << FixItHint::CreateInsertionFromRange(
10564 InsertLoc, CharSourceRange::getTokenRange(Before))
10565 << FixItHint::CreateRemoval(Before);
10566 }
10567 } else if (!Proto->getReturnType()->isDependentType()) {
10568 DB << /*typedef*/1 << Proto->getReturnType();
10569 } else if (getLangOpts().CPlusPlus11) {
10570 DB << /*alias template*/2 << Proto->getReturnType();
10571 } else {
10572 DB << /*might not be fixable*/3;
10573 }
10574
10575 // Recover by incorporating the other type chunks into the result type.
10576 // Note, this does *not* change the name of the function. This is compatible
10577 // with the GCC extension:
10578 // struct S { &operator int(); } s;
10579 // int &r = s.operator int(); // ok in GCC
10580 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10581 ConvType = Proto->getReturnType();
10582 }
10583
10584 // C++ [class.conv.fct]p4:
10585 // The conversion-type-id shall not represent a function type nor
10586 // an array type.
10587 if (ConvType->isArrayType()) {
10588 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10589 ConvType = Context.getPointerType(ConvType);
10590 D.setInvalidType();
10591 } else if (ConvType->isFunctionType()) {
10592 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10593 ConvType = Context.getPointerType(ConvType);
10594 D.setInvalidType();
10595 }
10596
10597 // Rebuild the function type "R" without any parameters (in case any
10598 // of the errors above fired) and with the conversion type as the
10599 // return type.
10600 if (D.isInvalidType())
10601 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10602
10603 // C++0x explicit conversion operators.
10604 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10605 Diag(DS.getExplicitSpecLoc(),
10606 getLangOpts().CPlusPlus11
10607 ? diag::warn_cxx98_compat_explicit_conversion_functions
10608 : diag::ext_explicit_conversion_functions)
10609 << SourceRange(DS.getExplicitSpecRange());
10610}
10611
10612/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10613/// the declaration of the given C++ conversion function. This routine
10614/// is responsible for recording the conversion function in the C++
10615/// class, if possible.
10616Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10617 assert(Conversion && "Expected to receive a conversion function declaration")((Conversion && "Expected to receive a conversion function declaration"
) ? static_cast<void> (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 10617, __PRETTY_FUNCTION__))
;
10618
10619 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10620
10621 // Make sure we aren't redeclaring the conversion function.
10622 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10623 // C++ [class.conv.fct]p1:
10624 // [...] A conversion function is never used to convert a
10625 // (possibly cv-qualified) object to the (possibly cv-qualified)
10626 // same object type (or a reference to it), to a (possibly
10627 // cv-qualified) base class of that type (or a reference to it),
10628 // or to (possibly cv-qualified) void.
10629 QualType ClassType
10630 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10631 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10632 ConvType = ConvTypeRef->getPointeeType();
10633 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10634 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10635 /* Suppress diagnostics for instantiations. */;
10636 else if (Conversion->size_overridden_methods() != 0)
10637 /* Suppress diagnostics for overriding virtual function in a base class. */;
10638 else if (ConvType->isRecordType()) {
10639 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10640 if (ConvType == ClassType)
10641 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10642 << ClassType;
10643 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10644 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10645 << ClassType << ConvType;
10646 } else if (ConvType->isVoidType()) {
10647 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10648 << ClassType << ConvType;
10649 }
10650
10651 if (FunctionTemplateDecl *ConversionTemplate
10652 = Conversion->getDescribedFunctionTemplate())
10653 return ConversionTemplate;
10654
10655 return Conversion;
10656}
10657
10658namespace {
10659/// Utility class to accumulate and print a diagnostic listing the invalid
10660/// specifier(s) on a declaration.
10661struct BadSpecifierDiagnoser {
10662 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10663 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10664 ~BadSpecifierDiagnoser() {
10665 Diagnostic << Specifiers;
10666 }
10667
10668 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10669 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10670 }
10671 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10672 return check(SpecLoc,
10673 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10674 }
10675 void check(SourceLocation SpecLoc, const char *Spec) {
10676 if (SpecLoc.isInvalid()) return;
10677 Diagnostic << SourceRange(SpecLoc, SpecLoc);
10678 if (!Specifiers.empty()) Specifiers += " ";
10679 Specifiers += Spec;
10680 }
10681
10682 Sema &S;
10683 Sema::SemaDiagnosticBuilder Diagnostic;
10684 std::string Specifiers;
10685};
10686}
10687
10688/// Check the validity of a declarator that we parsed for a deduction-guide.
10689/// These aren't actually declarators in the grammar, so we need to check that
10690/// the user didn't specify any pieces that are not part of the deduction-guide
10691/// grammar.
10692void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10693 StorageClass &SC) {
10694 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10695 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10696 assert(GuidedTemplateDecl && "missing template decl for deduction guide")((GuidedTemplateDecl && "missing template decl for deduction guide"
) ? static_cast<void> (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 10696, __PRETTY_FUNCTION__))
;
10697
10698 // C++ [temp.deduct.guide]p3:
10699 // A deduction-gide shall be declared in the same scope as the
10700 // corresponding class template.
10701 if (!CurContext->getRedeclContext()->Equals(
10702 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10703 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10704 << GuidedTemplateDecl;
10705 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10706 }
10707
10708 auto &DS = D.getMutableDeclSpec();
10709 // We leave 'friend' and 'virtual' to be rejected in the normal way.
10710 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10711 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10712 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10713 BadSpecifierDiagnoser Diagnoser(
10714 *this, D.getIdentifierLoc(),
10715 diag::err_deduction_guide_invalid_specifier);
10716
10717 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10718 DS.ClearStorageClassSpecs();
10719 SC = SC_None;
10720
10721 // 'explicit' is permitted.
10722 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10723 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10724 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10725 DS.ClearConstexprSpec();
10726
10727 Diagnoser.check(DS.getConstSpecLoc(), "const");
10728 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10729 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10730 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10731 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10732 DS.ClearTypeQualifiers();
10733
10734 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10735 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10736 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10737 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10738 DS.ClearTypeSpecType();
10739 }
10740
10741 if (D.isInvalidType())
10742 return;
10743
10744 // Check the declarator is simple enough.
10745 bool FoundFunction = false;
10746 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10747 if (Chunk.Kind == DeclaratorChunk::Paren)
10748 continue;
10749 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10750 Diag(D.getDeclSpec().getBeginLoc(),
10751 diag::err_deduction_guide_with_complex_decl)
10752 << D.getSourceRange();
10753 break;
10754 }
10755 if (!Chunk.Fun.hasTrailingReturnType()) {
10756 Diag(D.getName().getBeginLoc(),
10757 diag::err_deduction_guide_no_trailing_return_type);
10758 break;
10759 }
10760
10761 // Check that the return type is written as a specialization of
10762 // the template specified as the deduction-guide's name.
10763 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10764 TypeSourceInfo *TSI = nullptr;
10765 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10766 assert(TSI && "deduction guide has valid type but invalid return type?")((TSI && "deduction guide has valid type but invalid return type?"
) ? static_cast<void> (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 10766, __PRETTY_FUNCTION__))
;
10767 bool AcceptableReturnType = false;
10768 bool MightInstantiateToSpecialization = false;
10769 if (auto RetTST =
10770 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10771 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10772 bool TemplateMatches =
10773 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10774 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10775 AcceptableReturnType = true;
10776 else {
10777 // This could still instantiate to the right type, unless we know it
10778 // names the wrong class template.
10779 auto *TD = SpecifiedName.getAsTemplateDecl();
10780 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10781 !TemplateMatches);
10782 }
10783 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10784 MightInstantiateToSpecialization = true;
10785 }
10786
10787 if (!AcceptableReturnType) {
10788 Diag(TSI->getTypeLoc().getBeginLoc(),
10789 diag::err_deduction_guide_bad_trailing_return_type)
10790 << GuidedTemplate << TSI->getType()
10791 << MightInstantiateToSpecialization
10792 << TSI->getTypeLoc().getSourceRange();
10793 }
10794
10795 // Keep going to check that we don't have any inner declarator pieces (we
10796 // could still have a function returning a pointer to a function).
10797 FoundFunction = true;
10798 }
10799
10800 if (D.isFunctionDefinition())
10801 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10802}
10803
10804//===----------------------------------------------------------------------===//
10805// Namespace Handling
10806//===----------------------------------------------------------------------===//
10807
10808/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10809/// reopened.
10810static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10811 SourceLocation Loc,
10812 IdentifierInfo *II, bool *IsInline,
10813 NamespaceDecl *PrevNS) {
10814 assert(*IsInline != PrevNS->isInline())((*IsInline != PrevNS->isInline()) ? static_cast<void>
(0) : __assert_fail ("*IsInline != PrevNS->isInline()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 10814, __PRETTY_FUNCTION__))
;
10815
10816 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10817 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10818 // inline namespaces, with the intention of bringing names into namespace std.
10819 //
10820 // We support this just well enough to get that case working; this is not
10821 // sufficient to support reopening namespaces as inline in general.
10822 if (*IsInline && II && II->getName().startswith("__atomic") &&
10823 S.getSourceManager().isInSystemHeader(Loc)) {
10824 // Mark all prior declarations of the namespace as inline.
10825 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10826 NS = NS->getPreviousDecl())
10827 NS->setInline(*IsInline);
10828 // Patch up the lookup table for the containing namespace. This isn't really
10829 // correct, but it's good enough for this particular case.
10830 for (auto *I : PrevNS->decls())
10831 if (auto *ND = dyn_cast<NamedDecl>(I))
10832 PrevNS->getParent()->makeDeclVisibleInContext(ND);
10833 return;
10834 }
10835
10836 if (PrevNS->isInline())
10837 // The user probably just forgot the 'inline', so suggest that it
10838 // be added back.
10839 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10840 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10841 else
10842 S.Diag(Loc, diag::err_inline_namespace_mismatch);
10843
10844 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10845 *IsInline = PrevNS->isInline();
10846}
10847
10848/// ActOnStartNamespaceDef - This is called at the start of a namespace
10849/// definition.
10850Decl *Sema::ActOnStartNamespaceDef(
10851 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10852 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10853 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10854 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10855 // For anonymous namespace, take the location of the left brace.
10856 SourceLocation Loc = II ? IdentLoc : LBrace;
10857 bool IsInline = InlineLoc.isValid();
10858 bool IsInvalid = false;
10859 bool IsStd = false;
10860 bool AddToKnown = false;
10861 Scope *DeclRegionScope = NamespcScope->getParent();
10862
10863 NamespaceDecl *PrevNS = nullptr;
10864 if (II) {
10865 // C++ [namespace.def]p2:
10866 // The identifier in an original-namespace-definition shall not
10867 // have been previously defined in the declarative region in
10868 // which the original-namespace-definition appears. The
10869 // identifier in an original-namespace-definition is the name of
10870 // the namespace. Subsequently in that declarative region, it is
10871 // treated as an original-namespace-name.
10872 //
10873 // Since namespace names are unique in their scope, and we don't
10874 // look through using directives, just look for any ordinary names
10875 // as if by qualified name lookup.
10876 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10877 ForExternalRedeclaration);
10878 LookupQualifiedName(R, CurContext->getRedeclContext());
10879 NamedDecl *PrevDecl =
10880 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10881 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10882
10883 if (PrevNS) {
10884 // This is an extended namespace definition.
10885 if (IsInline != PrevNS->isInline())
10886 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10887 &IsInline, PrevNS);
10888 } else if (PrevDecl) {
10889 // This is an invalid name redefinition.
10890 Diag(Loc, diag::err_redefinition_different_kind)
10891 << II;
10892 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10893 IsInvalid = true;
10894 // Continue on to push Namespc as current DeclContext and return it.
10895 } else if (II->isStr("std") &&
10896 CurContext->getRedeclContext()->isTranslationUnit()) {
10897 // This is the first "real" definition of the namespace "std", so update
10898 // our cache of the "std" namespace to point at this definition.
10899 PrevNS = getStdNamespace();
10900 IsStd = true;
10901 AddToKnown = !IsInline;
10902 } else {
10903 // We've seen this namespace for the first time.
10904 AddToKnown = !IsInline;
10905 }
10906 } else {
10907 // Anonymous namespaces.
10908
10909 // Determine whether the parent already has an anonymous namespace.
10910 DeclContext *Parent = CurContext->getRedeclContext();
10911 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10912 PrevNS = TU->getAnonymousNamespace();
10913 } else {
10914 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10915 PrevNS = ND->getAnonymousNamespace();
10916 }
10917
10918 if (PrevNS && IsInline != PrevNS->isInline())
10919 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10920 &IsInline, PrevNS);
10921 }
10922
10923 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10924 StartLoc, Loc, II, PrevNS);
10925 if (IsInvalid)
10926 Namespc->setInvalidDecl();
10927
10928 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10929 AddPragmaAttributes(DeclRegionScope, Namespc);
10930
10931 // FIXME: Should we be merging attributes?
10932 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10933 PushNamespaceVisibilityAttr(Attr, Loc);
10934
10935 if (IsStd)
10936 StdNamespace = Namespc;
10937 if (AddToKnown)
10938 KnownNamespaces[Namespc] = false;
10939
10940 if (II) {
10941 PushOnScopeChains(Namespc, DeclRegionScope);
10942 } else {
10943 // Link the anonymous namespace into its parent.
10944 DeclContext *Parent = CurContext->getRedeclContext();
10945 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10946 TU->setAnonymousNamespace(Namespc);
10947 } else {
10948 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10949 }
10950
10951 CurContext->addDecl(Namespc);
10952
10953 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
10954 // behaves as if it were replaced by
10955 // namespace unique { /* empty body */ }
10956 // using namespace unique;
10957 // namespace unique { namespace-body }
10958 // where all occurrences of 'unique' in a translation unit are
10959 // replaced by the same identifier and this identifier differs
10960 // from all other identifiers in the entire program.
10961
10962 // We just create the namespace with an empty name and then add an
10963 // implicit using declaration, just like the standard suggests.
10964 //
10965 // CodeGen enforces the "universally unique" aspect by giving all
10966 // declarations semantically contained within an anonymous
10967 // namespace internal linkage.
10968
10969 if (!PrevNS) {
10970 UD = UsingDirectiveDecl::Create(Context, Parent,
10971 /* 'using' */ LBrace,
10972 /* 'namespace' */ SourceLocation(),
10973 /* qualifier */ NestedNameSpecifierLoc(),
10974 /* identifier */ SourceLocation(),
10975 Namespc,
10976 /* Ancestor */ Parent);
10977 UD->setImplicit();
10978 Parent->addDecl(UD);
10979 }
10980 }
10981
10982 ActOnDocumentableDecl(Namespc);
10983
10984 // Although we could have an invalid decl (i.e. the namespace name is a
10985 // redefinition), push it as current DeclContext and try to continue parsing.
10986 // FIXME: We should be able to push Namespc here, so that the each DeclContext
10987 // for the namespace has the declarations that showed up in that particular
10988 // namespace definition.
10989 PushDeclContext(NamespcScope, Namespc);
10990 return Namespc;
10991}
10992
10993/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10994/// is a namespace alias, returns the namespace it points to.
10995static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10996 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10997 return AD->getNamespace();
10998 return dyn_cast_or_null<NamespaceDecl>(D);
10999}
11000
11001/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11002/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11003void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11004 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11005 assert(Namespc && "Invalid parameter, expected NamespaceDecl")((Namespc && "Invalid parameter, expected NamespaceDecl"
) ? static_cast<void> (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11005, __PRETTY_FUNCTION__))
;
11006 Namespc->setRBraceLoc(RBrace);
11007 PopDeclContext();
11008 if (Namespc->hasAttr<VisibilityAttr>())
11009 PopPragmaVisibility(true, RBrace);
11010 // If this namespace contains an export-declaration, export it now.
11011 if (DeferredExportedNamespaces.erase(Namespc))
11012 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11013}
11014
11015CXXRecordDecl *Sema::getStdBadAlloc() const {
11016 return cast_or_null<CXXRecordDecl>(
11017 StdBadAlloc.get(Context.getExternalSource()));
11018}
11019
11020EnumDecl *Sema::getStdAlignValT() const {
11021 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11022}
11023
11024NamespaceDecl *Sema::getStdNamespace() const {
11025 return cast_or_null<NamespaceDecl>(
11026 StdNamespace.get(Context.getExternalSource()));
11027}
11028
11029NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11030 if (!StdExperimentalNamespaceCache) {
11031 if (auto Std = getStdNamespace()) {
11032 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11033 SourceLocation(), LookupNamespaceName);
11034 if (!LookupQualifiedName(Result, Std) ||
11035 !(StdExperimentalNamespaceCache =
11036 Result.getAsSingle<NamespaceDecl>()))
11037 Result.suppressDiagnostics();
11038 }
11039 }
11040 return StdExperimentalNamespaceCache;
11041}
11042
11043namespace {
11044
11045enum UnsupportedSTLSelect {
11046 USS_InvalidMember,
11047 USS_MissingMember,
11048 USS_NonTrivial,
11049 USS_Other
11050};
11051
11052struct InvalidSTLDiagnoser {
11053 Sema &S;
11054 SourceLocation Loc;
11055 QualType TyForDiags;
11056
11057 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11058 const VarDecl *VD = nullptr) {
11059 {
11060 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11061 << TyForDiags << ((int)Sel);
11062 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11063 assert(!Name.empty())((!Name.empty()) ? static_cast<void> (0) : __assert_fail
("!Name.empty()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11063, __PRETTY_FUNCTION__))
;
11064 D << Name;
11065 }
11066 }
11067 if (Sel == USS_InvalidMember) {
11068 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11069 << VD << VD->getSourceRange();
11070 }
11071 return QualType();
11072 }
11073};
11074} // namespace
11075
11076QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11077 SourceLocation Loc,
11078 ComparisonCategoryUsage Usage) {
11079 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11080, __PRETTY_FUNCTION__))
11080 "Looking for comparison category type outside of C++.")((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11080, __PRETTY_FUNCTION__))
;
11081
11082 // Use an elaborated type for diagnostics which has a name containing the
11083 // prepended 'std' namespace but not any inline namespace names.
11084 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11085 auto *NNS =
11086 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11087 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11088 };
11089
11090 // Check if we've already successfully checked the comparison category type
11091 // before. If so, skip checking it again.
11092 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11093 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11094 // The only thing we need to check is that the type has a reachable
11095 // definition in the current context.
11096 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11097 return QualType();
11098
11099 return Info->getType();
11100 }
11101
11102 // If lookup failed
11103 if (!Info) {
11104 std::string NameForDiags = "std::";
11105 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11106 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11107 << NameForDiags << (int)Usage;
11108 return QualType();
11109 }
11110
11111 assert(Info->Kind == Kind)((Info->Kind == Kind) ? static_cast<void> (0) : __assert_fail
("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11111, __PRETTY_FUNCTION__))
;
11112 assert(Info->Record)((Info->Record) ? static_cast<void> (0) : __assert_fail
("Info->Record", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11112, __PRETTY_FUNCTION__))
;
11113
11114 // Update the Record decl in case we encountered a forward declaration on our
11115 // first pass. FIXME: This is a bit of a hack.
11116 if (Info->Record->hasDefinition())
11117 Info->Record = Info->Record->getDefinition();
11118
11119 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11120 return QualType();
11121
11122 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11123
11124 if (!Info->Record->isTriviallyCopyable())
11125 return UnsupportedSTLError(USS_NonTrivial);
11126
11127 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11128 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11129 // Tolerate empty base classes.
11130 if (Base->isEmpty())
11131 continue;
11132 // Reject STL implementations which have at least one non-empty base.
11133 return UnsupportedSTLError();
11134 }
11135
11136 // Check that the STL has implemented the types using a single integer field.
11137 // This expectation allows better codegen for builtin operators. We require:
11138 // (1) The class has exactly one field.
11139 // (2) The field is an integral or enumeration type.
11140 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11141 if (std::distance(FIt, FEnd) != 1 ||
11142 !FIt->getType()->isIntegralOrEnumerationType()) {
11143 return UnsupportedSTLError();
11144 }
11145
11146 // Build each of the require values and store them in Info.
11147 for (ComparisonCategoryResult CCR :
11148 ComparisonCategories::getPossibleResultsForType(Kind)) {
11149 StringRef MemName = ComparisonCategories::getResultString(CCR);
11150 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11151
11152 if (!ValInfo)
11153 return UnsupportedSTLError(USS_MissingMember, MemName);
11154
11155 VarDecl *VD = ValInfo->VD;
11156 assert(VD && "should not be null!")((VD && "should not be null!") ? static_cast<void>
(0) : __assert_fail ("VD && \"should not be null!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11156, __PRETTY_FUNCTION__))
;
11157
11158 // Attempt to diagnose reasons why the STL definition of this type
11159 // might be foobar, including it failing to be a constant expression.
11160 // TODO Handle more ways the lookup or result can be invalid.
11161 if (!VD->isStaticDataMember() ||
11162 !VD->isUsableInConstantExpressions(Context))
11163 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11164
11165 // Attempt to evaluate the var decl as a constant expression and extract
11166 // the value of its first field as a ICE. If this fails, the STL
11167 // implementation is not supported.
11168 if (!ValInfo->hasValidIntValue())
11169 return UnsupportedSTLError();
11170
11171 MarkVariableReferenced(Loc, VD);
11172 }
11173
11174 // We've successfully built the required types and expressions. Update
11175 // the cache and return the newly cached value.
11176 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11177 return Info->getType();
11178}
11179
11180/// Retrieve the special "std" namespace, which may require us to
11181/// implicitly define the namespace.
11182NamespaceDecl *Sema::getOrCreateStdNamespace() {
11183 if (!StdNamespace) {
11184 // The "std" namespace has not yet been defined, so build one implicitly.
11185 StdNamespace = NamespaceDecl::Create(Context,
11186 Context.getTranslationUnitDecl(),
11187 /*Inline=*/false,
11188 SourceLocation(), SourceLocation(),
11189 &PP.getIdentifierTable().get("std"),
11190 /*PrevDecl=*/nullptr);
11191 getStdNamespace()->setImplicit(true);
11192 }
11193
11194 return getStdNamespace();
11195}
11196
11197bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11198 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11199, __PRETTY_FUNCTION__))
11199 "Looking for std::initializer_list outside of C++.")((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11199, __PRETTY_FUNCTION__))
;
11200
11201 // We're looking for implicit instantiations of
11202 // template <typename E> class std::initializer_list.
11203
11204 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11205 return false;
11206
11207 ClassTemplateDecl *Template = nullptr;
11208 const TemplateArgument *Arguments = nullptr;
11209
11210 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11211
11212 ClassTemplateSpecializationDecl *Specialization =
11213 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11214 if (!Specialization)
11215 return false;
11216
11217 Template = Specialization->getSpecializedTemplate();
11218 Arguments = Specialization->getTemplateArgs().data();
11219 } else if (const TemplateSpecializationType *TST =
11220 Ty->getAs<TemplateSpecializationType>()) {
11221 Template = dyn_cast_or_null<ClassTemplateDecl>(
11222 TST->getTemplateName().getAsTemplateDecl());
11223 Arguments = TST->getArgs();
11224 }
11225 if (!Template)
11226 return false;
11227
11228 if (!StdInitializerList) {
11229 // Haven't recognized std::initializer_list yet, maybe this is it.
11230 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11231 if (TemplateClass->getIdentifier() !=
11232 &PP.getIdentifierTable().get("initializer_list") ||
11233 !getStdNamespace()->InEnclosingNamespaceSetOf(
11234 TemplateClass->getDeclContext()))
11235 return false;
11236 // This is a template called std::initializer_list, but is it the right
11237 // template?
11238 TemplateParameterList *Params = Template->getTemplateParameters();
11239 if (Params->getMinRequiredArguments() != 1)
11240 return false;
11241 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11242 return false;
11243
11244 // It's the right template.
11245 StdInitializerList = Template;
11246 }
11247
11248 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11249 return false;
11250
11251 // This is an instance of std::initializer_list. Find the argument type.
11252 if (Element)
11253 *Element = Arguments[0].getAsType();
11254 return true;
11255}
11256
11257static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11258 NamespaceDecl *Std = S.getStdNamespace();
11259 if (!Std) {
11260 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11261 return nullptr;
11262 }
11263
11264 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11265 Loc, Sema::LookupOrdinaryName);
11266 if (!S.LookupQualifiedName(Result, Std)) {
11267 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11268 return nullptr;
11269 }
11270 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11271 if (!Template) {
11272 Result.suppressDiagnostics();
11273 // We found something weird. Complain about the first thing we found.
11274 NamedDecl *Found = *Result.begin();
11275 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11276 return nullptr;
11277 }
11278
11279 // We found some template called std::initializer_list. Now verify that it's
11280 // correct.
11281 TemplateParameterList *Params = Template->getTemplateParameters();
11282 if (Params->getMinRequiredArguments() != 1 ||
11283 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11284 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11285 return nullptr;
11286 }
11287
11288 return Template;
11289}
11290
11291QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11292 if (!StdInitializerList) {
11293 StdInitializerList = LookupStdInitializerList(*this, Loc);
11294 if (!StdInitializerList)
11295 return QualType();
11296 }
11297
11298 TemplateArgumentListInfo Args(Loc, Loc);
11299 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11300 Context.getTrivialTypeSourceInfo(Element,
11301 Loc)));
11302 return Context.getCanonicalType(
11303 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11304}
11305
11306bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11307 // C++ [dcl.init.list]p2:
11308 // A constructor is an initializer-list constructor if its first parameter
11309 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11310 // std::initializer_list<E> for some type E, and either there are no other
11311 // parameters or else all other parameters have default arguments.
11312 if (!Ctor->hasOneParamOrDefaultArgs())
11313 return false;
11314
11315 QualType ArgType = Ctor->getParamDecl(0)->getType();
11316 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11317 ArgType = RT->getPointeeType().getUnqualifiedType();
11318
11319 return isStdInitializerList(ArgType, nullptr);
11320}
11321
11322/// Determine whether a using statement is in a context where it will be
11323/// apply in all contexts.
11324static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11325 switch (CurContext->getDeclKind()) {
11326 case Decl::TranslationUnit:
11327 return true;
11328 case Decl::LinkageSpec:
11329 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11330 default:
11331 return false;
11332 }
11333}
11334
11335namespace {
11336
11337// Callback to only accept typo corrections that are namespaces.
11338class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11339public:
11340 bool ValidateCandidate(const TypoCorrection &candidate) override {
11341 if (NamedDecl *ND = candidate.getCorrectionDecl())
11342 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11343 return false;
11344 }
11345
11346 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11347 return std::make_unique<NamespaceValidatorCCC>(*this);
11348 }
11349};
11350
11351}
11352
11353static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11354 CXXScopeSpec &SS,
11355 SourceLocation IdentLoc,
11356 IdentifierInfo *Ident) {
11357 R.clear();
11358 NamespaceValidatorCCC CCC{};
11359 if (TypoCorrection Corrected =
11360 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11361 Sema::CTK_ErrorRecovery)) {
11362 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11363 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11364 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11365 Ident->getName().equals(CorrectedStr);
11366 S.diagnoseTypo(Corrected,
11367 S.PDiag(diag::err_using_directive_member_suggest)
11368 << Ident << DC << DroppedSpecifier << SS.getRange(),
11369 S.PDiag(diag::note_namespace_defined_here));
11370 } else {
11371 S.diagnoseTypo(Corrected,
11372 S.PDiag(diag::err_using_directive_suggest) << Ident,
11373 S.PDiag(diag::note_namespace_defined_here));
11374 }
11375 R.addDecl(Corrected.getFoundDecl());
11376 return true;
11377 }
11378 return false;
11379}
11380
11381Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11382 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11383 SourceLocation IdentLoc,
11384 IdentifierInfo *NamespcName,
11385 const ParsedAttributesView &AttrList) {
11386 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast
<void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11386, __PRETTY_FUNCTION__))
;
11387 assert(NamespcName && "Invalid NamespcName.")((NamespcName && "Invalid NamespcName.") ? static_cast
<void> (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11387, __PRETTY_FUNCTION__))
;
11388 assert(IdentLoc.isValid() && "Invalid NamespceName location.")((IdentLoc.isValid() && "Invalid NamespceName location."
) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11388, __PRETTY_FUNCTION__))
;
11389
11390 // This can only happen along a recovery path.
11391 while (S->isTemplateParamScope())
11392 S = S->getParent();
11393 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope."
) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11393, __PRETTY_FUNCTION__))
;
11394
11395 UsingDirectiveDecl *UDir = nullptr;
11396 NestedNameSpecifier *Qualifier = nullptr;
11397 if (SS.isSet())
11398 Qualifier = SS.getScopeRep();
11399
11400 // Lookup namespace name.
11401 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11402 LookupParsedName(R, S, &SS);
11403 if (R.isAmbiguous())
11404 return nullptr;
11405
11406 if (R.empty()) {
11407 R.clear();
11408 // Allow "using namespace std;" or "using namespace ::std;" even if
11409 // "std" hasn't been defined yet, for GCC compatibility.
11410 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11411 NamespcName->isStr("std")) {
11412 Diag(IdentLoc, diag::ext_using_undefined_std);
11413 R.addDecl(getOrCreateStdNamespace());
11414 R.resolveKind();
11415 }
11416 // Otherwise, attempt typo correction.
11417 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11418 }
11419
11420 if (!R.empty()) {
11421 NamedDecl *Named = R.getRepresentativeDecl();
11422 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11423 assert(NS && "expected namespace decl")((NS && "expected namespace decl") ? static_cast<void
> (0) : __assert_fail ("NS && \"expected namespace decl\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11423, __PRETTY_FUNCTION__))
;
11424
11425 // The use of a nested name specifier may trigger deprecation warnings.
11426 DiagnoseUseOfDecl(Named, IdentLoc);
11427
11428 // C++ [namespace.udir]p1:
11429 // A using-directive specifies that the names in the nominated
11430 // namespace can be used in the scope in which the
11431 // using-directive appears after the using-directive. During
11432 // unqualified name lookup (3.4.1), the names appear as if they
11433 // were declared in the nearest enclosing namespace which
11434 // contains both the using-directive and the nominated
11435 // namespace. [Note: in this context, "contains" means "contains
11436 // directly or indirectly". ]
11437
11438 // Find enclosing context containing both using-directive and
11439 // nominated namespace.
11440 DeclContext *CommonAncestor = NS;
11441 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11442 CommonAncestor = CommonAncestor->getParent();
11443
11444 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11445 SS.getWithLocInContext(Context),
11446 IdentLoc, Named, CommonAncestor);
11447
11448 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11449 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11450 Diag(IdentLoc, diag::warn_using_directive_in_header);
11451 }
11452
11453 PushUsingDirective(S, UDir);
11454 } else {
11455 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11456 }
11457
11458 if (UDir)
11459 ProcessDeclAttributeList(S, UDir, AttrList);
11460
11461 return UDir;
11462}
11463
11464void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11465 // If the scope has an associated entity and the using directive is at
11466 // namespace or translation unit scope, add the UsingDirectiveDecl into
11467 // its lookup structure so qualified name lookup can find it.
11468 DeclContext *Ctx = S->getEntity();
11469 if (Ctx && !Ctx->isFunctionOrMethod())
11470 Ctx->addDecl(UDir);
11471 else
11472 // Otherwise, it is at block scope. The using-directives will affect lookup
11473 // only to the end of the scope.
11474 S->PushUsingDirective(UDir);
11475}
11476
11477Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11478 SourceLocation UsingLoc,
11479 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11480 UnqualifiedId &Name,
11481 SourceLocation EllipsisLoc,
11482 const ParsedAttributesView &AttrList) {
11483 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope."
) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11483, __PRETTY_FUNCTION__))
;
11484
11485 if (SS.isEmpty()) {
11486 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11487 return nullptr;
11488 }
11489
11490 switch (Name.getKind()) {
11491 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11492 case UnqualifiedIdKind::IK_Identifier:
11493 case UnqualifiedIdKind::IK_OperatorFunctionId:
11494 case UnqualifiedIdKind::IK_LiteralOperatorId:
11495 case UnqualifiedIdKind::IK_ConversionFunctionId:
11496 break;
11497
11498 case UnqualifiedIdKind::IK_ConstructorName:
11499 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11500 // C++11 inheriting constructors.
11501 Diag(Name.getBeginLoc(),
11502 getLangOpts().CPlusPlus11
11503 ? diag::warn_cxx98_compat_using_decl_constructor
11504 : diag::err_using_decl_constructor)
11505 << SS.getRange();
11506
11507 if (getLangOpts().CPlusPlus11) break;
11508
11509 return nullptr;
11510
11511 case UnqualifiedIdKind::IK_DestructorName:
11512 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11513 return nullptr;
11514
11515 case UnqualifiedIdKind::IK_TemplateId:
11516 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11517 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11518 return nullptr;
11519
11520 case UnqualifiedIdKind::IK_DeductionGuideName:
11521 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11521)
;
11522 }
11523
11524 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11525 DeclarationName TargetName = TargetNameInfo.getName();
11526 if (!TargetName)
11527 return nullptr;
11528
11529 // Warn about access declarations.
11530 if (UsingLoc.isInvalid()) {
11531 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11532 ? diag::err_access_decl
11533 : diag::warn_access_decl_deprecated)
11534 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11535 }
11536
11537 if (EllipsisLoc.isInvalid()) {
11538 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11539 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11540 return nullptr;
11541 } else {
11542 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11543 !TargetNameInfo.containsUnexpandedParameterPack()) {
11544 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11545 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11546 EllipsisLoc = SourceLocation();
11547 }
11548 }
11549
11550 NamedDecl *UD =
11551 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11552 SS, TargetNameInfo, EllipsisLoc, AttrList,
11553 /*IsInstantiation*/false);
11554 if (UD)
11555 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11556
11557 return UD;
11558}
11559
11560/// Determine whether a using declaration considers the given
11561/// declarations as "equivalent", e.g., if they are redeclarations of
11562/// the same entity or are both typedefs of the same type.
11563static bool
11564IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11565 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11566 return true;
11567
11568 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11569 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11570 return Context.hasSameType(TD1->getUnderlyingType(),
11571 TD2->getUnderlyingType());
11572
11573 return false;
11574}
11575
11576
11577/// Determines whether to create a using shadow decl for a particular
11578/// decl, given the set of decls existing prior to this using lookup.
11579bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11580 const LookupResult &Previous,
11581 UsingShadowDecl *&PrevShadow) {
11582 // Diagnose finding a decl which is not from a base class of the
11583 // current class. We do this now because there are cases where this
11584 // function will silently decide not to build a shadow decl, which
11585 // will pre-empt further diagnostics.
11586 //
11587 // We don't need to do this in C++11 because we do the check once on
11588 // the qualifier.
11589 //
11590 // FIXME: diagnose the following if we care enough:
11591 // struct A { int foo; };
11592 // struct B : A { using A::foo; };
11593 // template <class T> struct C : A {};
11594 // template <class T> struct D : C<T> { using B::foo; } // <---
11595 // This is invalid (during instantiation) in C++03 because B::foo
11596 // resolves to the using decl in B, which is not a base class of D<T>.
11597 // We can't diagnose it immediately because C<T> is an unknown
11598 // specialization. The UsingShadowDecl in D<T> then points directly
11599 // to A::foo, which will look well-formed when we instantiate.
11600 // The right solution is to not collapse the shadow-decl chain.
11601 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11602 DeclContext *OrigDC = Orig->getDeclContext();
11603
11604 // Handle enums and anonymous structs.
11605 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11606 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11607 while (OrigRec->isAnonymousStructOrUnion())
11608 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11609
11610 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11611 if (OrigDC == CurContext) {
11612 Diag(Using->getLocation(),
11613 diag::err_using_decl_nested_name_specifier_is_current_class)
11614 << Using->getQualifierLoc().getSourceRange();
11615 Diag(Orig->getLocation(), diag::note_using_decl_target);
11616 Using->setInvalidDecl();
11617 return true;
11618 }
11619
11620 Diag(Using->getQualifierLoc().getBeginLoc(),
11621 diag::err_using_decl_nested_name_specifier_is_not_base_class)
11622 << Using->getQualifier()
11623 << cast<CXXRecordDecl>(CurContext)
11624 << Using->getQualifierLoc().getSourceRange();
11625 Diag(Orig->getLocation(), diag::note_using_decl_target);
11626 Using->setInvalidDecl();
11627 return true;
11628 }
11629 }
11630
11631 if (Previous.empty()) return false;
11632
11633 NamedDecl *Target = Orig;
11634 if (isa<UsingShadowDecl>(Target))
11635 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11636
11637 // If the target happens to be one of the previous declarations, we
11638 // don't have a conflict.
11639 //
11640 // FIXME: but we might be increasing its access, in which case we
11641 // should redeclare it.
11642 NamedDecl *NonTag = nullptr, *Tag = nullptr;
11643 bool FoundEquivalentDecl = false;
11644 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11645 I != E; ++I) {
11646 NamedDecl *D = (*I)->getUnderlyingDecl();
11647 // We can have UsingDecls in our Previous results because we use the same
11648 // LookupResult for checking whether the UsingDecl itself is a valid
11649 // redeclaration.
11650 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11651 continue;
11652
11653 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11654 // C++ [class.mem]p19:
11655 // If T is the name of a class, then [every named member other than
11656 // a non-static data member] shall have a name different from T
11657 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11658 !isa<IndirectFieldDecl>(Target) &&
11659 !isa<UnresolvedUsingValueDecl>(Target) &&
11660 DiagnoseClassNameShadow(
11661 CurContext,
11662 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11663 return true;
11664 }
11665
11666 if (IsEquivalentForUsingDecl(Context, D, Target)) {
11667 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11668 PrevShadow = Shadow;
11669 FoundEquivalentDecl = true;
11670 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11671 // We don't conflict with an existing using shadow decl of an equivalent
11672 // declaration, but we're not a redeclaration of it.
11673 FoundEquivalentDecl = true;
11674 }
11675
11676 if (isVisible(D))
11677 (isa<TagDecl>(D) ? Tag : NonTag) = D;
11678 }
11679
11680 if (FoundEquivalentDecl)
11681 return false;
11682
11683 if (FunctionDecl *FD = Target->getAsFunction()) {
11684 NamedDecl *OldDecl = nullptr;
11685 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11686 /*IsForUsingDecl*/ true)) {
11687 case Ovl_Overload:
11688 return false;
11689
11690 case Ovl_NonFunction:
11691 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11692 break;
11693
11694 // We found a decl with the exact signature.
11695 case Ovl_Match:
11696 // If we're in a record, we want to hide the target, so we
11697 // return true (without a diagnostic) to tell the caller not to
11698 // build a shadow decl.
11699 if (CurContext->isRecord())
11700 return true;
11701
11702 // If we're not in a record, this is an error.
11703 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11704 break;
11705 }
11706
11707 Diag(Target->getLocation(), diag::note_using_decl_target);
11708 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11709 Using->setInvalidDecl();
11710 return true;
11711 }
11712
11713 // Target is not a function.
11714
11715 if (isa<TagDecl>(Target)) {
11716 // No conflict between a tag and a non-tag.
11717 if (!Tag) return false;
11718
11719 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11720 Diag(Target->getLocation(), diag::note_using_decl_target);
11721 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11722 Using->setInvalidDecl();
11723 return true;
11724 }
11725
11726 // No conflict between a tag and a non-tag.
11727 if (!NonTag) return false;
11728
11729 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11730 Diag(Target->getLocation(), diag::note_using_decl_target);
11731 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11732 Using->setInvalidDecl();
11733 return true;
11734}
11735
11736/// Determine whether a direct base class is a virtual base class.
11737static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11738 if (!Derived->getNumVBases())
11739 return false;
11740 for (auto &B : Derived->bases())
11741 if (B.getType()->getAsCXXRecordDecl() == Base)
11742 return B.isVirtual();
11743 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11743)
;
11744}
11745
11746/// Builds a shadow declaration corresponding to a 'using' declaration.
11747UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11748 UsingDecl *UD,
11749 NamedDecl *Orig,
11750 UsingShadowDecl *PrevDecl) {
11751 // If we resolved to another shadow declaration, just coalesce them.
11752 NamedDecl *Target = Orig;
11753 if (isa<UsingShadowDecl>(Target)) {
11754 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11755 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")((!isa<UsingShadowDecl>(Target) && "nested shadow declaration"
) ? static_cast<void> (0) : __assert_fail ("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11755, __PRETTY_FUNCTION__))
;
11756 }
11757
11758 NamedDecl *NonTemplateTarget = Target;
11759 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11760 NonTemplateTarget = TargetTD->getTemplatedDecl();
11761
11762 UsingShadowDecl *Shadow;
11763 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11764 bool IsVirtualBase =
11765 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11766 UD->getQualifier()->getAsRecordDecl());
11767 Shadow = ConstructorUsingShadowDecl::Create(
11768 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11769 } else {
11770 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11771 Target);
11772 }
11773 UD->addShadowDecl(Shadow);
11774
11775 Shadow->setAccess(UD->getAccess());
11776 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11777 Shadow->setInvalidDecl();
11778
11779 Shadow->setPreviousDecl(PrevDecl);
11780
11781 if (S)
11782 PushOnScopeChains(Shadow, S);
11783 else
11784 CurContext->addDecl(Shadow);
11785
11786
11787 return Shadow;
11788}
11789
11790/// Hides a using shadow declaration. This is required by the current
11791/// using-decl implementation when a resolvable using declaration in a
11792/// class is followed by a declaration which would hide or override
11793/// one or more of the using decl's targets; for example:
11794///
11795/// struct Base { void foo(int); };
11796/// struct Derived : Base {
11797/// using Base::foo;
11798/// void foo(int);
11799/// };
11800///
11801/// The governing language is C++03 [namespace.udecl]p12:
11802///
11803/// When a using-declaration brings names from a base class into a
11804/// derived class scope, member functions in the derived class
11805/// override and/or hide member functions with the same name and
11806/// parameter types in a base class (rather than conflicting).
11807///
11808/// There are two ways to implement this:
11809/// (1) optimistically create shadow decls when they're not hidden
11810/// by existing declarations, or
11811/// (2) don't create any shadow decls (or at least don't make them
11812/// visible) until we've fully parsed/instantiated the class.
11813/// The problem with (1) is that we might have to retroactively remove
11814/// a shadow decl, which requires several O(n) operations because the
11815/// decl structures are (very reasonably) not designed for removal.
11816/// (2) avoids this but is very fiddly and phase-dependent.
11817void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11818 if (Shadow->getDeclName().getNameKind() ==
11819 DeclarationName::CXXConversionFunctionName)
11820 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11821
11822 // Remove it from the DeclContext...
11823 Shadow->getDeclContext()->removeDecl(Shadow);
11824
11825 // ...and the scope, if applicable...
11826 if (S) {
11827 S->RemoveDecl(Shadow);
11828 IdResolver.RemoveDecl(Shadow);
11829 }
11830
11831 // ...and the using decl.
11832 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11833
11834 // TODO: complain somehow if Shadow was used. It shouldn't
11835 // be possible for this to happen, because...?
11836}
11837
11838/// Find the base specifier for a base class with the given type.
11839static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11840 QualType DesiredBase,
11841 bool &AnyDependentBases) {
11842 // Check whether the named type is a direct base class.
11843 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11844 .getUnqualifiedType();
11845 for (auto &Base : Derived->bases()) {
11846 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11847 if (CanonicalDesiredBase == BaseType)
11848 return &Base;
11849 if (BaseType->isDependentType())
11850 AnyDependentBases = true;
11851 }
11852 return nullptr;
11853}
11854
11855namespace {
11856class UsingValidatorCCC final : public CorrectionCandidateCallback {
11857public:
11858 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11859 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11860 : HasTypenameKeyword(HasTypenameKeyword),
11861 IsInstantiation(IsInstantiation), OldNNS(NNS),
11862 RequireMemberOf(RequireMemberOf) {}
11863
11864 bool ValidateCandidate(const TypoCorrection &Candidate) override {
11865 NamedDecl *ND = Candidate.getCorrectionDecl();
11866
11867 // Keywords are not valid here.
11868 if (!ND || isa<NamespaceDecl>(ND))
11869 return false;
11870
11871 // Completely unqualified names are invalid for a 'using' declaration.
11872 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11873 return false;
11874
11875 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11876 // reject.
11877
11878 if (RequireMemberOf) {
11879 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11880 if (FoundRecord && FoundRecord->isInjectedClassName()) {
11881 // No-one ever wants a using-declaration to name an injected-class-name
11882 // of a base class, unless they're declaring an inheriting constructor.
11883 ASTContext &Ctx = ND->getASTContext();
11884 if (!Ctx.getLangOpts().CPlusPlus11)
11885 return false;
11886 QualType FoundType = Ctx.getRecordType(FoundRecord);
11887
11888 // Check that the injected-class-name is named as a member of its own
11889 // type; we don't want to suggest 'using Derived::Base;', since that
11890 // means something else.
11891 NestedNameSpecifier *Specifier =
11892 Candidate.WillReplaceSpecifier()
11893 ? Candidate.getCorrectionSpecifier()
11894 : OldNNS;
11895 if (!Specifier->getAsType() ||
11896 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11897 return false;
11898
11899 // Check that this inheriting constructor declaration actually names a
11900 // direct base class of the current class.
11901 bool AnyDependentBases = false;
11902 if (!findDirectBaseWithType(RequireMemberOf,
11903 Ctx.getRecordType(FoundRecord),
11904 AnyDependentBases) &&
11905 !AnyDependentBases)
11906 return false;
11907 } else {
11908 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11909 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11910 return false;
11911
11912 // FIXME: Check that the base class member is accessible?
11913 }
11914 } else {
11915 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11916 if (FoundRecord && FoundRecord->isInjectedClassName())
11917 return false;
11918 }
11919
11920 if (isa<TypeDecl>(ND))
11921 return HasTypenameKeyword || !IsInstantiation;
11922
11923 return !HasTypenameKeyword;
11924 }
11925
11926 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11927 return std::make_unique<UsingValidatorCCC>(*this);
11928 }
11929
11930private:
11931 bool HasTypenameKeyword;
11932 bool IsInstantiation;
11933 NestedNameSpecifier *OldNNS;
11934 CXXRecordDecl *RequireMemberOf;
11935};
11936} // end anonymous namespace
11937
11938/// Builds a using declaration.
11939///
11940/// \param IsInstantiation - Whether this call arises from an
11941/// instantiation of an unresolved using declaration. We treat
11942/// the lookup differently for these declarations.
11943NamedDecl *Sema::BuildUsingDeclaration(
11944 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11945 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11946 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11947 const ParsedAttributesView &AttrList, bool IsInstantiation) {
11948 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast
<void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11948, __PRETTY_FUNCTION__))
;
11949 SourceLocation IdentLoc = NameInfo.getLoc();
11950 assert(IdentLoc.isValid() && "Invalid TargetName location.")((IdentLoc.isValid() && "Invalid TargetName location."
) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11950, __PRETTY_FUNCTION__))
;
11951
11952 // FIXME: We ignore attributes for now.
11953
11954 // For an inheriting constructor declaration, the name of the using
11955 // declaration is the name of a constructor in this class, not in the
11956 // base class.
11957 DeclarationNameInfo UsingName = NameInfo;
11958 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11959 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11960 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11961 Context.getCanonicalType(Context.getRecordType(RD))));
11962
11963 // Do the redeclaration lookup in the current scope.
11964 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11965 ForVisibleRedeclaration);
11966 Previous.setHideTags(false);
11967 if (S) {
11968 LookupName(Previous, S);
11969
11970 // It is really dumb that we have to do this.
11971 LookupResult::Filter F = Previous.makeFilter();
11972 while (F.hasNext()) {
11973 NamedDecl *D = F.next();
11974 if (!isDeclInScope(D, CurContext, S))
11975 F.erase();
11976 // If we found a local extern declaration that's not ordinarily visible,
11977 // and this declaration is being added to a non-block scope, ignore it.
11978 // We're only checking for scope conflicts here, not also for violations
11979 // of the linkage rules.
11980 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11981 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11982 F.erase();
11983 }
11984 F.done();
11985 } else {
11986 assert(IsInstantiation && "no scope in non-instantiation")((IsInstantiation && "no scope in non-instantiation")
? static_cast<void> (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 11986, __PRETTY_FUNCTION__))
;
11987 if (CurContext->isRecord())
11988 LookupQualifiedName(Previous, CurContext);
11989 else {
11990 // No redeclaration check is needed here; in non-member contexts we
11991 // diagnosed all possible conflicts with other using-declarations when
11992 // building the template:
11993 //
11994 // For a dependent non-type using declaration, the only valid case is
11995 // if we instantiate to a single enumerator. We check for conflicts
11996 // between shadow declarations we introduce, and we check in the template
11997 // definition for conflicts between a non-type using declaration and any
11998 // other declaration, which together covers all cases.
11999 //
12000 // A dependent typename using declaration will never successfully
12001 // instantiate, since it will always name a class member, so we reject
12002 // that in the template definition.
12003 }
12004 }
12005
12006 // Check for invalid redeclarations.
12007 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12008 SS, IdentLoc, Previous))
12009 return nullptr;
12010
12011 // Check for bad qualifiers.
12012 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12013 IdentLoc))
12014 return nullptr;
12015
12016 DeclContext *LookupContext = computeDeclContext(SS);
12017 NamedDecl *D;
12018 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12019 if (!LookupContext || EllipsisLoc.isValid()) {
12020 if (HasTypenameKeyword) {
12021 // FIXME: not all declaration name kinds are legal here
12022 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12023 UsingLoc, TypenameLoc,
12024 QualifierLoc,
12025 IdentLoc, NameInfo.getName(),
12026 EllipsisLoc);
12027 } else {
12028 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12029 QualifierLoc, NameInfo, EllipsisLoc);
12030 }
12031 D->setAccess(AS);
12032 CurContext->addDecl(D);
12033 return D;
12034 }
12035
12036 auto Build = [&](bool Invalid) {
12037 UsingDecl *UD =
12038 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12039 UsingName, HasTypenameKeyword);
12040 UD->setAccess(AS);
12041 CurContext->addDecl(UD);
12042 UD->setInvalidDecl(Invalid);
12043 return UD;
12044 };
12045 auto BuildInvalid = [&]{ return Build(true); };
12046 auto BuildValid = [&]{ return Build(false); };
12047
12048 if (RequireCompleteDeclContext(SS, LookupContext))
12049 return BuildInvalid();
12050
12051 // Look up the target name.
12052 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12053
12054 // Unlike most lookups, we don't always want to hide tag
12055 // declarations: tag names are visible through the using declaration
12056 // even if hidden by ordinary names, *except* in a dependent context
12057 // where it's important for the sanity of two-phase lookup.
12058 if (!IsInstantiation)
12059 R.setHideTags(false);
12060
12061 // For the purposes of this lookup, we have a base object type
12062 // equal to that of the current context.
12063 if (CurContext->isRecord()) {
12064 R.setBaseObjectType(
12065 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12066 }
12067
12068 LookupQualifiedName(R, LookupContext);
12069
12070 // Try to correct typos if possible. If constructor name lookup finds no
12071 // results, that means the named class has no explicit constructors, and we
12072 // suppressed declaring implicit ones (probably because it's dependent or
12073 // invalid).
12074 if (R.empty() &&
12075 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12076 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12077 // it will believe that glibc provides a ::gets in cases where it does not,
12078 // and will try to pull it into namespace std with a using-declaration.
12079 // Just ignore the using-declaration in that case.
12080 auto *II = NameInfo.getName().getAsIdentifierInfo();
12081 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12082 CurContext->isStdNamespace() &&
12083 isa<TranslationUnitDecl>(LookupContext) &&
12084 getSourceManager().isInSystemHeader(UsingLoc))
12085 return nullptr;
12086 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12087 dyn_cast<CXXRecordDecl>(CurContext));
12088 if (TypoCorrection Corrected =
12089 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12090 CTK_ErrorRecovery)) {
12091 // We reject candidates where DroppedSpecifier == true, hence the
12092 // literal '0' below.
12093 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12094 << NameInfo.getName() << LookupContext << 0
12095 << SS.getRange());
12096
12097 // If we picked a correction with no attached Decl we can't do anything
12098 // useful with it, bail out.
12099 NamedDecl *ND = Corrected.getCorrectionDecl();
12100 if (!ND)
12101 return BuildInvalid();
12102
12103 // If we corrected to an inheriting constructor, handle it as one.
12104 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12105 if (RD && RD->isInjectedClassName()) {
12106 // The parent of the injected class name is the class itself.
12107 RD = cast<CXXRecordDecl>(RD->getParent());
12108
12109 // Fix up the information we'll use to build the using declaration.
12110 if (Corrected.WillReplaceSpecifier()) {
12111 NestedNameSpecifierLocBuilder Builder;
12112 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12113 QualifierLoc.getSourceRange());
12114 QualifierLoc = Builder.getWithLocInContext(Context);
12115 }
12116
12117 // In this case, the name we introduce is the name of a derived class
12118 // constructor.
12119 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12120 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12121 Context.getCanonicalType(Context.getRecordType(CurClass))));
12122 UsingName.setNamedTypeInfo(nullptr);
12123 for (auto *Ctor : LookupConstructors(RD))
12124 R.addDecl(Ctor);
12125 R.resolveKind();
12126 } else {
12127 // FIXME: Pick up all the declarations if we found an overloaded
12128 // function.
12129 UsingName.setName(ND->getDeclName());
12130 R.addDecl(ND);
12131 }
12132 } else {
12133 Diag(IdentLoc, diag::err_no_member)
12134 << NameInfo.getName() << LookupContext << SS.getRange();
12135 return BuildInvalid();
12136 }
12137 }
12138
12139 if (R.isAmbiguous())
12140 return BuildInvalid();
12141
12142 if (HasTypenameKeyword) {
12143 // If we asked for a typename and got a non-type decl, error out.
12144 if (!R.getAsSingle<TypeDecl>()) {
12145 Diag(IdentLoc, diag::err_using_typename_non_type);
12146 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12147 Diag((*I)->getUnderlyingDecl()->getLocation(),
12148 diag::note_using_decl_target);
12149 return BuildInvalid();
12150 }
12151 } else {
12152 // If we asked for a non-typename and we got a type, error out,
12153 // but only if this is an instantiation of an unresolved using
12154 // decl. Otherwise just silently find the type name.
12155 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12156 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12157 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12158 return BuildInvalid();
12159 }
12160 }
12161
12162 // C++14 [namespace.udecl]p6:
12163 // A using-declaration shall not name a namespace.
12164 if (R.getAsSingle<NamespaceDecl>()) {
12165 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12166 << SS.getRange();
12167 return BuildInvalid();
12168 }
12169
12170 // C++14 [namespace.udecl]p7:
12171 // A using-declaration shall not name a scoped enumerator.
12172 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12173 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12174 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12175 << SS.getRange();
12176 return BuildInvalid();
12177 }
12178 }
12179
12180 UsingDecl *UD = BuildValid();
12181
12182 // Some additional rules apply to inheriting constructors.
12183 if (UsingName.getName().getNameKind() ==
12184 DeclarationName::CXXConstructorName) {
12185 // Suppress access diagnostics; the access check is instead performed at the
12186 // point of use for an inheriting constructor.
12187 R.suppressDiagnostics();
12188 if (CheckInheritingConstructorUsingDecl(UD))
12189 return UD;
12190 }
12191
12192 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12193 UsingShadowDecl *PrevDecl = nullptr;
12194 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12195 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12196 }
12197
12198 return UD;
12199}
12200
12201NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12202 ArrayRef<NamedDecl *> Expansions) {
12203 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12205, __PRETTY_FUNCTION__))
12204 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12205, __PRETTY_FUNCTION__))
12205 isa<UsingPackDecl>(InstantiatedFrom))((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12205, __PRETTY_FUNCTION__))
;
12206
12207 auto *UPD =
12208 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12209 UPD->setAccess(InstantiatedFrom->getAccess());
12210 CurContext->addDecl(UPD);
12211 return UPD;
12212}
12213
12214/// Additional checks for a using declaration referring to a constructor name.
12215bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12216 assert(!UD->hasTypename() && "expecting a constructor name")((!UD->hasTypename() && "expecting a constructor name"
) ? static_cast<void> (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12216, __PRETTY_FUNCTION__))
;
12217
12218 const Type *SourceType = UD->getQualifier()->getAsType();
12219 assert(SourceType &&((SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12220, __PRETTY_FUNCTION__))
12220 "Using decl naming constructor doesn't have type in scope spec.")((SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12220, __PRETTY_FUNCTION__))
;
12221 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12222
12223 // Check whether the named type is a direct base class.
12224 bool AnyDependentBases = false;
12225 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12226 AnyDependentBases);
12227 if (!Base && !AnyDependentBases) {
12228 Diag(UD->getUsingLoc(),
12229 diag::err_using_decl_constructor_not_in_direct_base)
12230 << UD->getNameInfo().getSourceRange()
12231 << QualType(SourceType, 0) << TargetClass;
12232 UD->setInvalidDecl();
12233 return true;
12234 }
12235
12236 if (Base)
12237 Base->setInheritConstructors();
12238
12239 return false;
12240}
12241
12242/// Checks that the given using declaration is not an invalid
12243/// redeclaration. Note that this is checking only for the using decl
12244/// itself, not for any ill-formedness among the UsingShadowDecls.
12245bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12246 bool HasTypenameKeyword,
12247 const CXXScopeSpec &SS,
12248 SourceLocation NameLoc,
12249 const LookupResult &Prev) {
12250 NestedNameSpecifier *Qual = SS.getScopeRep();
12251
12252 // C++03 [namespace.udecl]p8:
12253 // C++0x [namespace.udecl]p10:
12254 // A using-declaration is a declaration and can therefore be used
12255 // repeatedly where (and only where) multiple declarations are
12256 // allowed.
12257 //
12258 // That's in non-member contexts.
12259 if (!CurContext->getRedeclContext()->isRecord()) {
12260 // A dependent qualifier outside a class can only ever resolve to an
12261 // enumeration type. Therefore it conflicts with any other non-type
12262 // declaration in the same scope.
12263 // FIXME: How should we check for dependent type-type conflicts at block
12264 // scope?
12265 if (Qual->isDependent() && !HasTypenameKeyword) {
12266 for (auto *D : Prev) {
12267 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12268 bool OldCouldBeEnumerator =
12269 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12270 Diag(NameLoc,
12271 OldCouldBeEnumerator ? diag::err_redefinition
12272 : diag::err_redefinition_different_kind)
12273 << Prev.getLookupName();
12274 Diag(D->getLocation(), diag::note_previous_definition);
12275 return true;
12276 }
12277 }
12278 }
12279 return false;
12280 }
12281
12282 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12283 NamedDecl *D = *I;
12284
12285 bool DTypename;
12286 NestedNameSpecifier *DQual;
12287 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12288 DTypename = UD->hasTypename();
12289 DQual = UD->getQualifier();
12290 } else if (UnresolvedUsingValueDecl *UD
12291 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12292 DTypename = false;
12293 DQual = UD->getQualifier();
12294 } else if (UnresolvedUsingTypenameDecl *UD
12295 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12296 DTypename = true;
12297 DQual = UD->getQualifier();
12298 } else continue;
12299
12300 // using decls differ if one says 'typename' and the other doesn't.
12301 // FIXME: non-dependent using decls?
12302 if (HasTypenameKeyword != DTypename) continue;
12303
12304 // using decls differ if they name different scopes (but note that
12305 // template instantiation can cause this check to trigger when it
12306 // didn't before instantiation).
12307 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12308 Context.getCanonicalNestedNameSpecifier(DQual))
12309 continue;
12310
12311 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12312 Diag(D->getLocation(), diag::note_using_decl) << 1;
12313 return true;
12314 }
12315
12316 return false;
12317}
12318
12319
12320/// Checks that the given nested-name qualifier used in a using decl
12321/// in the current context is appropriately related to the current
12322/// scope. If an error is found, diagnoses it and returns true.
12323bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12324 bool HasTypename,
12325 const CXXScopeSpec &SS,
12326 const DeclarationNameInfo &NameInfo,
12327 SourceLocation NameLoc) {
12328 DeclContext *NamedContext = computeDeclContext(SS);
12329
12330 if (!CurContext->isRecord()) {
12331 // C++03 [namespace.udecl]p3:
12332 // C++0x [namespace.udecl]p8:
12333 // A using-declaration for a class member shall be a member-declaration.
12334
12335 // If we weren't able to compute a valid scope, it might validly be a
12336 // dependent class scope or a dependent enumeration unscoped scope. If
12337 // we have a 'typename' keyword, the scope must resolve to a class type.
12338 if ((HasTypename && !NamedContext) ||
12339 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12340 auto *RD = NamedContext
12341 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12342 : nullptr;
12343 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12344 RD = nullptr;
12345
12346 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12347 << SS.getRange();
12348
12349 // If we have a complete, non-dependent source type, try to suggest a
12350 // way to get the same effect.
12351 if (!RD)
12352 return true;
12353
12354 // Find what this using-declaration was referring to.
12355 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12356 R.setHideTags(false);
12357 R.suppressDiagnostics();
12358 LookupQualifiedName(R, RD);
12359
12360 if (R.getAsSingle<TypeDecl>()) {
12361 if (getLangOpts().CPlusPlus11) {
12362 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12363 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12364 << 0 // alias declaration
12365 << FixItHint::CreateInsertion(SS.getBeginLoc(),
12366 NameInfo.getName().getAsString() +
12367 " = ");
12368 } else {
12369 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12370 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12371 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12372 << 1 // typedef declaration
12373 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12374 << FixItHint::CreateInsertion(
12375 InsertLoc, " " + NameInfo.getName().getAsString());
12376 }
12377 } else if (R.getAsSingle<VarDecl>()) {
12378 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12379 // repeating the type of the static data member here.
12380 FixItHint FixIt;
12381 if (getLangOpts().CPlusPlus11) {
12382 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12383 FixIt = FixItHint::CreateReplacement(
12384 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12385 }
12386
12387 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12388 << 2 // reference declaration
12389 << FixIt;
12390 } else if (R.getAsSingle<EnumConstantDecl>()) {
12391 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12392 // repeating the type of the enumeration here, and we can't do so if
12393 // the type is anonymous.
12394 FixItHint FixIt;
12395 if (getLangOpts().CPlusPlus11) {
12396 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12397 FixIt = FixItHint::CreateReplacement(
12398 UsingLoc,
12399 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12400 }
12401
12402 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12403 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12404 << FixIt;
12405 }
12406 return true;
12407 }
12408
12409 // Otherwise, this might be valid.
12410 return false;
12411 }
12412
12413 // The current scope is a record.
12414
12415 // If the named context is dependent, we can't decide much.
12416 if (!NamedContext) {
12417 // FIXME: in C++0x, we can diagnose if we can prove that the
12418 // nested-name-specifier does not refer to a base class, which is
12419 // still possible in some cases.
12420
12421 // Otherwise we have to conservatively report that things might be
12422 // okay.
12423 return false;
12424 }
12425
12426 if (!NamedContext->isRecord()) {
12427 // Ideally this would point at the last name in the specifier,
12428 // but we don't have that level of source info.
12429 Diag(SS.getRange().getBegin(),
12430 diag::err_using_decl_nested_name_specifier_is_not_class)
12431 << SS.getScopeRep() << SS.getRange();
12432 return true;
12433 }
12434
12435 if (!NamedContext->isDependentContext() &&
12436 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12437 return true;
12438
12439 if (getLangOpts().CPlusPlus11) {
12440 // C++11 [namespace.udecl]p3:
12441 // In a using-declaration used as a member-declaration, the
12442 // nested-name-specifier shall name a base class of the class
12443 // being defined.
12444
12445 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12446 cast<CXXRecordDecl>(NamedContext))) {
12447 if (CurContext == NamedContext) {
12448 Diag(NameLoc,
12449 diag::err_using_decl_nested_name_specifier_is_current_class)
12450 << SS.getRange();
12451 return true;
12452 }
12453
12454 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12455 Diag(SS.getRange().getBegin(),
12456 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12457 << SS.getScopeRep()
12458 << cast<CXXRecordDecl>(CurContext)
12459 << SS.getRange();
12460 }
12461 return true;
12462 }
12463
12464 return false;
12465 }
12466
12467 // C++03 [namespace.udecl]p4:
12468 // A using-declaration used as a member-declaration shall refer
12469 // to a member of a base class of the class being defined [etc.].
12470
12471 // Salient point: SS doesn't have to name a base class as long as
12472 // lookup only finds members from base classes. Therefore we can
12473 // diagnose here only if we can prove that that can't happen,
12474 // i.e. if the class hierarchies provably don't intersect.
12475
12476 // TODO: it would be nice if "definitely valid" results were cached
12477 // in the UsingDecl and UsingShadowDecl so that these checks didn't
12478 // need to be repeated.
12479
12480 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12481 auto Collect = [&Bases](const CXXRecordDecl *Base) {
12482 Bases.insert(Base);
12483 return true;
12484 };
12485
12486 // Collect all bases. Return false if we find a dependent base.
12487 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12488 return false;
12489
12490 // Returns true if the base is dependent or is one of the accumulated base
12491 // classes.
12492 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12493 return !Bases.count(Base);
12494 };
12495
12496 // Return false if the class has a dependent base or if it or one
12497 // of its bases is present in the base set of the current context.
12498 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12499 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12500 return false;
12501
12502 Diag(SS.getRange().getBegin(),
12503 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12504 << SS.getScopeRep()
12505 << cast<CXXRecordDecl>(CurContext)
12506 << SS.getRange();
12507
12508 return true;
12509}
12510
12511Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12512 MultiTemplateParamsArg TemplateParamLists,
12513 SourceLocation UsingLoc, UnqualifiedId &Name,
12514 const ParsedAttributesView &AttrList,
12515 TypeResult Type, Decl *DeclFromDeclSpec) {
12516 // Skip up to the relevant declaration scope.
12517 while (S->isTemplateParamScope())
12518 S = S->getParent();
12519 assert((S->getFlags() & Scope::DeclScope) &&(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope"
) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12520, __PRETTY_FUNCTION__))
12520 "got alias-declaration outside of declaration scope")(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope"
) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12520, __PRETTY_FUNCTION__))
;
12521
12522 if (Type.isInvalid())
12523 return nullptr;
12524
12525 bool Invalid = false;
12526 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12527 TypeSourceInfo *TInfo = nullptr;
12528 GetTypeFromParser(Type.get(), &TInfo);
12529
12530 if (DiagnoseClassNameShadow(CurContext, NameInfo))
12531 return nullptr;
12532
12533 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12534 UPPC_DeclarationType)) {
12535 Invalid = true;
12536 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12537 TInfo->getTypeLoc().getBeginLoc());
12538 }
12539
12540 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12541 TemplateParamLists.size()
12542 ? forRedeclarationInCurContext()
12543 : ForVisibleRedeclaration);
12544 LookupName(Previous, S);
12545
12546 // Warn about shadowing the name of a template parameter.
12547 if (Previous.isSingleResult() &&
12548 Previous.getFoundDecl()->isTemplateParameter()) {
12549 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12550 Previous.clear();
12551 }
12552
12553 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12554, __PRETTY_FUNCTION__))
12554 "name in alias declaration must be an identifier")((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12554, __PRETTY_FUNCTION__))
;
12555 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12556 Name.StartLocation,
12557 Name.Identifier, TInfo);
12558
12559 NewTD->setAccess(AS);
12560
12561 if (Invalid)
12562 NewTD->setInvalidDecl();
12563
12564 ProcessDeclAttributeList(S, NewTD, AttrList);
12565 AddPragmaAttributes(S, NewTD);
12566
12567 CheckTypedefForVariablyModifiedType(S, NewTD);
12568 Invalid |= NewTD->isInvalidDecl();
12569
12570 bool Redeclaration = false;
12571
12572 NamedDecl *NewND;
12573 if (TemplateParamLists.size()) {
12574 TypeAliasTemplateDecl *OldDecl = nullptr;
12575 TemplateParameterList *OldTemplateParams = nullptr;
12576
12577 if (TemplateParamLists.size() != 1) {
12578 Diag(UsingLoc, diag::err_alias_template_extra_headers)
12579 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12580 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12581 }
12582 TemplateParameterList *TemplateParams = TemplateParamLists[0];
12583
12584 // Check that we can declare a template here.
12585 if (CheckTemplateDeclScope(S, TemplateParams))
12586 return nullptr;
12587
12588 // Only consider previous declarations in the same scope.
12589 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12590 /*ExplicitInstantiationOrSpecialization*/false);
12591 if (!Previous.empty()) {
12592 Redeclaration = true;
12593
12594 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12595 if (!OldDecl && !Invalid) {
12596 Diag(UsingLoc, diag::err_redefinition_different_kind)
12597 << Name.Identifier;
12598
12599 NamedDecl *OldD = Previous.getRepresentativeDecl();
12600 if (OldD->getLocation().isValid())
12601 Diag(OldD->getLocation(), diag::note_previous_definition);
12602
12603 Invalid = true;
12604 }
12605
12606 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12607 if (TemplateParameterListsAreEqual(TemplateParams,
12608 OldDecl->getTemplateParameters(),
12609 /*Complain=*/true,
12610 TPL_TemplateMatch))
12611 OldTemplateParams =
12612 OldDecl->getMostRecentDecl()->getTemplateParameters();
12613 else
12614 Invalid = true;
12615
12616 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12617 if (!Invalid &&
12618 !Context.hasSameType(OldTD->getUnderlyingType(),
12619 NewTD->getUnderlyingType())) {
12620 // FIXME: The C++0x standard does not clearly say this is ill-formed,
12621 // but we can't reasonably accept it.
12622 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12623 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12624 if (OldTD->getLocation().isValid())
12625 Diag(OldTD->getLocation(), diag::note_previous_definition);
12626 Invalid = true;
12627 }
12628 }
12629 }
12630
12631 // Merge any previous default template arguments into our parameters,
12632 // and check the parameter list.
12633 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12634 TPC_TypeAliasTemplate))
12635 return nullptr;
12636
12637 TypeAliasTemplateDecl *NewDecl =
12638 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12639 Name.Identifier, TemplateParams,
12640 NewTD);
12641 NewTD->setDescribedAliasTemplate(NewDecl);
12642
12643 NewDecl->setAccess(AS);
12644
12645 if (Invalid)
12646 NewDecl->setInvalidDecl();
12647 else if (OldDecl) {
12648 NewDecl->setPreviousDecl(OldDecl);
12649 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12650 }
12651
12652 NewND = NewDecl;
12653 } else {
12654 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12655 setTagNameForLinkagePurposes(TD, NewTD);
12656 handleTagNumbering(TD, S);
12657 }
12658 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12659 NewND = NewTD;
12660 }
12661
12662 PushOnScopeChains(NewND, S);
12663 ActOnDocumentableDecl(NewND);
12664 return NewND;
12665}
12666
12667Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12668 SourceLocation AliasLoc,
12669 IdentifierInfo *Alias, CXXScopeSpec &SS,
12670 SourceLocation IdentLoc,
12671 IdentifierInfo *Ident) {
12672
12673 // Lookup the namespace name.
12674 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12675 LookupParsedName(R, S, &SS);
12676
12677 if (R.isAmbiguous())
12678 return nullptr;
12679
12680 if (R.empty()) {
12681 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12682 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12683 return nullptr;
12684 }
12685 }
12686 assert(!R.isAmbiguous() && !R.empty())((!R.isAmbiguous() && !R.empty()) ? static_cast<void
> (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12686, __PRETTY_FUNCTION__))
;
12687 NamedDecl *ND = R.getRepresentativeDecl();
12688
12689 // Check if we have a previous declaration with the same name.
12690 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12691 ForVisibleRedeclaration);
12692 LookupName(PrevR, S);
12693
12694 // Check we're not shadowing a template parameter.
12695 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12696 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12697 PrevR.clear();
12698 }
12699
12700 // Filter out any other lookup result from an enclosing scope.
12701 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12702 /*AllowInlineNamespace*/false);
12703
12704 // Find the previous declaration and check that we can redeclare it.
12705 NamespaceAliasDecl *Prev = nullptr;
12706 if (PrevR.isSingleResult()) {
12707 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12708 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12709 // We already have an alias with the same name that points to the same
12710 // namespace; check that it matches.
12711 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12712 Prev = AD;
12713 } else if (isVisible(PrevDecl)) {
12714 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12715 << Alias;
12716 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12717 << AD->getNamespace();
12718 return nullptr;
12719 }
12720 } else if (isVisible(PrevDecl)) {
12721 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12722 ? diag::err_redefinition
12723 : diag::err_redefinition_different_kind;
12724 Diag(AliasLoc, DiagID) << Alias;
12725 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12726 return nullptr;
12727 }
12728 }
12729
12730 // The use of a nested name specifier may trigger deprecation warnings.
12731 DiagnoseUseOfDecl(ND, IdentLoc);
12732
12733 NamespaceAliasDecl *AliasDecl =
12734 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12735 Alias, SS.getWithLocInContext(Context),
12736 IdentLoc, ND);
12737 if (Prev)
12738 AliasDecl->setPreviousDecl(Prev);
12739
12740 PushOnScopeChains(AliasDecl, S);
12741 return AliasDecl;
12742}
12743
12744namespace {
12745struct SpecialMemberExceptionSpecInfo
12746 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12747 SourceLocation Loc;
12748 Sema::ImplicitExceptionSpecification ExceptSpec;
12749
12750 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12751 Sema::CXXSpecialMember CSM,
12752 Sema::InheritedConstructorInfo *ICI,
12753 SourceLocation Loc)
12754 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12755
12756 bool visitBase(CXXBaseSpecifier *Base);
12757 bool visitField(FieldDecl *FD);
12758
12759 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12760 unsigned Quals);
12761
12762 void visitSubobjectCall(Subobject Subobj,
12763 Sema::SpecialMemberOverloadResult SMOR);
12764};
12765}
12766
12767bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12768 auto *RT = Base->getType()->getAs<RecordType>();
12769 if (!RT)
12770 return false;
12771
12772 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12773 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12774 if (auto *BaseCtor = SMOR.getMethod()) {
12775 visitSubobjectCall(Base, BaseCtor);
12776 return false;
12777 }
12778
12779 visitClassSubobject(BaseClass, Base, 0);
12780 return false;
12781}
12782
12783bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12784 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12785 Expr *E = FD->getInClassInitializer();
12786 if (!E)
12787 // FIXME: It's a little wasteful to build and throw away a
12788 // CXXDefaultInitExpr here.
12789 // FIXME: We should have a single context note pointing at Loc, and
12790 // this location should be MD->getLocation() instead, since that's
12791 // the location where we actually use the default init expression.
12792 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12793 if (E)
12794 ExceptSpec.CalledExpr(E);
12795 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12796 ->getAs<RecordType>()) {
12797 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12798 FD->getType().getCVRQualifiers());
12799 }
12800 return false;
12801}
12802
12803void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12804 Subobject Subobj,
12805 unsigned Quals) {
12806 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12807 bool IsMutable = Field && Field->isMutable();
12808 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12809}
12810
12811void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12812 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12813 // Note, if lookup fails, it doesn't matter what exception specification we
12814 // choose because the special member will be deleted.
12815 if (CXXMethodDecl *MD = SMOR.getMethod())
12816 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12817}
12818
12819bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12820 llvm::APSInt Result;
12821 ExprResult Converted = CheckConvertedConstantExpression(
12822 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12823 ExplicitSpec.setExpr(Converted.get());
12824 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12825 ExplicitSpec.setKind(Result.getBoolValue()
12826 ? ExplicitSpecKind::ResolvedTrue
12827 : ExplicitSpecKind::ResolvedFalse);
12828 return true;
12829 }
12830 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12831 return false;
12832}
12833
12834ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12835 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12836 if (!ExplicitExpr->isTypeDependent())
12837 tryResolveExplicitSpecifier(ES);
12838 return ES;
12839}
12840
12841static Sema::ImplicitExceptionSpecification
12842ComputeDefaultedSpecialMemberExceptionSpec(
12843 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12844 Sema::InheritedConstructorInfo *ICI) {
12845 ComputingExceptionSpec CES(S, MD, Loc);
12846
12847 CXXRecordDecl *ClassDecl = MD->getParent();
12848
12849 // C++ [except.spec]p14:
12850 // An implicitly declared special member function (Clause 12) shall have an
12851 // exception-specification. [...]
12852 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12853 if (ClassDecl->isInvalidDecl())
12854 return Info.ExceptSpec;
12855
12856 // FIXME: If this diagnostic fires, we're probably missing a check for
12857 // attempting to resolve an exception specification before it's known
12858 // at a higher level.
12859 if (S.RequireCompleteType(MD->getLocation(),
12860 S.Context.getRecordType(ClassDecl),
12861 diag::err_exception_spec_incomplete_type))
12862 return Info.ExceptSpec;
12863
12864 // C++1z [except.spec]p7:
12865 // [Look for exceptions thrown by] a constructor selected [...] to
12866 // initialize a potentially constructed subobject,
12867 // C++1z [except.spec]p8:
12868 // The exception specification for an implicitly-declared destructor, or a
12869 // destructor without a noexcept-specifier, is potentially-throwing if and
12870 // only if any of the destructors for any of its potentially constructed
12871 // subojects is potentially throwing.
12872 // FIXME: We respect the first rule but ignore the "potentially constructed"
12873 // in the second rule to resolve a core issue (no number yet) that would have
12874 // us reject:
12875 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12876 // struct B : A {};
12877 // struct C : B { void f(); };
12878 // ... due to giving B::~B() a non-throwing exception specification.
12879 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12880 : Info.VisitAllBases);
12881
12882 return Info.ExceptSpec;
12883}
12884
12885namespace {
12886/// RAII object to register a special member as being currently declared.
12887struct DeclaringSpecialMember {
12888 Sema &S;
12889 Sema::SpecialMemberDecl D;
12890 Sema::ContextRAII SavedContext;
12891 bool WasAlreadyBeingDeclared;
12892
12893 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12894 : S(S), D(RD, CSM), SavedContext(S, RD) {
12895 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12896 if (WasAlreadyBeingDeclared)
12897 // This almost never happens, but if it does, ensure that our cache
12898 // doesn't contain a stale result.
12899 S.SpecialMemberCache.clear();
12900 else {
12901 // Register a note to be produced if we encounter an error while
12902 // declaring the special member.
12903 Sema::CodeSynthesisContext Ctx;
12904 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12905 // FIXME: We don't have a location to use here. Using the class's
12906 // location maintains the fiction that we declare all special members
12907 // with the class, but (1) it's not clear that lying about that helps our
12908 // users understand what's going on, and (2) there may be outer contexts
12909 // on the stack (some of which are relevant) and printing them exposes
12910 // our lies.
12911 Ctx.PointOfInstantiation = RD->getLocation();
12912 Ctx.Entity = RD;
12913 Ctx.SpecialMember = CSM;
12914 S.pushCodeSynthesisContext(Ctx);
12915 }
12916 }
12917 ~DeclaringSpecialMember() {
12918 if (!WasAlreadyBeingDeclared) {
12919 S.SpecialMembersBeingDeclared.erase(D);
12920 S.popCodeSynthesisContext();
12921 }
12922 }
12923
12924 /// Are we already trying to declare this special member?
12925 bool isAlreadyBeingDeclared() const {
12926 return WasAlreadyBeingDeclared;
12927 }
12928};
12929}
12930
12931void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12932 // Look up any existing declarations, but don't trigger declaration of all
12933 // implicit special members with this name.
12934 DeclarationName Name = FD->getDeclName();
12935 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12936 ForExternalRedeclaration);
12937 for (auto *D : FD->getParent()->lookup(Name))
12938 if (auto *Acceptable = R.getAcceptableDecl(D))
12939 R.addDecl(Acceptable);
12940 R.resolveKind();
12941 R.suppressDiagnostics();
12942
12943 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12944}
12945
12946void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12947 QualType ResultTy,
12948 ArrayRef<QualType> Args) {
12949 // Build an exception specification pointing back at this constructor.
12950 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12951
12952 LangAS AS = getDefaultCXXMethodAddrSpace();
12953 if (AS != LangAS::Default) {
12954 EPI.TypeQuals.addAddressSpace(AS);
12955 }
12956
12957 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12958 SpecialMem->setType(QT);
12959}
12960
12961CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12962 CXXRecordDecl *ClassDecl) {
12963 // C++ [class.ctor]p5:
12964 // A default constructor for a class X is a constructor of class X
12965 // that can be called without an argument. If there is no
12966 // user-declared constructor for class X, a default constructor is
12967 // implicitly declared. An implicitly-declared default constructor
12968 // is an inline public member of its class.
12969 assert(ClassDecl->needsImplicitDefaultConstructor() &&((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12970, __PRETTY_FUNCTION__))
12970 "Should not build implicit default constructor!")((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 12970, __PRETTY_FUNCTION__))
;
12971
12972 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12973 if (DSM.isAlreadyBeingDeclared())
12974 return nullptr;
12975
12976 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12977 CXXDefaultConstructor,
12978 false);
12979
12980 // Create the actual constructor declaration.
12981 CanQualType ClassType
12982 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12983 SourceLocation ClassLoc = ClassDecl->getLocation();
12984 DeclarationName Name
12985 = Context.DeclarationNames.getCXXConstructorName(ClassType);
12986 DeclarationNameInfo NameInfo(Name, ClassLoc);
12987 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12988 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12989 /*TInfo=*/nullptr, ExplicitSpecifier(),
12990 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12991 Constexpr ? ConstexprSpecKind::Constexpr
12992 : ConstexprSpecKind::Unspecified);
12993 DefaultCon->setAccess(AS_public);
12994 DefaultCon->setDefaulted();
12995
12996 if (getLangOpts().CUDA) {
12997 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12998 DefaultCon,
12999 /* ConstRHS */ false,
13000 /* Diagnose */ false);
13001 }
13002
13003 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13004
13005 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13006 // constructors is easy to compute.
13007 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13008
13009 // Note that we have declared this constructor.
13010 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13011
13012 Scope *S = getScopeForContext(ClassDecl);
13013 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13014
13015 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13016 SetDeclDeleted(DefaultCon, ClassLoc);
13017
13018 if (S)
13019 PushOnScopeChains(DefaultCon, S, false);
13020 ClassDecl->addDecl(DefaultCon);
13021
13022 return DefaultCon;
13023}
13024
13025void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13026 CXXConstructorDecl *Constructor) {
13027 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13030, __PRETTY_FUNCTION__))
13028 !Constructor->doesThisDeclarationHaveABody() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13030, __PRETTY_FUNCTION__))
13029 !Constructor->isDeleted()) &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13030, __PRETTY_FUNCTION__))
13030 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13030, __PRETTY_FUNCTION__))
;
13031 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13032 return;
13033
13034 CXXRecordDecl *ClassDecl = Constructor->getParent();
13035 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")((ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13035, __PRETTY_FUNCTION__))
;
13036
13037 SynthesizedFunctionScope Scope(*this, Constructor);
13038
13039 // The exception specification is needed because we are defining the
13040 // function.
13041 ResolveExceptionSpec(CurrentLocation,
13042 Constructor->getType()->castAs<FunctionProtoType>());
13043 MarkVTableUsed(CurrentLocation, ClassDecl);
13044
13045 // Add a context note for diagnostics produced after this point.
13046 Scope.addContextNote(CurrentLocation);
13047
13048 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13049 Constructor->setInvalidDecl();
13050 return;
13051 }
13052
13053 SourceLocation Loc = Constructor->getEndLoc().isValid()
13054 ? Constructor->getEndLoc()
13055 : Constructor->getLocation();
13056 Constructor->setBody(new (Context) CompoundStmt(Loc));
13057 Constructor->markUsed(Context);
13058
13059 if (ASTMutationListener *L = getASTMutationListener()) {
13060 L->CompletedImplicitDefinition(Constructor);
13061 }
13062
13063 DiagnoseUninitializedFields(*this, Constructor);
13064}
13065
13066void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13067 // Perform any delayed checks on exception specifications.
13068 CheckDelayedMemberExceptionSpecs();
13069}
13070
13071/// Find or create the fake constructor we synthesize to model constructing an
13072/// object of a derived class via a constructor of a base class.
13073CXXConstructorDecl *
13074Sema::findInheritingConstructor(SourceLocation Loc,
13075 CXXConstructorDecl *BaseCtor,
13076 ConstructorUsingShadowDecl *Shadow) {
13077 CXXRecordDecl *Derived = Shadow->getParent();
13078 SourceLocation UsingLoc = Shadow->getLocation();
13079
13080 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13081 // For now we use the name of the base class constructor as a member of the
13082 // derived class to indicate a (fake) inherited constructor name.
13083 DeclarationName Name = BaseCtor->getDeclName();
13084
13085 // Check to see if we already have a fake constructor for this inherited
13086 // constructor call.
13087 for (NamedDecl *Ctor : Derived->lookup(Name))
13088 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13089 ->getInheritedConstructor()
13090 .getConstructor(),
13091 BaseCtor))
13092 return cast<CXXConstructorDecl>(Ctor);
13093
13094 DeclarationNameInfo NameInfo(Name, UsingLoc);
13095 TypeSourceInfo *TInfo =
13096 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13097 FunctionProtoTypeLoc ProtoLoc =
13098 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13099
13100 // Check the inherited constructor is valid and find the list of base classes
13101 // from which it was inherited.
13102 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13103
13104 bool Constexpr =
13105 BaseCtor->isConstexpr() &&
13106 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13107 false, BaseCtor, &ICI);
13108
13109 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13110 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13111 BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13112 /*isImplicitlyDeclared=*/true,
13113 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13114 InheritedConstructor(Shadow, BaseCtor),
13115 BaseCtor->getTrailingRequiresClause());
13116 if (Shadow->isInvalidDecl())
13117 DerivedCtor->setInvalidDecl();
13118
13119 // Build an unevaluated exception specification for this fake constructor.
13120 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13121 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13122 EPI.ExceptionSpec.Type = EST_Unevaluated;
13123 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13124 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13125 FPT->getParamTypes(), EPI));
13126
13127 // Build the parameter declarations.
13128 SmallVector<ParmVarDecl *, 16> ParamDecls;
13129 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13130 TypeSourceInfo *TInfo =
13131 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13132 ParmVarDecl *PD = ParmVarDecl::Create(
13133 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13134 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13135 PD->setScopeInfo(0, I);
13136 PD->setImplicit();
13137 // Ensure attributes are propagated onto parameters (this matters for
13138 // format, pass_object_size, ...).
13139 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13140 ParamDecls.push_back(PD);
13141 ProtoLoc.setParam(I, PD);
13142 }
13143
13144 // Set up the new constructor.
13145 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")((!BaseCtor->isDeleted() && "should not use deleted constructor"
) ? static_cast<void> (0) : __assert_fail ("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13145, __PRETTY_FUNCTION__))
;
13146 DerivedCtor->setAccess(BaseCtor->getAccess());
13147 DerivedCtor->setParams(ParamDecls);
13148 Derived->addDecl(DerivedCtor);
13149
13150 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13151 SetDeclDeleted(DerivedCtor, UsingLoc);
13152
13153 return DerivedCtor;
13154}
13155
13156void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13157 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13158 Ctor->getInheritedConstructor().getShadowDecl());
13159 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13160 /*Diagnose*/true);
13161}
13162
13163void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13164 CXXConstructorDecl *Constructor) {
13165 CXXRecordDecl *ClassDecl = Constructor->getParent();
13166 assert(Constructor->getInheritedConstructor() &&((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13168, __PRETTY_FUNCTION__))
13167 !Constructor->doesThisDeclarationHaveABody() &&((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13168, __PRETTY_FUNCTION__))
13168 !Constructor->isDeleted())((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13168, __PRETTY_FUNCTION__))
;
13169 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13170 return;
13171
13172 // Initializations are performed "as if by a defaulted default constructor",
13173 // so enter the appropriate scope.
13174 SynthesizedFunctionScope Scope(*this, Constructor);
13175
13176 // The exception specification is needed because we are defining the
13177 // function.
13178 ResolveExceptionSpec(CurrentLocation,
13179 Constructor->getType()->castAs<FunctionProtoType>());
13180 MarkVTableUsed(CurrentLocation, ClassDecl);
13181
13182 // Add a context note for diagnostics produced after this point.
13183 Scope.addContextNote(CurrentLocation);
13184
13185 ConstructorUsingShadowDecl *Shadow =
13186 Constructor->getInheritedConstructor().getShadowDecl();
13187 CXXConstructorDecl *InheritedCtor =
13188 Constructor->getInheritedConstructor().getConstructor();
13189
13190 // [class.inhctor.init]p1:
13191 // initialization proceeds as if a defaulted default constructor is used to
13192 // initialize the D object and each base class subobject from which the
13193 // constructor was inherited
13194
13195 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13196 CXXRecordDecl *RD = Shadow->getParent();
13197 SourceLocation InitLoc = Shadow->getLocation();
13198
13199 // Build explicit initializers for all base classes from which the
13200 // constructor was inherited.
13201 SmallVector<CXXCtorInitializer*, 8> Inits;
13202 for (bool VBase : {false, true}) {
13203 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13204 if (B.isVirtual() != VBase)
13205 continue;
13206
13207 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13208 if (!BaseRD)
13209 continue;
13210
13211 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13212 if (!BaseCtor.first)
13213 continue;
13214
13215 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13216 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13217 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13218
13219 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13220 Inits.push_back(new (Context) CXXCtorInitializer(
13221 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13222 SourceLocation()));
13223 }
13224 }
13225
13226 // We now proceed as if for a defaulted default constructor, with the relevant
13227 // initializers replaced.
13228
13229 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13230 Constructor->setInvalidDecl();
13231 return;
13232 }
13233
13234 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13235 Constructor->markUsed(Context);
13236
13237 if (ASTMutationListener *L = getASTMutationListener()) {
13238 L->CompletedImplicitDefinition(Constructor);
13239 }
13240
13241 DiagnoseUninitializedFields(*this, Constructor);
13242}
13243
13244CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13245 // C++ [class.dtor]p2:
13246 // If a class has no user-declared destructor, a destructor is
13247 // declared implicitly. An implicitly-declared destructor is an
13248 // inline public member of its class.
13249 assert(ClassDecl->needsImplicitDestructor())((ClassDecl->needsImplicitDestructor()) ? static_cast<void
> (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13249, __PRETTY_FUNCTION__))
;
13250
13251 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13252 if (DSM.isAlreadyBeingDeclared())
13253 return nullptr;
13254
13255 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13256 CXXDestructor,
13257 false);
13258
13259 // Create the actual destructor declaration.
13260 CanQualType ClassType
13261 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13262 SourceLocation ClassLoc = ClassDecl->getLocation();
13263 DeclarationName Name
13264 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13265 DeclarationNameInfo NameInfo(Name, ClassLoc);
13266 CXXDestructorDecl *Destructor =
13267 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13268 QualType(), nullptr, /*isInline=*/true,
13269 /*isImplicitlyDeclared=*/true,
13270 Constexpr ? ConstexprSpecKind::Constexpr
13271 : ConstexprSpecKind::Unspecified);
13272 Destructor->setAccess(AS_public);
13273 Destructor->setDefaulted();
13274
13275 if (getLangOpts().CUDA) {
13276 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13277 Destructor,
13278 /* ConstRHS */ false,
13279 /* Diagnose */ false);
13280 }
13281
13282 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13283
13284 // We don't need to use SpecialMemberIsTrivial here; triviality for
13285 // destructors is easy to compute.
13286 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13287 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13288 ClassDecl->hasTrivialDestructorForCall());
13289
13290 // Note that we have declared this destructor.
13291 ++getASTContext().NumImplicitDestructorsDeclared;
13292
13293 Scope *S = getScopeForContext(ClassDecl);
13294 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13295
13296 // We can't check whether an implicit destructor is deleted before we complete
13297 // the definition of the class, because its validity depends on the alignment
13298 // of the class. We'll check this from ActOnFields once the class is complete.
13299 if (ClassDecl->isCompleteDefinition() &&
13300 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13301 SetDeclDeleted(Destructor, ClassLoc);
13302
13303 // Introduce this destructor into its scope.
13304 if (S)
13305 PushOnScopeChains(Destructor, S, false);
13306 ClassDecl->addDecl(Destructor);
13307
13308 return Destructor;
13309}
13310
13311void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13312 CXXDestructorDecl *Destructor) {
13313 assert((Destructor->isDefaulted() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13316, __PRETTY_FUNCTION__))
8
Assuming the condition is true
9
Assuming the condition is true
10
Assuming the condition is true
11
'?' condition is true
13314 !Destructor->doesThisDeclarationHaveABody() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13316, __PRETTY_FUNCTION__))
13315 !Destructor->isDeleted()) &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13316, __PRETTY_FUNCTION__))
13316 "DefineImplicitDestructor - call it for implicit default dtor")(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13316, __PRETTY_FUNCTION__))
;
13317 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
12
Assuming the condition is false
13
Assuming the condition is false
14
Taking false branch
13318 return;
13319
13320 CXXRecordDecl *ClassDecl = Destructor->getParent();
13321 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")((ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13321, __PRETTY_FUNCTION__))
;
15
'?' condition is true
13322
13323 SynthesizedFunctionScope Scope(*this, Destructor);
13324
13325 // The exception specification is needed because we are defining the
13326 // function.
13327 ResolveExceptionSpec(CurrentLocation,
13328 Destructor->getType()->castAs<FunctionProtoType>());
16
The object is a 'FunctionProtoType'
13329 MarkVTableUsed(CurrentLocation, ClassDecl);
13330
13331 // Add a context note for diagnostics produced after this point.
13332 Scope.addContextNote(CurrentLocation);
13333
13334 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
17
Calling 'Sema::MarkBaseAndMemberDestructorsReferenced'
13335 Destructor->getParent());
13336
13337 if (CheckDestructor(Destructor)) {
13338 Destructor->setInvalidDecl();
13339 return;
13340 }
13341
13342 SourceLocation Loc = Destructor->getEndLoc().isValid()
13343 ? Destructor->getEndLoc()
13344 : Destructor->getLocation();
13345 Destructor->setBody(new (Context) CompoundStmt(Loc));
13346 Destructor->markUsed(Context);
13347
13348 if (ASTMutationListener *L = getASTMutationListener()) {
13349 L->CompletedImplicitDefinition(Destructor);
13350 }
13351}
13352
13353void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13354 CXXDestructorDecl *Destructor) {
13355 if (Destructor->isInvalidDecl())
13356 return;
13357
13358 CXXRecordDecl *ClassDecl = Destructor->getParent();
13359 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&((Context.getTargetInfo().getCXXABI().isMicrosoft() &&
"implicit complete dtors unneeded outside MS ABI") ? static_cast
<void> (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13360, __PRETTY_FUNCTION__))
13360 "implicit complete dtors unneeded outside MS ABI")((Context.getTargetInfo().getCXXABI().isMicrosoft() &&
"implicit complete dtors unneeded outside MS ABI") ? static_cast
<void> (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13360, __PRETTY_FUNCTION__))
;
13361 assert(ClassDecl->getNumVBases() > 0 &&((ClassDecl->getNumVBases() > 0 && "complete dtor only exists for classes with vbases"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13362, __PRETTY_FUNCTION__))
13362 "complete dtor only exists for classes with vbases")((ClassDecl->getNumVBases() > 0 && "complete dtor only exists for classes with vbases"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13362, __PRETTY_FUNCTION__))
;
13363
13364 SynthesizedFunctionScope Scope(*this, Destructor);
13365
13366 // Add a context note for diagnostics produced after this point.
13367 Scope.addContextNote(CurrentLocation);
13368
13369 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13370}
13371
13372/// Perform any semantic analysis which needs to be delayed until all
13373/// pending class member declarations have been parsed.
13374void Sema::ActOnFinishCXXMemberDecls() {
13375 // If the context is an invalid C++ class, just suppress these checks.
13376 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13377 if (Record->isInvalidDecl()) {
13378 DelayedOverridingExceptionSpecChecks.clear();
13379 DelayedEquivalentExceptionSpecChecks.clear();
13380 return;
13381 }
13382 checkForMultipleExportedDefaultConstructors(*this, Record);
13383 }
13384}
13385
13386void Sema::ActOnFinishCXXNonNestedClass() {
13387 referenceDLLExportedClassMethods();
13388
13389 if (!DelayedDllExportMemberFunctions.empty()) {
1
Taking true branch
13390 SmallVector<CXXMethodDecl*, 4> WorkList;
13391 std::swap(DelayedDllExportMemberFunctions, WorkList);
13392 for (CXXMethodDecl *M : WorkList) {
2
Assuming '__begin2' is not equal to '__end2'
13393 DefineDefaultedFunction(*this, M, M->getLocation());
3
Calling 'DefineDefaultedFunction'
13394
13395 // Pass the method to the consumer to get emitted. This is not necessary
13396 // for explicit instantiation definitions, as they will get emitted
13397 // anyway.
13398 if (M->getParent()->getTemplateSpecializationKind() !=
13399 TSK_ExplicitInstantiationDefinition)
13400 ActOnFinishInlineFunctionDef(M);
13401 }
13402 }
13403}
13404
13405void Sema::referenceDLLExportedClassMethods() {
13406 if (!DelayedDllExportClasses.empty()) {
13407 // Calling ReferenceDllExportedMembers might cause the current function to
13408 // be called again, so use a local copy of DelayedDllExportClasses.
13409 SmallVector<CXXRecordDecl *, 4> WorkList;
13410 std::swap(DelayedDllExportClasses, WorkList);
13411 for (CXXRecordDecl *Class : WorkList)
13412 ReferenceDllExportedMembers(*this, Class);
13413 }
13414}
13415
13416void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13417 assert(getLangOpts().CPlusPlus11 &&((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13418, __PRETTY_FUNCTION__))
13418 "adjusting dtor exception specs was introduced in c++11")((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13418, __PRETTY_FUNCTION__))
;
13419
13420 if (Destructor->isDependentContext())
13421 return;
13422
13423 // C++11 [class.dtor]p3:
13424 // A declaration of a destructor that does not have an exception-
13425 // specification is implicitly considered to have the same exception-
13426 // specification as an implicit declaration.
13427 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13428 if (DtorType->hasExceptionSpec())
13429 return;
13430
13431 // Replace the destructor's type, building off the existing one. Fortunately,
13432 // the only thing of interest in the destructor type is its extended info.
13433 // The return and arguments are fixed.
13434 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13435 EPI.ExceptionSpec.Type = EST_Unevaluated;
13436 EPI.ExceptionSpec.SourceDecl = Destructor;
13437 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13438
13439 // FIXME: If the destructor has a body that could throw, and the newly created
13440 // spec doesn't allow exceptions, we should emit a warning, because this
13441 // change in behavior can break conforming C++03 programs at runtime.
13442 // However, we don't have a body or an exception specification yet, so it
13443 // needs to be done somewhere else.
13444}
13445
13446namespace {
13447/// An abstract base class for all helper classes used in building the
13448// copy/move operators. These classes serve as factory functions and help us
13449// avoid using the same Expr* in the AST twice.
13450class ExprBuilder {
13451 ExprBuilder(const ExprBuilder&) = delete;
13452 ExprBuilder &operator=(const ExprBuilder&) = delete;
13453
13454protected:
13455 static Expr *assertNotNull(Expr *E) {
13456 assert(E && "Expression construction must not fail.")((E && "Expression construction must not fail.") ? static_cast
<void> (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13456, __PRETTY_FUNCTION__))
;
13457 return E;
13458 }
13459
13460public:
13461 ExprBuilder() {}
13462 virtual ~ExprBuilder() {}
13463
13464 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13465};
13466
13467class RefBuilder: public ExprBuilder {
13468 VarDecl *Var;
13469 QualType VarType;
13470
13471public:
13472 Expr *build(Sema &S, SourceLocation Loc) const override {
13473 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13474 }
13475
13476 RefBuilder(VarDecl *Var, QualType VarType)
13477 : Var(Var), VarType(VarType) {}
13478};
13479
13480class ThisBuilder: public ExprBuilder {
13481public:
13482 Expr *build(Sema &S, SourceLocation Loc) const override {
13483 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13484 }
13485};
13486
13487class CastBuilder: public ExprBuilder {
13488 const ExprBuilder &Builder;
13489 QualType Type;
13490 ExprValueKind Kind;
13491 const CXXCastPath &Path;
13492
13493public:
13494 Expr *build(Sema &S, SourceLocation Loc) const override {
13495 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13496 CK_UncheckedDerivedToBase, Kind,
13497 &Path).get());
13498 }
13499
13500 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13501 const CXXCastPath &Path)
13502 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13503};
13504
13505class DerefBuilder: public ExprBuilder {
13506 const ExprBuilder &Builder;
13507
13508public:
13509 Expr *build(Sema &S, SourceLocation Loc) const override {
13510 return assertNotNull(
13511 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13512 }
13513
13514 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13515};
13516
13517class MemberBuilder: public ExprBuilder {
13518 const ExprBuilder &Builder;
13519 QualType Type;
13520 CXXScopeSpec SS;
13521 bool IsArrow;
13522 LookupResult &MemberLookup;
13523
13524public:
13525 Expr *build(Sema &S, SourceLocation Loc) const override {
13526 return assertNotNull(S.BuildMemberReferenceExpr(
13527 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13528 nullptr, MemberLookup, nullptr, nullptr).get());
13529 }
13530
13531 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13532 LookupResult &MemberLookup)
13533 : Builder(Builder), Type(Type), IsArrow(IsArrow),
13534 MemberLookup(MemberLookup) {}
13535};
13536
13537class MoveCastBuilder: public ExprBuilder {
13538 const ExprBuilder &Builder;
13539
13540public:
13541 Expr *build(Sema &S, SourceLocation Loc) const override {
13542 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13543 }
13544
13545 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13546};
13547
13548class LvalueConvBuilder: public ExprBuilder {
13549 const ExprBuilder &Builder;
13550
13551public:
13552 Expr *build(Sema &S, SourceLocation Loc) const override {
13553 return assertNotNull(
13554 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13555 }
13556
13557 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13558};
13559
13560class SubscriptBuilder: public ExprBuilder {
13561 const ExprBuilder &Base;
13562 const ExprBuilder &Index;
13563
13564public:
13565 Expr *build(Sema &S, SourceLocation Loc) const override {
13566 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13567 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13568 }
13569
13570 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13571 : Base(Base), Index(Index) {}
13572};
13573
13574} // end anonymous namespace
13575
13576/// When generating a defaulted copy or move assignment operator, if a field
13577/// should be copied with __builtin_memcpy rather than via explicit assignments,
13578/// do so. This optimization only applies for arrays of scalars, and for arrays
13579/// of class type where the selected copy/move-assignment operator is trivial.
13580static StmtResult
13581buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13582 const ExprBuilder &ToB, const ExprBuilder &FromB) {
13583 // Compute the size of the memory buffer to be copied.
13584 QualType SizeType = S.Context.getSizeType();
13585 llvm::APInt Size(S.Context.getTypeSize(SizeType),
13586 S.Context.getTypeSizeInChars(T).getQuantity());
13587
13588 // Take the address of the field references for "from" and "to". We
13589 // directly construct UnaryOperators here because semantic analysis
13590 // does not permit us to take the address of an xvalue.
13591 Expr *From = FromB.build(S, Loc);
13592 From = UnaryOperator::Create(
13593 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13594 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13595 Expr *To = ToB.build(S, Loc);
13596 To = UnaryOperator::Create(
13597 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13598 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13599
13600 const Type *E = T->getBaseElementTypeUnsafe();
13601 bool NeedsCollectableMemCpy =
13602 E->isRecordType() &&
13603 E->castAs<RecordType>()->getDecl()->hasObjectMember();
13604
13605 // Create a reference to the __builtin_objc_memmove_collectable function
13606 StringRef MemCpyName = NeedsCollectableMemCpy ?
13607 "__builtin_objc_memmove_collectable" :
13608 "__builtin_memcpy";
13609 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13610 Sema::LookupOrdinaryName);
13611 S.LookupName(R, S.TUScope, true);
13612
13613 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13614 if (!MemCpy)
13615 // Something went horribly wrong earlier, and we will have complained
13616 // about it.
13617 return StmtError();
13618
13619 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13620 VK_RValue, Loc, nullptr);
13621 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")((MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? static_cast<void> (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13621, __PRETTY_FUNCTION__))
;
13622
13623 Expr *CallArgs[] = {
13624 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13625 };
13626 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13627 Loc, CallArgs, Loc);
13628
13629 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")((!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? static_cast<void> (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13629, __PRETTY_FUNCTION__))
;
13630 return Call.getAs<Stmt>();
13631}
13632
13633/// Builds a statement that copies/moves the given entity from \p From to
13634/// \c To.
13635///
13636/// This routine is used to copy/move the members of a class with an
13637/// implicitly-declared copy/move assignment operator. When the entities being
13638/// copied are arrays, this routine builds for loops to copy them.
13639///
13640/// \param S The Sema object used for type-checking.
13641///
13642/// \param Loc The location where the implicit copy/move is being generated.
13643///
13644/// \param T The type of the expressions being copied/moved. Both expressions
13645/// must have this type.
13646///
13647/// \param To The expression we are copying/moving to.
13648///
13649/// \param From The expression we are copying/moving from.
13650///
13651/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13652/// Otherwise, it's a non-static member subobject.
13653///
13654/// \param Copying Whether we're copying or moving.
13655///
13656/// \param Depth Internal parameter recording the depth of the recursion.
13657///
13658/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13659/// if a memcpy should be used instead.
13660static StmtResult
13661buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13662 const ExprBuilder &To, const ExprBuilder &From,
13663 bool CopyingBaseSubobject, bool Copying,
13664 unsigned Depth = 0) {
13665 // C++11 [class.copy]p28:
13666 // Each subobject is assigned in the manner appropriate to its type:
13667 //
13668 // - if the subobject is of class type, as if by a call to operator= with
13669 // the subobject as the object expression and the corresponding
13670 // subobject of x as a single function argument (as if by explicit
13671 // qualification; that is, ignoring any possible virtual overriding
13672 // functions in more derived classes);
13673 //
13674 // C++03 [class.copy]p13:
13675 // - if the subobject is of class type, the copy assignment operator for
13676 // the class is used (as if by explicit qualification; that is,
13677 // ignoring any possible virtual overriding functions in more derived
13678 // classes);
13679 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13680 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13681
13682 // Look for operator=.
13683 DeclarationName Name
13684 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13685 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13686 S.LookupQualifiedName(OpLookup, ClassDecl, false);
13687
13688 // Prior to C++11, filter out any result that isn't a copy/move-assignment
13689 // operator.
13690 if (!S.getLangOpts().CPlusPlus11) {
13691 LookupResult::Filter F = OpLookup.makeFilter();
13692 while (F.hasNext()) {
13693 NamedDecl *D = F.next();
13694 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13695 if (Method->isCopyAssignmentOperator() ||
13696 (!Copying && Method->isMoveAssignmentOperator()))
13697 continue;
13698
13699 F.erase();
13700 }
13701 F.done();
13702 }
13703
13704 // Suppress the protected check (C++ [class.protected]) for each of the
13705 // assignment operators we found. This strange dance is required when
13706 // we're assigning via a base classes's copy-assignment operator. To
13707 // ensure that we're getting the right base class subobject (without
13708 // ambiguities), we need to cast "this" to that subobject type; to
13709 // ensure that we don't go through the virtual call mechanism, we need
13710 // to qualify the operator= name with the base class (see below). However,
13711 // this means that if the base class has a protected copy assignment
13712 // operator, the protected member access check will fail. So, we
13713 // rewrite "protected" access to "public" access in this case, since we
13714 // know by construction that we're calling from a derived class.
13715 if (CopyingBaseSubobject) {
13716 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13717 L != LEnd; ++L) {
13718 if (L.getAccess() == AS_protected)
13719 L.setAccess(AS_public);
13720 }
13721 }
13722
13723 // Create the nested-name-specifier that will be used to qualify the
13724 // reference to operator=; this is required to suppress the virtual
13725 // call mechanism.
13726 CXXScopeSpec SS;
13727 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13728 SS.MakeTrivial(S.Context,
13729 NestedNameSpecifier::Create(S.Context, nullptr, false,
13730 CanonicalT),
13731 Loc);
13732
13733 // Create the reference to operator=.
13734 ExprResult OpEqualRef
13735 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13736 SS, /*TemplateKWLoc=*/SourceLocation(),
13737 /*FirstQualifierInScope=*/nullptr,
13738 OpLookup,
13739 /*TemplateArgs=*/nullptr, /*S*/nullptr,
13740 /*SuppressQualifierCheck=*/true);
13741 if (OpEqualRef.isInvalid())
13742 return StmtError();
13743
13744 // Build the call to the assignment operator.
13745
13746 Expr *FromInst = From.build(S, Loc);
13747 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13748 OpEqualRef.getAs<Expr>(),
13749 Loc, FromInst, Loc);
13750 if (Call.isInvalid())
13751 return StmtError();
13752
13753 // If we built a call to a trivial 'operator=' while copying an array,
13754 // bail out. We'll replace the whole shebang with a memcpy.
13755 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13756 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13757 return StmtResult((Stmt*)nullptr);
13758
13759 // Convert to an expression-statement, and clean up any produced
13760 // temporaries.
13761 return S.ActOnExprStmt(Call);
13762 }
13763
13764 // - if the subobject is of scalar type, the built-in assignment
13765 // operator is used.
13766 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13767 if (!ArrayTy) {
13768 ExprResult Assignment = S.CreateBuiltinBinOp(
13769 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13770 if (Assignment.isInvalid())
13771 return StmtError();
13772 return S.ActOnExprStmt(Assignment);
13773 }
13774
13775 // - if the subobject is an array, each element is assigned, in the
13776 // manner appropriate to the element type;
13777
13778 // Construct a loop over the array bounds, e.g.,
13779 //
13780 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13781 //
13782 // that will copy each of the array elements.
13783 QualType SizeType = S.Context.getSizeType();
13784
13785 // Create the iteration variable.
13786 IdentifierInfo *IterationVarName = nullptr;
13787 {
13788 SmallString<8> Str;
13789 llvm::raw_svector_ostream OS(Str);
13790 OS << "__i" << Depth;
13791 IterationVarName = &S.Context.Idents.get(OS.str());
13792 }
13793 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13794 IterationVarName, SizeType,
13795 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13796 SC_None);
13797
13798 // Initialize the iteration variable to zero.
13799 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13800 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13801
13802 // Creates a reference to the iteration variable.
13803 RefBuilder IterationVarRef(IterationVar, SizeType);
13804 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13805
13806 // Create the DeclStmt that holds the iteration variable.
13807 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13808
13809 // Subscript the "from" and "to" expressions with the iteration variable.
13810 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13811 MoveCastBuilder FromIndexMove(FromIndexCopy);
13812 const ExprBuilder *FromIndex;
13813 if (Copying)
13814 FromIndex = &FromIndexCopy;
13815 else
13816 FromIndex = &FromIndexMove;
13817
13818 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13819
13820 // Build the copy/move for an individual element of the array.
13821 StmtResult Copy =
13822 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13823 ToIndex, *FromIndex, CopyingBaseSubobject,
13824 Copying, Depth + 1);
13825 // Bail out if copying fails or if we determined that we should use memcpy.
13826 if (Copy.isInvalid() || !Copy.get())
13827 return Copy;
13828
13829 // Create the comparison against the array bound.
13830 llvm::APInt Upper
13831 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13832 Expr *Comparison = BinaryOperator::Create(
13833 S.Context, IterationVarRefRVal.build(S, Loc),
13834 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13835 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13836
13837 // Create the pre-increment of the iteration variable. We can determine
13838 // whether the increment will overflow based on the value of the array
13839 // bound.
13840 Expr *Increment = UnaryOperator::Create(
13841 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13842 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13843
13844 // Construct the loop that copies all elements of this array.
13845 return S.ActOnForStmt(
13846 Loc, Loc, InitStmt,
13847 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13848 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13849}
13850
13851static StmtResult
13852buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13853 const ExprBuilder &To, const ExprBuilder &From,
13854 bool CopyingBaseSubobject, bool Copying) {
13855 // Maybe we should use a memcpy?
13856 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13857 T.isTriviallyCopyableType(S.Context))
13858 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13859
13860 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13861 CopyingBaseSubobject,
13862 Copying, 0));
13863
13864 // If we ended up picking a trivial assignment operator for an array of a
13865 // non-trivially-copyable class type, just emit a memcpy.
13866 if (!Result.isInvalid() && !Result.get())
13867 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13868
13869 return Result;
13870}
13871
13872CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13873 // Note: The following rules are largely analoguous to the copy
13874 // constructor rules. Note that virtual bases are not taken into account
13875 // for determining the argument type of the operator. Note also that
13876 // operators taking an object instead of a reference are allowed.
13877 assert(ClassDecl->needsImplicitCopyAssignment())((ClassDecl->needsImplicitCopyAssignment()) ? static_cast<
void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13877, __PRETTY_FUNCTION__))
;
13878
13879 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13880 if (DSM.isAlreadyBeingDeclared())
13881 return nullptr;
13882
13883 QualType ArgType = Context.getTypeDeclType(ClassDecl);
13884 LangAS AS = getDefaultCXXMethodAddrSpace();
13885 if (AS != LangAS::Default)
13886 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13887 QualType RetType = Context.getLValueReferenceType(ArgType);
13888 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13889 if (Const)
13890 ArgType = ArgType.withConst();
13891
13892 ArgType = Context.getLValueReferenceType(ArgType);
13893
13894 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13895 CXXCopyAssignment,
13896 Const);
13897
13898 // An implicitly-declared copy assignment operator is an inline public
13899 // member of its class.
13900 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13901 SourceLocation ClassLoc = ClassDecl->getLocation();
13902 DeclarationNameInfo NameInfo(Name, ClassLoc);
13903 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13904 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13905 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13906 /*isInline=*/true,
13907 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
13908 SourceLocation());
13909 CopyAssignment->setAccess(AS_public);
13910 CopyAssignment->setDefaulted();
13911 CopyAssignment->setImplicit();
13912
13913 if (getLangOpts().CUDA) {
13914 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13915 CopyAssignment,
13916 /* ConstRHS */ Const,
13917 /* Diagnose */ false);
13918 }
13919
13920 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13921
13922 // Add the parameter to the operator.
13923 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13924 ClassLoc, ClassLoc,
13925 /*Id=*/nullptr, ArgType,
13926 /*TInfo=*/nullptr, SC_None,
13927 nullptr);
13928 CopyAssignment->setParams(FromParam);
13929
13930 CopyAssignment->setTrivial(
13931 ClassDecl->needsOverloadResolutionForCopyAssignment()
13932 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13933 : ClassDecl->hasTrivialCopyAssignment());
13934
13935 // Note that we have added this copy-assignment operator.
13936 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13937
13938 Scope *S = getScopeForContext(ClassDecl);
13939 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13940
13941 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13942 ClassDecl->setImplicitCopyAssignmentIsDeleted();
13943 SetDeclDeleted(CopyAssignment, ClassLoc);
13944 }
13945
13946 if (S)
13947 PushOnScopeChains(CopyAssignment, S, false);
13948 ClassDecl->addDecl(CopyAssignment);
13949
13950 return CopyAssignment;
13951}
13952
13953/// Diagnose an implicit copy operation for a class which is odr-used, but
13954/// which is deprecated because the class has a user-declared copy constructor,
13955/// copy assignment operator, or destructor.
13956static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13957 assert(CopyOp->isImplicit())((CopyOp->isImplicit()) ? static_cast<void> (0) : __assert_fail
("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13957, __PRETTY_FUNCTION__))
;
13958
13959 CXXRecordDecl *RD = CopyOp->getParent();
13960 CXXMethodDecl *UserDeclaredOperation = nullptr;
13961
13962 // In Microsoft mode, assignment operations don't affect constructors and
13963 // vice versa.
13964 if (RD->hasUserDeclaredDestructor()) {
13965 UserDeclaredOperation = RD->getDestructor();
13966 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13967 RD->hasUserDeclaredCopyConstructor() &&
13968 !S.getLangOpts().MSVCCompat) {
13969 // Find any user-declared copy constructor.
13970 for (auto *I : RD->ctors()) {
13971 if (I->isCopyConstructor()) {
13972 UserDeclaredOperation = I;
13973 break;
13974 }
13975 }
13976 assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail
("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13976, __PRETTY_FUNCTION__))
;
13977 } else if (isa<CXXConstructorDecl>(CopyOp) &&
13978 RD->hasUserDeclaredCopyAssignment() &&
13979 !S.getLangOpts().MSVCCompat) {
13980 // Find any user-declared move assignment operator.
13981 for (auto *I : RD->methods()) {
13982 if (I->isCopyAssignmentOperator()) {
13983 UserDeclaredOperation = I;
13984 break;
13985 }
13986 }
13987 assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail
("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 13987, __PRETTY_FUNCTION__))
;
13988 }
13989
13990 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13991 S.Diag(UserDeclaredOperation->getLocation(),
13992 isa<CXXDestructorDecl>(UserDeclaredOperation)
13993 ? diag::warn_deprecated_copy_dtor_operation
13994 : diag::warn_deprecated_copy_operation)
13995 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13996 }
13997}
13998
13999void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14000 CXXMethodDecl *CopyAssignOperator) {
14001 assert((CopyAssignOperator->isDefaulted() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14006, __PRETTY_FUNCTION__))
14002 CopyAssignOperator->isOverloadedOperator() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14006, __PRETTY_FUNCTION__))
14003 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14006, __PRETTY_FUNCTION__))
14004 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14006, __PRETTY_FUNCTION__))
14005 !CopyAssignOperator->isDeleted()) &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14006, __PRETTY_FUNCTION__))
14006 "DefineImplicitCopyAssignment called for wrong function")(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14006, __PRETTY_FUNCTION__))
;
14007 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14008 return;
14009
14010 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14011 if (ClassDecl->isInvalidDecl()) {
14012 CopyAssignOperator->setInvalidDecl();
14013 return;
14014 }
14015
14016 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14017
14018 // The exception specification is needed because we are defining the
14019 // function.
14020 ResolveExceptionSpec(CurrentLocation,
14021 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14022
14023 // Add a context note for diagnostics produced after this point.
14024 Scope.addContextNote(CurrentLocation);
14025
14026 // C++11 [class.copy]p18:
14027 // The [definition of an implicitly declared copy assignment operator] is
14028 // deprecated if the class has a user-declared copy constructor or a
14029 // user-declared destructor.
14030 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14031 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14032
14033 // C++0x [class.copy]p30:
14034 // The implicitly-defined or explicitly-defaulted copy assignment operator
14035 // for a non-union class X performs memberwise copy assignment of its
14036 // subobjects. The direct base classes of X are assigned first, in the
14037 // order of their declaration in the base-specifier-list, and then the
14038 // immediate non-static data members of X are assigned, in the order in
14039 // which they were declared in the class definition.
14040
14041 // The statements that form the synthesized function body.
14042 SmallVector<Stmt*, 8> Statements;
14043
14044 // The parameter for the "other" object, which we are copying from.
14045 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14046 Qualifiers OtherQuals = Other->getType().getQualifiers();
14047 QualType OtherRefType = Other->getType();
14048 if (const LValueReferenceType *OtherRef
14049 = OtherRefType->getAs<LValueReferenceType>()) {
14050 OtherRefType = OtherRef->getPointeeType();
14051 OtherQuals = OtherRefType.getQualifiers();
14052 }
14053
14054 // Our location for everything implicitly-generated.
14055 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14056 ? CopyAssignOperator->getEndLoc()
14057 : CopyAssignOperator->getLocation();
14058
14059 // Builds a DeclRefExpr for the "other" object.
14060 RefBuilder OtherRef(Other, OtherRefType);
14061
14062 // Builds the "this" pointer.
14063 ThisBuilder This;
14064
14065 // Assign base classes.
14066 bool Invalid = false;
14067 for (auto &Base : ClassDecl->bases()) {
14068 // Form the assignment:
14069 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14070 QualType BaseType = Base.getType().getUnqualifiedType();
14071 if (!BaseType->isRecordType()) {
14072 Invalid = true;
14073 continue;
14074 }
14075
14076 CXXCastPath BasePath;
14077 BasePath.push_back(&Base);
14078
14079 // Construct the "from" expression, which is an implicit cast to the
14080 // appropriately-qualified base type.
14081 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14082 VK_LValue, BasePath);
14083
14084 // Dereference "this".
14085 DerefBuilder DerefThis(This);
14086 CastBuilder To(DerefThis,
14087 Context.getQualifiedType(
14088 BaseType, CopyAssignOperator->getMethodQualifiers()),
14089 VK_LValue, BasePath);
14090
14091 // Build the copy.
14092 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14093 To, From,
14094 /*CopyingBaseSubobject=*/true,
14095 /*Copying=*/true);
14096 if (Copy.isInvalid()) {
14097 CopyAssignOperator->setInvalidDecl();
14098 return;
14099 }
14100
14101 // Success! Record the copy.
14102 Statements.push_back(Copy.getAs<Expr>());
14103 }
14104
14105 // Assign non-static members.
14106 for (auto *Field : ClassDecl->fields()) {
14107 // FIXME: We should form some kind of AST representation for the implied
14108 // memcpy in a union copy operation.
14109 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14110 continue;
14111
14112 if (Field->isInvalidDecl()) {
14113 Invalid = true;
14114 continue;
14115 }
14116
14117 // Check for members of reference type; we can't copy those.
14118 if (Field->getType()->isReferenceType()) {
14119 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14120 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14121 Diag(Field->getLocation(), diag::note_declared_at);
14122 Invalid = true;
14123 continue;
14124 }
14125
14126 // Check for members of const-qualified, non-class type.
14127 QualType BaseType = Context.getBaseElementType(Field->getType());
14128 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14129 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14130 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14131 Diag(Field->getLocation(), diag::note_declared_at);
14132 Invalid = true;
14133 continue;
14134 }
14135
14136 // Suppress assigning zero-width bitfields.
14137 if (Field->isZeroLengthBitField(Context))
14138 continue;
14139
14140 QualType FieldType = Field->getType().getNonReferenceType();
14141 if (FieldType->isIncompleteArrayType()) {
14142 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14143, __PRETTY_FUNCTION__))
14143 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14143, __PRETTY_FUNCTION__))
;
14144 continue;
14145 }
14146
14147 // Build references to the field in the object we're copying from and to.
14148 CXXScopeSpec SS; // Intentionally empty
14149 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14150 LookupMemberName);
14151 MemberLookup.addDecl(Field);
14152 MemberLookup.resolveKind();
14153
14154 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14155
14156 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14157
14158 // Build the copy of this field.
14159 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14160 To, From,
14161 /*CopyingBaseSubobject=*/false,
14162 /*Copying=*/true);
14163 if (Copy.isInvalid()) {
14164 CopyAssignOperator->setInvalidDecl();
14165 return;
14166 }
14167
14168 // Success! Record the copy.
14169 Statements.push_back(Copy.getAs<Stmt>());
14170 }
14171
14172 if (!Invalid) {
14173 // Add a "return *this;"
14174 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14175
14176 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14177 if (Return.isInvalid())
14178 Invalid = true;
14179 else
14180 Statements.push_back(Return.getAs<Stmt>());
14181 }
14182
14183 if (Invalid) {
14184 CopyAssignOperator->setInvalidDecl();
14185 return;
14186 }
14187
14188 StmtResult Body;
14189 {
14190 CompoundScopeRAII CompoundScope(*this);
14191 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14192 /*isStmtExpr=*/false);
14193 assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail"
) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14193, __PRETTY_FUNCTION__))
;
14194 }
14195 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14196 CopyAssignOperator->markUsed(Context);
14197
14198 if (ASTMutationListener *L = getASTMutationListener()) {
14199 L->CompletedImplicitDefinition(CopyAssignOperator);
14200 }
14201}
14202
14203CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14204 assert(ClassDecl->needsImplicitMoveAssignment())((ClassDecl->needsImplicitMoveAssignment()) ? static_cast<
void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14204, __PRETTY_FUNCTION__))
;
14205
14206 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14207 if (DSM.isAlreadyBeingDeclared())
14208 return nullptr;
14209
14210 // Note: The following rules are largely analoguous to the move
14211 // constructor rules.
14212
14213 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14214 LangAS AS = getDefaultCXXMethodAddrSpace();
14215 if (AS != LangAS::Default)
14216 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14217 QualType RetType = Context.getLValueReferenceType(ArgType);
14218 ArgType = Context.getRValueReferenceType(ArgType);
14219
14220 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14221 CXXMoveAssignment,
14222 false);
14223
14224 // An implicitly-declared move assignment operator is an inline public
14225 // member of its class.
14226 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14227 SourceLocation ClassLoc = ClassDecl->getLocation();
14228 DeclarationNameInfo NameInfo(Name, ClassLoc);
14229 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14230 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14231 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14232 /*isInline=*/true,
14233 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14234 SourceLocation());
14235 MoveAssignment->setAccess(AS_public);
14236 MoveAssignment->setDefaulted();
14237 MoveAssignment->setImplicit();
14238
14239 if (getLangOpts().CUDA) {
14240 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14241 MoveAssignment,
14242 /* ConstRHS */ false,
14243 /* Diagnose */ false);
14244 }
14245
14246 // Build an exception specification pointing back at this member.
14247 FunctionProtoType::ExtProtoInfo EPI =
14248 getImplicitMethodEPI(*this, MoveAssignment);
14249 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14250
14251 // Add the parameter to the operator.
14252 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14253 ClassLoc, ClassLoc,
14254 /*Id=*/nullptr, ArgType,
14255 /*TInfo=*/nullptr, SC_None,
14256 nullptr);
14257 MoveAssignment->setParams(FromParam);
14258
14259 MoveAssignment->setTrivial(
14260 ClassDecl->needsOverloadResolutionForMoveAssignment()
14261 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14262 : ClassDecl->hasTrivialMoveAssignment());
14263
14264 // Note that we have added this copy-assignment operator.
14265 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14266
14267 Scope *S = getScopeForContext(ClassDecl);
14268 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14269
14270 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14271 ClassDecl->setImplicitMoveAssignmentIsDeleted();
14272 SetDeclDeleted(MoveAssignment, ClassLoc);
14273 }
14274
14275 if (S)
14276 PushOnScopeChains(MoveAssignment, S, false);
14277 ClassDecl->addDecl(MoveAssignment);
14278
14279 return MoveAssignment;
14280}
14281
14282/// Check if we're implicitly defining a move assignment operator for a class
14283/// with virtual bases. Such a move assignment might move-assign the virtual
14284/// base multiple times.
14285static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14286 SourceLocation CurrentLocation) {
14287 assert(!Class->isDependentContext() && "should not define dependent move")((!Class->isDependentContext() && "should not define dependent move"
) ? static_cast<void> (0) : __assert_fail ("!Class->isDependentContext() && \"should not define dependent move\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14287, __PRETTY_FUNCTION__))
;
14288
14289 // Only a virtual base could get implicitly move-assigned multiple times.
14290 // Only a non-trivial move assignment can observe this. We only want to
14291 // diagnose if we implicitly define an assignment operator that assigns
14292 // two base classes, both of which move-assign the same virtual base.
14293 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14294 Class->getNumBases() < 2)
14295 return;
14296
14297 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14298 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14299 VBaseMap VBases;
14300
14301 for (auto &BI : Class->bases()) {
14302 Worklist.push_back(&BI);
14303 while (!Worklist.empty()) {
14304 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14305 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14306
14307 // If the base has no non-trivial move assignment operators,
14308 // we don't care about moves from it.
14309 if (!Base->hasNonTrivialMoveAssignment())
14310 continue;
14311
14312 // If there's nothing virtual here, skip it.
14313 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14314 continue;
14315
14316 // If we're not actually going to call a move assignment for this base,
14317 // or the selected move assignment is trivial, skip it.
14318 Sema::SpecialMemberOverloadResult SMOR =
14319 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14320 /*ConstArg*/false, /*VolatileArg*/false,
14321 /*RValueThis*/true, /*ConstThis*/false,
14322 /*VolatileThis*/false);
14323 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14324 !SMOR.getMethod()->isMoveAssignmentOperator())
14325 continue;
14326
14327 if (BaseSpec->isVirtual()) {
14328 // We're going to move-assign this virtual base, and its move
14329 // assignment operator is not trivial. If this can happen for
14330 // multiple distinct direct bases of Class, diagnose it. (If it
14331 // only happens in one base, we'll diagnose it when synthesizing
14332 // that base class's move assignment operator.)
14333 CXXBaseSpecifier *&Existing =
14334 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14335 .first->second;
14336 if (Existing && Existing != &BI) {
14337 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14338 << Class << Base;
14339 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14340 << (Base->getCanonicalDecl() ==
14341 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14342 << Base << Existing->getType() << Existing->getSourceRange();
14343 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14344 << (Base->getCanonicalDecl() ==
14345 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14346 << Base << BI.getType() << BaseSpec->getSourceRange();
14347
14348 // Only diagnose each vbase once.
14349 Existing = nullptr;
14350 }
14351 } else {
14352 // Only walk over bases that have defaulted move assignment operators.
14353 // We assume that any user-provided move assignment operator handles
14354 // the multiple-moves-of-vbase case itself somehow.
14355 if (!SMOR.getMethod()->isDefaulted())
14356 continue;
14357
14358 // We're going to move the base classes of Base. Add them to the list.
14359 for (auto &BI : Base->bases())
14360 Worklist.push_back(&BI);
14361 }
14362 }
14363 }
14364}
14365
14366void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14367 CXXMethodDecl *MoveAssignOperator) {
14368 assert((MoveAssignOperator->isDefaulted() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14373, __PRETTY_FUNCTION__))
14369 MoveAssignOperator->isOverloadedOperator() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14373, __PRETTY_FUNCTION__))
14370 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14373, __PRETTY_FUNCTION__))
14371 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14373, __PRETTY_FUNCTION__))
14372 !MoveAssignOperator->isDeleted()) &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14373, __PRETTY_FUNCTION__))
14373 "DefineImplicitMoveAssignment called for wrong function")(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14373, __PRETTY_FUNCTION__))
;
14374 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14375 return;
14376
14377 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14378 if (ClassDecl->isInvalidDecl()) {
14379 MoveAssignOperator->setInvalidDecl();
14380 return;
14381 }
14382
14383 // C++0x [class.copy]p28:
14384 // The implicitly-defined or move assignment operator for a non-union class
14385 // X performs memberwise move assignment of its subobjects. The direct base
14386 // classes of X are assigned first, in the order of their declaration in the
14387 // base-specifier-list, and then the immediate non-static data members of X
14388 // are assigned, in the order in which they were declared in the class
14389 // definition.
14390
14391 // Issue a warning if our implicit move assignment operator will move
14392 // from a virtual base more than once.
14393 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14394
14395 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14396
14397 // The exception specification is needed because we are defining the
14398 // function.
14399 ResolveExceptionSpec(CurrentLocation,
14400 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14401
14402 // Add a context note for diagnostics produced after this point.
14403 Scope.addContextNote(CurrentLocation);
14404
14405 // The statements that form the synthesized function body.
14406 SmallVector<Stmt*, 8> Statements;
14407
14408 // The parameter for the "other" object, which we are move from.
14409 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14410 QualType OtherRefType =
14411 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14412
14413 // Our location for everything implicitly-generated.
14414 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14415 ? MoveAssignOperator->getEndLoc()
14416 : MoveAssignOperator->getLocation();
14417
14418 // Builds a reference to the "other" object.
14419 RefBuilder OtherRef(Other, OtherRefType);
14420 // Cast to rvalue.
14421 MoveCastBuilder MoveOther(OtherRef);
14422
14423 // Builds the "this" pointer.
14424 ThisBuilder This;
14425
14426 // Assign base classes.
14427 bool Invalid = false;
14428 for (auto &Base : ClassDecl->bases()) {
14429 // C++11 [class.copy]p28:
14430 // It is unspecified whether subobjects representing virtual base classes
14431 // are assigned more than once by the implicitly-defined copy assignment
14432 // operator.
14433 // FIXME: Do not assign to a vbase that will be assigned by some other base
14434 // class. For a move-assignment, this can result in the vbase being moved
14435 // multiple times.
14436
14437 // Form the assignment:
14438 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14439 QualType BaseType = Base.getType().getUnqualifiedType();
14440 if (!BaseType->isRecordType()) {
14441 Invalid = true;
14442 continue;
14443 }
14444
14445 CXXCastPath BasePath;
14446 BasePath.push_back(&Base);
14447
14448 // Construct the "from" expression, which is an implicit cast to the
14449 // appropriately-qualified base type.
14450 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14451
14452 // Dereference "this".
14453 DerefBuilder DerefThis(This);
14454
14455 // Implicitly cast "this" to the appropriately-qualified base type.
14456 CastBuilder To(DerefThis,
14457 Context.getQualifiedType(
14458 BaseType, MoveAssignOperator->getMethodQualifiers()),
14459 VK_LValue, BasePath);
14460
14461 // Build the move.
14462 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14463 To, From,
14464 /*CopyingBaseSubobject=*/true,
14465 /*Copying=*/false);
14466 if (Move.isInvalid()) {
14467 MoveAssignOperator->setInvalidDecl();
14468 return;
14469 }
14470
14471 // Success! Record the move.
14472 Statements.push_back(Move.getAs<Expr>());
14473 }
14474
14475 // Assign non-static members.
14476 for (auto *Field : ClassDecl->fields()) {
14477 // FIXME: We should form some kind of AST representation for the implied
14478 // memcpy in a union copy operation.
14479 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14480 continue;
14481
14482 if (Field->isInvalidDecl()) {
14483 Invalid = true;
14484 continue;
14485 }
14486
14487 // Check for members of reference type; we can't move those.
14488 if (Field->getType()->isReferenceType()) {
14489 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14490 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14491 Diag(Field->getLocation(), diag::note_declared_at);
14492 Invalid = true;
14493 continue;
14494 }
14495
14496 // Check for members of const-qualified, non-class type.
14497 QualType BaseType = Context.getBaseElementType(Field->getType());
14498 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14499 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14500 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14501 Diag(Field->getLocation(), diag::note_declared_at);
14502 Invalid = true;
14503 continue;
14504 }
14505
14506 // Suppress assigning zero-width bitfields.
14507 if (Field->isZeroLengthBitField(Context))
14508 continue;
14509
14510 QualType FieldType = Field->getType().getNonReferenceType();
14511 if (FieldType->isIncompleteArrayType()) {
14512 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14513, __PRETTY_FUNCTION__))
14513 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14513, __PRETTY_FUNCTION__))
;
14514 continue;
14515 }
14516
14517 // Build references to the field in the object we're copying from and to.
14518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14519 LookupMemberName);
14520 MemberLookup.addDecl(Field);
14521 MemberLookup.resolveKind();
14522 MemberBuilder From(MoveOther, OtherRefType,
14523 /*IsArrow=*/false, MemberLookup);
14524 MemberBuilder To(This, getCurrentThisType(),
14525 /*IsArrow=*/true, MemberLookup);
14526
14527 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<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.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14529, __PRETTY_FUNCTION__))
14528 "Member reference with rvalue base must be rvalue except for reference "((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<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.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14529, __PRETTY_FUNCTION__))
14529 "members, which aren't allowed for move assignment.")((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<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.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14529, __PRETTY_FUNCTION__))
;
14530
14531 // Build the move of this field.
14532 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14533 To, From,
14534 /*CopyingBaseSubobject=*/false,
14535 /*Copying=*/false);
14536 if (Move.isInvalid()) {
14537 MoveAssignOperator->setInvalidDecl();
14538 return;
14539 }
14540
14541 // Success! Record the copy.
14542 Statements.push_back(Move.getAs<Stmt>());
14543 }
14544
14545 if (!Invalid) {
14546 // Add a "return *this;"
14547 ExprResult ThisObj =
14548 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14549
14550 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14551 if (Return.isInvalid())
14552 Invalid = true;
14553 else
14554 Statements.push_back(Return.getAs<Stmt>());
14555 }
14556
14557 if (Invalid) {
14558 MoveAssignOperator->setInvalidDecl();
14559 return;
14560 }
14561
14562 StmtResult Body;
14563 {
14564 CompoundScopeRAII CompoundScope(*this);
14565 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14566 /*isStmtExpr=*/false);
14567 assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail"
) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14567, __PRETTY_FUNCTION__))
;
14568 }
14569 MoveAssignOperator->setBody(Body.getAs<Stmt>());
14570 MoveAssignOperator->markUsed(Context);
14571
14572 if (ASTMutationListener *L = getASTMutationListener()) {
14573 L->CompletedImplicitDefinition(MoveAssignOperator);
14574 }
14575}
14576
14577CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14578 CXXRecordDecl *ClassDecl) {
14579 // C++ [class.copy]p4:
14580 // If the class definition does not explicitly declare a copy
14581 // constructor, one is declared implicitly.
14582 assert(ClassDecl->needsImplicitCopyConstructor())((ClassDecl->needsImplicitCopyConstructor()) ? static_cast
<void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14582, __PRETTY_FUNCTION__))
;
14583
14584 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14585 if (DSM.isAlreadyBeingDeclared())
14586 return nullptr;
14587
14588 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14589 QualType ArgType = ClassType;
14590 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14591 if (Const)
14592 ArgType = ArgType.withConst();
14593
14594 LangAS AS = getDefaultCXXMethodAddrSpace();
14595 if (AS != LangAS::Default)
14596 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14597
14598 ArgType = Context.getLValueReferenceType(ArgType);
14599
14600 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14601 CXXCopyConstructor,
14602 Const);
14603
14604 DeclarationName Name
14605 = Context.DeclarationNames.getCXXConstructorName(
14606 Context.getCanonicalType(ClassType));
14607 SourceLocation ClassLoc = ClassDecl->getLocation();
14608 DeclarationNameInfo NameInfo(Name, ClassLoc);
14609
14610 // An implicitly-declared copy constructor is an inline public
14611 // member of its class.
14612 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14613 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14614 ExplicitSpecifier(),
14615 /*isInline=*/true,
14616 /*isImplicitlyDeclared=*/true,
14617 Constexpr ? ConstexprSpecKind::Constexpr
14618 : ConstexprSpecKind::Unspecified);
14619 CopyConstructor->setAccess(AS_public);
14620 CopyConstructor->setDefaulted();
14621
14622 if (getLangOpts().CUDA) {
14623 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14624 CopyConstructor,
14625 /* ConstRHS */ Const,
14626 /* Diagnose */ false);
14627 }
14628
14629 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14630
14631 // Add the parameter to the constructor.
14632 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14633 ClassLoc, ClassLoc,
14634 /*IdentifierInfo=*/nullptr,
14635 ArgType, /*TInfo=*/nullptr,
14636 SC_None, nullptr);
14637 CopyConstructor->setParams(FromParam);
14638
14639 CopyConstructor->setTrivial(
14640 ClassDecl->needsOverloadResolutionForCopyConstructor()
14641 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14642 : ClassDecl->hasTrivialCopyConstructor());
14643
14644 CopyConstructor->setTrivialForCall(
14645 ClassDecl->hasAttr<TrivialABIAttr>() ||
14646 (ClassDecl->needsOverloadResolutionForCopyConstructor()
14647 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14648 TAH_ConsiderTrivialABI)
14649 : ClassDecl->hasTrivialCopyConstructorForCall()));
14650
14651 // Note that we have declared this constructor.
14652 ++getASTContext().NumImplicitCopyConstructorsDeclared;
14653
14654 Scope *S = getScopeForContext(ClassDecl);
14655 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14656
14657 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14658 ClassDecl->setImplicitCopyConstructorIsDeleted();
14659 SetDeclDeleted(CopyConstructor, ClassLoc);
14660 }
14661
14662 if (S)
14663 PushOnScopeChains(CopyConstructor, S, false);
14664 ClassDecl->addDecl(CopyConstructor);
14665
14666 return CopyConstructor;
14667}
14668
14669void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14670 CXXConstructorDecl *CopyConstructor) {
14671 assert((CopyConstructor->isDefaulted() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14675, __PRETTY_FUNCTION__))
14672 CopyConstructor->isCopyConstructor() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14675, __PRETTY_FUNCTION__))
14673 !CopyConstructor->doesThisDeclarationHaveABody() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14675, __PRETTY_FUNCTION__))
14674 !CopyConstructor->isDeleted()) &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14675, __PRETTY_FUNCTION__))
14675 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14675, __PRETTY_FUNCTION__))
;
14676 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14677 return;
14678
14679 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14680 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")((ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14680, __PRETTY_FUNCTION__))
;
14681
14682 SynthesizedFunctionScope Scope(*this, CopyConstructor);
14683
14684 // The exception specification is needed because we are defining the
14685 // function.
14686 ResolveExceptionSpec(CurrentLocation,
14687 CopyConstructor->getType()->castAs<FunctionProtoType>());
14688 MarkVTableUsed(CurrentLocation, ClassDecl);
14689
14690 // Add a context note for diagnostics produced after this point.
14691 Scope.addContextNote(CurrentLocation);
14692
14693 // C++11 [class.copy]p7:
14694 // The [definition of an implicitly declared copy constructor] is
14695 // deprecated if the class has a user-declared copy assignment operator
14696 // or a user-declared destructor.
14697 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14698 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14699
14700 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14701 CopyConstructor->setInvalidDecl();
14702 } else {
14703 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14704 ? CopyConstructor->getEndLoc()
14705 : CopyConstructor->getLocation();
14706 Sema::CompoundScopeRAII CompoundScope(*this);
14707 CopyConstructor->setBody(
14708 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14709 CopyConstructor->markUsed(Context);
14710 }
14711
14712 if (ASTMutationListener *L = getASTMutationListener()) {
14713 L->CompletedImplicitDefinition(CopyConstructor);
14714 }
14715}
14716
14717CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14718 CXXRecordDecl *ClassDecl) {
14719 assert(ClassDecl->needsImplicitMoveConstructor())((ClassDecl->needsImplicitMoveConstructor()) ? static_cast
<void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14719, __PRETTY_FUNCTION__))
;
14720
14721 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14722 if (DSM.isAlreadyBeingDeclared())
14723 return nullptr;
14724
14725 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14726
14727 QualType ArgType = ClassType;
14728 LangAS AS = getDefaultCXXMethodAddrSpace();
14729 if (AS != LangAS::Default)
14730 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14731 ArgType = Context.getRValueReferenceType(ArgType);
14732
14733 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14734 CXXMoveConstructor,
14735 false);
14736
14737 DeclarationName Name
14738 = Context.DeclarationNames.getCXXConstructorName(
14739 Context.getCanonicalType(ClassType));
14740 SourceLocation ClassLoc = ClassDecl->getLocation();
14741 DeclarationNameInfo NameInfo(Name, ClassLoc);
14742
14743 // C++11 [class.copy]p11:
14744 // An implicitly-declared copy/move constructor is an inline public
14745 // member of its class.
14746 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14747 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14748 ExplicitSpecifier(),
14749 /*isInline=*/true,
14750 /*isImplicitlyDeclared=*/true,
14751 Constexpr ? ConstexprSpecKind::Constexpr
14752 : ConstexprSpecKind::Unspecified);
14753 MoveConstructor->setAccess(AS_public);
14754 MoveConstructor->setDefaulted();
14755
14756 if (getLangOpts().CUDA) {
14757 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14758 MoveConstructor,
14759 /* ConstRHS */ false,
14760 /* Diagnose */ false);
14761 }
14762
14763 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14764
14765 // Add the parameter to the constructor.
14766 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14767 ClassLoc, ClassLoc,
14768 /*IdentifierInfo=*/nullptr,
14769 ArgType, /*TInfo=*/nullptr,
14770 SC_None, nullptr);
14771 MoveConstructor->setParams(FromParam);
14772
14773 MoveConstructor->setTrivial(
14774 ClassDecl->needsOverloadResolutionForMoveConstructor()
14775 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14776 : ClassDecl->hasTrivialMoveConstructor());
14777
14778 MoveConstructor->setTrivialForCall(
14779 ClassDecl->hasAttr<TrivialABIAttr>() ||
14780 (ClassDecl->needsOverloadResolutionForMoveConstructor()
14781 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14782 TAH_ConsiderTrivialABI)
14783 : ClassDecl->hasTrivialMoveConstructorForCall()));
14784
14785 // Note that we have declared this constructor.
14786 ++getASTContext().NumImplicitMoveConstructorsDeclared;
14787
14788 Scope *S = getScopeForContext(ClassDecl);
14789 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14790
14791 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14792 ClassDecl->setImplicitMoveConstructorIsDeleted();
14793 SetDeclDeleted(MoveConstructor, ClassLoc);
14794 }
14795
14796 if (S)
14797 PushOnScopeChains(MoveConstructor, S, false);
14798 ClassDecl->addDecl(MoveConstructor);
14799
14800 return MoveConstructor;
14801}
14802
14803void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14804 CXXConstructorDecl *MoveConstructor) {
14805 assert((MoveConstructor->isDefaulted() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14809, __PRETTY_FUNCTION__))
14806 MoveConstructor->isMoveConstructor() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14809, __PRETTY_FUNCTION__))
14807 !MoveConstructor->doesThisDeclarationHaveABody() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14809, __PRETTY_FUNCTION__))
14808 !MoveConstructor->isDeleted()) &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14809, __PRETTY_FUNCTION__))
14809 "DefineImplicitMoveConstructor - call it for implicit move ctor")(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14809, __PRETTY_FUNCTION__))
;
14810 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14811 return;
14812
14813 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14814 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")((ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14814, __PRETTY_FUNCTION__))
;
14815
14816 SynthesizedFunctionScope Scope(*this, MoveConstructor);
14817
14818 // The exception specification is needed because we are defining the
14819 // function.
14820 ResolveExceptionSpec(CurrentLocation,
14821 MoveConstructor->getType()->castAs<FunctionProtoType>());
14822 MarkVTableUsed(CurrentLocation, ClassDecl);
14823
14824 // Add a context note for diagnostics produced after this point.
14825 Scope.addContextNote(CurrentLocation);
14826
14827 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14828 MoveConstructor->setInvalidDecl();
14829 } else {
14830 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14831 ? MoveConstructor->getEndLoc()
14832 : MoveConstructor->getLocation();
14833 Sema::CompoundScopeRAII CompoundScope(*this);
14834 MoveConstructor->setBody(ActOnCompoundStmt(
14835 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14836 MoveConstructor->markUsed(Context);
14837 }
14838
14839 if (ASTMutationListener *L = getASTMutationListener()) {
14840 L->CompletedImplicitDefinition(MoveConstructor);
14841 }
14842}
14843
14844bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14845 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14846}
14847
14848void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14849 SourceLocation CurrentLocation,
14850 CXXConversionDecl *Conv) {
14851 SynthesizedFunctionScope Scope(*this, Conv);
14852 assert(!Conv->getReturnType()->isUndeducedType())((!Conv->getReturnType()->isUndeducedType()) ? static_cast
<void> (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14852, __PRETTY_FUNCTION__))
;
14853
14854 QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType();
14855 CallingConv CC =
14856 ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv();
14857
14858 CXXRecordDecl *Lambda = Conv->getParent();
14859 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14860 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14861
14862 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14863 CallOp = InstantiateFunctionDeclaration(
14864 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14865 if (!CallOp)
14866 return;
14867
14868 Invoker = InstantiateFunctionDeclaration(
14869 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14870 if (!Invoker)
14871 return;
14872 }
14873
14874 if (CallOp->isInvalidDecl())
14875 return;
14876
14877 // Mark the call operator referenced (and add to pending instantiations
14878 // if necessary).
14879 // For both the conversion and static-invoker template specializations
14880 // we construct their body's in this function, so no need to add them
14881 // to the PendingInstantiations.
14882 MarkFunctionReferenced(CurrentLocation, CallOp);
14883
14884 // Fill in the __invoke function with a dummy implementation. IR generation
14885 // will fill in the actual details. Update its type in case it contained
14886 // an 'auto'.
14887 Invoker->markUsed(Context);
14888 Invoker->setReferenced();
14889 Invoker->setType(Conv->getReturnType()->getPointeeType());
14890 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14891
14892 // Construct the body of the conversion function { return __invoke; }.
14893 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14894 VK_LValue, Conv->getLocation());
14895 assert(FunctionRef && "Can't refer to __invoke function?")((FunctionRef && "Can't refer to __invoke function?")
? static_cast<void> (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14895, __PRETTY_FUNCTION__))
;
14896 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14897 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14898 Conv->getLocation()));
14899 Conv->markUsed(Context);
14900 Conv->setReferenced();
14901
14902 if (ASTMutationListener *L = getASTMutationListener()) {
14903 L->CompletedImplicitDefinition(Conv);
14904 L->CompletedImplicitDefinition(Invoker);
14905 }
14906}
14907
14908
14909
14910void Sema::DefineImplicitLambdaToBlockPointerConversion(
14911 SourceLocation CurrentLocation,
14912 CXXConversionDecl *Conv)
14913{
14914 assert(!Conv->getParent()->isGenericLambda())((!Conv->getParent()->isGenericLambda()) ? static_cast<
void> (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 14914, __PRETTY_FUNCTION__))
;
14915
14916 SynthesizedFunctionScope Scope(*this, Conv);
14917
14918 // Copy-initialize the lambda object as needed to capture it.
14919 Expr *This = ActOnCXXThis(CurrentLocation).get();
14920 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14921
14922 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14923 Conv->getLocation(),
14924 Conv, DerefThis);
14925
14926 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14927 // behavior. Note that only the general conversion function does this
14928 // (since it's unusable otherwise); in the case where we inline the
14929 // block literal, it has block literal lifetime semantics.
14930 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14931 BuildBlock = ImplicitCastExpr::Create(
14932 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14933 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14934
14935 if (BuildBlock.isInvalid()) {
14936 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14937 Conv->setInvalidDecl();
14938 return;
14939 }
14940
14941 // Create the return statement that returns the block from the conversion
14942 // function.
14943 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14944 if (Return.isInvalid()) {
14945 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14946 Conv->setInvalidDecl();
14947 return;
14948 }
14949
14950 // Set the body of the conversion function.
14951 Stmt *ReturnS = Return.get();
14952 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14953 Conv->getLocation()));
14954 Conv->markUsed(Context);
14955
14956 // We're done; notify the mutation listener, if any.
14957 if (ASTMutationListener *L = getASTMutationListener()) {
14958 L->CompletedImplicitDefinition(Conv);
14959 }
14960}
14961
14962/// Determine whether the given list arguments contains exactly one
14963/// "real" (non-default) argument.
14964static bool hasOneRealArgument(MultiExprArg Args) {
14965 switch (Args.size()) {
14966 case 0:
14967 return false;
14968
14969 default:
14970 if (!Args[1]->isDefaultArgument())
14971 return false;
14972
14973 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14974 case 1:
14975 return !Args[0]->isDefaultArgument();
14976 }
14977
14978 return false;
14979}
14980
14981ExprResult
14982Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14983 NamedDecl *FoundDecl,
14984 CXXConstructorDecl *Constructor,
14985 MultiExprArg ExprArgs,
14986 bool HadMultipleCandidates,
14987 bool IsListInitialization,
14988 bool IsStdInitListInitialization,
14989 bool RequiresZeroInit,
14990 unsigned ConstructKind,
14991 SourceRange ParenRange) {
14992 bool Elidable = false;
14993
14994 // C++0x [class.copy]p34:
14995 // When certain criteria are met, an implementation is allowed to
14996 // omit the copy/move construction of a class object, even if the
14997 // copy/move constructor and/or destructor for the object have
14998 // side effects. [...]
14999 // - when a temporary class object that has not been bound to a
15000 // reference (12.2) would be copied/moved to a class object
15001 // with the same cv-unqualified type, the copy/move operation
15002 // can be omitted by constructing the temporary object
15003 // directly into the target of the omitted copy/move
15004 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15005 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15006 Expr *SubExpr = ExprArgs[0];
15007 Elidable = SubExpr->isTemporaryObject(
15008 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15009 }
15010
15011 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15012 FoundDecl, Constructor,
15013 Elidable, ExprArgs, HadMultipleCandidates,
15014 IsListInitialization,
15015 IsStdInitListInitialization, RequiresZeroInit,
15016 ConstructKind, ParenRange);
15017}
15018
15019ExprResult
15020Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15021 NamedDecl *FoundDecl,
15022 CXXConstructorDecl *Constructor,
15023 bool Elidable,
15024 MultiExprArg ExprArgs,
15025 bool HadMultipleCandidates,
15026 bool IsListInitialization,
15027 bool IsStdInitListInitialization,
15028 bool RequiresZeroInit,
15029 unsigned ConstructKind,
15030 SourceRange ParenRange) {
15031 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15032 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15033 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15034 return ExprError();
15035 }
15036
15037 return BuildCXXConstructExpr(
15038 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15039 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15040 RequiresZeroInit, ConstructKind, ParenRange);
15041}
15042
15043/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15044/// including handling of its default argument expressions.
15045ExprResult
15046Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15047 CXXConstructorDecl *Constructor,
15048 bool Elidable,
15049 MultiExprArg ExprArgs,
15050 bool HadMultipleCandidates,
15051 bool IsListInitialization,
15052 bool IsStdInitListInitialization,
15053 bool RequiresZeroInit,
15054 unsigned ConstructKind,
15055 SourceRange ParenRange) {
15056 assert(declaresSameEntity(((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15059, __PRETTY_FUNCTION__))
15057 Constructor->getParent(),((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15059, __PRETTY_FUNCTION__))
15058 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15059, __PRETTY_FUNCTION__))
15059 "given constructor for wrong type")((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15059, __PRETTY_FUNCTION__))
;
15060 MarkFunctionReferenced(ConstructLoc, Constructor);
15061 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15062 return ExprError();
15063 if (getLangOpts().SYCLIsDevice &&
15064 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15065 return ExprError();
15066
15067 return CheckForImmediateInvocation(
15068 CXXConstructExpr::Create(
15069 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15070 HadMultipleCandidates, IsListInitialization,
15071 IsStdInitListInitialization, RequiresZeroInit,
15072 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15073 ParenRange),
15074 Constructor);
15075}
15076
15077ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15078 assert(Field->hasInClassInitializer())((Field->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Field->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15078, __PRETTY_FUNCTION__))
;
15079
15080 // If we already have the in-class initializer nothing needs to be done.
15081 if (Field->getInClassInitializer())
15082 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15083
15084 // If we might have already tried and failed to instantiate, don't try again.
15085 if (Field->isInvalidDecl())
15086 return ExprError();
15087
15088 // Maybe we haven't instantiated the in-class initializer. Go check the
15089 // pattern FieldDecl to see if it has one.
15090 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15091
15092 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15093 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15094 DeclContext::lookup_result Lookup =
15095 ClassPattern->lookup(Field->getDeclName());
15096
15097 FieldDecl *Pattern = nullptr;
15098 for (auto L : Lookup) {
15099 if (isa<FieldDecl>(L)) {
15100 Pattern = cast<FieldDecl>(L);
15101 break;
15102 }
15103 }
15104 assert(Pattern && "We must have set the Pattern!")((Pattern && "We must have set the Pattern!") ? static_cast
<void> (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15104, __PRETTY_FUNCTION__))
;
15105
15106 if (!Pattern->hasInClassInitializer() ||
15107 InstantiateInClassInitializer(Loc, Field, Pattern,
15108 getTemplateInstantiationArgs(Field))) {
15109 // Don't diagnose this again.
15110 Field->setInvalidDecl();
15111 return ExprError();
15112 }
15113 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15114 }
15115
15116 // DR1351:
15117 // If the brace-or-equal-initializer of a non-static data member
15118 // invokes a defaulted default constructor of its class or of an
15119 // enclosing class in a potentially evaluated subexpression, the
15120 // program is ill-formed.
15121 //
15122 // This resolution is unworkable: the exception specification of the
15123 // default constructor can be needed in an unevaluated context, in
15124 // particular, in the operand of a noexcept-expression, and we can be
15125 // unable to compute an exception specification for an enclosed class.
15126 //
15127 // Any attempt to resolve the exception specification of a defaulted default
15128 // constructor before the initializer is lexically complete will ultimately
15129 // come here at which point we can diagnose it.
15130 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15131 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15132 << OutermostClass << Field;
15133 Diag(Field->getEndLoc(),
15134 diag::note_default_member_initializer_not_yet_parsed);
15135 // Recover by marking the field invalid, unless we're in a SFINAE context.
15136 if (!isSFINAEContext())
15137 Field->setInvalidDecl();
15138 return ExprError();
15139}
15140
15141void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15142 if (VD->isInvalidDecl()) return;
15143 // If initializing the variable failed, don't also diagnose problems with
15144 // the desctructor, they're likely related.
15145 if (VD->getInit() && VD->getInit()->containsErrors())
15146 return;
15147
15148 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15149 if (ClassDecl->isInvalidDecl()) return;
15150 if (ClassDecl->hasIrrelevantDestructor()) return;
15151 if (ClassDecl->isDependentContext()) return;
15152
15153 if (VD->isNoDestroy(getASTContext()))
15154 return;
15155
15156 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15157
15158 // If this is an array, we'll require the destructor during initialization, so
15159 // we can skip over this. We still want to emit exit-time destructor warnings
15160 // though.
15161 if (!VD->getType()->isArrayType()) {
15162 MarkFunctionReferenced(VD->getLocation(), Destructor);
15163 CheckDestructorAccess(VD->getLocation(), Destructor,
15164 PDiag(diag::err_access_dtor_var)
15165 << VD->getDeclName() << VD->getType());
15166 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15167 }
15168
15169 if (Destructor->isTrivial()) return;
15170
15171 // If the destructor is constexpr, check whether the variable has constant
15172 // destruction now.
15173 if (Destructor->isConstexpr()) {
15174 bool HasConstantInit = false;
15175 if (VD->getInit() && !VD->getInit()->isValueDependent())
15176 HasConstantInit = VD->evaluateValue();
15177 SmallVector<PartialDiagnosticAt, 8> Notes;
15178 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15179 HasConstantInit) {
15180 Diag(VD->getLocation(),
15181 diag::err_constexpr_var_requires_const_destruction) << VD;
15182 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15183 Diag(Notes[I].first, Notes[I].second);
15184 }
15185 }
15186
15187 if (!VD->hasGlobalStorage()) return;
15188
15189 // Emit warning for non-trivial dtor in global scope (a real global,
15190 // class-static, function-static).
15191 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15192
15193 // TODO: this should be re-enabled for static locals by !CXAAtExit
15194 if (!VD->isStaticLocal())
15195 Diag(VD->getLocation(), diag::warn_global_destructor);
15196}
15197
15198/// Given a constructor and the set of arguments provided for the
15199/// constructor, convert the arguments and add any required default arguments
15200/// to form a proper call to this constructor.
15201///
15202/// \returns true if an error occurred, false otherwise.
15203bool
15204Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15205 MultiExprArg ArgsPtr,
15206 SourceLocation Loc,
15207 SmallVectorImpl<Expr*> &ConvertedArgs,
15208 bool AllowExplicit,
15209 bool IsListInitialization) {
15210 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15211 unsigned NumArgs = ArgsPtr.size();
15212 Expr **Args = ArgsPtr.data();
15213
15214 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15215 unsigned NumParams = Proto->getNumParams();
15216
15217 // If too few arguments are available, we'll fill in the rest with defaults.
15218 if (NumArgs < NumParams)
15219 ConvertedArgs.reserve(NumParams);
15220 else
15221 ConvertedArgs.reserve(NumArgs);
15222
15223 VariadicCallType CallType =
15224 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15225 SmallVector<Expr *, 8> AllArgs;
15226 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15227 Proto, 0,
15228 llvm::makeArrayRef(Args, NumArgs),
15229 AllArgs,
15230 CallType, AllowExplicit,
15231 IsListInitialization);
15232 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15233
15234 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15235
15236 CheckConstructorCall(Constructor,
15237 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15238 Proto, Loc);
15239
15240 return Invalid;
15241}
15242
15243static inline bool
15244CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15245 const FunctionDecl *FnDecl) {
15246 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15247 if (isa<NamespaceDecl>(DC)) {
15248 return SemaRef.Diag(FnDecl->getLocation(),
15249 diag::err_operator_new_delete_declared_in_namespace)
15250 << FnDecl->getDeclName();
15251 }
15252
15253 if (isa<TranslationUnitDecl>(DC) &&
15254 FnDecl->getStorageClass() == SC_Static) {
15255 return SemaRef.Diag(FnDecl->getLocation(),
15256 diag::err_operator_new_delete_declared_static)
15257 << FnDecl->getDeclName();
15258 }
15259
15260 return false;
15261}
15262
15263static QualType
15264RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15265 QualType QTy = PtrTy->getPointeeType();
15266 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15267 return SemaRef.Context.getPointerType(QTy);
15268}
15269
15270static inline bool
15271CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15272 CanQualType ExpectedResultType,
15273 CanQualType ExpectedFirstParamType,
15274 unsigned DependentParamTypeDiag,
15275 unsigned InvalidParamTypeDiag) {
15276 QualType ResultType =
15277 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15278
15279 // The operator is valid on any address space for OpenCL.
15280 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15281 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15282 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15283 }
15284 }
15285
15286 // Check that the result type is what we expect.
15287 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15288 // Reject even if the type is dependent; an operator delete function is
15289 // required to have a non-dependent result type.
15290 return SemaRef.Diag(
15291 FnDecl->getLocation(),
15292 ResultType->isDependentType()
15293 ? diag::err_operator_new_delete_dependent_result_type
15294 : diag::err_operator_new_delete_invalid_result_type)
15295 << FnDecl->getDeclName() << ExpectedResultType;
15296 }
15297
15298 // A function template must have at least 2 parameters.
15299 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15300 return SemaRef.Diag(FnDecl->getLocation(),
15301 diag::err_operator_new_delete_template_too_few_parameters)
15302 << FnDecl->getDeclName();
15303
15304 // The function decl must have at least 1 parameter.
15305 if (FnDecl->getNumParams() == 0)
15306 return SemaRef.Diag(FnDecl->getLocation(),
15307 diag::err_operator_new_delete_too_few_parameters)
15308 << FnDecl->getDeclName();
15309
15310 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15311 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15312 // The operator is valid on any address space for OpenCL.
15313 if (auto *PtrTy =
15314 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15315 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15316 }
15317 }
15318
15319 // Check that the first parameter type is what we expect.
15320 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15321 ExpectedFirstParamType) {
15322 // The first parameter type is not allowed to be dependent. As a tentative
15323 // DR resolution, we allow a dependent parameter type if it is the right
15324 // type anyway, to allow destroying operator delete in class templates.
15325 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15326 ? DependentParamTypeDiag
15327 : InvalidParamTypeDiag)
15328 << FnDecl->getDeclName() << ExpectedFirstParamType;
15329 }
15330
15331 return false;
15332}
15333
15334static bool
15335CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15336 // C++ [basic.stc.dynamic.allocation]p1:
15337 // A program is ill-formed if an allocation function is declared in a
15338 // namespace scope other than global scope or declared static in global
15339 // scope.
15340 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15341 return true;
15342
15343 CanQualType SizeTy =
15344 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15345
15346 // C++ [basic.stc.dynamic.allocation]p1:
15347 // The return type shall be void*. The first parameter shall have type
15348 // std::size_t.
15349 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15350 SizeTy,
15351 diag::err_operator_new_dependent_param_type,
15352 diag::err_operator_new_param_type))
15353 return true;
15354
15355 // C++ [basic.stc.dynamic.allocation]p1:
15356 // The first parameter shall not have an associated default argument.
15357 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15358 return SemaRef.Diag(FnDecl->getLocation(),
15359 diag::err_operator_new_default_arg)
15360 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15361
15362 return false;
15363}
15364
15365static bool
15366CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15367 // C++ [basic.stc.dynamic.deallocation]p1:
15368 // A program is ill-formed if deallocation functions are declared in a
15369 // namespace scope other than global scope or declared static in global
15370 // scope.
15371 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15372 return true;
15373
15374 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15375
15376 // C++ P0722:
15377 // Within a class C, the first parameter of a destroying operator delete
15378 // shall be of type C *. The first parameter of any other deallocation
15379 // function shall be of type void *.
15380 CanQualType ExpectedFirstParamType =
15381 MD && MD->isDestroyingOperatorDelete()
15382 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15383 SemaRef.Context.getRecordType(MD->getParent())))
15384 : SemaRef.Context.VoidPtrTy;
15385
15386 // C++ [basic.stc.dynamic.deallocation]p2:
15387 // Each deallocation function shall return void
15388 if (CheckOperatorNewDeleteTypes(
15389 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15390 diag::err_operator_delete_dependent_param_type,
15391 diag::err_operator_delete_param_type))
15392 return true;
15393
15394 // C++ P0722:
15395 // A destroying operator delete shall be a usual deallocation function.
15396 if (MD && !MD->getParent()->isDependentContext() &&
15397 MD->isDestroyingOperatorDelete() &&
15398 !SemaRef.isUsualDeallocationFunction(MD)) {
15399 SemaRef.Diag(MD->getLocation(),
15400 diag::err_destroying_operator_delete_not_usual);
15401 return true;
15402 }
15403
15404 return false;
15405}
15406
15407/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15408/// of this overloaded operator is well-formed. If so, returns false;
15409/// otherwise, emits appropriate diagnostics and returns true.
15410bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15411 assert(FnDecl && FnDecl->isOverloadedOperator() &&((FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration") ? static_cast
<void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15412, __PRETTY_FUNCTION__))
15412 "Expected an overloaded operator declaration")((FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration") ? static_cast
<void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15412, __PRETTY_FUNCTION__))
;
15413
15414 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15415
15416 // C++ [over.oper]p5:
15417 // The allocation and deallocation functions, operator new,
15418 // operator new[], operator delete and operator delete[], are
15419 // described completely in 3.7.3. The attributes and restrictions
15420 // found in the rest of this subclause do not apply to them unless
15421 // explicitly stated in 3.7.3.
15422 if (Op == OO_Delete || Op == OO_Array_Delete)
15423 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15424
15425 if (Op == OO_New || Op == OO_Array_New)
15426 return CheckOperatorNewDeclaration(*this, FnDecl);
15427
15428 // C++ [over.oper]p6:
15429 // An operator function shall either be a non-static member
15430 // function or be a non-member function and have at least one
15431 // parameter whose type is a class, a reference to a class, an
15432 // enumeration, or a reference to an enumeration.
15433 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15434 if (MethodDecl->isStatic())
15435 return Diag(FnDecl->getLocation(),
15436 diag::err_operator_overload_static) << FnDecl->getDeclName();
15437 } else {
15438 bool ClassOrEnumParam = false;
15439 for (auto Param : FnDecl->parameters()) {
15440 QualType ParamType = Param->getType().getNonReferenceType();
15441 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15442 ParamType->isEnumeralType()) {
15443 ClassOrEnumParam = true;
15444 break;
15445 }
15446 }
15447
15448 if (!ClassOrEnumParam)
15449 return Diag(FnDecl->getLocation(),
15450 diag::err_operator_overload_needs_class_or_enum)
15451 << FnDecl->getDeclName();
15452 }
15453
15454 // C++ [over.oper]p8:
15455 // An operator function cannot have default arguments (8.3.6),
15456 // except where explicitly stated below.
15457 //
15458 // Only the function-call operator allows default arguments
15459 // (C++ [over.call]p1).
15460 if (Op != OO_Call) {
15461 for (auto Param : FnDecl->parameters()) {
15462 if (Param->hasDefaultArg())
15463 return Diag(Param->getLocation(),
15464 diag::err_operator_overload_default_arg)
15465 << FnDecl->getDeclName() << Param->getDefaultArgRange();
15466 }
15467 }
15468
15469 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15470 { false, false, false }
15471#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15472 , { Unary, Binary, MemberOnly }
15473#include "clang/Basic/OperatorKinds.def"
15474 };
15475
15476 bool CanBeUnaryOperator = OperatorUses[Op][0];
15477 bool CanBeBinaryOperator = OperatorUses[Op][1];
15478 bool MustBeMemberOperator = OperatorUses[Op][2];
15479
15480 // C++ [over.oper]p8:
15481 // [...] Operator functions cannot have more or fewer parameters
15482 // than the number required for the corresponding operator, as
15483 // described in the rest of this subclause.
15484 unsigned NumParams = FnDecl->getNumParams()
15485 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15486 if (Op != OO_Call &&
15487 ((NumParams == 1 && !CanBeUnaryOperator) ||
15488 (NumParams == 2 && !CanBeBinaryOperator) ||
15489 (NumParams < 1) || (NumParams > 2))) {
15490 // We have the wrong number of parameters.
15491 unsigned ErrorKind;
15492 if (CanBeUnaryOperator && CanBeBinaryOperator) {
15493 ErrorKind = 2; // 2 -> unary or binary.
15494 } else if (CanBeUnaryOperator) {
15495 ErrorKind = 0; // 0 -> unary
15496 } else {
15497 assert(CanBeBinaryOperator &&((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15498, __PRETTY_FUNCTION__))
15498 "All non-call overloaded operators are unary or binary!")((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15498, __PRETTY_FUNCTION__))
;
15499 ErrorKind = 1; // 1 -> binary
15500 }
15501
15502 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15503 << FnDecl->getDeclName() << NumParams << ErrorKind;
15504 }
15505
15506 // Overloaded operators other than operator() cannot be variadic.
15507 if (Op != OO_Call &&
15508 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15509 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15510 << FnDecl->getDeclName();
15511 }
15512
15513 // Some operators must be non-static member functions.
15514 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15515 return Diag(FnDecl->getLocation(),
15516 diag::err_operator_overload_must_be_member)
15517 << FnDecl->getDeclName();
15518 }
15519
15520 // C++ [over.inc]p1:
15521 // The user-defined function called operator++ implements the
15522 // prefix and postfix ++ operator. If this function is a member
15523 // function with no parameters, or a non-member function with one
15524 // parameter of class or enumeration type, it defines the prefix
15525 // increment operator ++ for objects of that type. If the function
15526 // is a member function with one parameter (which shall be of type
15527 // int) or a non-member function with two parameters (the second
15528 // of which shall be of type int), it defines the postfix
15529 // increment operator ++ for objects of that type.
15530 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15531 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15532 QualType ParamType = LastParam->getType();
15533
15534 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15535 !ParamType->isDependentType())
15536 return Diag(LastParam->getLocation(),
15537 diag::err_operator_overload_post_incdec_must_be_int)
15538 << LastParam->getType() << (Op == OO_MinusMinus);
15539 }
15540
15541 return false;
15542}
15543
15544static bool
15545checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15546 FunctionTemplateDecl *TpDecl) {
15547 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15548
15549 // Must have one or two template parameters.
15550 if (TemplateParams->size() == 1) {
15551 NonTypeTemplateParmDecl *PmDecl =
15552 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15553
15554 // The template parameter must be a char parameter pack.
15555 if (PmDecl && PmDecl->isTemplateParameterPack() &&
15556 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15557 return false;
15558
15559 // C++20 [over.literal]p5:
15560 // A string literal operator template is a literal operator template
15561 // whose template-parameter-list comprises a single non-type
15562 // template-parameter of class type.
15563 //
15564 // As a DR resolution, we also allow placeholders for deduced class
15565 // template specializations.
15566 if (SemaRef.getLangOpts().CPlusPlus20 &&
15567 !PmDecl->isTemplateParameterPack() &&
15568 (PmDecl->getType()->isRecordType() ||
15569 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15570 return false;
15571 } else if (TemplateParams->size() == 2) {
15572 TemplateTypeParmDecl *PmType =
15573 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15574 NonTypeTemplateParmDecl *PmArgs =
15575 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15576
15577 // The second template parameter must be a parameter pack with the
15578 // first template parameter as its type.
15579 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15580 PmArgs->isTemplateParameterPack()) {
15581 const TemplateTypeParmType *TArgs =
15582 PmArgs->getType()->getAs<TemplateTypeParmType>();
15583 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15584 TArgs->getIndex() == PmType->getIndex()) {
15585 if (!SemaRef.inTemplateInstantiation())
15586 SemaRef.Diag(TpDecl->getLocation(),
15587 diag::ext_string_literal_operator_template);
15588 return false;
15589 }
15590 }
15591 }
15592
15593 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15594 diag::err_literal_operator_template)
15595 << TpDecl->getTemplateParameters()->getSourceRange();
15596 return true;
15597}
15598
15599/// CheckLiteralOperatorDeclaration - Check whether the declaration
15600/// of this literal operator function is well-formed. If so, returns
15601/// false; otherwise, emits appropriate diagnostics and returns true.
15602bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15603 if (isa<CXXMethodDecl>(FnDecl)) {
15604 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15605 << FnDecl->getDeclName();
15606 return true;
15607 }
15608
15609 if (FnDecl->isExternC()) {
15610 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15611 if (const LinkageSpecDecl *LSD =
15612 FnDecl->getDeclContext()->getExternCContext())
15613 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15614 return true;
15615 }
15616
15617 // This might be the definition of a literal operator template.
15618 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15619
15620 // This might be a specialization of a literal operator template.
15621 if (!TpDecl)
15622 TpDecl = FnDecl->getPrimaryTemplate();
15623
15624 // template <char...> type operator "" name() and
15625 // template <class T, T...> type operator "" name() are the only valid
15626 // template signatures, and the only valid signatures with no parameters.
15627 //
15628 // C++20 also allows template <SomeClass T> type operator "" name().
15629 if (TpDecl) {
15630 if (FnDecl->param_size() != 0) {
15631 Diag(FnDecl->getLocation(),
15632 diag::err_literal_operator_template_with_params);
15633 return true;
15634 }
15635
15636 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15637 return true;
15638
15639 } else if (FnDecl->param_size() == 1) {
15640 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15641
15642 QualType ParamType = Param->getType().getUnqualifiedType();
15643
15644 // Only unsigned long long int, long double, any character type, and const
15645 // char * are allowed as the only parameters.
15646 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15647 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15648 Context.hasSameType(ParamType, Context.CharTy) ||
15649 Context.hasSameType(ParamType, Context.WideCharTy) ||
15650 Context.hasSameType(ParamType, Context.Char8Ty) ||
15651 Context.hasSameType(ParamType, Context.Char16Ty) ||
15652 Context.hasSameType(ParamType, Context.Char32Ty)) {
15653 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15654 QualType InnerType = Ptr->getPointeeType();
15655
15656 // Pointer parameter must be a const char *.
15657 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15658 Context.CharTy) &&
15659 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15660 Diag(Param->getSourceRange().getBegin(),
15661 diag::err_literal_operator_param)
15662 << ParamType << "'const char *'" << Param->getSourceRange();
15663 return true;
15664 }
15665
15666 } else if (ParamType->isRealFloatingType()) {
15667 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15668 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15669 return true;
15670
15671 } else if (ParamType->isIntegerType()) {
15672 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15673 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15674 return true;
15675
15676 } else {
15677 Diag(Param->getSourceRange().getBegin(),
15678 diag::err_literal_operator_invalid_param)
15679 << ParamType << Param->getSourceRange();
15680 return true;
15681 }
15682
15683 } else if (FnDecl->param_size() == 2) {
15684 FunctionDecl::param_iterator Param = FnDecl->param_begin();
15685
15686 // First, verify that the first parameter is correct.
15687
15688 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15689
15690 // Two parameter function must have a pointer to const as a
15691 // first parameter; let's strip those qualifiers.
15692 const PointerType *PT = FirstParamType->getAs<PointerType>();
15693
15694 if (!PT) {
15695 Diag((*Param)->getSourceRange().getBegin(),
15696 diag::err_literal_operator_param)
15697 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15698 return true;
15699 }
15700
15701 QualType PointeeType = PT->getPointeeType();
15702 // First parameter must be const
15703 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15704 Diag((*Param)->getSourceRange().getBegin(),
15705 diag::err_literal_operator_param)
15706 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15707 return true;
15708 }
15709
15710 QualType InnerType = PointeeType.getUnqualifiedType();
15711 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15712 // const char32_t* are allowed as the first parameter to a two-parameter
15713 // function
15714 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15715 Context.hasSameType(InnerType, Context.WideCharTy) ||
15716 Context.hasSameType(InnerType, Context.Char8Ty) ||
15717 Context.hasSameType(InnerType, Context.Char16Ty) ||
15718 Context.hasSameType(InnerType, Context.Char32Ty))) {
15719 Diag((*Param)->getSourceRange().getBegin(),
15720 diag::err_literal_operator_param)
15721 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15722 return true;
15723 }
15724
15725 // Move on to the second and final parameter.
15726 ++Param;
15727
15728 // The second parameter must be a std::size_t.
15729 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15730 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15731 Diag((*Param)->getSourceRange().getBegin(),
15732 diag::err_literal_operator_param)
15733 << SecondParamType << Context.getSizeType()
15734 << (*Param)->getSourceRange();
15735 return true;
15736 }
15737 } else {
15738 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15739 return true;
15740 }
15741
15742 // Parameters are good.
15743
15744 // A parameter-declaration-clause containing a default argument is not
15745 // equivalent to any of the permitted forms.
15746 for (auto Param : FnDecl->parameters()) {
15747 if (Param->hasDefaultArg()) {
15748 Diag(Param->getDefaultArgRange().getBegin(),
15749 diag::err_literal_operator_default_argument)
15750 << Param->getDefaultArgRange();
15751 break;
15752 }
15753 }
15754
15755 StringRef LiteralName
15756 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15757 if (LiteralName[0] != '_' &&
15758 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15759 // C++11 [usrlit.suffix]p1:
15760 // Literal suffix identifiers that do not start with an underscore
15761 // are reserved for future standardization.
15762 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15763 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15764 }
15765
15766 return false;
15767}
15768
15769/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15770/// linkage specification, including the language and (if present)
15771/// the '{'. ExternLoc is the location of the 'extern', Lang is the
15772/// language string literal. LBraceLoc, if valid, provides the location of
15773/// the '{' brace. Otherwise, this linkage specification does not
15774/// have any braces.
15775Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15776 Expr *LangStr,
15777 SourceLocation LBraceLoc) {
15778 StringLiteral *Lit = cast<StringLiteral>(LangStr);
15779 if (!Lit->isAscii()) {
15780 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15781 << LangStr->getSourceRange();
15782 return nullptr;
15783 }
15784
15785 StringRef Lang = Lit->getString();
15786 LinkageSpecDecl::LanguageIDs Language;
15787 if (Lang == "C")
15788 Language = LinkageSpecDecl::lang_c;
15789 else if (Lang == "C++")
15790 Language = LinkageSpecDecl::lang_cxx;
15791 else {
15792 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15793 << LangStr->getSourceRange();
15794 return nullptr;
15795 }
15796
15797 // FIXME: Add all the various semantics of linkage specifications
15798
15799 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15800 LangStr->getExprLoc(), Language,
15801 LBraceLoc.isValid());
15802 CurContext->addDecl(D);
15803 PushDeclContext(S, D);
15804 return D;
15805}
15806
15807/// ActOnFinishLinkageSpecification - Complete the definition of
15808/// the C++ linkage specification LinkageSpec. If RBraceLoc is
15809/// valid, it's the position of the closing '}' brace in a linkage
15810/// specification that uses braces.
15811Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15812 Decl *LinkageSpec,
15813 SourceLocation RBraceLoc) {
15814 if (RBraceLoc.isValid()) {
15815 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15816 LSDecl->setRBraceLoc(RBraceLoc);
15817 }
15818 PopDeclContext();
15819 return LinkageSpec;
15820}
15821
15822Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15823 const ParsedAttributesView &AttrList,
15824 SourceLocation SemiLoc) {
15825 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15826 // Attribute declarations appertain to empty declaration so we handle
15827 // them here.
15828 ProcessDeclAttributeList(S, ED, AttrList);
15829
15830 CurContext->addDecl(ED);
15831 return ED;
15832}
15833
15834/// Perform semantic analysis for the variable declaration that
15835/// occurs within a C++ catch clause, returning the newly-created
15836/// variable.
15837VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15838 TypeSourceInfo *TInfo,
15839 SourceLocation StartLoc,
15840 SourceLocation Loc,
15841 IdentifierInfo *Name) {
15842 bool Invalid = false;
15843 QualType ExDeclType = TInfo->getType();
15844
15845 // Arrays and functions decay.
15846 if (ExDeclType->isArrayType())
15847 ExDeclType = Context.getArrayDecayedType(ExDeclType);
15848 else if (ExDeclType->isFunctionType())
15849 ExDeclType = Context.getPointerType(ExDeclType);
15850
15851 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15852 // The exception-declaration shall not denote a pointer or reference to an
15853 // incomplete type, other than [cv] void*.
15854 // N2844 forbids rvalue references.
15855 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15856 Diag(Loc, diag::err_catch_rvalue_ref);
15857 Invalid = true;
15858 }
15859
15860 if (ExDeclType->isVariablyModifiedType()) {
15861 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15862 Invalid = true;
15863 }
15864
15865 QualType BaseType = ExDeclType;
15866 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15867 unsigned DK = diag::err_catch_incomplete;
15868 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15869 BaseType = Ptr->getPointeeType();
15870 Mode = 1;
15871 DK = diag::err_catch_incomplete_ptr;
15872 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15873 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15874 BaseType = Ref->getPointeeType();
15875 Mode = 2;
15876 DK = diag::err_catch_incomplete_ref;
15877 }
15878 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15879 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15880 Invalid = true;
15881
15882 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15883 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15884 Invalid = true;
15885 }
15886
15887 if (!Invalid && !ExDeclType->isDependentType() &&
15888 RequireNonAbstractType(Loc, ExDeclType,
15889 diag::err_abstract_type_in_decl,
15890 AbstractVariableType))
15891 Invalid = true;
15892
15893 // Only the non-fragile NeXT runtime currently supports C++ catches
15894 // of ObjC types, and no runtime supports catching ObjC types by value.
15895 if (!Invalid && getLangOpts().ObjC) {
15896 QualType T = ExDeclType;
15897 if (const ReferenceType *RT = T->getAs<ReferenceType>())
15898 T = RT->getPointeeType();
15899
15900 if (T->isObjCObjectType()) {
15901 Diag(Loc, diag::err_objc_object_catch);
15902 Invalid = true;
15903 } else if (T->isObjCObjectPointerType()) {
15904 // FIXME: should this be a test for macosx-fragile specifically?
15905 if (getLangOpts().ObjCRuntime.isFragile())
15906 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15907 }
15908 }
15909
15910 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15911 ExDeclType, TInfo, SC_None);
15912 ExDecl->setExceptionVariable(true);
15913
15914 // In ARC, infer 'retaining' for variables of retainable type.
15915 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15916 Invalid = true;
15917
15918 if (!Invalid && !ExDeclType->isDependentType()) {
15919 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15920 // Insulate this from anything else we might currently be parsing.
15921 EnterExpressionEvaluationContext scope(
15922 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15923
15924 // C++ [except.handle]p16:
15925 // The object declared in an exception-declaration or, if the
15926 // exception-declaration does not specify a name, a temporary (12.2) is
15927 // copy-initialized (8.5) from the exception object. [...]
15928 // The object is destroyed when the handler exits, after the destruction
15929 // of any automatic objects initialized within the handler.
15930 //
15931 // We just pretend to initialize the object with itself, then make sure
15932 // it can be destroyed later.
15933 QualType initType = Context.getExceptionObjectType(ExDeclType);
15934
15935 InitializedEntity entity =
15936 InitializedEntity::InitializeVariable(ExDecl);
15937 InitializationKind initKind =
15938 InitializationKind::CreateCopy(Loc, SourceLocation());
15939
15940 Expr *opaqueValue =
15941 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15942 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15943 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15944 if (result.isInvalid())
15945 Invalid = true;
15946 else {
15947 // If the constructor used was non-trivial, set this as the
15948 // "initializer".
15949 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15950 if (!construct->getConstructor()->isTrivial()) {
15951 Expr *init = MaybeCreateExprWithCleanups(construct);
15952 ExDecl->setInit(init);
15953 }
15954
15955 // And make sure it's destructable.
15956 FinalizeVarWithDestructor(ExDecl, recordType);
15957 }
15958 }
15959 }
15960
15961 if (Invalid)
15962 ExDecl->setInvalidDecl();
15963
15964 return ExDecl;
15965}
15966
15967/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15968/// handler.
15969Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15970 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15971 bool Invalid = D.isInvalidType();
15972
15973 // Check for unexpanded parameter packs.
15974 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15975 UPPC_ExceptionType)) {
15976 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15977 D.getIdentifierLoc());
15978 Invalid = true;
15979 }
15980
15981 IdentifierInfo *II = D.getIdentifier();
15982 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15983 LookupOrdinaryName,
15984 ForVisibleRedeclaration)) {
15985 // The scope should be freshly made just for us. There is just no way
15986 // it contains any previous declaration, except for function parameters in
15987 // a function-try-block's catch statement.
15988 assert(!S->isDeclScope(PrevDecl))((!S->isDeclScope(PrevDecl)) ? static_cast<void> (0)
: __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 15988, __PRETTY_FUNCTION__))
;
15989 if (isDeclInScope(PrevDecl, CurContext, S)) {
15990 Diag(D.getIdentifierLoc(), diag::err_redefinition)
15991 << D.getIdentifier();
15992 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15993 Invalid = true;
15994 } else if (PrevDecl->isTemplateParameter())
15995 // Maybe we will complain about the shadowed template parameter.
15996 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15997 }
15998
15999 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16000 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16001 << D.getCXXScopeSpec().getRange();
16002 Invalid = true;
16003 }
16004
16005 VarDecl *ExDecl = BuildExceptionDeclaration(
16006 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16007 if (Invalid)
16008 ExDecl->setInvalidDecl();
16009
16010 // Add the exception declaration into this scope.
16011 if (II)
16012 PushOnScopeChains(ExDecl, S);
16013 else
16014 CurContext->addDecl(ExDecl);
16015
16016 ProcessDeclAttributes(S, ExDecl, D);
16017 return ExDecl;
16018}
16019
16020Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16021 Expr *AssertExpr,
16022 Expr *AssertMessageExpr,
16023 SourceLocation RParenLoc) {
16024 StringLiteral *AssertMessage =
16025 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16026
16027 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16028 return nullptr;
16029
16030 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16031 AssertMessage, RParenLoc, false);
16032}
16033
16034Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16035 Expr *AssertExpr,
16036 StringLiteral *AssertMessage,
16037 SourceLocation RParenLoc,
16038 bool Failed) {
16039 assert(AssertExpr != nullptr && "Expected non-null condition")((AssertExpr != nullptr && "Expected non-null condition"
) ? static_cast<void> (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16039, __PRETTY_FUNCTION__))
;
16040 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16041 !Failed) {
16042 // In a static_assert-declaration, the constant-expression shall be a
16043 // constant expression that can be contextually converted to bool.
16044 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16045 if (Converted.isInvalid())
16046 Failed = true;
16047
16048 ExprResult FullAssertExpr =
16049 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16050 /*DiscardedValue*/ false,
16051 /*IsConstexpr*/ true);
16052 if (FullAssertExpr.isInvalid())
16053 Failed = true;
16054 else
16055 AssertExpr = FullAssertExpr.get();
16056
16057 llvm::APSInt Cond;
16058 if (!Failed && VerifyIntegerConstantExpression(
16059 AssertExpr, &Cond,
16060 diag::err_static_assert_expression_is_not_constant)
16061 .isInvalid())
16062 Failed = true;
16063
16064 if (!Failed && !Cond) {
16065 SmallString<256> MsgBuffer;
16066 llvm::raw_svector_ostream Msg(MsgBuffer);
16067 if (AssertMessage)
16068 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16069
16070 Expr *InnerCond = nullptr;
16071 std::string InnerCondDescription;
16072 std::tie(InnerCond, InnerCondDescription) =
16073 findFailedBooleanCondition(Converted.get());
16074 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16075 // Drill down into concept specialization expressions to see why they
16076 // weren't satisfied.
16077 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16078 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16079 ConstraintSatisfaction Satisfaction;
16080 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16081 DiagnoseUnsatisfiedConstraint(Satisfaction);
16082 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16083 && !isa<IntegerLiteral>(InnerCond)) {
16084 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16085 << InnerCondDescription << !AssertMessage
16086 << Msg.str() << InnerCond->getSourceRange();
16087 } else {
16088 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16089 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16090 }
16091 Failed = true;
16092 }
16093 } else {
16094 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16095 /*DiscardedValue*/false,
16096 /*IsConstexpr*/true);
16097 if (FullAssertExpr.isInvalid())
16098 Failed = true;
16099 else
16100 AssertExpr = FullAssertExpr.get();
16101 }
16102
16103 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16104 AssertExpr, AssertMessage, RParenLoc,
16105 Failed);
16106
16107 CurContext->addDecl(Decl);
16108 return Decl;
16109}
16110
16111/// Perform semantic analysis of the given friend type declaration.
16112///
16113/// \returns A friend declaration that.
16114FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16115 SourceLocation FriendLoc,
16116 TypeSourceInfo *TSInfo) {
16117 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")((TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? static_cast<void> (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16117, __PRETTY_FUNCTION__))
;
16118
16119 QualType T = TSInfo->getType();
16120 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16121
16122 // C++03 [class.friend]p2:
16123 // An elaborated-type-specifier shall be used in a friend declaration
16124 // for a class.*
16125 //
16126 // * The class-key of the elaborated-type-specifier is required.
16127 if (!CodeSynthesisContexts.empty()) {
16128 // Do not complain about the form of friend template types during any kind
16129 // of code synthesis. For template instantiation, we will have complained
16130 // when the template was defined.
16131 } else {
16132 if (!T->isElaboratedTypeSpecifier()) {
16133 // If we evaluated the type to a record type, suggest putting
16134 // a tag in front.
16135 if (const RecordType *RT = T->getAs<RecordType>()) {
16136 RecordDecl *RD = RT->getDecl();
16137
16138 SmallString<16> InsertionText(" ");
16139 InsertionText += RD->getKindName();
16140
16141 Diag(TypeRange.getBegin(),
16142 getLangOpts().CPlusPlus11 ?
16143 diag::warn_cxx98_compat_unelaborated_friend_type :
16144 diag::ext_unelaborated_friend_type)
16145 << (unsigned) RD->getTagKind()
16146 << T
16147 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16148 InsertionText);
16149 } else {
16150 Diag(FriendLoc,
16151 getLangOpts().CPlusPlus11 ?
16152 diag::warn_cxx98_compat_nonclass_type_friend :
16153 diag::ext_nonclass_type_friend)
16154 << T
16155 << TypeRange;
16156 }
16157 } else if (T->getAs<EnumType>()) {
16158 Diag(FriendLoc,
16159 getLangOpts().CPlusPlus11 ?
16160 diag::warn_cxx98_compat_enum_friend :
16161 diag::ext_enum_friend)
16162 << T
16163 << TypeRange;
16164 }
16165
16166 // C++11 [class.friend]p3:
16167 // A friend declaration that does not declare a function shall have one
16168 // of the following forms:
16169 // friend elaborated-type-specifier ;
16170 // friend simple-type-specifier ;
16171 // friend typename-specifier ;
16172 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16173 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16174 }
16175
16176 // If the type specifier in a friend declaration designates a (possibly
16177 // cv-qualified) class type, that class is declared as a friend; otherwise,
16178 // the friend declaration is ignored.
16179 return FriendDecl::Create(Context, CurContext,
16180 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16181 FriendLoc);
16182}
16183
16184/// Handle a friend tag declaration where the scope specifier was
16185/// templated.
16186Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16187 unsigned TagSpec, SourceLocation TagLoc,
16188 CXXScopeSpec &SS, IdentifierInfo *Name,
16189 SourceLocation NameLoc,
16190 const ParsedAttributesView &Attr,
16191 MultiTemplateParamsArg TempParamLists) {
16192 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16193
16194 bool IsMemberSpecialization = false;
16195 bool Invalid = false;
16196
16197 if (TemplateParameterList *TemplateParams =
16198 MatchTemplateParametersToScopeSpecifier(
16199 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16200 IsMemberSpecialization, Invalid)) {
16201 if (TemplateParams->size() > 0) {
16202 // This is a declaration of a class template.
16203 if (Invalid)
16204 return nullptr;
16205
16206 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16207 NameLoc, Attr, TemplateParams, AS_public,
16208 /*ModulePrivateLoc=*/SourceLocation(),
16209 FriendLoc, TempParamLists.size() - 1,
16210 TempParamLists.data()).get();
16211 } else {
16212 // The "template<>" header is extraneous.
16213 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16214 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16215 IsMemberSpecialization = true;
16216 }
16217 }
16218
16219 if (Invalid) return nullptr;
16220
16221 bool isAllExplicitSpecializations = true;
16222 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16223 if (TempParamLists[I]->size()) {
16224 isAllExplicitSpecializations = false;
16225 break;
16226 }
16227 }
16228
16229 // FIXME: don't ignore attributes.
16230
16231 // If it's explicit specializations all the way down, just forget
16232 // about the template header and build an appropriate non-templated
16233 // friend. TODO: for source fidelity, remember the headers.
16234 if (isAllExplicitSpecializations) {
16235 if (SS.isEmpty()) {
16236 bool Owned = false;
16237 bool IsDependent = false;
16238 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16239 Attr, AS_public,
16240 /*ModulePrivateLoc=*/SourceLocation(),
16241 MultiTemplateParamsArg(), Owned, IsDependent,
16242 /*ScopedEnumKWLoc=*/SourceLocation(),
16243 /*ScopedEnumUsesClassTag=*/false,
16244 /*UnderlyingType=*/TypeResult(),
16245 /*IsTypeSpecifier=*/false,
16246 /*IsTemplateParamOrArg=*/false);
16247 }
16248
16249 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16250 ElaboratedTypeKeyword Keyword
16251 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16252 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16253 *Name, NameLoc);
16254 if (T.isNull())
16255 return nullptr;
16256
16257 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16258 if (isa<DependentNameType>(T)) {
16259 DependentNameTypeLoc TL =
16260 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16261 TL.setElaboratedKeywordLoc(TagLoc);
16262 TL.setQualifierLoc(QualifierLoc);
16263 TL.setNameLoc(NameLoc);
16264 } else {
16265 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16266 TL.setElaboratedKeywordLoc(TagLoc);
16267 TL.setQualifierLoc(QualifierLoc);
16268 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16269 }
16270
16271 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16272 TSI, FriendLoc, TempParamLists);
16273 Friend->setAccess(AS_public);
16274 CurContext->addDecl(Friend);
16275 return Friend;
16276 }
16277
16278 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")((SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? static_cast<void> (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16278, __PRETTY_FUNCTION__))
;
16279
16280
16281
16282 // Handle the case of a templated-scope friend class. e.g.
16283 // template <class T> class A<T>::B;
16284 // FIXME: we don't support these right now.
16285 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16286 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16287 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16288 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16289 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16290 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16291 TL.setElaboratedKeywordLoc(TagLoc);
16292 TL.setQualifierLoc(SS.getWithLocInContext(Context));
16293 TL.setNameLoc(NameLoc);
16294
16295 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16296 TSI, FriendLoc, TempParamLists);
16297 Friend->setAccess(AS_public);
16298 Friend->setUnsupportedFriend(true);
16299 CurContext->addDecl(Friend);
16300 return Friend;
16301}
16302
16303/// Handle a friend type declaration. This works in tandem with
16304/// ActOnTag.
16305///
16306/// Notes on friend class templates:
16307///
16308/// We generally treat friend class declarations as if they were
16309/// declaring a class. So, for example, the elaborated type specifier
16310/// in a friend declaration is required to obey the restrictions of a
16311/// class-head (i.e. no typedefs in the scope chain), template
16312/// parameters are required to match up with simple template-ids, &c.
16313/// However, unlike when declaring a template specialization, it's
16314/// okay to refer to a template specialization without an empty
16315/// template parameter declaration, e.g.
16316/// friend class A<T>::B<unsigned>;
16317/// We permit this as a special case; if there are any template
16318/// parameters present at all, require proper matching, i.e.
16319/// template <> template \<class T> friend class A<int>::B;
16320Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16321 MultiTemplateParamsArg TempParams) {
16322 SourceLocation Loc = DS.getBeginLoc();
16323
16324 assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16324, __PRETTY_FUNCTION__))
;
16325 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast
<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16325, __PRETTY_FUNCTION__))
;
16326
16327 // C++ [class.friend]p3:
16328 // A friend declaration that does not declare a function shall have one of
16329 // the following forms:
16330 // friend elaborated-type-specifier ;
16331 // friend simple-type-specifier ;
16332 // friend typename-specifier ;
16333 //
16334 // Any declaration with a type qualifier does not have that form. (It's
16335 // legal to specify a qualified type as a friend, you just can't write the
16336 // keywords.)
16337 if (DS.getTypeQualifiers()) {
16338 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16339 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16340 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16341 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16342 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16343 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16344 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16345 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16346 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16347 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16348 }
16349
16350 // Try to convert the decl specifier to a type. This works for
16351 // friend templates because ActOnTag never produces a ClassTemplateDecl
16352 // for a TUK_Friend.
16353 Declarator TheDeclarator(DS, DeclaratorContext::Member);
16354 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16355 QualType T = TSI->getType();
16356 if (TheDeclarator.isInvalidType())
16357 return nullptr;
16358
16359 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16360 return nullptr;
16361
16362 // This is definitely an error in C++98. It's probably meant to
16363 // be forbidden in C++0x, too, but the specification is just
16364 // poorly written.
16365 //
16366 // The problem is with declarations like the following:
16367 // template <T> friend A<T>::foo;
16368 // where deciding whether a class C is a friend or not now hinges
16369 // on whether there exists an instantiation of A that causes
16370 // 'foo' to equal C. There are restrictions on class-heads
16371 // (which we declare (by fiat) elaborated friend declarations to
16372 // be) that makes this tractable.
16373 //
16374 // FIXME: handle "template <> friend class A<T>;", which
16375 // is possibly well-formed? Who even knows?
16376 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16377 Diag(Loc, diag::err_tagless_friend_type_template)
16378 << DS.getSourceRange();
16379 return nullptr;
16380 }
16381
16382 // C++98 [class.friend]p1: A friend of a class is a function
16383 // or class that is not a member of the class . . .
16384 // This is fixed in DR77, which just barely didn't make the C++03
16385 // deadline. It's also a very silly restriction that seriously
16386 // affects inner classes and which nobody else seems to implement;
16387 // thus we never diagnose it, not even in -pedantic.
16388 //
16389 // But note that we could warn about it: it's always useless to
16390 // friend one of your own members (it's not, however, worthless to
16391 // friend a member of an arbitrary specialization of your template).
16392
16393 Decl *D;
16394 if (!TempParams.empty())
16395 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16396 TempParams,
16397 TSI,
16398 DS.getFriendSpecLoc());
16399 else
16400 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16401
16402 if (!D)
16403 return nullptr;
16404
16405 D->setAccess(AS_public);
16406 CurContext->addDecl(D);
16407
16408 return D;
16409}
16410
16411NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16412 MultiTemplateParamsArg TemplateParams) {
16413 const DeclSpec &DS = D.getDeclSpec();
16414
16415 assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16415, __PRETTY_FUNCTION__))
;
16416 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast
<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16416, __PRETTY_FUNCTION__))
;
16417
16418 SourceLocation Loc = D.getIdentifierLoc();
16419 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16420
16421 // C++ [class.friend]p1
16422 // A friend of a class is a function or class....
16423 // Note that this sees through typedefs, which is intended.
16424 // It *doesn't* see through dependent types, which is correct
16425 // according to [temp.arg.type]p3:
16426 // If a declaration acquires a function type through a
16427 // type dependent on a template-parameter and this causes
16428 // a declaration that does not use the syntactic form of a
16429 // function declarator to have a function type, the program
16430 // is ill-formed.
16431 if (!TInfo->getType()->isFunctionType()) {
16432 Diag(Loc, diag::err_unexpected_friend);
16433
16434 // It might be worthwhile to try to recover by creating an
16435 // appropriate declaration.
16436 return nullptr;
16437 }
16438
16439 // C++ [namespace.memdef]p3
16440 // - If a friend declaration in a non-local class first declares a
16441 // class or function, the friend class or function is a member
16442 // of the innermost enclosing namespace.
16443 // - The name of the friend is not found by simple name lookup
16444 // until a matching declaration is provided in that namespace
16445 // scope (either before or after the class declaration granting
16446 // friendship).
16447 // - If a friend function is called, its name may be found by the
16448 // name lookup that considers functions from namespaces and
16449 // classes associated with the types of the function arguments.
16450 // - When looking for a prior declaration of a class or a function
16451 // declared as a friend, scopes outside the innermost enclosing
16452 // namespace scope are not considered.
16453
16454 CXXScopeSpec &SS = D.getCXXScopeSpec();
16455 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16456 assert(NameInfo.getName())((NameInfo.getName()) ? static_cast<void> (0) : __assert_fail
("NameInfo.getName()", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16456, __PRETTY_FUNCTION__))
;
16457
16458 // Check for unexpanded parameter packs.
16459 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16460 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16461 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16462 return nullptr;
16463
16464 // The context we found the declaration in, or in which we should
16465 // create the declaration.
16466 DeclContext *DC;
16467 Scope *DCScope = S;
16468 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16469 ForExternalRedeclaration);
16470
16471 // There are five cases here.
16472 // - There's no scope specifier and we're in a local class. Only look
16473 // for functions declared in the immediately-enclosing block scope.
16474 // We recover from invalid scope qualifiers as if they just weren't there.
16475 FunctionDecl *FunctionContainingLocalClass = nullptr;
16476 if ((SS.isInvalid() || !SS.isSet()) &&
16477 (FunctionContainingLocalClass =
16478 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16479 // C++11 [class.friend]p11:
16480 // If a friend declaration appears in a local class and the name
16481 // specified is an unqualified name, a prior declaration is
16482 // looked up without considering scopes that are outside the
16483 // innermost enclosing non-class scope. For a friend function
16484 // declaration, if there is no prior declaration, the program is
16485 // ill-formed.
16486
16487 // Find the innermost enclosing non-class scope. This is the block
16488 // scope containing the local class definition (or for a nested class,
16489 // the outer local class).
16490 DCScope = S->getFnParent();
16491
16492 // Look up the function name in the scope.
16493 Previous.clear(LookupLocalFriendName);
16494 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16495
16496 if (!Previous.empty()) {
16497 // All possible previous declarations must have the same context:
16498 // either they were declared at block scope or they are members of
16499 // one of the enclosing local classes.
16500 DC = Previous.getRepresentativeDecl()->getDeclContext();
16501 } else {
16502 // This is ill-formed, but provide the context that we would have
16503 // declared the function in, if we were permitted to, for error recovery.
16504 DC = FunctionContainingLocalClass;
16505 }
16506 adjustContextForLocalExternDecl(DC);
16507
16508 // C++ [class.friend]p6:
16509 // A function can be defined in a friend declaration of a class if and
16510 // only if the class is a non-local class (9.8), the function name is
16511 // unqualified, and the function has namespace scope.
16512 if (D.isFunctionDefinition()) {
16513 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16514 }
16515
16516 // - There's no scope specifier, in which case we just go to the
16517 // appropriate scope and look for a function or function template
16518 // there as appropriate.
16519 } else if (SS.isInvalid() || !SS.isSet()) {
16520 // C++11 [namespace.memdef]p3:
16521 // If the name in a friend declaration is neither qualified nor
16522 // a template-id and the declaration is a function or an
16523 // elaborated-type-specifier, the lookup to determine whether
16524 // the entity has been previously declared shall not consider
16525 // any scopes outside the innermost enclosing namespace.
16526 bool isTemplateId =
16527 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16528
16529 // Find the appropriate context according to the above.
16530 DC = CurContext;
16531
16532 // Skip class contexts. If someone can cite chapter and verse
16533 // for this behavior, that would be nice --- it's what GCC and
16534 // EDG do, and it seems like a reasonable intent, but the spec
16535 // really only says that checks for unqualified existing
16536 // declarations should stop at the nearest enclosing namespace,
16537 // not that they should only consider the nearest enclosing
16538 // namespace.
16539 while (DC->isRecord())
16540 DC = DC->getParent();
16541
16542 DeclContext *LookupDC = DC;
16543 while (LookupDC->isTransparentContext())
16544 LookupDC = LookupDC->getParent();
16545
16546 while (true) {
16547 LookupQualifiedName(Previous, LookupDC);
16548
16549 if (!Previous.empty()) {
16550 DC = LookupDC;
16551 break;
16552 }
16553
16554 if (isTemplateId) {
16555 if (isa<TranslationUnitDecl>(LookupDC)) break;
16556 } else {
16557 if (LookupDC->isFileContext()) break;
16558 }
16559 LookupDC = LookupDC->getParent();
16560 }
16561
16562 DCScope = getScopeForDeclContext(S, DC);
16563
16564 // - There's a non-dependent scope specifier, in which case we
16565 // compute it and do a previous lookup there for a function
16566 // or function template.
16567 } else if (!SS.getScopeRep()->isDependent()) {
16568 DC = computeDeclContext(SS);
16569 if (!DC) return nullptr;
16570
16571 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16572
16573 LookupQualifiedName(Previous, DC);
16574
16575 // C++ [class.friend]p1: A friend of a class is a function or
16576 // class that is not a member of the class . . .
16577 if (DC->Equals(CurContext))
16578 Diag(DS.getFriendSpecLoc(),
16579 getLangOpts().CPlusPlus11 ?
16580 diag::warn_cxx98_compat_friend_is_member :
16581 diag::err_friend_is_member);
16582
16583 if (D.isFunctionDefinition()) {
16584 // C++ [class.friend]p6:
16585 // A function can be defined in a friend declaration of a class if and
16586 // only if the class is a non-local class (9.8), the function name is
16587 // unqualified, and the function has namespace scope.
16588 //
16589 // FIXME: We should only do this if the scope specifier names the
16590 // innermost enclosing namespace; otherwise the fixit changes the
16591 // meaning of the code.
16592 SemaDiagnosticBuilder DB
16593 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16594
16595 DB << SS.getScopeRep();
16596 if (DC->isFileContext())
16597 DB << FixItHint::CreateRemoval(SS.getRange());
16598 SS.clear();
16599 }
16600
16601 // - There's a scope specifier that does not match any template
16602 // parameter lists, in which case we use some arbitrary context,
16603 // create a method or method template, and wait for instantiation.
16604 // - There's a scope specifier that does match some template
16605 // parameter lists, which we don't handle right now.
16606 } else {
16607 if (D.isFunctionDefinition()) {
16608 // C++ [class.friend]p6:
16609 // A function can be defined in a friend declaration of a class if and
16610 // only if the class is a non-local class (9.8), the function name is
16611 // unqualified, and the function has namespace scope.
16612 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16613 << SS.getScopeRep();
16614 }
16615
16616 DC = CurContext;
16617 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")((isa<CXXRecordDecl>(DC) && "friend declaration not in class?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16617, __PRETTY_FUNCTION__))
;
16618 }
16619
16620 if (!DC->isRecord()) {
16621 int DiagArg = -1;
16622 switch (D.getName().getKind()) {
16623 case UnqualifiedIdKind::IK_ConstructorTemplateId:
16624 case UnqualifiedIdKind::IK_ConstructorName:
16625 DiagArg = 0;
16626 break;
16627 case UnqualifiedIdKind::IK_DestructorName:
16628 DiagArg = 1;
16629 break;
16630 case UnqualifiedIdKind::IK_ConversionFunctionId:
16631 DiagArg = 2;
16632 break;
16633 case UnqualifiedIdKind::IK_DeductionGuideName:
16634 DiagArg = 3;
16635 break;
16636 case UnqualifiedIdKind::IK_Identifier:
16637 case UnqualifiedIdKind::IK_ImplicitSelfParam:
16638 case UnqualifiedIdKind::IK_LiteralOperatorId:
16639 case UnqualifiedIdKind::IK_OperatorFunctionId:
16640 case UnqualifiedIdKind::IK_TemplateId:
16641 break;
16642 }
16643 // This implies that it has to be an operator or function.
16644 if (DiagArg >= 0) {
16645 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16646 return nullptr;
16647 }
16648 }
16649
16650 // FIXME: This is an egregious hack to cope with cases where the scope stack
16651 // does not contain the declaration context, i.e., in an out-of-line
16652 // definition of a class.
16653 Scope FakeDCScope(S, Scope::DeclScope, Diags);
16654 if (!DCScope) {
16655 FakeDCScope.setEntity(DC);
16656 DCScope = &FakeDCScope;
16657 }
16658
16659 bool AddToScope = true;
16660 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16661 TemplateParams, AddToScope);
16662 if (!ND) return nullptr;
16663
16664 assert(ND->getLexicalDeclContext() == CurContext)((ND->getLexicalDeclContext() == CurContext) ? static_cast
<void> (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 16664, __PRETTY_FUNCTION__))
;
16665
16666 // If we performed typo correction, we might have added a scope specifier
16667 // and changed the decl context.
16668 DC = ND->getDeclContext();
16669
16670 // Add the function declaration to the appropriate lookup tables,
16671 // adjusting the redeclarations list as necessary. We don't
16672 // want to do this yet if the friending class is dependent.
16673 //
16674 // Also update the scope-based lookup if the target context's
16675 // lookup context is in lexical scope.
16676 if (!CurContext->isDependentContext()) {
16677 DC = DC->getRedeclContext();
16678 DC->makeDeclVisibleInContext(ND);
16679 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16680 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16681 }
16682
16683 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16684 D.getIdentifierLoc(), ND,
16685 DS.getFriendSpecLoc());
16686 FrD->setAccess(AS_public);
16687 CurContext->addDecl(FrD);
16688
16689 if (ND->isInvalidDecl()) {
16690 FrD->setInvalidDecl();
16691 } else {
16692 if (DC->isRecord()) CheckFriendAccess(ND);
16693
16694 FunctionDecl *FD;
16695 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16696 FD = FTD->getTemplatedDecl();
16697 else
16698 FD = cast<FunctionDecl>(ND);
16699
16700 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16701 // default argument expression, that declaration shall be a definition
16702 // and shall be the only declaration of the function or function
16703 // template in the translation unit.
16704 if (functionDeclHasDefaultArgument(FD)) {
16705 // We can't look at FD->getPreviousDecl() because it may not have been set
16706 // if we're in a dependent context. If the function is known to be a
16707 // redeclaration, we will have narrowed Previous down to the right decl.
16708 if (D.isRedeclaration()) {
16709 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16710 Diag(Previous.getRepresentativeDecl()->getLocation(),
16711 diag::note_previous_declaration);
16712 } else if (!D.isFunctionDefinition())
16713 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16714 }
16715
16716 // Mark templated-scope function declarations as unsupported.
16717 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16718 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16719 << SS.getScopeRep() << SS.getRange()
16720 << cast<CXXRecordDecl>(CurContext);
16721 FrD->setUnsupportedFriend(true);
16722 }
16723 }
16724
16725 return ND;
16726}
16727
16728void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16729 AdjustDeclIfTemplate(Dcl);
16730
16731 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16732 if (!Fn) {
16733 Diag(DelLoc, diag::err_deleted_non_function);
16734 return;
16735 }
16736
16737 // Deleted function does not have a body.
16738 Fn->setWillHaveBody(false);
16739
16740 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16741 // Don't consider the implicit declaration we generate for explicit
16742 // specializations. FIXME: Do not generate these implicit declarations.
16743 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16744 Prev->getPreviousDecl()) &&
16745 !Prev->isDefined()) {
16746 Diag(DelLoc, diag::err_deleted_decl_not_first);
16747 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16748 Prev->isImplicit() ? diag::note_previous_implicit_declaration
16749 : diag::note_previous_declaration);
16750 // We can't recover from this; the declaration might have already
16751 // been used.
16752 Fn->setInvalidDecl();
16753 return;
16754 }
16755
16756 // To maintain the invariant that functions are only deleted on their first
16757 // declaration, mark the implicitly-instantiated declaration of the
16758 // explicitly-specialized function as deleted instead of marking the
16759 // instantiated redeclaration.
16760 Fn = Fn->getCanonicalDecl();
16761 }
16762
16763 // dllimport/dllexport cannot be deleted.
16764 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16765 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16766 Fn->setInvalidDecl();
16767 }
16768
16769 // C++11 [basic.start.main]p3:
16770 // A program that defines main as deleted [...] is ill-formed.
16771 if (Fn->isMain())
16772 Diag(DelLoc, diag::err_deleted_main);
16773
16774 // C++11 [dcl.fct.def.delete]p4:
16775 // A deleted function is implicitly inline.
16776 Fn->setImplicitlyInline();
16777 Fn->setDeletedAsWritten();
16778}
16779
16780void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16781 if (!Dcl || Dcl->isInvalidDecl())
16782 return;
16783
16784 auto *FD = dyn_cast<FunctionDecl>(Dcl);
16785 if (!FD) {
16786 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16787 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16788 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16789 return;
16790 }
16791 }
16792
16793 Diag(DefaultLoc, diag::err_default_special_members)
16794 << getLangOpts().CPlusPlus20;
16795 return;
16796 }
16797
16798 // Reject if this can't possibly be a defaultable function.
16799 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16800 if (!DefKind &&
16801 // A dependent function that doesn't locally look defaultable can
16802 // still instantiate to a defaultable function if it's a constructor
16803 // or assignment operator.
16804 (!FD->isDependentContext() ||
16805 (!isa<CXXConstructorDecl>(FD) &&
16806 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16807 Diag(DefaultLoc, diag::err_default_special_members)
16808 << getLangOpts().CPlusPlus20;
16809 return;
16810 }
16811
16812 if (DefKind.isComparison() &&
16813 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16814 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16815 << (int)DefKind.asComparison();
16816 return;
16817 }
16818
16819 // Issue compatibility warning. We already warned if the operator is
16820 // 'operator<=>' when parsing the '<=>' token.
16821 if (DefKind.isComparison() &&
16822 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16823 Diag(DefaultLoc, getLangOpts().CPlusPlus20
16824 ? diag::warn_cxx17_compat_defaulted_comparison
16825 : diag::ext_defaulted_comparison);
16826 }
16827
16828 FD->setDefaulted();
16829 FD->setExplicitlyDefaulted();
16830
16831 // Defer checking functions that are defaulted in a dependent context.
16832 if (FD->isDependentContext())
16833 return;
16834
16835 // Unset that we will have a body for this function. We might not,
16836 // if it turns out to be trivial, and we don't need this marking now
16837 // that we've marked it as defaulted.
16838 FD->setWillHaveBody(false);
16839
16840 // If this definition appears within the record, do the checking when
16841 // the record is complete. This is always the case for a defaulted
16842 // comparison.
16843 if (DefKind.isComparison())
16844 return;
16845 auto *MD = cast<CXXMethodDecl>(FD);
16846
16847 const FunctionDecl *Primary = FD;
16848 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16849 // Ask the template instantiation pattern that actually had the
16850 // '= default' on it.
16851 Primary = Pattern;
16852
16853 // If the method was defaulted on its first declaration, we will have
16854 // already performed the checking in CheckCompletedCXXClass. Such a
16855 // declaration doesn't trigger an implicit definition.
16856 if (Primary->getCanonicalDecl()->isDefaulted())
16857 return;
16858
16859 // FIXME: Once we support defining comparisons out of class, check for a
16860 // defaulted comparison here.
16861 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16862 MD->setInvalidDecl();
16863 else
16864 DefineDefaultedFunction(*this, MD, DefaultLoc);
16865}
16866
16867static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16868 for (Stmt *SubStmt : S->children()) {
16869 if (!SubStmt)
16870 continue;
16871 if (isa<ReturnStmt>(SubStmt))
16872 Self.Diag(SubStmt->getBeginLoc(),
16873 diag::err_return_in_constructor_handler);
16874 if (!isa<Expr>(SubStmt))
16875 SearchForReturnInStmt(Self, SubStmt);
16876 }
16877}
16878
16879void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16880 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16881 CXXCatchStmt *Handler = TryBlock->getHandler(I);
16882 SearchForReturnInStmt(*this, Handler);
16883 }
16884}
16885
16886bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16887 const CXXMethodDecl *Old) {
16888 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16889 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16890
16891 if (OldFT->hasExtParameterInfos()) {
16892 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16893 // A parameter of the overriding method should be annotated with noescape
16894 // if the corresponding parameter of the overridden method is annotated.
16895 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16896 !NewFT->getExtParameterInfo(I).isNoEscape()) {
16897 Diag(New->getParamDecl(I)->getLocation(),
16898 diag::warn_overriding_method_missing_noescape);
16899 Diag(Old->getParamDecl(I)->getLocation(),
16900 diag::note_overridden_marked_noescape);
16901 }
16902 }
16903
16904 // Virtual overrides must have the same code_seg.
16905 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16906 const auto *NewCSA = New->getAttr<CodeSegAttr>();
16907 if ((NewCSA || OldCSA) &&
16908 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16909 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16910 Diag(Old->getLocation(), diag::note_previous_declaration);
16911 return true;
16912 }
16913
16914 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16915
16916 // If the calling conventions match, everything is fine
16917 if (NewCC == OldCC)
16918 return false;
16919
16920 // If the calling conventions mismatch because the new function is static,
16921 // suppress the calling convention mismatch error; the error about static
16922 // function override (err_static_overrides_virtual from
16923 // Sema::CheckFunctionDeclaration) is more clear.
16924 if (New->getStorageClass() == SC_Static)
16925 return false;
16926
16927 Diag(New->getLocation(),
16928 diag::err_conflicting_overriding_cc_attributes)
16929 << New->getDeclName() << New->getType() << Old->getType();
16930 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16931 return true;
16932}
16933
16934bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16935 const CXXMethodDecl *Old) {
16936 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16937 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16938
16939 if (Context.hasSameType(NewTy, OldTy) ||
16940 NewTy->isDependentType() || OldTy->isDependentType())
16941 return false;
16942
16943 // Check if the return types are covariant
16944 QualType NewClassTy, OldClassTy;
16945
16946 /// Both types must be pointers or references to classes.
16947 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16948 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16949 NewClassTy = NewPT->getPointeeType();
16950 OldClassTy = OldPT->getPointeeType();
16951 }
16952 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16953 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16954 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16955 NewClassTy = NewRT->getPointeeType();
16956 OldClassTy = OldRT->getPointeeType();
16957 }
16958 }
16959 }
16960
16961 // The return types aren't either both pointers or references to a class type.
16962 if (NewClassTy.isNull()) {
16963 Diag(New->getLocation(),
16964 diag::err_different_return_type_for_overriding_virtual_function)
16965 << New->getDeclName() << NewTy << OldTy
16966 << New->getReturnTypeSourceRange();
16967 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16968 << Old->getReturnTypeSourceRange();
16969
16970 return true;
16971 }
16972
16973 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16974 // C++14 [class.virtual]p8:
16975 // If the class type in the covariant return type of D::f differs from
16976 // that of B::f, the class type in the return type of D::f shall be
16977 // complete at the point of declaration of D::f or shall be the class
16978 // type D.
16979 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16980 if (!RT->isBeingDefined() &&
16981 RequireCompleteType(New->getLocation(), NewClassTy,
16982 diag::err_covariant_return_incomplete,
16983 New->getDeclName()))
16984 return true;
16985 }
16986
16987 // Check if the new class derives from the old class.
16988 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16989 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16990 << New->getDeclName() << NewTy << OldTy
16991 << New->getReturnTypeSourceRange();
16992 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16993 << Old->getReturnTypeSourceRange();
16994 return true;
16995 }
16996
16997 // Check if we the conversion from derived to base is valid.
16998 if (CheckDerivedToBaseConversion(
16999 NewClassTy, OldClassTy,
17000 diag::err_covariant_return_inaccessible_base,
17001 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17002 New->getLocation(), New->getReturnTypeSourceRange(),
17003 New->getDeclName(), nullptr)) {
17004 // FIXME: this note won't trigger for delayed access control
17005 // diagnostics, and it's impossible to get an undelayed error
17006 // here from access control during the original parse because
17007 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17008 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17009 << Old->getReturnTypeSourceRange();
17010 return true;
17011 }
17012 }
17013
17014 // The qualifiers of the return types must be the same.
17015 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17016 Diag(New->getLocation(),
17017 diag::err_covariant_return_type_different_qualifications)
17018 << New->getDeclName() << NewTy << OldTy
17019 << New->getReturnTypeSourceRange();
17020 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17021 << Old->getReturnTypeSourceRange();
17022 return true;
17023 }
17024
17025
17026 // The new class type must have the same or less qualifiers as the old type.
17027 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17028 Diag(New->getLocation(),
17029 diag::err_covariant_return_type_class_type_more_qualified)
17030 << New->getDeclName() << NewTy << OldTy
17031 << New->getReturnTypeSourceRange();
17032 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17033 << Old->getReturnTypeSourceRange();
17034 return true;
17035 }
17036
17037 return false;
17038}
17039
17040/// Mark the given method pure.
17041///
17042/// \param Method the method to be marked pure.
17043///
17044/// \param InitRange the source range that covers the "0" initializer.
17045bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17046 SourceLocation EndLoc = InitRange.getEnd();
17047 if (EndLoc.isValid())
17048 Method->setRangeEnd(EndLoc);
17049
17050 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17051 Method->setPure();
17052 return false;
17053 }
17054
17055 if (!Method->isInvalidDecl())
17056 Diag(Method->getLocation(), diag::err_non_virtual_pure)
17057 << Method->getDeclName() << InitRange;
17058 return true;
17059}
17060
17061void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17062 if (D->getFriendObjectKind())
17063 Diag(D->getLocation(), diag::err_pure_friend);
17064 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17065 CheckPureMethod(M, ZeroLoc);
17066 else
17067 Diag(D->getLocation(), diag::err_illegal_initializer);
17068}
17069
17070/// Determine whether the given declaration is a global variable or
17071/// static data member.
17072static bool isNonlocalVariable(const Decl *D) {
17073 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17074 return Var->hasGlobalStorage();
17075
17076 return false;
17077}
17078
17079/// Invoked when we are about to parse an initializer for the declaration
17080/// 'Dcl'.
17081///
17082/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17083/// static data member of class X, names should be looked up in the scope of
17084/// class X. If the declaration had a scope specifier, a scope will have
17085/// been created and passed in for this purpose. Otherwise, S will be null.
17086void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17087 // If there is no declaration, there was an error parsing it.
17088 if (!D || D->isInvalidDecl())
17089 return;
17090
17091 // We will always have a nested name specifier here, but this declaration
17092 // might not be out of line if the specifier names the current namespace:
17093 // extern int n;
17094 // int ::n = 0;
17095 if (S && D->isOutOfLine())
17096 EnterDeclaratorContext(S, D->getDeclContext());
17097
17098 // If we are parsing the initializer for a static data member, push a
17099 // new expression evaluation context that is associated with this static
17100 // data member.
17101 if (isNonlocalVariable(D))
17102 PushExpressionEvaluationContext(
17103 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17104}
17105
17106/// Invoked after we are finished parsing an initializer for the declaration D.
17107void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17108 // If there is no declaration, there was an error parsing it.
17109 if (!D || D->isInvalidDecl())
17110 return;
17111
17112 if (isNonlocalVariable(D))
17113 PopExpressionEvaluationContext();
17114
17115 if (S && D->isOutOfLine())
17116 ExitDeclaratorContext(S);
17117}
17118
17119/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17120/// C++ if/switch/while/for statement.
17121/// e.g: "if (int x = f()) {...}"
17122DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17123 // C++ 6.4p2:
17124 // The declarator shall not specify a function or an array.
17125 // The type-specifier-seq shall not contain typedef and shall not declare a
17126 // new class or enumeration.
17127 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class of condition decl."
) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17128, __PRETTY_FUNCTION__))
17128 "Parser allowed 'typedef' as storage class of condition decl.")((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class of condition decl."
) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17128, __PRETTY_FUNCTION__))
;
17129
17130 Decl *Dcl = ActOnDeclarator(S, D);
17131 if (!Dcl)
17132 return true;
17133
17134 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17135 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17136 << D.getSourceRange();
17137 return true;
17138 }
17139
17140 return Dcl;
17141}
17142
17143void Sema::LoadExternalVTableUses() {
17144 if (!ExternalSource)
17145 return;
17146
17147 SmallVector<ExternalVTableUse, 4> VTables;
17148 ExternalSource->ReadUsedVTables(VTables);
17149 SmallVector<VTableUse, 4> NewUses;
17150 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17151 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17152 = VTablesUsed.find(VTables[I].Record);
17153 // Even if a definition wasn't required before, it may be required now.
17154 if (Pos != VTablesUsed.end()) {
17155 if (!Pos->second && VTables[I].DefinitionRequired)
17156 Pos->second = true;
17157 continue;
17158 }
17159
17160 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17161 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17162 }
17163
17164 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17165}
17166
17167void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17168 bool DefinitionRequired) {
17169 // Ignore any vtable uses in unevaluated operands or for classes that do
17170 // not have a vtable.
17171 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17172 CurContext->isDependentContext() || isUnevaluatedContext())
17173 return;
17174 // Do not mark as used if compiling for the device outside of the target
17175 // region.
17176 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17177 !isInOpenMPDeclareTargetContext() &&
17178 !isInOpenMPTargetExecutionDirective()) {
17179 if (!DefinitionRequired)
17180 MarkVirtualMembersReferenced(Loc, Class);
17181 return;
17182 }
17183
17184 // Try to insert this class into the map.
17185 LoadExternalVTableUses();
17186 Class = Class->getCanonicalDecl();
17187 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17188 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17189 if (!Pos.second) {
17190 // If we already had an entry, check to see if we are promoting this vtable
17191 // to require a definition. If so, we need to reappend to the VTableUses
17192 // list, since we may have already processed the first entry.
17193 if (DefinitionRequired && !Pos.first->second) {
17194 Pos.first->second = true;
17195 } else {
17196 // Otherwise, we can early exit.
17197 return;
17198 }
17199 } else {
17200 // The Microsoft ABI requires that we perform the destructor body
17201 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17202 // the deleting destructor is emitted with the vtable, not with the
17203 // destructor definition as in the Itanium ABI.
17204 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17205 CXXDestructorDecl *DD = Class->getDestructor();
17206 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17207 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17208 // If this is an out-of-line declaration, marking it referenced will
17209 // not do anything. Manually call CheckDestructor to look up operator
17210 // delete().
17211 ContextRAII SavedContext(*this, DD);
17212 CheckDestructor(DD);
17213 } else {
17214 MarkFunctionReferenced(Loc, Class->getDestructor());
17215 }
17216 }
17217 }
17218 }
17219
17220 // Local classes need to have their virtual members marked
17221 // immediately. For all other classes, we mark their virtual members
17222 // at the end of the translation unit.
17223 if (Class->isLocalClass())
17224 MarkVirtualMembersReferenced(Loc, Class);
17225 else
17226 VTableUses.push_back(std::make_pair(Class, Loc));
17227}
17228
17229bool Sema::DefineUsedVTables() {
17230 LoadExternalVTableUses();
17231 if (VTableUses.empty())
17232 return false;
17233
17234 // Note: The VTableUses vector could grow as a result of marking
17235 // the members of a class as "used", so we check the size each
17236 // time through the loop and prefer indices (which are stable) to
17237 // iterators (which are not).
17238 bool DefinedAnything = false;
17239 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17240 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17241 if (!Class)
17242 continue;
17243 TemplateSpecializationKind ClassTSK =
17244 Class->getTemplateSpecializationKind();
17245
17246 SourceLocation Loc = VTableUses[I].second;
17247
17248 bool DefineVTable = true;
17249
17250 // If this class has a key function, but that key function is
17251 // defined in another translation unit, we don't need to emit the
17252 // vtable even though we're using it.
17253 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17254 if (KeyFunction && !KeyFunction->hasBody()) {
17255 // The key function is in another translation unit.
17256 DefineVTable = false;
17257 TemplateSpecializationKind TSK =
17258 KeyFunction->getTemplateSpecializationKind();
17259 assert(TSK != TSK_ExplicitInstantiationDefinition &&((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17261, __PRETTY_FUNCTION__))
17260 TSK != TSK_ImplicitInstantiation &&((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17261, __PRETTY_FUNCTION__))
17261 "Instantiations don't have key functions")((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17261, __PRETTY_FUNCTION__))
;
17262 (void)TSK;
17263 } else if (!KeyFunction) {
17264 // If we have a class with no key function that is the subject
17265 // of an explicit instantiation declaration, suppress the
17266 // vtable; it will live with the explicit instantiation
17267 // definition.
17268 bool IsExplicitInstantiationDeclaration =
17269 ClassTSK == TSK_ExplicitInstantiationDeclaration;
17270 for (auto R : Class->redecls()) {
17271 TemplateSpecializationKind TSK
17272 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17273 if (TSK == TSK_ExplicitInstantiationDeclaration)
17274 IsExplicitInstantiationDeclaration = true;
17275 else if (TSK == TSK_ExplicitInstantiationDefinition) {
17276 IsExplicitInstantiationDeclaration = false;
17277 break;
17278 }
17279 }
17280
17281 if (IsExplicitInstantiationDeclaration)
17282 DefineVTable = false;
17283 }
17284
17285 // The exception specifications for all virtual members may be needed even
17286 // if we are not providing an authoritative form of the vtable in this TU.
17287 // We may choose to emit it available_externally anyway.
17288 if (!DefineVTable) {
17289 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17290 continue;
17291 }
17292
17293 // Mark all of the virtual members of this class as referenced, so
17294 // that we can build a vtable. Then, tell the AST consumer that a
17295 // vtable for this class is required.
17296 DefinedAnything = true;
17297 MarkVirtualMembersReferenced(Loc, Class);
17298 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17299 if (VTablesUsed[Canonical])
17300 Consumer.HandleVTable(Class);
17301
17302 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17303 // no key function or the key function is inlined. Don't warn in C++ ABIs
17304 // that lack key functions, since the user won't be able to make one.
17305 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17306 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17307 const FunctionDecl *KeyFunctionDef = nullptr;
17308 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17309 KeyFunctionDef->isInlined())) {
17310 Diag(Class->getLocation(),
17311 ClassTSK == TSK_ExplicitInstantiationDefinition
17312 ? diag::warn_weak_template_vtable
17313 : diag::warn_weak_vtable)
17314 << Class;
17315 }
17316 }
17317 }
17318 VTableUses.clear();
17319
17320 return DefinedAnything;
17321}
17322
17323void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17324 const CXXRecordDecl *RD) {
17325 for (const auto *I : RD->methods())
17326 if (I->isVirtual() && !I->isPure())
17327 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17328}
17329
17330void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17331 const CXXRecordDecl *RD,
17332 bool ConstexprOnly) {
17333 // Mark all functions which will appear in RD's vtable as used.
17334 CXXFinalOverriderMap FinalOverriders;
17335 RD->getFinalOverriders(FinalOverriders);
17336 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17337 E = FinalOverriders.end();
17338 I != E; ++I) {
17339 for (OverridingMethods::const_iterator OI = I->second.begin(),
17340 OE = I->second.end();
17341 OI != OE; ++OI) {
17342 assert(OI->second.size() > 0 && "no final overrider")((OI->second.size() > 0 && "no final overrider"
) ? static_cast<void> (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17342, __PRETTY_FUNCTION__))
;
17343 CXXMethodDecl *Overrider = OI->second.front().Method;
17344
17345 // C++ [basic.def.odr]p2:
17346 // [...] A virtual member function is used if it is not pure. [...]
17347 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17348 MarkFunctionReferenced(Loc, Overrider);
17349 }
17350 }
17351
17352 // Only classes that have virtual bases need a VTT.
17353 if (RD->getNumVBases() == 0)
17354 return;
17355
17356 for (const auto &I : RD->bases()) {
17357 const auto *Base =
17358 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17359 if (Base->getNumVBases() == 0)
17360 continue;
17361 MarkVirtualMembersReferenced(Loc, Base);
17362 }
17363}
17364
17365/// SetIvarInitializers - This routine builds initialization ASTs for the
17366/// Objective-C implementation whose ivars need be initialized.
17367void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17368 if (!getLangOpts().CPlusPlus)
17369 return;
17370 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17371 SmallVector<ObjCIvarDecl*, 8> ivars;
17372 CollectIvarsToConstructOrDestruct(OID, ivars);
17373 if (ivars.empty())
17374 return;
17375 SmallVector<CXXCtorInitializer*, 32> AllToInit;
17376 for (unsigned i = 0; i < ivars.size(); i++) {
17377 FieldDecl *Field = ivars[i];
17378 if (Field->isInvalidDecl())
17379 continue;
17380
17381 CXXCtorInitializer *Member;
17382 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17383 InitializationKind InitKind =
17384 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17385
17386 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17387 ExprResult MemberInit =
17388 InitSeq.Perform(*this, InitEntity, InitKind, None);
17389 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17390 // Note, MemberInit could actually come back empty if no initialization
17391 // is required (e.g., because it would call a trivial default constructor)
17392 if (!MemberInit.get() || MemberInit.isInvalid())
17393 continue;
17394
17395 Member =
17396 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17397 SourceLocation(),
17398 MemberInit.getAs<Expr>(),
17399 SourceLocation());
17400 AllToInit.push_back(Member);
17401
17402 // Be sure that the destructor is accessible and is marked as referenced.
17403 if (const RecordType *RecordTy =
17404 Context.getBaseElementType(Field->getType())
17405 ->getAs<RecordType>()) {
17406 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17407 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17408 MarkFunctionReferenced(Field->getLocation(), Destructor);
17409 CheckDestructorAccess(Field->getLocation(), Destructor,
17410 PDiag(diag::err_access_dtor_ivar)
17411 << Context.getBaseElementType(Field->getType()));
17412 }
17413 }
17414 }
17415 ObjCImplementation->setIvarInitializers(Context,
17416 AllToInit.data(), AllToInit.size());
17417 }
17418}
17419
17420static
17421void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17422 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17423 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17424 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17425 Sema &S) {
17426 if (Ctor->isInvalidDecl())
17427 return;
17428
17429 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17430
17431 // Target may not be determinable yet, for instance if this is a dependent
17432 // call in an uninstantiated template.
17433 if (Target) {
17434 const FunctionDecl *FNTarget = nullptr;
17435 (void)Target->hasBody(FNTarget);
17436 Target = const_cast<CXXConstructorDecl*>(
17437 cast_or_null<CXXConstructorDecl>(FNTarget));
17438 }
17439
17440 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17441 // Avoid dereferencing a null pointer here.
17442 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17443
17444 if (!Current.insert(Canonical).second)
17445 return;
17446
17447 // We know that beyond here, we aren't chaining into a cycle.
17448 if (!Target || !Target->isDelegatingConstructor() ||
17449 Target->isInvalidDecl() || Valid.count(TCanonical)) {
17450 Valid.insert(Current.begin(), Current.end());
17451 Current.clear();
17452 // We've hit a cycle.
17453 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17454 Current.count(TCanonical)) {
17455 // If we haven't diagnosed this cycle yet, do so now.
17456 if (!Invalid.count(TCanonical)) {
17457 S.Diag((*Ctor->init_begin())->getSourceLocation(),
17458 diag::warn_delegating_ctor_cycle)
17459 << Ctor;
17460
17461 // Don't add a note for a function delegating directly to itself.
17462 if (TCanonical != Canonical)
17463 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17464
17465 CXXConstructorDecl *C = Target;
17466 while (C->getCanonicalDecl() != Canonical) {
17467 const FunctionDecl *FNTarget = nullptr;
17468 (void)C->getTargetConstructor()->hasBody(FNTarget);
17469 assert(FNTarget && "Ctor cycle through bodiless function")((FNTarget && "Ctor cycle through bodiless function")
? static_cast<void> (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17469, __PRETTY_FUNCTION__))
;
17470
17471 C = const_cast<CXXConstructorDecl*>(
17472 cast<CXXConstructorDecl>(FNTarget));
17473 S.Diag(C->getLocation(), diag::note_which_delegates_to);
17474 }
17475 }
17476
17477 Invalid.insert(Current.begin(), Current.end());
17478 Current.clear();
17479 } else {
17480 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17481 }
17482}
17483
17484
17485void Sema::CheckDelegatingCtorCycles() {
17486 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17487
17488 for (DelegatingCtorDeclsType::iterator
17489 I = DelegatingCtorDecls.begin(ExternalSource),
17490 E = DelegatingCtorDecls.end();
17491 I != E; ++I)
17492 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17493
17494 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17495 (*CI)->setInvalidDecl();
17496}
17497
17498namespace {
17499 /// AST visitor that finds references to the 'this' expression.
17500 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17501 Sema &S;
17502
17503 public:
17504 explicit FindCXXThisExpr(Sema &S) : S(S) { }
17505
17506 bool VisitCXXThisExpr(CXXThisExpr *E) {
17507 S.Diag(E->getLocation(), diag::err_this_static_member_func)
17508 << E->isImplicit();
17509 return false;
17510 }
17511 };
17512}
17513
17514bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17515 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17516 if (!TSInfo)
17517 return false;
17518
17519 TypeLoc TL = TSInfo->getTypeLoc();
17520 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17521 if (!ProtoTL)
17522 return false;
17523
17524 // C++11 [expr.prim.general]p3:
17525 // [The expression this] shall not appear before the optional
17526 // cv-qualifier-seq and it shall not appear within the declaration of a
17527 // static member function (although its type and value category are defined
17528 // within a static member function as they are within a non-static member
17529 // function). [ Note: this is because declaration matching does not occur
17530 // until the complete declarator is known. - end note ]
17531 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17532 FindCXXThisExpr Finder(*this);
17533
17534 // If the return type came after the cv-qualifier-seq, check it now.
17535 if (Proto->hasTrailingReturn() &&
17536 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17537 return true;
17538
17539 // Check the exception specification.
17540 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17541 return true;
17542
17543 // Check the trailing requires clause
17544 if (Expr *E = Method->getTrailingRequiresClause())
17545 if (!Finder.TraverseStmt(E))
17546 return true;
17547
17548 return checkThisInStaticMemberFunctionAttributes(Method);
17549}
17550
17551bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17552 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17553 if (!TSInfo)
17554 return false;
17555
17556 TypeLoc TL = TSInfo->getTypeLoc();
17557 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17558 if (!ProtoTL)
17559 return false;
17560
17561 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17562 FindCXXThisExpr Finder(*this);
17563
17564 switch (Proto->getExceptionSpecType()) {
17565 case EST_Unparsed:
17566 case EST_Uninstantiated:
17567 case EST_Unevaluated:
17568 case EST_BasicNoexcept:
17569 case EST_NoThrow:
17570 case EST_DynamicNone:
17571 case EST_MSAny:
17572 case EST_None:
17573 break;
17574
17575 case EST_DependentNoexcept:
17576 case EST_NoexceptFalse:
17577 case EST_NoexceptTrue:
17578 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17579 return true;
17580 LLVM_FALLTHROUGH[[gnu::fallthrough]];
17581
17582 case EST_Dynamic:
17583 for (const auto &E : Proto->exceptions()) {
17584 if (!Finder.TraverseType(E))
17585 return true;
17586 }
17587 break;
17588 }
17589
17590 return false;
17591}
17592
17593bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17594 FindCXXThisExpr Finder(*this);
17595
17596 // Check attributes.
17597 for (const auto *A : Method->attrs()) {
17598 // FIXME: This should be emitted by tblgen.
17599 Expr *Arg = nullptr;
17600 ArrayRef<Expr *> Args;
17601 if (const auto *G = dyn_cast<GuardedByAttr>(A))
17602 Arg = G->getArg();
17603 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17604 Arg = G->getArg();
17605 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17606 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17607 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17608 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17609 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17610 Arg = ETLF->getSuccessValue();
17611 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17612 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17613 Arg = STLF->getSuccessValue();
17614 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17615 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17616 Arg = LR->getArg();
17617 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17618 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17619 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17620 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17621 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17622 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17623 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17624 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17625 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17626 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17627
17628 if (Arg && !Finder.TraverseStmt(Arg))
17629 return true;
17630
17631 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17632 if (!Finder.TraverseStmt(Args[I]))
17633 return true;
17634 }
17635 }
17636
17637 return false;
17638}
17639
17640void Sema::checkExceptionSpecification(
17641 bool IsTopLevel, ExceptionSpecificationType EST,
17642 ArrayRef<ParsedType> DynamicExceptions,
17643 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17644 SmallVectorImpl<QualType> &Exceptions,
17645 FunctionProtoType::ExceptionSpecInfo &ESI) {
17646 Exceptions.clear();
17647 ESI.Type = EST;
17648 if (EST == EST_Dynamic) {
17649 Exceptions.reserve(DynamicExceptions.size());
17650 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17651 // FIXME: Preserve type source info.
17652 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17653
17654 if (IsTopLevel) {
17655 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17656 collectUnexpandedParameterPacks(ET, Unexpanded);
17657 if (!Unexpanded.empty()) {
17658 DiagnoseUnexpandedParameterPacks(
17659 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17660 Unexpanded);
17661 continue;
17662 }
17663 }
17664
17665 // Check that the type is valid for an exception spec, and
17666 // drop it if not.
17667 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17668 Exceptions.push_back(ET);
17669 }
17670 ESI.Exceptions = Exceptions;
17671 return;
17672 }
17673
17674 if (isComputedNoexcept(EST)) {
17675 assert((NoexceptExpr->isTypeDependent() ||(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17678, __PRETTY_FUNCTION__))
17676 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17678, __PRETTY_FUNCTION__))
17677 Context.BoolTy) &&(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17678, __PRETTY_FUNCTION__))
17678 "Parser should have made sure that the expression is boolean")(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/lib/Sema/SemaDeclCXX.cpp"
, 17678, __PRETTY_FUNCTION__))
;
17679 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17680 ESI.Type = EST_BasicNoexcept;
17681 return;
17682 }
17683
17684 ESI.NoexceptExpr = NoexceptExpr;
17685 return;
17686 }
17687}
17688
17689void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17690 ExceptionSpecificationType EST,
17691 SourceRange SpecificationRange,
17692 ArrayRef<ParsedType> DynamicExceptions,
17693 ArrayRef<SourceRange> DynamicExceptionRanges,
17694 Expr *NoexceptExpr) {
17695 if (!MethodD)
17696 return;
17697
17698 // Dig out the method we're referring to.
17699 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17700 MethodD = FunTmpl->getTemplatedDecl();
17701
17702 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17703 if (!Method)
17704 return;
17705
17706 // Check the exception specification.
17707 llvm::SmallVector<QualType, 4> Exceptions;
17708 FunctionProtoType::ExceptionSpecInfo ESI;
17709 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17710 DynamicExceptionRanges, NoexceptExpr, Exceptions,
17711 ESI);
17712
17713 // Update the exception specification on the function type.
17714 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17715
17716 if (Method->isStatic())
17717 checkThisInStaticMemberFunctionExceptionSpec(Method);
17718
17719 if (Method->isVirtual()) {
17720 // Check overrides, which we previously had to delay.
17721 for (const CXXMethodDecl *O : Method->overridden_methods())
17722 CheckOverridingFunctionExceptionSpec(Method, O);
17723 }
17724}
17725
17726/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17727///
17728MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17729 SourceLocation DeclStart, Declarator &D,
17730 Expr *BitWidth,
17731 InClassInitStyle InitStyle,
17732 AccessSpecifier AS,
17733 const ParsedAttr &MSPropertyAttr) {
17734 IdentifierInfo *II = D.getIdentifier();
17735 if (!II) {
17736 Diag(DeclStart, diag::err_anonymous_property);
17737 return nullptr;
17738 }
17739 SourceLocation Loc = D.getIdentifierLoc();
17740
17741 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17742 QualType T = TInfo->getType();
17743 if (getLangOpts().CPlusPlus) {
17744 CheckExtraCXXDefaultArguments(D);
17745
17746 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17747 UPPC_DataMemberType)) {
17748 D.setInvalidType();
17749 T = Context.IntTy;
17750 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17751 }
17752 }
17753
17754 DiagnoseFunctionSpecifiers(D.getDeclSpec());
17755
17756 if (D.getDeclSpec().isInlineSpecified())
17757 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17758 << getLangOpts().CPlusPlus17;
17759 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17760 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17761 diag::err_invalid_thread)
17762 << DeclSpec::getSpecifierName(TSCS);
17763
17764 // Check to see if this name was declared as a member previously
17765 NamedDecl *PrevDecl = nullptr;
17766 LookupResult Previous(*this, II, Loc, LookupMemberName,
17767 ForVisibleRedeclaration);
17768 LookupName(Previous, S);
17769 switch (Previous.getResultKind()) {
17770 case LookupResult::Found:
17771 case LookupResult::FoundUnresolvedValue:
17772 PrevDecl = Previous.getAsSingle<NamedDecl>();
17773 break;
17774
17775 case LookupResult::FoundOverloaded:
17776 PrevDecl = Previous.getRepresentativeDecl();
17777 break;
17778
17779 case LookupResult::NotFound:
17780 case LookupResult::NotFoundInCurrentInstantiation:
17781 case LookupResult::Ambiguous:
17782 break;
17783 }
17784
17785 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17786 // Maybe we will complain about the shadowed template parameter.
17787 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17788 // Just pretend that we didn't see the previous declaration.
17789 PrevDecl = nullptr;
17790 }
17791
17792 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17793 PrevDecl = nullptr;
17794
17795 SourceLocation TSSL = D.getBeginLoc();
17796 MSPropertyDecl *NewPD =
17797 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17798 MSPropertyAttr.getPropertyDataGetter(),
17799 MSPropertyAttr.getPropertyDataSetter());
17800 ProcessDeclAttributes(TUScope, NewPD, D);
17801 NewPD->setAccess(AS);
17802
17803 if (NewPD->isInvalidDecl())
17804 Record->setInvalidDecl();
17805
17806 if (D.getDeclSpec().isModulePrivateSpecified())
17807 NewPD->setModulePrivate();
17808
17809 if (NewPD->isInvalidDecl() && PrevDecl) {
17810 // Don't introduce NewFD into scope; there's already something
17811 // with the same name in the same scope.
17812 } else if (II) {
17813 PushOnScopeChains(NewPD, S);
17814 } else
17815 Record->addDecl(NewPD);
17816
17817 return NewPD;
17818}
17819
17820void Sema::ActOnStartFunctionDeclarationDeclarator(
17821 Declarator &Declarator, unsigned TemplateParameterDepth) {
17822 auto &Info = InventedParameterInfos.emplace_back();
17823 TemplateParameterList *ExplicitParams = nullptr;
17824 ArrayRef<TemplateParameterList *> ExplicitLists =
17825 Declarator.getTemplateParameterLists();
17826 if (!ExplicitLists.empty()) {
17827 bool IsMemberSpecialization, IsInvalid;
17828 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17829 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17830 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17831 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17832 /*SuppressDiagnostic=*/true);
17833 }
17834 if (ExplicitParams) {
17835 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17836 for (NamedDecl *Param : *ExplicitParams)
17837 Info.TemplateParams.push_back(Param);
17838 Info.NumExplicitTemplateParams = ExplicitParams->size();
17839 } else {
17840 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17841 Info.NumExplicitTemplateParams = 0;
17842 }
17843}
17844
17845void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17846 auto &FSI = InventedParameterInfos.back();
17847 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17848 if (FSI.NumExplicitTemplateParams != 0) {
17849 TemplateParameterList *ExplicitParams =
17850 Declarator.getTemplateParameterLists().back();
17851 Declarator.setInventedTemplateParameterList(
17852 TemplateParameterList::Create(
17853 Context, ExplicitParams->getTemplateLoc(),
17854 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17855 ExplicitParams->getRAngleLoc(),
17856 ExplicitParams->getRequiresClause()));
17857 } else {
17858 Declarator.setInventedTemplateParameterList(
17859 TemplateParameterList::Create(
17860 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17861 SourceLocation(), /*RequiresClause=*/nullptr));
17862 }
17863 }
17864 InventedParameterInfos.pop_back();
17865}

/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
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 defines the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/ExternalASTSource.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Redeclarable.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/AddressSpaces.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/IdentifierTable.h"
28#include "clang/Basic/LLVM.h"
29#include "clang/Basic/Linkage.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/PragmaKinds.h"
33#include "clang/Basic/SourceLocation.h"
34#include "clang/Basic/Specifiers.h"
35#include "clang/Basic/Visibility.h"
36#include "llvm/ADT/APSInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/TrailingObjects.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <string>
50#include <utility>
51
52namespace clang {
53
54class ASTContext;
55struct ASTTemplateArgumentListInfo;
56class Attr;
57class CompoundStmt;
58class DependentFunctionTemplateSpecializationInfo;
59class EnumDecl;
60class Expr;
61class FunctionTemplateDecl;
62class FunctionTemplateSpecializationInfo;
63class FunctionTypeLoc;
64class LabelStmt;
65class MemberSpecializationInfo;
66class Module;
67class NamespaceDecl;
68class ParmVarDecl;
69class RecordDecl;
70class Stmt;
71class StringLiteral;
72class TagDecl;
73class TemplateArgumentList;
74class TemplateArgumentListInfo;
75class TemplateParameterList;
76class TypeAliasTemplateDecl;
77class TypeLoc;
78class UnresolvedSetImpl;
79class VarTemplateDecl;
80
81/// The top declaration context.
82class TranslationUnitDecl : public Decl, public DeclContext {
83 ASTContext &Ctx;
84
85 /// The (most recently entered) anonymous namespace for this
86 /// translation unit, if one has been created.
87 NamespaceDecl *AnonymousNamespace = nullptr;
88
89 explicit TranslationUnitDecl(ASTContext &ctx);
90
91 virtual void anchor();
92
93public:
94 ASTContext &getASTContext() const { return Ctx; }
95
96 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
97 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
98
99 static TranslationUnitDecl *Create(ASTContext &C);
100
101 // Implement isa/cast/dyncast/etc.
102 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
103 static bool classofKind(Kind K) { return K == TranslationUnit; }
104 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
105 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
106 }
107 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
108 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
109 }
110};
111
112/// Represents a `#pragma comment` line. Always a child of
113/// TranslationUnitDecl.
114class PragmaCommentDecl final
115 : public Decl,
116 private llvm::TrailingObjects<PragmaCommentDecl, char> {
117 friend class ASTDeclReader;
118 friend class ASTDeclWriter;
119 friend TrailingObjects;
120
121 PragmaMSCommentKind CommentKind;
122
123 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
124 PragmaMSCommentKind CommentKind)
125 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
126
127 virtual void anchor();
128
129public:
130 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
131 SourceLocation CommentLoc,
132 PragmaMSCommentKind CommentKind,
133 StringRef Arg);
134 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
135 unsigned ArgSize);
136
137 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
138
139 StringRef getArg() const { return getTrailingObjects<char>(); }
140
141 // Implement isa/cast/dyncast/etc.
142 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
143 static bool classofKind(Kind K) { return K == PragmaComment; }
144};
145
146/// Represents a `#pragma detect_mismatch` line. Always a child of
147/// TranslationUnitDecl.
148class PragmaDetectMismatchDecl final
149 : public Decl,
150 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
151 friend class ASTDeclReader;
152 friend class ASTDeclWriter;
153 friend TrailingObjects;
154
155 size_t ValueStart;
156
157 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
158 size_t ValueStart)
159 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
160
161 virtual void anchor();
162
163public:
164 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
165 TranslationUnitDecl *DC,
166 SourceLocation Loc, StringRef Name,
167 StringRef Value);
168 static PragmaDetectMismatchDecl *
169 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
170
171 StringRef getName() const { return getTrailingObjects<char>(); }
172 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
173
174 // Implement isa/cast/dyncast/etc.
175 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
176 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
177};
178
179/// Declaration context for names declared as extern "C" in C++. This
180/// is neither the semantic nor lexical context for such declarations, but is
181/// used to check for conflicts with other extern "C" declarations. Example:
182///
183/// \code
184/// namespace N { extern "C" void f(); } // #1
185/// void N::f() {} // #2
186/// namespace M { extern "C" void f(); } // #3
187/// \endcode
188///
189/// The semantic context of #1 is namespace N and its lexical context is the
190/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
191/// context is the TU. However, both declarations are also visible in the
192/// extern "C" context.
193///
194/// The declaration at #3 finds it is a redeclaration of \c N::f through
195/// lookup in the extern "C" context.
196class ExternCContextDecl : public Decl, public DeclContext {
197 explicit ExternCContextDecl(TranslationUnitDecl *TU)
198 : Decl(ExternCContext, TU, SourceLocation()),
199 DeclContext(ExternCContext) {}
200
201 virtual void anchor();
202
203public:
204 static ExternCContextDecl *Create(const ASTContext &C,
205 TranslationUnitDecl *TU);
206
207 // Implement isa/cast/dyncast/etc.
208 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
209 static bool classofKind(Kind K) { return K == ExternCContext; }
210 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
211 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
212 }
213 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
214 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
215 }
216};
217
218/// This represents a decl that may have a name. Many decls have names such
219/// as ObjCMethodDecl, but not \@class, etc.
220///
221/// Note that not every NamedDecl is actually named (e.g., a struct might
222/// be anonymous), and not every name is an identifier.
223class NamedDecl : public Decl {
224 /// The name of this declaration, which is typically a normal
225 /// identifier but may also be a special kind of name (C++
226 /// constructor, Objective-C selector, etc.)
227 DeclarationName Name;
228
229 virtual void anchor();
230
231private:
232 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
233
234protected:
235 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
236 : Decl(DK, DC, L), Name(N) {}
237
238public:
239 /// Get the identifier that names this declaration, if there is one.
240 ///
241 /// This will return NULL if this declaration has no name (e.g., for
242 /// an unnamed class) or if the name is a special name (C++ constructor,
243 /// Objective-C selector, etc.).
244 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
245
246 /// Get the name of identifier for this declaration as a StringRef.
247 ///
248 /// This requires that the declaration have a name and that it be a simple
249 /// identifier.
250 StringRef getName() const {
251 assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 251, __PRETTY_FUNCTION__))
;
252 return getIdentifier() ? getIdentifier()->getName() : "";
253 }
254
255 /// Get a human-readable name for the declaration, even if it is one of the
256 /// special kinds of names (C++ constructor, Objective-C selector, etc).
257 ///
258 /// Creating this name requires expensive string manipulation, so it should
259 /// be called only when performance doesn't matter. For simple declarations,
260 /// getNameAsCString() should suffice.
261 //
262 // FIXME: This function should be renamed to indicate that it is not just an
263 // alternate form of getName(), and clients should move as appropriate.
264 //
265 // FIXME: Deprecated, move clients to getName().
266 std::string getNameAsString() const { return Name.getAsString(); }
267
268 /// Pretty-print the unqualified name of this declaration. Can be overloaded
269 /// by derived classes to provide a more user-friendly name when appropriate.
270 virtual void printName(raw_ostream &os) const;
271
272 /// Get the actual, stored name of the declaration, which may be a special
273 /// name.
274 ///
275 /// Note that generally in diagnostics, the non-null \p NamedDecl* itself
276 /// should be sent into the diagnostic instead of using the result of
277 /// \p getDeclName().
278 ///
279 /// A \p DeclarationName in a diagnostic will just be streamed to the output,
280 /// which will directly result in a call to \p DeclarationName::print.
281 ///
282 /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to
283 /// \p DeclarationName::print, but with two customisation points along the
284 /// way (\p getNameForDiagnostic and \p printName). These are used to print
285 /// the template arguments if any, and to provide a user-friendly name for
286 /// some entities (such as unnamed variables and anonymous records).
287 DeclarationName getDeclName() const { return Name; }
288
289 /// Set the name of this declaration.
290 void setDeclName(DeclarationName N) { Name = N; }
291
292 /// Returns a human-readable qualified name for this declaration, like
293 /// A::B::i, for i being member of namespace A::B.
294 ///
295 /// If the declaration is not a member of context which can be named (record,
296 /// namespace), it will return the same result as printName().
297 ///
298 /// Creating this name is expensive, so it should be called only when
299 /// performance doesn't matter.
300 void printQualifiedName(raw_ostream &OS) const;
301 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
302
303 /// Print only the nested name specifier part of a fully-qualified name,
304 /// including the '::' at the end. E.g.
305 /// when `printQualifiedName(D)` prints "A::B::i",
306 /// this function prints "A::B::".
307 void printNestedNameSpecifier(raw_ostream &OS) const;
308 void printNestedNameSpecifier(raw_ostream &OS,
309 const PrintingPolicy &Policy) const;
310
311 // FIXME: Remove string version.
312 std::string getQualifiedNameAsString() const;
313
314 /// Appends a human-readable name for this declaration into the given stream.
315 ///
316 /// This is the method invoked by Sema when displaying a NamedDecl
317 /// in a diagnostic. It does not necessarily produce the same
318 /// result as printName(); for example, class template
319 /// specializations are printed with their template arguments.
320 virtual void getNameForDiagnostic(raw_ostream &OS,
321 const PrintingPolicy &Policy,
322 bool Qualified) const;
323
324 /// Determine whether this declaration, if known to be well-formed within
325 /// its context, will replace the declaration OldD if introduced into scope.
326 ///
327 /// A declaration will replace another declaration if, for example, it is
328 /// a redeclaration of the same variable or function, but not if it is a
329 /// declaration of a different kind (function vs. class) or an overloaded
330 /// function.
331 ///
332 /// \param IsKnownNewer \c true if this declaration is known to be newer
333 /// than \p OldD (for instance, if this declaration is newly-created).
334 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
335
336 /// Determine whether this declaration has linkage.
337 bool hasLinkage() const;
338
339 using Decl::isModulePrivate;
340 using Decl::setModulePrivate;
341
342 /// Determine whether this declaration is a C++ class member.
343 bool isCXXClassMember() const {
344 const DeclContext *DC = getDeclContext();
345
346 // C++0x [class.mem]p1:
347 // The enumerators of an unscoped enumeration defined in
348 // the class are members of the class.
349 if (isa<EnumDecl>(DC))
350 DC = DC->getRedeclContext();
351
352 return DC->isRecord();
353 }
354
355 /// Determine whether the given declaration is an instance member of
356 /// a C++ class.
357 bool isCXXInstanceMember() const;
358
359 /// Determine what kind of linkage this entity has.
360 ///
361 /// This is not the linkage as defined by the standard or the codegen notion
362 /// of linkage. It is just an implementation detail that is used to compute
363 /// those.
364 Linkage getLinkageInternal() const;
365
366 /// Get the linkage from a semantic point of view. Entities in
367 /// anonymous namespaces are external (in c++98).
368 Linkage getFormalLinkage() const {
369 return clang::getFormalLinkage(getLinkageInternal());
370 }
371
372 /// True if this decl has external linkage.
373 bool hasExternalFormalLinkage() const {
374 return isExternalFormalLinkage(getLinkageInternal());
375 }
376
377 bool isExternallyVisible() const {
378 return clang::isExternallyVisible(getLinkageInternal());
379 }
380
381 /// Determine whether this declaration can be redeclared in a
382 /// different translation unit.
383 bool isExternallyDeclarable() const {
384 return isExternallyVisible() && !getOwningModuleForLinkage();
385 }
386
387 /// Determines the visibility of this entity.
388 Visibility getVisibility() const {
389 return getLinkageAndVisibility().getVisibility();
390 }
391
392 /// Determines the linkage and visibility of this entity.
393 LinkageInfo getLinkageAndVisibility() const;
394
395 /// Kinds of explicit visibility.
396 enum ExplicitVisibilityKind {
397 /// Do an LV computation for, ultimately, a type.
398 /// Visibility may be restricted by type visibility settings and
399 /// the visibility of template arguments.
400 VisibilityForType,
401
402 /// Do an LV computation for, ultimately, a non-type declaration.
403 /// Visibility may be restricted by value visibility settings and
404 /// the visibility of template arguments.
405 VisibilityForValue
406 };
407
408 /// If visibility was explicitly specified for this
409 /// declaration, return that visibility.
410 Optional<Visibility>
411 getExplicitVisibility(ExplicitVisibilityKind kind) const;
412
413 /// True if the computed linkage is valid. Used for consistency
414 /// checking. Should always return true.
415 bool isLinkageValid() const;
416
417 /// True if something has required us to compute the linkage
418 /// of this declaration.
419 ///
420 /// Language features which can retroactively change linkage (like a
421 /// typedef name for linkage purposes) may need to consider this,
422 /// but hopefully only in transitory ways during parsing.
423 bool hasLinkageBeenComputed() const {
424 return hasCachedLinkage();
425 }
426
427 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
428 /// the underlying named decl.
429 NamedDecl *getUnderlyingDecl() {
430 // Fast-path the common case.
431 if (this->getKind() != UsingShadow &&
432 this->getKind() != ConstructorUsingShadow &&
433 this->getKind() != ObjCCompatibleAlias &&
434 this->getKind() != NamespaceAlias)
435 return this;
436
437 return getUnderlyingDeclImpl();
438 }
439 const NamedDecl *getUnderlyingDecl() const {
440 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
441 }
442
443 NamedDecl *getMostRecentDecl() {
444 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
445 }
446 const NamedDecl *getMostRecentDecl() const {
447 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
448 }
449
450 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
451
452 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
453 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
454};
455
456inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
457 ND.printName(OS);
458 return OS;
459}
460
461/// Represents the declaration of a label. Labels also have a
462/// corresponding LabelStmt, which indicates the position that the label was
463/// defined at. For normal labels, the location of the decl is the same as the
464/// location of the statement. For GNU local labels (__label__), the decl
465/// location is where the __label__ is.
466class LabelDecl : public NamedDecl {
467 LabelStmt *TheStmt;
468 StringRef MSAsmName;
469 bool MSAsmNameResolved = false;
470
471 /// For normal labels, this is the same as the main declaration
472 /// label, i.e., the location of the identifier; for GNU local labels,
473 /// this is the location of the __label__ keyword.
474 SourceLocation LocStart;
475
476 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
477 LabelStmt *S, SourceLocation StartL)
478 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
479
480 void anchor() override;
481
482public:
483 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
484 SourceLocation IdentL, IdentifierInfo *II);
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II,
487 SourceLocation GnuLabelL);
488 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
489
490 LabelStmt *getStmt() const { return TheStmt; }
491 void setStmt(LabelStmt *T) { TheStmt = T; }
492
493 bool isGnuLocal() const { return LocStart != getLocation(); }
494 void setLocStart(SourceLocation L) { LocStart = L; }
495
496 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
497 return SourceRange(LocStart, getLocation());
498 }
499
500 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
501 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
502 void setMSAsmLabel(StringRef Name);
503 StringRef getMSAsmLabel() const { return MSAsmName; }
504 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
505
506 // Implement isa/cast/dyncast/etc.
507 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
508 static bool classofKind(Kind K) { return K == Label; }
509};
510
511/// Represent a C++ namespace.
512class NamespaceDecl : public NamedDecl, public DeclContext,
513 public Redeclarable<NamespaceDecl>
514{
515 /// The starting location of the source range, pointing
516 /// to either the namespace or the inline keyword.
517 SourceLocation LocStart;
518
519 /// The ending location of the source range.
520 SourceLocation RBraceLoc;
521
522 /// A pointer to either the anonymous namespace that lives just inside
523 /// this namespace or to the first namespace in the chain (the latter case
524 /// only when this is not the first in the chain), along with a
525 /// boolean value indicating whether this is an inline namespace.
526 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
527
528 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
529 SourceLocation StartLoc, SourceLocation IdLoc,
530 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
531
532 using redeclarable_base = Redeclarable<NamespaceDecl>;
533
534 NamespaceDecl *getNextRedeclarationImpl() override;
535 NamespaceDecl *getPreviousDeclImpl() override;
536 NamespaceDecl *getMostRecentDeclImpl() override;
537
538public:
539 friend class ASTDeclReader;
540 friend class ASTDeclWriter;
541
542 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
543 bool Inline, SourceLocation StartLoc,
544 SourceLocation IdLoc, IdentifierInfo *Id,
545 NamespaceDecl *PrevDecl);
546
547 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
548
549 using redecl_range = redeclarable_base::redecl_range;
550 using redecl_iterator = redeclarable_base::redecl_iterator;
551
552 using redeclarable_base::redecls_begin;
553 using redeclarable_base::redecls_end;
554 using redeclarable_base::redecls;
555 using redeclarable_base::getPreviousDecl;
556 using redeclarable_base::getMostRecentDecl;
557 using redeclarable_base::isFirstDecl;
558
559 /// Returns true if this is an anonymous namespace declaration.
560 ///
561 /// For example:
562 /// \code
563 /// namespace {
564 /// ...
565 /// };
566 /// \endcode
567 /// q.v. C++ [namespace.unnamed]
568 bool isAnonymousNamespace() const {
569 return !getIdentifier();
570 }
571
572 /// Returns true if this is an inline namespace declaration.
573 bool isInline() const {
574 return AnonOrFirstNamespaceAndInline.getInt();
575 }
576
577 /// Set whether this is an inline namespace declaration.
578 void setInline(bool Inline) {
579 AnonOrFirstNamespaceAndInline.setInt(Inline);
580 }
581
582 /// Get the original (first) namespace declaration.
583 NamespaceDecl *getOriginalNamespace();
584
585 /// Get the original (first) namespace declaration.
586 const NamespaceDecl *getOriginalNamespace() const;
587
588 /// Return true if this declaration is an original (first) declaration
589 /// of the namespace. This is false for non-original (subsequent) namespace
590 /// declarations and anonymous namespaces.
591 bool isOriginalNamespace() const;
592
593 /// Retrieve the anonymous namespace nested inside this namespace,
594 /// if any.
595 NamespaceDecl *getAnonymousNamespace() const {
596 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
597 }
598
599 void setAnonymousNamespace(NamespaceDecl *D) {
600 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
601 }
602
603 /// Retrieves the canonical declaration of this namespace.
604 NamespaceDecl *getCanonicalDecl() override {
605 return getOriginalNamespace();
606 }
607 const NamespaceDecl *getCanonicalDecl() const {
608 return getOriginalNamespace();
609 }
610
611 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
612 return SourceRange(LocStart, RBraceLoc);
613 }
614
615 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
616 SourceLocation getRBraceLoc() const { return RBraceLoc; }
617 void setLocStart(SourceLocation L) { LocStart = L; }
618 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
619
620 // Implement isa/cast/dyncast/etc.
621 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
622 static bool classofKind(Kind K) { return K == Namespace; }
623 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
624 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
625 }
626 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
627 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
628 }
629};
630
631/// Represent the declaration of a variable (in which case it is
632/// an lvalue) a function (in which case it is a function designator) or
633/// an enum constant.
634class ValueDecl : public NamedDecl {
635 QualType DeclType;
636
637 void anchor() override;
638
639protected:
640 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
641 DeclarationName N, QualType T)
642 : NamedDecl(DK, DC, L, N), DeclType(T) {}
643
644public:
645 QualType getType() const { return DeclType; }
646 void setType(QualType newType) { DeclType = newType; }
647
648 /// Determine whether this symbol is weakly-imported,
649 /// or declared with the weak or weak-ref attr.
650 bool isWeak() const;
651
652 // Implement isa/cast/dyncast/etc.
653 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
654 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
655};
656
657/// A struct with extended info about a syntactic
658/// name qualifier, to be used for the case of out-of-line declarations.
659struct QualifierInfo {
660 NestedNameSpecifierLoc QualifierLoc;
661
662 /// The number of "outer" template parameter lists.
663 /// The count includes all of the template parameter lists that were matched
664 /// against the template-ids occurring into the NNS and possibly (in the
665 /// case of an explicit specialization) a final "template <>".
666 unsigned NumTemplParamLists = 0;
667
668 /// A new-allocated array of size NumTemplParamLists,
669 /// containing pointers to the "outer" template parameter lists.
670 /// It includes all of the template parameter lists that were matched
671 /// against the template-ids occurring into the NNS and possibly (in the
672 /// case of an explicit specialization) a final "template <>".
673 TemplateParameterList** TemplParamLists = nullptr;
674
675 QualifierInfo() = default;
676 QualifierInfo(const QualifierInfo &) = delete;
677 QualifierInfo& operator=(const QualifierInfo &) = delete;
678
679 /// Sets info about "outer" template parameter lists.
680 void setTemplateParameterListsInfo(ASTContext &Context,
681 ArrayRef<TemplateParameterList *> TPLists);
682};
683
684/// Represents a ValueDecl that came out of a declarator.
685/// Contains type source information through TypeSourceInfo.
686class DeclaratorDecl : public ValueDecl {
687 // A struct representing a TInfo, a trailing requires-clause and a syntactic
688 // qualifier, to be used for the (uncommon) case of out-of-line declarations
689 // and constrained function decls.
690 struct ExtInfo : public QualifierInfo {
691 TypeSourceInfo *TInfo;
692 Expr *TrailingRequiresClause = nullptr;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 /// \brief Get the constraint-expression introduced by the trailing
760 /// requires-clause in the function/member declaration, or null if no
761 /// requires-clause was provided.
762 Expr *getTrailingRequiresClause() {
763 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
764 : nullptr;
765 }
766
767 const Expr *getTrailingRequiresClause() const {
768 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
769 : nullptr;
770 }
771
772 void setTrailingRequiresClause(Expr *TrailingRequiresClause);
773
774 unsigned getNumTemplateParameterLists() const {
775 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
776 }
777
778 TemplateParameterList *getTemplateParameterList(unsigned index) const {
779 assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast<
void> (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 779, __PRETTY_FUNCTION__))
;
780 return getExtInfo()->TemplParamLists[index];
781 }
782
783 void setTemplateParameterListsInfo(ASTContext &Context,
784 ArrayRef<TemplateParameterList *> TPLists);
785
786 SourceLocation getTypeSpecStartLoc() const;
787 SourceLocation getTypeSpecEndLoc() const;
788
789 // Implement isa/cast/dyncast/etc.
790 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
791 static bool classofKind(Kind K) {
792 return K >= firstDeclarator && K <= lastDeclarator;
793 }
794};
795
796/// Structure used to store a statement, the constant value to
797/// which it was evaluated (if any), and whether or not the statement
798/// is an integral constant expression (if known).
799struct EvaluatedStmt {
800 /// Whether this statement was already evaluated.
801 bool WasEvaluated : 1;
802
803 /// Whether this statement is being evaluated.
804 bool IsEvaluating : 1;
805
806 /// Whether this variable is known to have constant initialization. This is
807 /// currently only computed in C++, for static / thread storage duration
808 /// variables that might have constant initialization and for variables that
809 /// are usable in constant expressions.
810 bool HasConstantInitialization : 1;
811
812 /// Whether this variable is known to have constant destruction. That is,
813 /// whether running the destructor on the initial value is a side-effect
814 /// (and doesn't inspect any state that might have changed during program
815 /// execution). This is currently only computed if the destructor is
816 /// non-trivial.
817 bool HasConstantDestruction : 1;
818
819 /// In C++98, whether the initializer is an ICE. This affects whether the
820 /// variable is usable in constant expressions.
821 bool HasICEInit : 1;
822 bool CheckedForICEInit : 1;
823
824 Stmt *Value;
825 APValue Evaluated;
826
827 EvaluatedStmt()
828 : WasEvaluated(false), IsEvaluating(false),
829 HasConstantInitialization(false), HasConstantDestruction(false),
830 HasICEInit(false), CheckedForICEInit(false) {}
831};
832
833/// Represents a variable declaration or definition.
834class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
835public:
836 /// Initialization styles.
837 enum InitializationStyle {
838 /// C-style initialization with assignment
839 CInit,
840
841 /// Call-style initialization (C++98)
842 CallInit,
843
844 /// Direct list-initialization (C++11)
845 ListInit
846 };
847
848 /// Kinds of thread-local storage.
849 enum TLSKind {
850 /// Not a TLS variable.
851 TLS_None,
852
853 /// TLS with a known-constant initializer.
854 TLS_Static,
855
856 /// TLS with a dynamic initializer.
857 TLS_Dynamic
858 };
859
860 /// Return the string used to specify the storage class \p SC.
861 ///
862 /// It is illegal to call this function with SC == None.
863 static const char *getStorageClassSpecifierString(StorageClass SC);
864
865protected:
866 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
867 // have allocated the auxiliary struct of information there.
868 //
869 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
870 // this as *many* VarDecls are ParmVarDecls that don't have default
871 // arguments. We could save some space by moving this pointer union to be
872 // allocated in trailing space when necessary.
873 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
874
875 /// The initializer for this variable or, for a ParmVarDecl, the
876 /// C++ default argument.
877 mutable InitType Init;
878
879private:
880 friend class ASTDeclReader;
881 friend class ASTNodeImporter;
882 friend class StmtIteratorBase;
883
884 class VarDeclBitfields {
885 friend class ASTDeclReader;
886 friend class VarDecl;
887
888 unsigned SClass : 3;
889 unsigned TSCSpec : 2;
890 unsigned InitStyle : 2;
891
892 /// Whether this variable is an ARC pseudo-__strong variable; see
893 /// isARCPseudoStrong() for details.
894 unsigned ARCPseudoStrong : 1;
895 };
896 enum { NumVarDeclBits = 8 };
897
898protected:
899 enum { NumParameterIndexBits = 8 };
900
901 enum DefaultArgKind {
902 DAK_None,
903 DAK_Unparsed,
904 DAK_Uninstantiated,
905 DAK_Normal
906 };
907
908 enum { NumScopeDepthOrObjCQualsBits = 7 };
909
910 class ParmVarDeclBitfields {
911 friend class ASTDeclReader;
912 friend class ParmVarDecl;
913
914 unsigned : NumVarDeclBits;
915
916 /// Whether this parameter inherits a default argument from a
917 /// prior declaration.
918 unsigned HasInheritedDefaultArg : 1;
919
920 /// Describes the kind of default argument for this parameter. By default
921 /// this is none. If this is normal, then the default argument is stored in
922 /// the \c VarDecl initializer expression unless we were unable to parse
923 /// (even an invalid) expression for the default argument.
924 unsigned DefaultArgKind : 2;
925
926 /// Whether this parameter undergoes K&R argument promotion.
927 unsigned IsKNRPromoted : 1;
928
929 /// Whether this parameter is an ObjC method parameter or not.
930 unsigned IsObjCMethodParam : 1;
931
932 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
933 /// Otherwise, the number of function parameter scopes enclosing
934 /// the function parameter scope in which this parameter was
935 /// declared.
936 unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
937
938 /// The number of parameters preceding this parameter in the
939 /// function parameter scope in which it was declared.
940 unsigned ParameterIndex : NumParameterIndexBits;
941 };
942
943 class NonParmVarDeclBitfields {
944 friend class ASTDeclReader;
945 friend class ImplicitParamDecl;
946 friend class VarDecl;
947
948 unsigned : NumVarDeclBits;
949
950 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
951 /// Whether this variable is a definition which was demoted due to
952 /// module merge.
953 unsigned IsThisDeclarationADemotedDefinition : 1;
954
955 /// Whether this variable is the exception variable in a C++ catch
956 /// or an Objective-C @catch statement.
957 unsigned ExceptionVar : 1;
958
959 /// Whether this local variable could be allocated in the return
960 /// slot of its function, enabling the named return value optimization
961 /// (NRVO).
962 unsigned NRVOVariable : 1;
963
964 /// Whether this variable is the for-range-declaration in a C++0x
965 /// for-range statement.
966 unsigned CXXForRangeDecl : 1;
967
968 /// Whether this variable is the for-in loop declaration in Objective-C.
969 unsigned ObjCForDecl : 1;
970
971 /// Whether this variable is (C++1z) inline.
972 unsigned IsInline : 1;
973
974 /// Whether this variable has (C++1z) inline explicitly specified.
975 unsigned IsInlineSpecified : 1;
976
977 /// Whether this variable is (C++0x) constexpr.
978 unsigned IsConstexpr : 1;
979
980 /// Whether this variable is the implicit variable for a lambda
981 /// init-capture.
982 unsigned IsInitCapture : 1;
983
984 /// Whether this local extern variable's previous declaration was
985 /// declared in the same block scope. This controls whether we should merge
986 /// the type of this declaration with its previous declaration.
987 unsigned PreviousDeclInSameBlockScope : 1;
988
989 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
990 /// something else.
991 unsigned ImplicitParamKind : 3;
992
993 unsigned EscapingByref : 1;
994 };
995
996 union {
997 unsigned AllBits;
998 VarDeclBitfields VarDeclBits;
999 ParmVarDeclBitfields ParmVarDeclBits;
1000 NonParmVarDeclBitfields NonParmVarDeclBits;
1001 };
1002
1003 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1004 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1005 TypeSourceInfo *TInfo, StorageClass SC);
1006
1007 using redeclarable_base = Redeclarable<VarDecl>;
1008
1009 VarDecl *getNextRedeclarationImpl() override {
1010 return getNextRedeclaration();
1011 }
1012
1013 VarDecl *getPreviousDeclImpl() override {
1014 return getPreviousDecl();
1015 }
1016
1017 VarDecl *getMostRecentDeclImpl() override {
1018 return getMostRecentDecl();
1019 }
1020
1021public:
1022 using redecl_range = redeclarable_base::redecl_range;
1023 using redecl_iterator = redeclarable_base::redecl_iterator;
1024
1025 using redeclarable_base::redecls_begin;
1026 using redeclarable_base::redecls_end;
1027 using redeclarable_base::redecls;
1028 using redeclarable_base::getPreviousDecl;
1029 using redeclarable_base::getMostRecentDecl;
1030 using redeclarable_base::isFirstDecl;
1031
1032 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1033 SourceLocation StartLoc, SourceLocation IdLoc,
1034 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1035 StorageClass S);
1036
1037 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1038
1039 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1040
1041 /// Returns the storage class as written in the source. For the
1042 /// computed linkage of symbol, see getLinkage.
1043 StorageClass getStorageClass() const {
1044 return (StorageClass) VarDeclBits.SClass;
1045 }
1046 void setStorageClass(StorageClass SC);
1047
1048 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1049 VarDeclBits.TSCSpec = TSC;
1050 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1050, __PRETTY_FUNCTION__))
;
1051 }
1052 ThreadStorageClassSpecifier getTSCSpec() const {
1053 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1054 }
1055 TLSKind getTLSKind() const;
1056
1057 /// Returns true if a variable with function scope is a non-static local
1058 /// variable.
1059 bool hasLocalStorage() const {
1060 if (getStorageClass() == SC_None) {
1061 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1062 // used to describe variables allocated in global memory and which are
1063 // accessed inside a kernel(s) as read-only variables. As such, variables
1064 // in constant address space cannot have local storage.
1065 if (getType().getAddressSpace() == LangAS::opencl_constant)
1066 return false;
1067 // Second check is for C++11 [dcl.stc]p4.
1068 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1069 }
1070
1071 // Global Named Register (GNU extension)
1072 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1073 return false;
1074
1075 // Return true for: Auto, Register.
1076 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1077
1078 return getStorageClass() >= SC_Auto;
1079 }
1080
1081 /// Returns true if a variable with function scope is a static local
1082 /// variable.
1083 bool isStaticLocal() const {
1084 return (getStorageClass() == SC_Static ||
1085 // C++11 [dcl.stc]p4
1086 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1087 && !isFileVarDecl();
1088 }
1089
1090 /// Returns true if a variable has extern or __private_extern__
1091 /// storage.
1092 bool hasExternalStorage() const {
1093 return getStorageClass() == SC_Extern ||
1094 getStorageClass() == SC_PrivateExtern;
1095 }
1096
1097 /// Returns true for all variables that do not have local storage.
1098 ///
1099 /// This includes all global variables as well as static variables declared
1100 /// within a function.
1101 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1102
1103 /// Get the storage duration of this variable, per C++ [basic.stc].
1104 StorageDuration getStorageDuration() const {
1105 return hasLocalStorage() ? SD_Automatic :
1106 getTSCSpec() ? SD_Thread : SD_Static;
1107 }
1108
1109 /// Compute the language linkage.
1110 LanguageLinkage getLanguageLinkage() const;
1111
1112 /// Determines whether this variable is a variable with external, C linkage.
1113 bool isExternC() const;
1114
1115 /// Determines whether this variable's context is, or is nested within,
1116 /// a C++ extern "C" linkage spec.
1117 bool isInExternCContext() const;
1118
1119 /// Determines whether this variable's context is, or is nested within,
1120 /// a C++ extern "C++" linkage spec.
1121 bool isInExternCXXContext() const;
1122
1123 /// Returns true for local variable declarations other than parameters.
1124 /// Note that this includes static variables inside of functions. It also
1125 /// includes variables inside blocks.
1126 ///
1127 /// void foo() { int x; static int y; extern int z; }
1128 bool isLocalVarDecl() const {
1129 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1130 return false;
1131 if (const DeclContext *DC = getLexicalDeclContext())
1132 return DC->getRedeclContext()->isFunctionOrMethod();
1133 return false;
1134 }
1135
1136 /// Similar to isLocalVarDecl but also includes parameters.
1137 bool isLocalVarDeclOrParm() const {
1138 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1139 }
1140
1141 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1142 bool isFunctionOrMethodVarDecl() const {
1143 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1144 return false;
1145 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1146 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1147 }
1148
1149 /// Determines whether this is a static data member.
1150 ///
1151 /// This will only be true in C++, and applies to, e.g., the
1152 /// variable 'x' in:
1153 /// \code
1154 /// struct S {
1155 /// static int x;
1156 /// };
1157 /// \endcode
1158 bool isStaticDataMember() const {
1159 // If it wasn't static, it would be a FieldDecl.
1160 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1161 }
1162
1163 VarDecl *getCanonicalDecl() override;
1164 const VarDecl *getCanonicalDecl() const {
1165 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1166 }
1167
1168 enum DefinitionKind {
1169 /// This declaration is only a declaration.
1170 DeclarationOnly,
1171
1172 /// This declaration is a tentative definition.
1173 TentativeDefinition,
1174
1175 /// This declaration is definitely a definition.
1176 Definition
1177 };
1178
1179 /// Check whether this declaration is a definition. If this could be
1180 /// a tentative definition (in C), don't check whether there's an overriding
1181 /// definition.
1182 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1183 DefinitionKind isThisDeclarationADefinition() const {
1184 return isThisDeclarationADefinition(getASTContext());
1185 }
1186
1187 /// Check whether this variable is defined in this translation unit.
1188 DefinitionKind hasDefinition(ASTContext &) const;
1189 DefinitionKind hasDefinition() const {
1190 return hasDefinition(getASTContext());
1191 }
1192
1193 /// Get the tentative definition that acts as the real definition in a TU.
1194 /// Returns null if there is a proper definition available.
1195 VarDecl *getActingDefinition();
1196 const VarDecl *getActingDefinition() const {
1197 return const_cast<VarDecl*>(this)->getActingDefinition();
1198 }
1199
1200 /// Get the real (not just tentative) definition for this declaration.
1201 VarDecl *getDefinition(ASTContext &);
1202 const VarDecl *getDefinition(ASTContext &C) const {
1203 return const_cast<VarDecl*>(this)->getDefinition(C);
1204 }
1205 VarDecl *getDefinition() {
1206 return getDefinition(getASTContext());
1207 }
1208 const VarDecl *getDefinition() const {
1209 return const_cast<VarDecl*>(this)->getDefinition();
1210 }
1211
1212 /// Determine whether this is or was instantiated from an out-of-line
1213 /// definition of a static data member.
1214 bool isOutOfLine() const override;
1215
1216 /// Returns true for file scoped variable declaration.
1217 bool isFileVarDecl() const {
1218 Kind K = getKind();
1219 if (K == ParmVar || K == ImplicitParam)
1220 return false;
1221
1222 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1223 return true;
1224
1225 if (isStaticDataMember())
1226 return true;
1227
1228 return false;
1229 }
1230
1231 /// Get the initializer for this variable, no matter which
1232 /// declaration it is attached to.
1233 const Expr *getAnyInitializer() const {
1234 const VarDecl *D;
1235 return getAnyInitializer(D);
1236 }
1237
1238 /// Get the initializer for this variable, no matter which
1239 /// declaration it is attached to. Also get that declaration.
1240 const Expr *getAnyInitializer(const VarDecl *&D) const;
1241
1242 bool hasInit() const;
1243 const Expr *getInit() const {
1244 return const_cast<VarDecl *>(this)->getInit();
1245 }
1246 Expr *getInit();
1247
1248 /// Retrieve the address of the initializer expression.
1249 Stmt **getInitAddress();
1250
1251 void setInit(Expr *I);
1252
1253 /// Get the initializing declaration of this variable, if any. This is
1254 /// usually the definition, except that for a static data member it can be
1255 /// the in-class declaration.
1256 VarDecl *getInitializingDeclaration();
1257 const VarDecl *getInitializingDeclaration() const {
1258 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1259 }
1260
1261 /// Determine whether this variable's value might be usable in a
1262 /// constant expression, according to the relevant language standard.
1263 /// This only checks properties of the declaration, and does not check
1264 /// whether the initializer is in fact a constant expression.
1265 ///
1266 /// This corresponds to C++20 [expr.const]p3's notion of a
1267 /// "potentially-constant" variable.
1268 bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
1269
1270 /// Determine whether this variable's value can be used in a
1271 /// constant expression, according to the relevant language standard,
1272 /// including checking whether it was initialized by a constant expression.
1273 bool isUsableInConstantExpressions(const ASTContext &C) const;
1274
1275 EvaluatedStmt *ensureEvaluatedStmt() const;
1276 EvaluatedStmt *getEvaluatedStmt() const;
1277
1278 /// Attempt to evaluate the value of the initializer attached to this
1279 /// declaration, and produce notes explaining why it cannot be evaluated.
1280 /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
1281 APValue *evaluateValue() const;
1282
1283private:
1284 APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
1285 bool IsConstantInitialization) const;
1286
1287public:
1288 /// Return the already-evaluated value of this variable's
1289 /// initializer, or NULL if the value is not yet known. Returns pointer
1290 /// to untyped APValue if the value could not be evaluated.
1291 APValue *getEvaluatedValue() const;
1292
1293 /// Evaluate the destruction of this variable to determine if it constitutes
1294 /// constant destruction.
1295 ///
1296 /// \pre hasConstantInitialization()
1297 /// \return \c true if this variable has constant destruction, \c false if
1298 /// not.
1299 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1300
1301 /// Determine whether this variable has constant initialization.
1302 ///
1303 /// This is only set in two cases: when the language semantics require
1304 /// constant initialization (globals in C and some globals in C++), and when
1305 /// the variable is usable in constant expressions (constexpr, const int, and
1306 /// reference variables in C++).
1307 bool hasConstantInitialization() const;
1308
1309 /// Determine whether the initializer of this variable is an integer constant
1310 /// expression. For use in C++98, where this affects whether the variable is
1311 /// usable in constant expressions.
1312 bool hasICEInitializer(const ASTContext &Context) const;
1313
1314 /// Evaluate the initializer of this variable to determine whether it's a
1315 /// constant initializer. Should only be called once, after completing the
1316 /// definition of the variable.
1317 bool checkForConstantInitialization(
1318 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1319
1320 void setInitStyle(InitializationStyle Style) {
1321 VarDeclBits.InitStyle = Style;
1322 }
1323
1324 /// The style of initialization for this declaration.
1325 ///
1326 /// C-style initialization is "int x = 1;". Call-style initialization is
1327 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1328 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1329 /// expression for class types. List-style initialization is C++11 syntax,
1330 /// e.g. "int x{1};". Clients can distinguish between different forms of
1331 /// initialization by checking this value. In particular, "int x = {1};" is
1332 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1333 /// Init expression in all three cases is an InitListExpr.
1334 InitializationStyle getInitStyle() const {
1335 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1336 }
1337
1338 /// Whether the initializer is a direct-initializer (list or call).
1339 bool isDirectInit() const {
1340 return getInitStyle() != CInit;
1341 }
1342
1343 /// If this definition should pretend to be a declaration.
1344 bool isThisDeclarationADemotedDefinition() const {
1345 return isa<ParmVarDecl>(this) ? false :
1346 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1347 }
1348
1349 /// This is a definition which should be demoted to a declaration.
1350 ///
1351 /// In some cases (mostly module merging) we can end up with two visible
1352 /// definitions one of which needs to be demoted to a declaration to keep
1353 /// the AST invariants.
1354 void demoteThisDefinitionToDeclaration() {
1355 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1355, __PRETTY_FUNCTION__))
;
1356 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1356, __PRETTY_FUNCTION__))
;
1357 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1358 }
1359
1360 /// Determine whether this variable is the exception variable in a
1361 /// C++ catch statememt or an Objective-C \@catch statement.
1362 bool isExceptionVariable() const {
1363 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1364 }
1365 void setExceptionVariable(bool EV) {
1366 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1366, __PRETTY_FUNCTION__))
;
1367 NonParmVarDeclBits.ExceptionVar = EV;
1368 }
1369
1370 /// Determine whether this local variable can be used with the named
1371 /// return value optimization (NRVO).
1372 ///
1373 /// The named return value optimization (NRVO) works by marking certain
1374 /// non-volatile local variables of class type as NRVO objects. These
1375 /// locals can be allocated within the return slot of their containing
1376 /// function, in which case there is no need to copy the object to the
1377 /// return slot when returning from the function. Within the function body,
1378 /// each return that returns the NRVO object will have this variable as its
1379 /// NRVO candidate.
1380 bool isNRVOVariable() const {
1381 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1382 }
1383 void setNRVOVariable(bool NRVO) {
1384 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1384, __PRETTY_FUNCTION__))
;
1385 NonParmVarDeclBits.NRVOVariable = NRVO;
1386 }
1387
1388 /// Determine whether this variable is the for-range-declaration in
1389 /// a C++0x for-range statement.
1390 bool isCXXForRangeDecl() const {
1391 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1392 }
1393 void setCXXForRangeDecl(bool FRD) {
1394 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1394, __PRETTY_FUNCTION__))
;
1395 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1396 }
1397
1398 /// Determine whether this variable is a for-loop declaration for a
1399 /// for-in statement in Objective-C.
1400 bool isObjCForDecl() const {
1401 return NonParmVarDeclBits.ObjCForDecl;
1402 }
1403
1404 void setObjCForDecl(bool FRD) {
1405 NonParmVarDeclBits.ObjCForDecl = FRD;
1406 }
1407
1408 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1409 /// pseudo-__strong variable has a __strong-qualified type but does not
1410 /// actually retain the object written into it. Generally such variables are
1411 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1412 /// the variable is annotated with the objc_externally_retained attribute, 2)
1413 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1414 /// loop.
1415 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1416 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1417
1418 /// Whether this variable is (C++1z) inline.
1419 bool isInline() const {
1420 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1421 }
1422 bool isInlineSpecified() const {
1423 return isa<ParmVarDecl>(this) ? false
1424 : NonParmVarDeclBits.IsInlineSpecified;
1425 }
1426 void setInlineSpecified() {
1427 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1427, __PRETTY_FUNCTION__))
;
1428 NonParmVarDeclBits.IsInline = true;
1429 NonParmVarDeclBits.IsInlineSpecified = true;
1430 }
1431 void setImplicitlyInline() {
1432 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1432, __PRETTY_FUNCTION__))
;
1433 NonParmVarDeclBits.IsInline = true;
1434 }
1435
1436 /// Whether this variable is (C++11) constexpr.
1437 bool isConstexpr() const {
1438 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1439 }
1440 void setConstexpr(bool IC) {
1441 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1441, __PRETTY_FUNCTION__))
;
1442 NonParmVarDeclBits.IsConstexpr = IC;
1443 }
1444
1445 /// Whether this variable is the implicit variable for a lambda init-capture.
1446 bool isInitCapture() const {
1447 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1448 }
1449 void setInitCapture(bool IC) {
1450 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1450, __PRETTY_FUNCTION__))
;
1451 NonParmVarDeclBits.IsInitCapture = IC;
1452 }
1453
1454 /// Determine whether this variable is actually a function parameter pack or
1455 /// init-capture pack.
1456 bool isParameterPack() const;
1457
1458 /// Whether this local extern variable declaration's previous declaration
1459 /// was declared in the same block scope. Only correct in C++.
1460 bool isPreviousDeclInSameBlockScope() const {
1461 return isa<ParmVarDecl>(this)
1462 ? false
1463 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1464 }
1465 void setPreviousDeclInSameBlockScope(bool Same) {
1466 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1466, __PRETTY_FUNCTION__))
;
1467 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1468 }
1469
1470 /// Indicates the capture is a __block variable that is captured by a block
1471 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1472 /// returns false).
1473 bool isEscapingByref() const;
1474
1475 /// Indicates the capture is a __block variable that is never captured by an
1476 /// escaping block.
1477 bool isNonEscapingByref() const;
1478
1479 void setEscapingByref() {
1480 NonParmVarDeclBits.EscapingByref = true;
1481 }
1482
1483 /// Retrieve the variable declaration from which this variable could
1484 /// be instantiated, if it is an instantiation (rather than a non-template).
1485 VarDecl *getTemplateInstantiationPattern() const;
1486
1487 /// If this variable is an instantiated static data member of a
1488 /// class template specialization, returns the templated static data member
1489 /// from which it was instantiated.
1490 VarDecl *getInstantiatedFromStaticDataMember() const;
1491
1492 /// If this variable is an instantiation of a variable template or a
1493 /// static data member of a class template, determine what kind of
1494 /// template specialization or instantiation this is.
1495 TemplateSpecializationKind getTemplateSpecializationKind() const;
1496
1497 /// Get the template specialization kind of this variable for the purposes of
1498 /// template instantiation. This differs from getTemplateSpecializationKind()
1499 /// for an instantiation of a class-scope explicit specialization.
1500 TemplateSpecializationKind
1501 getTemplateSpecializationKindForInstantiation() const;
1502
1503 /// If this variable is an instantiation of a variable template or a
1504 /// static data member of a class template, determine its point of
1505 /// instantiation.
1506 SourceLocation getPointOfInstantiation() const;
1507
1508 /// If this variable is an instantiation of a static data member of a
1509 /// class template specialization, retrieves the member specialization
1510 /// information.
1511 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1512
1513 /// For a static data member that was instantiated from a static
1514 /// data member of a class template, set the template specialiation kind.
1515 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1516 SourceLocation PointOfInstantiation = SourceLocation());
1517
1518 /// Specify that this variable is an instantiation of the
1519 /// static data member VD.
1520 void setInstantiationOfStaticDataMember(VarDecl *VD,
1521 TemplateSpecializationKind TSK);
1522
1523 /// Retrieves the variable template that is described by this
1524 /// variable declaration.
1525 ///
1526 /// Every variable template is represented as a VarTemplateDecl and a
1527 /// VarDecl. The former contains template properties (such as
1528 /// the template parameter lists) while the latter contains the
1529 /// actual description of the template's
1530 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1531 /// VarDecl that from a VarTemplateDecl, while
1532 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1533 /// a VarDecl.
1534 VarTemplateDecl *getDescribedVarTemplate() const;
1535
1536 void setDescribedVarTemplate(VarTemplateDecl *Template);
1537
1538 // Is this variable known to have a definition somewhere in the complete
1539 // program? This may be true even if the declaration has internal linkage and
1540 // has no definition within this source file.
1541 bool isKnownToBeDefined() const;
1542
1543 /// Is destruction of this variable entirely suppressed? If so, the variable
1544 /// need not have a usable destructor at all.
1545 bool isNoDestroy(const ASTContext &) const;
1546
1547 /// Would the destruction of this variable have any effect, and if so, what
1548 /// kind?
1549 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1550
1551 // Implement isa/cast/dyncast/etc.
1552 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1553 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1554};
1555
1556class ImplicitParamDecl : public VarDecl {
1557 void anchor() override;
1558
1559public:
1560 /// Defines the kind of the implicit parameter: is this an implicit parameter
1561 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1562 /// context or something else.
1563 enum ImplicitParamKind : unsigned {
1564 /// Parameter for Objective-C 'self' argument
1565 ObjCSelf,
1566
1567 /// Parameter for Objective-C '_cmd' argument
1568 ObjCCmd,
1569
1570 /// Parameter for C++ 'this' argument
1571 CXXThis,
1572
1573 /// Parameter for C++ virtual table pointers
1574 CXXVTT,
1575
1576 /// Parameter for captured context
1577 CapturedContext,
1578
1579 /// Other implicit parameter
1580 Other,
1581 };
1582
1583 /// Create implicit parameter.
1584 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1585 SourceLocation IdLoc, IdentifierInfo *Id,
1586 QualType T, ImplicitParamKind ParamKind);
1587 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1588 ImplicitParamKind ParamKind);
1589
1590 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1591
1592 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1593 IdentifierInfo *Id, QualType Type,
1594 ImplicitParamKind ParamKind)
1595 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1596 /*TInfo=*/nullptr, SC_None) {
1597 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1598 setImplicit();
1599 }
1600
1601 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1602 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1603 SourceLocation(), /*Id=*/nullptr, Type,
1604 /*TInfo=*/nullptr, SC_None) {
1605 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1606 setImplicit();
1607 }
1608
1609 /// Returns the implicit parameter kind.
1610 ImplicitParamKind getParameterKind() const {
1611 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1612 }
1613
1614 // Implement isa/cast/dyncast/etc.
1615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1616 static bool classofKind(Kind K) { return K == ImplicitParam; }
1617};
1618
1619/// Represents a parameter to a function.
1620class ParmVarDecl : public VarDecl {
1621public:
1622 enum { MaxFunctionScopeDepth = 255 };
1623 enum { MaxFunctionScopeIndex = 255 };
1624
1625protected:
1626 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1627 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1628 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1629 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1630 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast
<void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1630, __PRETTY_FUNCTION__))
;
1631 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1631, __PRETTY_FUNCTION__))
;
1632 assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void
> (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1632, __PRETTY_FUNCTION__))
;
1633 assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1633, __PRETTY_FUNCTION__))
;
1634 setDefaultArg(DefArg);
1635 }
1636
1637public:
1638 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1639 SourceLocation StartLoc,
1640 SourceLocation IdLoc, IdentifierInfo *Id,
1641 QualType T, TypeSourceInfo *TInfo,
1642 StorageClass S, Expr *DefArg);
1643
1644 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1645
1646 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1647
1648 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1649 ParmVarDeclBits.IsObjCMethodParam = true;
1650 setParameterIndex(parameterIndex);
1651 }
1652
1653 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1654 assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1654, __PRETTY_FUNCTION__))
;
1655
1656 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1657 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1658, __PRETTY_FUNCTION__))
1658 && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1658, __PRETTY_FUNCTION__))
;
1659
1660 setParameterIndex(parameterIndex);
1661 }
1662
1663 bool isObjCMethodParameter() const {
1664 return ParmVarDeclBits.IsObjCMethodParam;
1665 }
1666
1667 /// Determines whether this parameter is destroyed in the callee function.
1668 bool isDestroyedInCallee() const;
1669
1670 unsigned getFunctionScopeDepth() const {
1671 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1672 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1673 }
1674
1675 static constexpr unsigned getMaxFunctionScopeDepth() {
1676 return (1u << NumScopeDepthOrObjCQualsBits) - 1;
1677 }
1678
1679 /// Returns the index of this parameter in its prototype or method scope.
1680 unsigned getFunctionScopeIndex() const {
1681 return getParameterIndex();
1682 }
1683
1684 ObjCDeclQualifier getObjCDeclQualifier() const {
1685 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1686 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1687 }
1688 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1689 assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1689, __PRETTY_FUNCTION__))
;
1690 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1691 }
1692
1693 /// True if the value passed to this parameter must undergo
1694 /// K&R-style default argument promotion:
1695 ///
1696 /// C99 6.5.2.2.
1697 /// If the expression that denotes the called function has a type
1698 /// that does not include a prototype, the integer promotions are
1699 /// performed on each argument, and arguments that have type float
1700 /// are promoted to double.
1701 bool isKNRPromoted() const {
1702 return ParmVarDeclBits.IsKNRPromoted;
1703 }
1704 void setKNRPromoted(bool promoted) {
1705 ParmVarDeclBits.IsKNRPromoted = promoted;
1706 }
1707
1708 Expr *getDefaultArg();
1709 const Expr *getDefaultArg() const {
1710 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1711 }
1712
1713 void setDefaultArg(Expr *defarg);
1714
1715 /// Retrieve the source range that covers the entire default
1716 /// argument.
1717 SourceRange getDefaultArgRange() const;
1718 void setUninstantiatedDefaultArg(Expr *arg);
1719 Expr *getUninstantiatedDefaultArg();
1720 const Expr *getUninstantiatedDefaultArg() const {
1721 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1722 }
1723
1724 /// Determines whether this parameter has a default argument,
1725 /// either parsed or not.
1726 bool hasDefaultArg() const;
1727
1728 /// Determines whether this parameter has a default argument that has not
1729 /// yet been parsed. This will occur during the processing of a C++ class
1730 /// whose member functions have default arguments, e.g.,
1731 /// @code
1732 /// class X {
1733 /// public:
1734 /// void f(int x = 17); // x has an unparsed default argument now
1735 /// }; // x has a regular default argument now
1736 /// @endcode
1737 bool hasUnparsedDefaultArg() const {
1738 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1739 }
1740
1741 bool hasUninstantiatedDefaultArg() const {
1742 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1743 }
1744
1745 /// Specify that this parameter has an unparsed default argument.
1746 /// The argument will be replaced with a real default argument via
1747 /// setDefaultArg when the class definition enclosing the function
1748 /// declaration that owns this default argument is completed.
1749 void setUnparsedDefaultArg() {
1750 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1751 }
1752
1753 bool hasInheritedDefaultArg() const {
1754 return ParmVarDeclBits.HasInheritedDefaultArg;
1755 }
1756
1757 void setHasInheritedDefaultArg(bool I = true) {
1758 ParmVarDeclBits.HasInheritedDefaultArg = I;
1759 }
1760
1761 QualType getOriginalType() const;
1762
1763 /// Sets the function declaration that owns this
1764 /// ParmVarDecl. Since ParmVarDecls are often created before the
1765 /// FunctionDecls that own them, this routine is required to update
1766 /// the DeclContext appropriately.
1767 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1768
1769 // Implement isa/cast/dyncast/etc.
1770 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1771 static bool classofKind(Kind K) { return K == ParmVar; }
1772
1773private:
1774 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1775
1776 void setParameterIndex(unsigned parameterIndex) {
1777 if (parameterIndex >= ParameterIndexSentinel) {
1778 setParameterIndexLarge(parameterIndex);
1779 return;
1780 }
1781
1782 ParmVarDeclBits.ParameterIndex = parameterIndex;
1783 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 1783, __PRETTY_FUNCTION__))
;
1784 }
1785 unsigned getParameterIndex() const {
1786 unsigned d = ParmVarDeclBits.ParameterIndex;
1787 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1788 }
1789
1790 void setParameterIndexLarge(unsigned parameterIndex);
1791 unsigned getParameterIndexLarge() const;
1792};
1793
1794enum class MultiVersionKind {
1795 None,
1796 Target,
1797 CPUSpecific,
1798 CPUDispatch
1799};
1800
1801/// Represents a function declaration or definition.
1802///
1803/// Since a given function can be declared several times in a program,
1804/// there may be several FunctionDecls that correspond to that
1805/// function. Only one of those FunctionDecls will be found when
1806/// traversing the list of declarations in the context of the
1807/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1808/// contains all of the information known about the function. Other,
1809/// previous declarations of the function are available via the
1810/// getPreviousDecl() chain.
1811class FunctionDecl : public DeclaratorDecl,
1812 public DeclContext,
1813 public Redeclarable<FunctionDecl> {
1814 // This class stores some data in DeclContext::FunctionDeclBits
1815 // to save some space. Use the provided accessors to access it.
1816public:
1817 /// The kind of templated function a FunctionDecl can be.
1818 enum TemplatedKind {
1819 // Not templated.
1820 TK_NonTemplate,
1821 // The pattern in a function template declaration.
1822 TK_FunctionTemplate,
1823 // A non-template function that is an instantiation or explicit
1824 // specialization of a member of a templated class.
1825 TK_MemberSpecialization,
1826 // An instantiation or explicit specialization of a function template.
1827 // Note: this might have been instantiated from a templated class if it
1828 // is a class-scope explicit specialization.
1829 TK_FunctionTemplateSpecialization,
1830 // A function template specialization that hasn't yet been resolved to a
1831 // particular specialized function template.
1832 TK_DependentFunctionTemplateSpecialization
1833 };
1834
1835 /// Stashed information about a defaulted function definition whose body has
1836 /// not yet been lazily generated.
1837 class DefaultedFunctionInfo final
1838 : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> {
1839 friend TrailingObjects;
1840 unsigned NumLookups;
1841
1842 public:
1843 static DefaultedFunctionInfo *Create(ASTContext &Context,
1844 ArrayRef<DeclAccessPair> Lookups);
1845 /// Get the unqualified lookup results that should be used in this
1846 /// defaulted function definition.
1847 ArrayRef<DeclAccessPair> getUnqualifiedLookups() const {
1848 return {getTrailingObjects<DeclAccessPair>(), NumLookups};
1849 }
1850 };
1851
1852private:
1853 /// A new[]'d array of pointers to VarDecls for the formal
1854 /// parameters of this function. This is null if a prototype or if there are
1855 /// no formals.
1856 ParmVarDecl **ParamInfo = nullptr;
1857
1858 /// The active member of this union is determined by
1859 /// FunctionDeclBits.HasDefaultedFunctionInfo.
1860 union {
1861 /// The body of the function.
1862 LazyDeclStmtPtr Body;
1863 /// Information about a future defaulted function definition.
1864 DefaultedFunctionInfo *DefaultedInfo;
1865 };
1866
1867 unsigned ODRHash;
1868
1869 /// End part of this FunctionDecl's source range.
1870 ///
1871 /// We could compute the full range in getSourceRange(). However, when we're
1872 /// dealing with a function definition deserialized from a PCH/AST file,
1873 /// we can only compute the full range once the function body has been
1874 /// de-serialized, so it's far better to have the (sometimes-redundant)
1875 /// EndRangeLoc.
1876 SourceLocation EndRangeLoc;
1877
1878 /// The template or declaration that this declaration
1879 /// describes or was instantiated from, respectively.
1880 ///
1881 /// For non-templates, this value will be NULL. For function
1882 /// declarations that describe a function template, this will be a
1883 /// pointer to a FunctionTemplateDecl. For member functions
1884 /// of class template specializations, this will be a MemberSpecializationInfo
1885 /// pointer containing information about the specialization.
1886 /// For function template specializations, this will be a
1887 /// FunctionTemplateSpecializationInfo, which contains information about
1888 /// the template being specialized and the template arguments involved in
1889 /// that specialization.
1890 llvm::PointerUnion<FunctionTemplateDecl *,
1891 MemberSpecializationInfo *,
1892 FunctionTemplateSpecializationInfo *,
1893 DependentFunctionTemplateSpecializationInfo *>
1894 TemplateOrSpecialization;
1895
1896 /// Provides source/type location info for the declaration name embedded in
1897 /// the DeclaratorDecl base class.
1898 DeclarationNameLoc DNLoc;
1899
1900 /// Specify that this function declaration is actually a function
1901 /// template specialization.
1902 ///
1903 /// \param C the ASTContext.
1904 ///
1905 /// \param Template the function template that this function template
1906 /// specialization specializes.
1907 ///
1908 /// \param TemplateArgs the template arguments that produced this
1909 /// function template specialization from the template.
1910 ///
1911 /// \param InsertPos If non-NULL, the position in the function template
1912 /// specialization set where the function template specialization data will
1913 /// be inserted.
1914 ///
1915 /// \param TSK the kind of template specialization this is.
1916 ///
1917 /// \param TemplateArgsAsWritten location info of template arguments.
1918 ///
1919 /// \param PointOfInstantiation point at which the function template
1920 /// specialization was first instantiated.
1921 void setFunctionTemplateSpecialization(ASTContext &C,
1922 FunctionTemplateDecl *Template,
1923 const TemplateArgumentList *TemplateArgs,
1924 void *InsertPos,
1925 TemplateSpecializationKind TSK,
1926 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1927 SourceLocation PointOfInstantiation);
1928
1929 /// Specify that this record is an instantiation of the
1930 /// member function FD.
1931 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1932 TemplateSpecializationKind TSK);
1933
1934 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1935
1936 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1937 // need to access this bit but we want to avoid making ASTDeclWriter
1938 // a friend of FunctionDeclBitfields just for this.
1939 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1940
1941 /// Whether an ODRHash has been stored.
1942 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1943
1944 /// State that an ODRHash has been stored.
1945 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1946
1947protected:
1948 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1949 const DeclarationNameInfo &NameInfo, QualType T,
1950 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1951 ConstexprSpecKind ConstexprKind,
1952 Expr *TrailingRequiresClause = nullptr);
1953
1954 using redeclarable_base = Redeclarable<FunctionDecl>;
1955
1956 FunctionDecl *getNextRedeclarationImpl() override {
1957 return getNextRedeclaration();
1958 }
1959
1960 FunctionDecl *getPreviousDeclImpl() override {
1961 return getPreviousDecl();
1962 }
1963
1964 FunctionDecl *getMostRecentDeclImpl() override {
1965 return getMostRecentDecl();
1966 }
1967
1968public:
1969 friend class ASTDeclReader;
1970 friend class ASTDeclWriter;
1971
1972 using redecl_range = redeclarable_base::redecl_range;
1973 using redecl_iterator = redeclarable_base::redecl_iterator;
1974
1975 using redeclarable_base::redecls_begin;
1976 using redeclarable_base::redecls_end;
1977 using redeclarable_base::redecls;
1978 using redeclarable_base::getPreviousDecl;
1979 using redeclarable_base::getMostRecentDecl;
1980 using redeclarable_base::isFirstDecl;
1981
1982 static FunctionDecl *
1983 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1984 SourceLocation NLoc, DeclarationName N, QualType T,
1985 TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
1986 bool hasWrittenPrototype = true,
1987 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified,
1988 Expr *TrailingRequiresClause = nullptr) {
1989 DeclarationNameInfo NameInfo(N, NLoc);
1990 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
1991 isInlineSpecified, hasWrittenPrototype,
1992 ConstexprKind, TrailingRequiresClause);
1993 }
1994
1995 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1996 SourceLocation StartLoc,
1997 const DeclarationNameInfo &NameInfo, QualType T,
1998 TypeSourceInfo *TInfo, StorageClass SC,
1999 bool isInlineSpecified, bool hasWrittenPrototype,
2000 ConstexprSpecKind ConstexprKind,
2001 Expr *TrailingRequiresClause);
2002
2003 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2004
2005 DeclarationNameInfo getNameInfo() const {
2006 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
2007 }
2008
2009 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2010 bool Qualified) const override;
2011
2012 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
2013
2014 /// Returns the location of the ellipsis of a variadic function.
2015 SourceLocation getEllipsisLoc() const {
2016 const auto *FPT = getType()->getAs<FunctionProtoType>();
2017 if (FPT && FPT->isVariadic())
2018 return FPT->getEllipsisLoc();
2019 return SourceLocation();
2020 }
2021
2022 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2023
2024 // Function definitions.
2025 //
2026 // A function declaration may be:
2027 // - a non defining declaration,
2028 // - a definition. A function may be defined because:
2029 // - it has a body, or will have it in the case of late parsing.
2030 // - it has an uninstantiated body. The body does not exist because the
2031 // function is not used yet, but the declaration is considered a
2032 // definition and does not allow other definition of this function.
2033 // - it does not have a user specified body, but it does not allow
2034 // redefinition, because it is deleted/defaulted or is defined through
2035 // some other mechanism (alias, ifunc).
2036
2037 /// Returns true if the function has a body.
2038 ///
2039 /// The function body might be in any of the (re-)declarations of this
2040 /// function. The variant that accepts a FunctionDecl pointer will set that
2041 /// function declaration to the actual declaration containing the body (if
2042 /// there is one).
2043 bool hasBody(const FunctionDecl *&Definition) const;
2044
2045 bool hasBody() const override {
2046 const FunctionDecl* Definition;
2047 return hasBody(Definition);
2048 }
2049
2050 /// Returns whether the function has a trivial body that does not require any
2051 /// specific codegen.
2052 bool hasTrivialBody() const;
2053
2054 /// Returns true if the function has a definition that does not need to be
2055 /// instantiated.
2056 ///
2057 /// The variant that accepts a FunctionDecl pointer will set that function
2058 /// declaration to the declaration that is a definition (if there is one).
2059 ///
2060 /// \param CheckForPendingFriendDefinition If \c true, also check for friend
2061 /// declarations that were instantiataed from function definitions.
2062 /// Such a declaration behaves as if it is a definition for the
2063 /// purpose of redefinition checking, but isn't actually a "real"
2064 /// definition until its body is instantiated.
2065 bool isDefined(const FunctionDecl *&Definition,
2066 bool CheckForPendingFriendDefinition = false) const;
2067
2068 bool isDefined() const {
2069 const FunctionDecl* Definition;
2070 return isDefined(Definition);
2071 }
2072
2073 /// Get the definition for this declaration.
2074 FunctionDecl *getDefinition() {
2075 const FunctionDecl *Definition;
2076 if (isDefined(Definition))
2077 return const_cast<FunctionDecl *>(Definition);
2078 return nullptr;
2079 }
2080 const FunctionDecl *getDefinition() const {
2081 return const_cast<FunctionDecl *>(this)->getDefinition();
2082 }
2083
2084 /// Retrieve the body (definition) of the function. The function body might be
2085 /// in any of the (re-)declarations of this function. The variant that accepts
2086 /// a FunctionDecl pointer will set that function declaration to the actual
2087 /// declaration containing the body (if there is one).
2088 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2089 /// unnecessary AST de-serialization of the body.
2090 Stmt *getBody(const FunctionDecl *&Definition) const;
2091
2092 Stmt *getBody() const override {
2093 const FunctionDecl* Definition;
2094 return getBody(Definition);
2095 }
2096
2097 /// Returns whether this specific declaration of the function is also a
2098 /// definition that does not contain uninstantiated body.
2099 ///
2100 /// This does not determine whether the function has been defined (e.g., in a
2101 /// previous definition); for that information, use isDefined.
2102 ///
2103 /// Note: the function declaration does not become a definition until the
2104 /// parser reaches the definition, if called before, this function will return
2105 /// `false`.
2106 bool isThisDeclarationADefinition() const {
2107 return isDeletedAsWritten() || isDefaulted() ||
2108 doesThisDeclarationHaveABody() || hasSkippedBody() ||
2109 willHaveBody() || hasDefiningAttr();
2110 }
2111
2112 /// Determine whether this specific declaration of the function is a friend
2113 /// declaration that was instantiated from a function definition. Such
2114 /// declarations behave like definitions in some contexts.
2115 bool isThisDeclarationInstantiatedFromAFriendDefinition() const;
2116
2117 /// Returns whether this specific declaration of the function has a body.
2118 bool doesThisDeclarationHaveABody() const {
2119 return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
2120 isLateTemplateParsed();
2121 }
2122
2123 void setBody(Stmt *B);
2124 void setLazyBody(uint64_t Offset) {
2125 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2126 Body = LazyDeclStmtPtr(Offset);
2127 }
2128
2129 void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info);
2130 DefaultedFunctionInfo *getDefaultedFunctionInfo() const;
2131
2132 /// Whether this function is variadic.
2133 bool isVariadic() const;
2134
2135 /// Whether this function is marked as virtual explicitly.
2136 bool isVirtualAsWritten() const {
2137 return FunctionDeclBits.IsVirtualAsWritten;
2138 }
2139
2140 /// State that this function is marked as virtual explicitly.
2141 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2142
2143 /// Whether this virtual function is pure, i.e. makes the containing class
2144 /// abstract.
2145 bool isPure() const { return FunctionDeclBits.IsPure; }
2146 void setPure(bool P = true);
2147
2148 /// Whether this templated function will be late parsed.
2149 bool isLateTemplateParsed() const {
2150 return FunctionDeclBits.IsLateTemplateParsed;
2151 }
2152
2153 /// State that this templated function will be late parsed.
2154 void setLateTemplateParsed(bool ILT = true) {
2155 FunctionDeclBits.IsLateTemplateParsed = ILT;
2156 }
2157
2158 /// Whether this function is "trivial" in some specialized C++ senses.
2159 /// Can only be true for default constructors, copy constructors,
2160 /// copy assignment operators, and destructors. Not meaningful until
2161 /// the class has been fully built by Sema.
2162 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2163 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2164
2165 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2166 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2167
2168 /// Whether this function is defaulted. Valid for e.g.
2169 /// special member functions, defaulted comparisions (not methods!).
2170 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2171 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2172
2173 /// Whether this function is explicitly defaulted.
2174 bool isExplicitlyDefaulted() const {
2175 return FunctionDeclBits.IsExplicitlyDefaulted;
2176 }
2177
2178 /// State that this function is explicitly defaulted.
2179 void setExplicitlyDefaulted(bool ED = true) {
2180 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2181 }
2182
2183 /// True if this method is user-declared and was not
2184 /// deleted or defaulted on its first declaration.
2185 bool isUserProvided() const {
2186 auto *DeclAsWritten = this;
2187 if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
2188 DeclAsWritten = Pattern;
2189 return !(DeclAsWritten->isDeleted() ||
2190 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2191 }
2192
2193 /// Whether falling off this function implicitly returns null/zero.
2194 /// If a more specific implicit return value is required, front-ends
2195 /// should synthesize the appropriate return statements.
2196 bool hasImplicitReturnZero() const {
2197 return FunctionDeclBits.HasImplicitReturnZero;
2198 }
2199
2200 /// State that falling off this function implicitly returns null/zero.
2201 /// If a more specific implicit return value is required, front-ends
2202 /// should synthesize the appropriate return statements.
2203 void setHasImplicitReturnZero(bool IRZ) {
2204 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2205 }
2206
2207 /// Whether this function has a prototype, either because one
2208 /// was explicitly written or because it was "inherited" by merging
2209 /// a declaration without a prototype with a declaration that has a
2210 /// prototype.
2211 bool hasPrototype() const {
2212 return hasWrittenPrototype() || hasInheritedPrototype();
2213 }
2214
2215 /// Whether this function has a written prototype.
2216 bool hasWrittenPrototype() const {
2217 return FunctionDeclBits.HasWrittenPrototype;
2218 }
2219
2220 /// State that this function has a written prototype.
2221 void setHasWrittenPrototype(bool P = true) {
2222 FunctionDeclBits.HasWrittenPrototype = P;
2223 }
2224
2225 /// Whether this function inherited its prototype from a
2226 /// previous declaration.
2227 bool hasInheritedPrototype() const {
2228 return FunctionDeclBits.HasInheritedPrototype;
2229 }
2230
2231 /// State that this function inherited its prototype from a
2232 /// previous declaration.
2233 void setHasInheritedPrototype(bool P = true) {
2234 FunctionDeclBits.HasInheritedPrototype = P;
2235 }
2236
2237 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2238 bool isConstexpr() const {
2239 return getConstexprKind() != ConstexprSpecKind::Unspecified;
2240 }
2241 void setConstexprKind(ConstexprSpecKind CSK) {
2242 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
2243 }
2244 ConstexprSpecKind getConstexprKind() const {
2245 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2246 }
2247 bool isConstexprSpecified() const {
2248 return getConstexprKind() == ConstexprSpecKind::Constexpr;
2249 }
2250 bool isConsteval() const {
2251 return getConstexprKind() == ConstexprSpecKind::Consteval;
2252 }
2253
2254 /// Whether the instantiation of this function is pending.
2255 /// This bit is set when the decision to instantiate this function is made
2256 /// and unset if and when the function body is created. That leaves out
2257 /// cases where instantiation did not happen because the template definition
2258 /// was not seen in this TU. This bit remains set in those cases, under the
2259 /// assumption that the instantiation will happen in some other TU.
2260 bool instantiationIsPending() const {
2261 return FunctionDeclBits.InstantiationIsPending;
2262 }
2263
2264 /// State that the instantiation of this function is pending.
2265 /// (see instantiationIsPending)
2266 void setInstantiationIsPending(bool IC) {
2267 FunctionDeclBits.InstantiationIsPending = IC;
2268 }
2269
2270 /// Indicates the function uses __try.
2271 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2272 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2273
2274 /// Whether this function has been deleted.
2275 ///
2276 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2277 /// acts like a normal function, except that it cannot actually be
2278 /// called or have its address taken. Deleted functions are
2279 /// typically used in C++ overload resolution to attract arguments
2280 /// whose type or lvalue/rvalue-ness would permit the use of a
2281 /// different overload that would behave incorrectly. For example,
2282 /// one might use deleted functions to ban implicit conversion from
2283 /// a floating-point number to an Integer type:
2284 ///
2285 /// @code
2286 /// struct Integer {
2287 /// Integer(long); // construct from a long
2288 /// Integer(double) = delete; // no construction from float or double
2289 /// Integer(long double) = delete; // no construction from long double
2290 /// };
2291 /// @endcode
2292 // If a function is deleted, its first declaration must be.
2293 bool isDeleted() const {
2294 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2295 }
2296
2297 bool isDeletedAsWritten() const {
2298 return FunctionDeclBits.IsDeleted && !isDefaulted();
2299 }
2300
2301 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2302
2303 /// Determines whether this function is "main", which is the
2304 /// entry point into an executable program.
2305 bool isMain() const;
2306
2307 /// Determines whether this function is a MSVCRT user defined entry
2308 /// point.
2309 bool isMSVCRTEntryPoint() const;
2310
2311 /// Determines whether this operator new or delete is one
2312 /// of the reserved global placement operators:
2313 /// void *operator new(size_t, void *);
2314 /// void *operator new[](size_t, void *);
2315 /// void operator delete(void *, void *);
2316 /// void operator delete[](void *, void *);
2317 /// These functions have special behavior under [new.delete.placement]:
2318 /// These functions are reserved, a C++ program may not define
2319 /// functions that displace the versions in the Standard C++ library.
2320 /// The provisions of [basic.stc.dynamic] do not apply to these
2321 /// reserved placement forms of operator new and operator delete.
2322 ///
2323 /// This function must be an allocation or deallocation function.
2324 bool isReservedGlobalPlacementOperator() const;
2325
2326 /// Determines whether this function is one of the replaceable
2327 /// global allocation functions:
2328 /// void *operator new(size_t);
2329 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2330 /// void *operator new[](size_t);
2331 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2332 /// void operator delete(void *) noexcept;
2333 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2334 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2335 /// void operator delete[](void *) noexcept;
2336 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2337 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2338 /// These functions have special behavior under C++1y [expr.new]:
2339 /// An implementation is allowed to omit a call to a replaceable global
2340 /// allocation function. [...]
2341 ///
2342 /// If this function is an aligned allocation/deallocation function, return
2343 /// the parameter number of the requested alignment through AlignmentParam.
2344 ///
2345 /// If this function is an allocation/deallocation function that takes
2346 /// the `std::nothrow_t` tag, return true through IsNothrow,
2347 bool isReplaceableGlobalAllocationFunction(
2348 Optional<unsigned> *AlignmentParam = nullptr,
2349 bool *IsNothrow = nullptr) const;
2350
2351 /// Determine if this function provides an inline implementation of a builtin.
2352 bool isInlineBuiltinDeclaration() const;
2353
2354 /// Determine whether this is a destroying operator delete.
2355 bool isDestroyingOperatorDelete() const;
2356
2357 /// Compute the language linkage.
2358 LanguageLinkage getLanguageLinkage() const;
2359
2360 /// Determines whether this function is a function with
2361 /// external, C linkage.
2362 bool isExternC() const;
2363
2364 /// Determines whether this function's context is, or is nested within,
2365 /// a C++ extern "C" linkage spec.
2366 bool isInExternCContext() const;
2367
2368 /// Determines whether this function's context is, or is nested within,
2369 /// a C++ extern "C++" linkage spec.
2370 bool isInExternCXXContext() const;
2371
2372 /// Determines whether this is a global function.
2373 bool isGlobal() const;
2374
2375 /// Determines whether this function is known to be 'noreturn', through
2376 /// an attribute on its declaration or its type.
2377 bool isNoReturn() const;
2378
2379 /// True if the function was a definition but its body was skipped.
2380 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2381 void setHasSkippedBody(bool Skipped = true) {
2382 FunctionDeclBits.HasSkippedBody = Skipped;
2383 }
2384
2385 /// True if this function will eventually have a body, once it's fully parsed.
2386 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2387 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2388
2389 /// True if this function is considered a multiversioned function.
2390 bool isMultiVersion() const {
2391 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2392 }
2393
2394 /// Sets the multiversion state for this declaration and all of its
2395 /// redeclarations.
2396 void setIsMultiVersion(bool V = true) {
2397 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2398 }
2399
2400 /// Gets the kind of multiversioning attribute this declaration has. Note that
2401 /// this can return a value even if the function is not multiversion, such as
2402 /// the case of 'target'.
2403 MultiVersionKind getMultiVersionKind() const;
2404
2405
2406 /// True if this function is a multiversioned dispatch function as a part of
2407 /// the cpu_specific/cpu_dispatch functionality.
2408 bool isCPUDispatchMultiVersion() const;
2409 /// True if this function is a multiversioned processor specific function as a
2410 /// part of the cpu_specific/cpu_dispatch functionality.
2411 bool isCPUSpecificMultiVersion() const;
2412
2413 /// True if this function is a multiversioned dispatch function as a part of
2414 /// the target functionality.
2415 bool isTargetMultiVersion() const;
2416
2417 /// \brief Get the associated-constraints of this function declaration.
2418 /// Currently, this will either be a vector of size 1 containing the
2419 /// trailing-requires-clause or an empty vector.
2420 ///
2421 /// Use this instead of getTrailingRequiresClause for concepts APIs that
2422 /// accept an ArrayRef of constraint expressions.
2423 void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
2424 if (auto *TRC = getTrailingRequiresClause())
2425 AC.push_back(TRC);
2426 }
2427
2428 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2429
2430 FunctionDecl *getCanonicalDecl() override;
2431 const FunctionDecl *getCanonicalDecl() const {
2432 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2433 }
2434
2435 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2436
2437 // ArrayRef interface to parameters.
2438 ArrayRef<ParmVarDecl *> parameters() const {
2439 return {ParamInfo, getNumParams()};
2440 }
2441 MutableArrayRef<ParmVarDecl *> parameters() {
2442 return {ParamInfo, getNumParams()};
2443 }
2444
2445 // Iterator access to formal parameters.
2446 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2447 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2448
2449 bool param_empty() const { return parameters().empty(); }
2450 param_iterator param_begin() { return parameters().begin(); }
2451 param_iterator param_end() { return parameters().end(); }
2452 param_const_iterator param_begin() const { return parameters().begin(); }
2453 param_const_iterator param_end() const { return parameters().end(); }
2454 size_t param_size() const { return parameters().size(); }
2455
2456 /// Return the number of parameters this function must have based on its
2457 /// FunctionType. This is the length of the ParamInfo array after it has been
2458 /// created.
2459 unsigned getNumParams() const;
2460
2461 const ParmVarDecl *getParamDecl(unsigned i) const {
2462 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2462, __PRETTY_FUNCTION__))
;
2463 return ParamInfo[i];
2464 }
2465 ParmVarDecl *getParamDecl(unsigned i) {
2466 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2466, __PRETTY_FUNCTION__))
;
2467 return ParamInfo[i];
2468 }
2469 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2470 setParams(getASTContext(), NewParamInfo);
2471 }
2472
2473 /// Returns the minimum number of arguments needed to call this function. This
2474 /// may be fewer than the number of function parameters, if some of the
2475 /// parameters have default arguments (in C++).
2476 unsigned getMinRequiredArguments() const;
2477
2478 /// Determine whether this function has a single parameter, or multiple
2479 /// parameters where all but the first have default arguments.
2480 ///
2481 /// This notion is used in the definition of copy/move constructors and
2482 /// initializer list constructors. Note that, unlike getMinRequiredArguments,
2483 /// parameter packs are not treated specially here.
2484 bool hasOneParamOrDefaultArgs() const;
2485
2486 /// Find the source location information for how the type of this function
2487 /// was written. May be absent (for example if the function was declared via
2488 /// a typedef) and may contain a different type from that of the function
2489 /// (for example if the function type was adjusted by an attribute).
2490 FunctionTypeLoc getFunctionTypeLoc() const;
2491
2492 QualType getReturnType() const {
2493 return getType()->castAs<FunctionType>()->getReturnType();
2494 }
2495
2496 /// Attempt to compute an informative source range covering the
2497 /// function return type. This may omit qualifiers and other information with
2498 /// limited representation in the AST.
2499 SourceRange getReturnTypeSourceRange() const;
2500
2501 /// Attempt to compute an informative source range covering the
2502 /// function parameters, including the ellipsis of a variadic function.
2503 /// The source range excludes the parentheses, and is invalid if there are
2504 /// no parameters and no ellipsis.
2505 SourceRange getParametersSourceRange() const;
2506
2507 /// Get the declared return type, which may differ from the actual return
2508 /// type if the return type is deduced.
2509 QualType getDeclaredReturnType() const {
2510 auto *TSI = getTypeSourceInfo();
2511 QualType T = TSI ? TSI->getType() : getType();
2512 return T->castAs<FunctionType>()->getReturnType();
2513 }
2514
2515 /// Gets the ExceptionSpecificationType as declared.
2516 ExceptionSpecificationType getExceptionSpecType() const {
2517 auto *TSI = getTypeSourceInfo();
2518 QualType T = TSI ? TSI->getType() : getType();
2519 const auto *FPT = T->getAs<FunctionProtoType>();
2520 return FPT ? FPT->getExceptionSpecType() : EST_None;
2521 }
2522
2523 /// Attempt to compute an informative source range covering the
2524 /// function exception specification, if any.
2525 SourceRange getExceptionSpecSourceRange() const;
2526
2527 /// Determine the type of an expression that calls this function.
2528 QualType getCallResultType() const {
2529 return getType()->castAs<FunctionType>()->getCallResultType(
2530 getASTContext());
2531 }
2532
2533 /// Returns the storage class as written in the source. For the
2534 /// computed linkage of symbol, see getLinkage.
2535 StorageClass getStorageClass() const {
2536 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2537 }
2538
2539 /// Sets the storage class as written in the source.
2540 void setStorageClass(StorageClass SClass) {
2541 FunctionDeclBits.SClass = SClass;
2542 }
2543
2544 /// Determine whether the "inline" keyword was specified for this
2545 /// function.
2546 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2547
2548 /// Set whether the "inline" keyword was specified for this function.
2549 void setInlineSpecified(bool I) {
2550 FunctionDeclBits.IsInlineSpecified = I;
2551 FunctionDeclBits.IsInline = I;
2552 }
2553
2554 /// Flag that this function is implicitly inline.
2555 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2556
2557 /// Determine whether this function should be inlined, because it is
2558 /// either marked "inline" or "constexpr" or is a member function of a class
2559 /// that was defined in the class body.
2560 bool isInlined() const { return FunctionDeclBits.IsInline; }
2561
2562 bool isInlineDefinitionExternallyVisible() const;
2563
2564 bool isMSExternInline() const;
2565
2566 bool doesDeclarationForceExternallyVisibleDefinition() const;
2567
2568 bool isStatic() const { return getStorageClass() == SC_Static; }
2569
2570 /// Whether this function declaration represents an C++ overloaded
2571 /// operator, e.g., "operator+".
2572 bool isOverloadedOperator() const {
2573 return getOverloadedOperator() != OO_None;
2574 }
2575
2576 OverloadedOperatorKind getOverloadedOperator() const;
2577
2578 const IdentifierInfo *getLiteralIdentifier() const;
2579
2580 /// If this function is an instantiation of a member function
2581 /// of a class template specialization, retrieves the function from
2582 /// which it was instantiated.
2583 ///
2584 /// This routine will return non-NULL for (non-templated) member
2585 /// functions of class templates and for instantiations of function
2586 /// templates. For example, given:
2587 ///
2588 /// \code
2589 /// template<typename T>
2590 /// struct X {
2591 /// void f(T);
2592 /// };
2593 /// \endcode
2594 ///
2595 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2596 /// whose parent is the class template specialization X<int>. For
2597 /// this declaration, getInstantiatedFromFunction() will return
2598 /// the FunctionDecl X<T>::A. When a complete definition of
2599 /// X<int>::A is required, it will be instantiated from the
2600 /// declaration returned by getInstantiatedFromMemberFunction().
2601 FunctionDecl *getInstantiatedFromMemberFunction() const;
2602
2603 /// What kind of templated function this is.
2604 TemplatedKind getTemplatedKind() const;
2605
2606 /// If this function is an instantiation of a member function of a
2607 /// class template specialization, retrieves the member specialization
2608 /// information.
2609 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2610
2611 /// Specify that this record is an instantiation of the
2612 /// member function FD.
2613 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2614 TemplateSpecializationKind TSK) {
2615 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2616 }
2617
2618 /// Retrieves the function template that is described by this
2619 /// function declaration.
2620 ///
2621 /// Every function template is represented as a FunctionTemplateDecl
2622 /// and a FunctionDecl (or something derived from FunctionDecl). The
2623 /// former contains template properties (such as the template
2624 /// parameter lists) while the latter contains the actual
2625 /// description of the template's
2626 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2627 /// FunctionDecl that describes the function template,
2628 /// getDescribedFunctionTemplate() retrieves the
2629 /// FunctionTemplateDecl from a FunctionDecl.
2630 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2631
2632 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2633
2634 /// Determine whether this function is a function template
2635 /// specialization.
2636 bool isFunctionTemplateSpecialization() const {
2637 return getPrimaryTemplate() != nullptr;
2638 }
2639
2640 /// If this function is actually a function template specialization,
2641 /// retrieve information about this function template specialization.
2642 /// Otherwise, returns NULL.
2643 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2644
2645 /// Determines whether this function is a function template
2646 /// specialization or a member of a class template specialization that can
2647 /// be implicitly instantiated.
2648 bool isImplicitlyInstantiable() const;
2649
2650 /// Determines if the given function was instantiated from a
2651 /// function template.
2652 bool isTemplateInstantiation() const;
2653
2654 /// Retrieve the function declaration from which this function could
2655 /// be instantiated, if it is an instantiation (rather than a non-template
2656 /// or a specialization, for example).
2657 ///
2658 /// If \p ForDefinition is \c false, explicit specializations will be treated
2659 /// as if they were implicit instantiations. This will then find the pattern
2660 /// corresponding to non-definition portions of the declaration, such as
2661 /// default arguments and the exception specification.
2662 FunctionDecl *
2663 getTemplateInstantiationPattern(bool ForDefinition = true) const;
2664
2665 /// Retrieve the primary template that this function template
2666 /// specialization either specializes or was instantiated from.
2667 ///
2668 /// If this function declaration is not a function template specialization,
2669 /// returns NULL.
2670 FunctionTemplateDecl *getPrimaryTemplate() const;
2671
2672 /// Retrieve the template arguments used to produce this function
2673 /// template specialization from the primary template.
2674 ///
2675 /// If this function declaration is not a function template specialization,
2676 /// returns NULL.
2677 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2678
2679 /// Retrieve the template argument list as written in the sources,
2680 /// if any.
2681 ///
2682 /// If this function declaration is not a function template specialization
2683 /// or if it had no explicit template argument list, returns NULL.
2684 /// Note that it an explicit template argument list may be written empty,
2685 /// e.g., template<> void foo<>(char* s);
2686 const ASTTemplateArgumentListInfo*
2687 getTemplateSpecializationArgsAsWritten() const;
2688
2689 /// Specify that this function declaration is actually a function
2690 /// template specialization.
2691 ///
2692 /// \param Template the function template that this function template
2693 /// specialization specializes.
2694 ///
2695 /// \param TemplateArgs the template arguments that produced this
2696 /// function template specialization from the template.
2697 ///
2698 /// \param InsertPos If non-NULL, the position in the function template
2699 /// specialization set where the function template specialization data will
2700 /// be inserted.
2701 ///
2702 /// \param TSK the kind of template specialization this is.
2703 ///
2704 /// \param TemplateArgsAsWritten location info of template arguments.
2705 ///
2706 /// \param PointOfInstantiation point at which the function template
2707 /// specialization was first instantiated.
2708 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2709 const TemplateArgumentList *TemplateArgs,
2710 void *InsertPos,
2711 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2712 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2713 SourceLocation PointOfInstantiation = SourceLocation()) {
2714 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2715 InsertPos, TSK, TemplateArgsAsWritten,
2716 PointOfInstantiation);
2717 }
2718
2719 /// Specifies that this function declaration is actually a
2720 /// dependent function template specialization.
2721 void setDependentTemplateSpecialization(ASTContext &Context,
2722 const UnresolvedSetImpl &Templates,
2723 const TemplateArgumentListInfo &TemplateArgs);
2724
2725 DependentFunctionTemplateSpecializationInfo *
2726 getDependentSpecializationInfo() const;
2727
2728 /// Determine what kind of template instantiation this function
2729 /// represents.
2730 TemplateSpecializationKind getTemplateSpecializationKind() const;
2731
2732 /// Determine the kind of template specialization this function represents
2733 /// for the purpose of template instantiation.
2734 TemplateSpecializationKind
2735 getTemplateSpecializationKindForInstantiation() const;
2736
2737 /// Determine what kind of template instantiation this function
2738 /// represents.
2739 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2740 SourceLocation PointOfInstantiation = SourceLocation());
2741
2742 /// Retrieve the (first) point of instantiation of a function template
2743 /// specialization or a member of a class template specialization.
2744 ///
2745 /// \returns the first point of instantiation, if this function was
2746 /// instantiated from a template; otherwise, returns an invalid source
2747 /// location.
2748 SourceLocation getPointOfInstantiation() const;
2749
2750 /// Determine whether this is or was instantiated from an out-of-line
2751 /// definition of a member function.
2752 bool isOutOfLine() const override;
2753
2754 /// Identify a memory copying or setting function.
2755 /// If the given function is a memory copy or setting function, returns
2756 /// the corresponding Builtin ID. If the function is not a memory function,
2757 /// returns 0.
2758 unsigned getMemoryFunctionKind() const;
2759
2760 /// Returns ODRHash of the function. This value is calculated and
2761 /// stored on first call, then the stored value returned on the other calls.
2762 unsigned getODRHash();
2763
2764 /// Returns cached ODRHash of the function. This must have been previously
2765 /// computed and stored.
2766 unsigned getODRHash() const;
2767
2768 // Implement isa/cast/dyncast/etc.
2769 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2770 static bool classofKind(Kind K) {
2771 return K >= firstFunction && K <= lastFunction;
2772 }
2773 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2774 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2775 }
2776 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2777 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2778 }
2779};
2780
2781/// Represents a member of a struct/union/class.
2782class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2783 unsigned BitField : 1;
2784 unsigned Mutable : 1;
2785 mutable unsigned CachedFieldIndex : 30;
2786
2787 /// The kinds of value we can store in InitializerOrBitWidth.
2788 ///
2789 /// Note that this is compatible with InClassInitStyle except for
2790 /// ISK_CapturedVLAType.
2791 enum InitStorageKind {
2792 /// If the pointer is null, there's nothing special. Otherwise,
2793 /// this is a bitfield and the pointer is the Expr* storing the
2794 /// bit-width.
2795 ISK_NoInit = (unsigned) ICIS_NoInit,
2796
2797 /// The pointer is an (optional due to delayed parsing) Expr*
2798 /// holding the copy-initializer.
2799 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2800
2801 /// The pointer is an (optional due to delayed parsing) Expr*
2802 /// holding the list-initializer.
2803 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2804
2805 /// The pointer is a VariableArrayType* that's been captured;
2806 /// the enclosing context is a lambda or captured statement.
2807 ISK_CapturedVLAType,
2808 };
2809
2810 /// If this is a bitfield with a default member initializer, this
2811 /// structure is used to represent the two expressions.
2812 struct InitAndBitWidth {
2813 Expr *Init;
2814 Expr *BitWidth;
2815 };
2816
2817 /// Storage for either the bit-width, the in-class initializer, or
2818 /// both (via InitAndBitWidth), or the captured variable length array bound.
2819 ///
2820 /// If the storage kind is ISK_InClassCopyInit or
2821 /// ISK_InClassListInit, but the initializer is null, then this
2822 /// field has an in-class initializer that has not yet been parsed
2823 /// and attached.
2824 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2825 // overwhelmingly common case that we have none of these things.
2826 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2827
2828protected:
2829 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2830 SourceLocation IdLoc, IdentifierInfo *Id,
2831 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2832 InClassInitStyle InitStyle)
2833 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2834 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2835 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2836 if (BW)
2837 setBitWidth(BW);
2838 }
2839
2840public:
2841 friend class ASTDeclReader;
2842 friend class ASTDeclWriter;
2843
2844 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2845 SourceLocation StartLoc, SourceLocation IdLoc,
2846 IdentifierInfo *Id, QualType T,
2847 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2848 InClassInitStyle InitStyle);
2849
2850 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2851
2852 /// Returns the index of this field within its record,
2853 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2854 unsigned getFieldIndex() const;
2855
2856 /// Determines whether this field is mutable (C++ only).
2857 bool isMutable() const { return Mutable; }
2858
2859 /// Determines whether this field is a bitfield.
2860 bool isBitField() const { return BitField; }
2861
2862 /// Determines whether this is an unnamed bitfield.
2863 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2864
2865 /// Determines whether this field is a
2866 /// representative for an anonymous struct or union. Such fields are
2867 /// unnamed and are implicitly generated by the implementation to
2868 /// store the data for the anonymous union or struct.
2869 bool isAnonymousStructOrUnion() const;
2870
2871 Expr *getBitWidth() const {
2872 if (!BitField)
2873 return nullptr;
2874 void *Ptr = InitStorage.getPointer();
2875 if (getInClassInitStyle())
2876 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2877 return static_cast<Expr*>(Ptr);
2878 }
2879
2880 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2881
2882 /// Set the bit-field width for this member.
2883 // Note: used by some clients (i.e., do not remove it).
2884 void setBitWidth(Expr *Width) {
2885 assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2886, __PRETTY_FUNCTION__))
2886 "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2886, __PRETTY_FUNCTION__))
;
2887 assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast<
void> (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2887, __PRETTY_FUNCTION__))
;
2888 InitStorage.setPointer(
2889 InitStorage.getInt()
2890 ? new (getASTContext())
2891 InitAndBitWidth{getInClassInitializer(), Width}
2892 : static_cast<void*>(Width));
2893 BitField = true;
2894 }
2895
2896 /// Remove the bit-field width from this member.
2897 // Note: used by some clients (i.e., do not remove it).
2898 void removeBitWidth() {
2899 assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast
<void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2899, __PRETTY_FUNCTION__))
;
2900 InitStorage.setPointer(getInClassInitializer());
2901 BitField = false;
2902 }
2903
2904 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2905 /// at all and instead act as a separator between contiguous runs of other
2906 /// bit-fields.
2907 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2908
2909 /// Determine if this field is a subobject of zero size, that is, either a
2910 /// zero-length bit-field or a field of empty class type with the
2911 /// [[no_unique_address]] attribute.
2912 bool isZeroSize(const ASTContext &Ctx) const;
2913
2914 /// Get the kind of (C++11) default member initializer that this field has.
2915 InClassInitStyle getInClassInitStyle() const {
2916 InitStorageKind storageKind = InitStorage.getInt();
2917 return (storageKind == ISK_CapturedVLAType
2918 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2919 }
2920
2921 /// Determine whether this member has a C++11 default member initializer.
2922 bool hasInClassInitializer() const {
2923 return getInClassInitStyle() != ICIS_NoInit;
2924 }
2925
2926 /// Get the C++11 default member initializer for this member, or null if one
2927 /// has not been set. If a valid declaration has a default member initializer,
2928 /// but this returns null, then we have not parsed and attached it yet.
2929 Expr *getInClassInitializer() const {
2930 if (!hasInClassInitializer())
2931 return nullptr;
2932 void *Ptr = InitStorage.getPointer();
2933 if (BitField)
2934 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2935 return static_cast<Expr*>(Ptr);
2936 }
2937
2938 /// Set the C++11 in-class initializer for this member.
2939 void setInClassInitializer(Expr *Init) {
2940 assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer()
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2940, __PRETTY_FUNCTION__))
;
2941 if (BitField)
2942 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2943 else
2944 InitStorage.setPointer(Init);
2945 }
2946
2947 /// Remove the C++11 in-class initializer from this member.
2948 void removeInClassInitializer() {
2949 assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove"
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 2949, __PRETTY_FUNCTION__))
;
2950 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2951 }
2952
2953 /// Determine whether this member captures the variable length array
2954 /// type.
2955 bool hasCapturedVLAType() const {
2956 return InitStorage.getInt() == ISK_CapturedVLAType;
2957 }
2958
2959 /// Get the captured variable length array type.
2960 const VariableArrayType *getCapturedVLAType() const {
2961 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2962 InitStorage.getPointer())
2963 : nullptr;
2964 }
2965
2966 /// Set the captured variable length array type for this field.
2967 void setCapturedVLAType(const VariableArrayType *VLAType);
2968
2969 /// Returns the parent of this field declaration, which
2970 /// is the struct in which this field is defined.
2971 ///
2972 /// Returns null if this is not a normal class/struct field declaration, e.g.
2973 /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
2974 const RecordDecl *getParent() const {
2975 return dyn_cast<RecordDecl>(getDeclContext());
2976 }
2977
2978 RecordDecl *getParent() {
2979 return dyn_cast<RecordDecl>(getDeclContext());
2980 }
2981
2982 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2983
2984 /// Retrieves the canonical declaration of this field.
2985 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2986 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2987
2988 // Implement isa/cast/dyncast/etc.
2989 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2990 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2991};
2992
2993/// An instance of this object exists for each enum constant
2994/// that is defined. For example, in "enum X {a,b}", each of a/b are
2995/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2996/// TagType for the X EnumDecl.
2997class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2998 Stmt *Init; // an integer constant expression
2999 llvm::APSInt Val; // The value.
3000
3001protected:
3002 EnumConstantDecl(DeclContext *DC, SourceLocation L,
3003 IdentifierInfo *Id, QualType T, Expr *E,
3004 const llvm::APSInt &V)
3005 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
3006
3007public:
3008 friend class StmtIteratorBase;
3009
3010 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
3011 SourceLocation L, IdentifierInfo *Id,
3012 QualType T, Expr *E,
3013 const llvm::APSInt &V);
3014 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3015
3016 const Expr *getInitExpr() const { return (const Expr*) Init; }
3017 Expr *getInitExpr() { return (Expr*) Init; }
3018 const llvm::APSInt &getInitVal() const { return Val; }
3019
3020 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
3021 void setInitVal(const llvm::APSInt &V) { Val = V; }
3022
3023 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3024
3025 /// Retrieves the canonical declaration of this enumerator.
3026 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
3027 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
3028
3029 // Implement isa/cast/dyncast/etc.
3030 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3031 static bool classofKind(Kind K) { return K == EnumConstant; }
3032};
3033
3034/// Represents a field injected from an anonymous union/struct into the parent
3035/// scope. These are always implicit.
3036class IndirectFieldDecl : public ValueDecl,
3037 public Mergeable<IndirectFieldDecl> {
3038 NamedDecl **Chaining;
3039 unsigned ChainingSize;
3040
3041 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
3042 DeclarationName N, QualType T,
3043 MutableArrayRef<NamedDecl *> CH);
3044
3045 void anchor() override;
3046
3047public:
3048 friend class ASTDeclReader;
3049
3050 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
3051 SourceLocation L, IdentifierInfo *Id,
3052 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
3053
3054 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3055
3056 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
3057
3058 ArrayRef<NamedDecl *> chain() const {
3059 return llvm::makeArrayRef(Chaining, ChainingSize);
3060 }
3061 chain_iterator chain_begin() const { return chain().begin(); }
3062 chain_iterator chain_end() const { return chain().end(); }
3063
3064 unsigned getChainingSize() const { return ChainingSize; }
3065
3066 FieldDecl *getAnonField() const {
3067 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 3067, __PRETTY_FUNCTION__))
;
3068 return cast<FieldDecl>(chain().back());
3069 }
3070
3071 VarDecl *getVarDecl() const {
3072 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 3072, __PRETTY_FUNCTION__))
;
3073 return dyn_cast<VarDecl>(chain().front());
3074 }
3075
3076 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
3077 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
3078
3079 // Implement isa/cast/dyncast/etc.
3080 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3081 static bool classofKind(Kind K) { return K == IndirectField; }
3082};
3083
3084/// Represents a declaration of a type.
3085class TypeDecl : public NamedDecl {
3086 friend class ASTContext;
3087
3088 /// This indicates the Type object that represents
3089 /// this TypeDecl. It is a cache maintained by
3090 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
3091 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
3092 mutable const Type *TypeForDecl = nullptr;
3093
3094 /// The start of the source range for this declaration.
3095 SourceLocation LocStart;
3096
3097 void anchor() override;
3098
3099protected:
3100 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
3101 SourceLocation StartL = SourceLocation())
3102 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
3103
3104public:
3105 // Low-level accessor. If you just want the type defined by this node,
3106 // check out ASTContext::getTypeDeclType or one of
3107 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
3108 // already know the specific kind of node this is.
3109 const Type *getTypeForDecl() const { return TypeForDecl; }
3110 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
3111
3112 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
3113 void setLocStart(SourceLocation L) { LocStart = L; }
3114 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3115 if (LocStart.isValid())
3116 return SourceRange(LocStart, getLocation());
3117 else
3118 return SourceRange(getLocation());
3119 }
3120
3121 // Implement isa/cast/dyncast/etc.
3122 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3123 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
3124};
3125
3126/// Base class for declarations which introduce a typedef-name.
3127class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
3128 struct alignas(8) ModedTInfo {
3129 TypeSourceInfo *first;
3130 QualType second;
3131 };
3132
3133 /// If int part is 0, we have not computed IsTransparentTag.
3134 /// Otherwise, IsTransparentTag is (getInt() >> 1).
3135 mutable llvm::PointerIntPair<
3136 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
3137 MaybeModedTInfo;
3138
3139 void anchor() override;
3140
3141protected:
3142 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3143 SourceLocation StartLoc, SourceLocation IdLoc,
3144 IdentifierInfo *Id, TypeSourceInfo *TInfo)
3145 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3146 MaybeModedTInfo(TInfo, 0) {}
3147
3148 using redeclarable_base = Redeclarable<TypedefNameDecl>;
3149
3150 TypedefNameDecl *getNextRedeclarationImpl() override {
3151 return getNextRedeclaration();
3152 }
3153
3154 TypedefNameDecl *getPreviousDeclImpl() override {
3155 return getPreviousDecl();
3156 }
3157
3158 TypedefNameDecl *getMostRecentDeclImpl() override {
3159 return getMostRecentDecl();
3160 }
3161
3162public:
3163 using redecl_range = redeclarable_base::redecl_range;
3164 using redecl_iterator = redeclarable_base::redecl_iterator;
3165
3166 using redeclarable_base::redecls_begin;
3167 using redeclarable_base::redecls_end;
3168 using redeclarable_base::redecls;
3169 using redeclarable_base::getPreviousDecl;
3170 using redeclarable_base::getMostRecentDecl;
3171 using redeclarable_base::isFirstDecl;
3172
3173 bool isModed() const {
3174 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3175 }
3176
3177 TypeSourceInfo *getTypeSourceInfo() const {
3178 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3179 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3180 }
3181
3182 QualType getUnderlyingType() const {
3183 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3184 : MaybeModedTInfo.getPointer()
3185 .get<TypeSourceInfo *>()
3186 ->getType();
3187 }
3188
3189 void setTypeSourceInfo(TypeSourceInfo *newType) {
3190 MaybeModedTInfo.setPointer(newType);
3191 }
3192
3193 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3194 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3195 ModedTInfo({unmodedTSI, modedTy}));
3196 }
3197
3198 /// Retrieves the canonical declaration of this typedef-name.
3199 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3200 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3201
3202 /// Retrieves the tag declaration for which this is the typedef name for
3203 /// linkage purposes, if any.
3204 ///
3205 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3206 /// this typedef declaration.
3207 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3208
3209 /// Determines if this typedef shares a name and spelling location with its
3210 /// underlying tag type, as is the case with the NS_ENUM macro.
3211 bool isTransparentTag() const {
3212 if (MaybeModedTInfo.getInt())
3213 return MaybeModedTInfo.getInt() & 0x2;
3214 return isTransparentTagSlow();
3215 }
3216
3217 // Implement isa/cast/dyncast/etc.
3218 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3219 static bool classofKind(Kind K) {
3220 return K >= firstTypedefName && K <= lastTypedefName;
3221 }
3222
3223private:
3224 bool isTransparentTagSlow() const;
3225};
3226
3227/// Represents the declaration of a typedef-name via the 'typedef'
3228/// type specifier.
3229class TypedefDecl : public TypedefNameDecl {
3230 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3231 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3232 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3233
3234public:
3235 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3236 SourceLocation StartLoc, SourceLocation IdLoc,
3237 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3238 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3239
3240 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3241
3242 // Implement isa/cast/dyncast/etc.
3243 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3244 static bool classofKind(Kind K) { return K == Typedef; }
3245};
3246
3247/// Represents the declaration of a typedef-name via a C++11
3248/// alias-declaration.
3249class TypeAliasDecl : public TypedefNameDecl {
3250 /// The template for which this is the pattern, if any.
3251 TypeAliasTemplateDecl *Template;
3252
3253 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3254 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3255 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3256 Template(nullptr) {}
3257
3258public:
3259 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3260 SourceLocation StartLoc, SourceLocation IdLoc,
3261 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3262 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3263
3264 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3265
3266 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3267 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3268
3269 // Implement isa/cast/dyncast/etc.
3270 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3271 static bool classofKind(Kind K) { return K == TypeAlias; }
3272};
3273
3274/// Represents the declaration of a struct/union/class/enum.
3275class TagDecl : public TypeDecl,
3276 public DeclContext,
3277 public Redeclarable<TagDecl> {
3278 // This class stores some data in DeclContext::TagDeclBits
3279 // to save some space. Use the provided accessors to access it.
3280public:
3281 // This is really ugly.
3282 using TagKind = TagTypeKind;
3283
3284private:
3285 SourceRange BraceRange;
3286
3287 // A struct representing syntactic qualifier info,
3288 // to be used for the (uncommon) case of out-of-line declarations.
3289 using ExtInfo = QualifierInfo;
3290
3291 /// If the (out-of-line) tag declaration name
3292 /// is qualified, it points to the qualifier info (nns and range);
3293 /// otherwise, if the tag declaration is anonymous and it is part of
3294 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3295 /// otherwise, if the tag declaration is anonymous and it is used as a
3296 /// declaration specifier for variables, it points to the first VarDecl (used
3297 /// for mangling);
3298 /// otherwise, it is a null (TypedefNameDecl) pointer.
3299 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3300
3301 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3302 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3303 const ExtInfo *getExtInfo() const {
3304 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3305 }
3306
3307protected:
3308 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3309 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3310 SourceLocation StartL);
3311
3312 using redeclarable_base = Redeclarable<TagDecl>;
3313
3314 TagDecl *getNextRedeclarationImpl() override {
3315 return getNextRedeclaration();
3316 }
3317
3318 TagDecl *getPreviousDeclImpl() override {
3319 return getPreviousDecl();
3320 }
3321
3322 TagDecl *getMostRecentDeclImpl() override {
3323 return getMostRecentDecl();
3324 }
3325
3326 /// Completes the definition of this tag declaration.
3327 ///
3328 /// This is a helper function for derived classes.
3329 void completeDefinition();
3330
3331 /// True if this decl is currently being defined.
3332 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3333
3334 /// Indicates whether it is possible for declarations of this kind
3335 /// to have an out-of-date definition.
3336 ///
3337 /// This option is only enabled when modules are enabled.
3338 void setMayHaveOutOfDateDef(bool V = true) {
3339 TagDeclBits.MayHaveOutOfDateDef = V;
3340 }
3341
3342public:
3343 friend class ASTDeclReader;
3344 friend class ASTDeclWriter;
3345
3346 using redecl_range = redeclarable_base::redecl_range;
3347 using redecl_iterator = redeclarable_base::redecl_iterator;
3348
3349 using redeclarable_base::redecls_begin;
3350 using redeclarable_base::redecls_end;
3351 using redeclarable_base::redecls;
3352 using redeclarable_base::getPreviousDecl;
3353 using redeclarable_base::getMostRecentDecl;
3354 using redeclarable_base::isFirstDecl;
3355
3356 SourceRange getBraceRange() const { return BraceRange; }
3357 void setBraceRange(SourceRange R) { BraceRange = R; }
3358
3359 /// Return SourceLocation representing start of source
3360 /// range ignoring outer template declarations.
3361 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3362
3363 /// Return SourceLocation representing start of source
3364 /// range taking into account any outer template declarations.
3365 SourceLocation getOuterLocStart() const;
3366 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3367
3368 TagDecl *getCanonicalDecl() override;
3369 const TagDecl *getCanonicalDecl() const {
3370 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3371 }
3372
3373 /// Return true if this declaration is a completion definition of the type.
3374 /// Provided for consistency.
3375 bool isThisDeclarationADefinition() const {
3376 return isCompleteDefinition();
3377 }
3378
3379 /// Return true if this decl has its body fully specified.
3380 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3381
3382 /// True if this decl has its body fully specified.
3383 void setCompleteDefinition(bool V = true) {
3384 TagDeclBits.IsCompleteDefinition = V;
3385 }
3386
3387 /// Return true if this complete decl is
3388 /// required to be complete for some existing use.
3389 bool isCompleteDefinitionRequired() const {
3390 return TagDeclBits.IsCompleteDefinitionRequired;
3391 }
3392
3393 /// True if this complete decl is
3394 /// required to be complete for some existing use.
3395 void setCompleteDefinitionRequired(bool V = true) {
3396 TagDeclBits.IsCompleteDefinitionRequired = V;
3397 }
3398
3399 /// Return true if this decl is currently being defined.
3400 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3401
3402 /// True if this tag declaration is "embedded" (i.e., defined or declared
3403 /// for the very first time) in the syntax of a declarator.
3404 bool isEmbeddedInDeclarator() const {
3405 return TagDeclBits.IsEmbeddedInDeclarator;
3406 }
3407
3408 /// True if this tag declaration is "embedded" (i.e., defined or declared
3409 /// for the very first time) in the syntax of a declarator.
3410 void setEmbeddedInDeclarator(bool isInDeclarator) {
3411 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3412 }
3413
3414 /// True if this tag is free standing, e.g. "struct foo;".
3415 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3416
3417 /// True if this tag is free standing, e.g. "struct foo;".
3418 void setFreeStanding(bool isFreeStanding = true) {
3419 TagDeclBits.IsFreeStanding = isFreeStanding;
3420 }
3421
3422 /// Indicates whether it is possible for declarations of this kind
3423 /// to have an out-of-date definition.
3424 ///
3425 /// This option is only enabled when modules are enabled.
3426 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3427
3428 /// Whether this declaration declares a type that is
3429 /// dependent, i.e., a type that somehow depends on template
3430 /// parameters.
3431 bool isDependentType() const { return isDependentContext(); }
3432
3433 /// Starts the definition of this tag declaration.
3434 ///
3435 /// This method should be invoked at the beginning of the definition
3436 /// of this tag declaration. It will set the tag type into a state
3437 /// where it is in the process of being defined.
3438 void startDefinition();
3439
3440 /// Returns the TagDecl that actually defines this
3441 /// struct/union/class/enum. When determining whether or not a
3442 /// struct/union/class/enum has a definition, one should use this
3443 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3444 /// whether or not a specific TagDecl is defining declaration, not
3445 /// whether or not the struct/union/class/enum type is defined.
3446 /// This method returns NULL if there is no TagDecl that defines
3447 /// the struct/union/class/enum.
3448 TagDecl *getDefinition() const;
3449
3450 StringRef getKindName() const {
3451 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3452 }
3453
3454 TagKind getTagKind() const {
3455 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3456 }
3457
3458 void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3459
3460 bool isStruct() const { return getTagKind() == TTK_Struct; }
3461 bool isInterface() const { return getTagKind() == TTK_Interface; }
3462 bool isClass() const { return getTagKind() == TTK_Class; }
3463 bool isUnion() const { return getTagKind() == TTK_Union; }
20
Assuming the condition is false
21
Returning zero, which participates in a condition later
3464 bool isEnum() const { return getTagKind() == TTK_Enum; }
3465
3466 /// Is this tag type named, either directly or via being defined in
3467 /// a typedef of this type?
3468 ///
3469 /// C++11 [basic.link]p8:
3470 /// A type is said to have linkage if and only if:
3471 /// - it is a class or enumeration type that is named (or has a
3472 /// name for linkage purposes) and the name has linkage; ...
3473 /// C++11 [dcl.typedef]p9:
3474 /// If the typedef declaration defines an unnamed class (or enum),
3475 /// the first typedef-name declared by the declaration to be that
3476 /// class type (or enum type) is used to denote the class type (or
3477 /// enum type) for linkage purposes only.
3478 ///
3479 /// C does not have an analogous rule, but the same concept is
3480 /// nonetheless useful in some places.
3481 bool hasNameForLinkage() const {
3482 return (getDeclName() || getTypedefNameForAnonDecl());
3483 }
3484
3485 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3486 return hasExtInfo() ? nullptr
3487 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3488 }
3489
3490 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3491
3492 /// Retrieve the nested-name-specifier that qualifies the name of this
3493 /// declaration, if it was present in the source.
3494 NestedNameSpecifier *getQualifier() const {
3495 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3496 : nullptr;
3497 }
3498
3499 /// Retrieve the nested-name-specifier (with source-location
3500 /// information) that qualifies the name of this declaration, if it was
3501 /// present in the source.
3502 NestedNameSpecifierLoc getQualifierLoc() const {
3503 return hasExtInfo() ? getExtInfo()->QualifierLoc
3504 : NestedNameSpecifierLoc();
3505 }
3506
3507 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3508
3509 unsigned getNumTemplateParameterLists() const {
3510 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3511 }
3512
3513 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3514 assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void
> (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 3514, __PRETTY_FUNCTION__))
;
3515 return getExtInfo()->TemplParamLists[i];
3516 }
3517
3518 void setTemplateParameterListsInfo(ASTContext &Context,
3519 ArrayRef<TemplateParameterList *> TPLists);
3520
3521 // Implement isa/cast/dyncast/etc.
3522 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3523 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3524
3525 static DeclContext *castToDeclContext(const TagDecl *D) {
3526 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3527 }
3528
3529 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3530 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3531 }
3532};
3533
3534/// Represents an enum. In C++11, enums can be forward-declared
3535/// with a fixed underlying type, and in C we allow them to be forward-declared
3536/// with no underlying type as an extension.
3537class EnumDecl : public TagDecl {
3538 // This class stores some data in DeclContext::EnumDeclBits
3539 // to save some space. Use the provided accessors to access it.
3540
3541 /// This represent the integer type that the enum corresponds
3542 /// to for code generation purposes. Note that the enumerator constants may
3543 /// have a different type than this does.
3544 ///
3545 /// If the underlying integer type was explicitly stated in the source
3546 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3547 /// was automatically deduced somehow, and this is a Type*.
3548 ///
3549 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3550 /// some cases it won't.
3551 ///
3552 /// The underlying type of an enumeration never has any qualifiers, so
3553 /// we can get away with just storing a raw Type*, and thus save an
3554 /// extra pointer when TypeSourceInfo is needed.
3555 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3556
3557 /// The integer type that values of this type should
3558 /// promote to. In C, enumerators are generally of an integer type
3559 /// directly, but gcc-style large enumerators (and all enumerators
3560 /// in C++) are of the enum type instead.
3561 QualType PromotionType;
3562
3563 /// If this enumeration is an instantiation of a member enumeration
3564 /// of a class template specialization, this is the member specialization
3565 /// information.
3566 MemberSpecializationInfo *SpecializationInfo = nullptr;
3567
3568 /// Store the ODRHash after first calculation.
3569 /// The corresponding flag HasODRHash is in EnumDeclBits
3570 /// and can be accessed with the provided accessors.
3571 unsigned ODRHash;
3572
3573 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3574 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3575 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3576
3577 void anchor() override;
3578
3579 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3580 TemplateSpecializationKind TSK);
3581
3582 /// Sets the width in bits required to store all the
3583 /// non-negative enumerators of this enum.
3584 void setNumPositiveBits(unsigned Num) {
3585 EnumDeclBits.NumPositiveBits = Num;
3586 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount"
) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 3586, __PRETTY_FUNCTION__))
;
3587 }
3588
3589 /// Returns the width in bits required to store all the
3590 /// negative enumerators of this enum. (see getNumNegativeBits)
3591 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3592
3593public:
3594 /// True if this tag declaration is a scoped enumeration. Only
3595 /// possible in C++11 mode.
3596 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3597
3598 /// If this tag declaration is a scoped enum,
3599 /// then this is true if the scoped enum was declared using the class
3600 /// tag, false if it was declared with the struct tag. No meaning is
3601 /// associated if this tag declaration is not a scoped enum.
3602 void setScopedUsingClassTag(bool ScopedUCT = true) {
3603 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3604 }
3605
3606 /// True if this is an Objective-C, C++11, or
3607 /// Microsoft-style enumeration with a fixed underlying type.
3608 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3609
3610private:
3611 /// True if a valid hash is stored in ODRHash.
3612 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3613 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3614
3615public:
3616 friend class ASTDeclReader;
3617
3618 EnumDecl *getCanonicalDecl() override {
3619 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3620 }
3621 const EnumDecl *getCanonicalDecl() const {
3622 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3623 }
3624
3625 EnumDecl *getPreviousDecl() {
3626 return cast_or_null<EnumDecl>(
3627 static_cast<TagDecl *>(this)->getPreviousDecl());
3628 }
3629 const EnumDecl *getPreviousDecl() const {
3630 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3631 }
3632
3633 EnumDecl *getMostRecentDecl() {
3634 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3635 }
3636 const EnumDecl *getMostRecentDecl() const {
3637 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3638 }
3639
3640 EnumDecl *getDefinition() const {
3641 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3642 }
3643
3644 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3645 SourceLocation StartLoc, SourceLocation IdLoc,
3646 IdentifierInfo *Id, EnumDecl *PrevDecl,
3647 bool IsScoped, bool IsScopedUsingClassTag,
3648 bool IsFixed);
3649 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3650
3651 /// When created, the EnumDecl corresponds to a
3652 /// forward-declared enum. This method is used to mark the
3653 /// declaration as being defined; its enumerators have already been
3654 /// added (via DeclContext::addDecl). NewType is the new underlying
3655 /// type of the enumeration type.
3656 void completeDefinition(QualType NewType,
3657 QualType PromotionType,
3658 unsigned NumPositiveBits,
3659 unsigned NumNegativeBits);
3660
3661 // Iterates through the enumerators of this enumeration.
3662 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3663 using enumerator_range =
3664 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3665
3666 enumerator_range enumerators() const {
3667 return enumerator_range(enumerator_begin(), enumerator_end());
3668 }
3669
3670 enumerator_iterator enumerator_begin() const {
3671 const EnumDecl *E = getDefinition();
3672 if (!E)
3673 E = this;
3674 return enumerator_iterator(E->decls_begin());
3675 }
3676
3677 enumerator_iterator enumerator_end() const {
3678 const EnumDecl *E = getDefinition();
3679 if (!E)
3680 E = this;
3681 return enumerator_iterator(E->decls_end());
3682 }
3683
3684 /// Return the integer type that enumerators should promote to.
3685 QualType getPromotionType() const { return PromotionType; }
3686
3687 /// Set the promotion type.
3688 void setPromotionType(QualType T) { PromotionType = T; }
3689
3690 /// Return the integer type this enum decl corresponds to.
3691 /// This returns a null QualType for an enum forward definition with no fixed
3692 /// underlying type.
3693 QualType getIntegerType() const {
3694 if (!IntegerType)
3695 return QualType();
3696 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3697 return QualType(T, 0);
3698 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3699 }
3700
3701 /// Set the underlying integer type.
3702 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3703
3704 /// Set the underlying integer type source info.
3705 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3706
3707 /// Return the type source info for the underlying integer type,
3708 /// if no type source info exists, return 0.
3709 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3710 return IntegerType.dyn_cast<TypeSourceInfo*>();
3711 }
3712
3713 /// Retrieve the source range that covers the underlying type if
3714 /// specified.
3715 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3716
3717 /// Returns the width in bits required to store all the
3718 /// non-negative enumerators of this enum.
3719 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3720
3721 /// Returns the width in bits required to store all the
3722 /// negative enumerators of this enum. These widths include
3723 /// the rightmost leading 1; that is:
3724 ///
3725 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3726 /// ------------------------ ------- -----------------
3727 /// -1 1111111 1
3728 /// -10 1110110 5
3729 /// -101 1001011 8
3730 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3731
3732 /// Returns true if this is a C++11 scoped enumeration.
3733 bool isScoped() const { return EnumDeclBits.IsScoped; }
3734
3735 /// Returns true if this is a C++11 scoped enumeration.
3736 bool isScopedUsingClassTag() const {
3737 return EnumDeclBits.IsScopedUsingClassTag;
3738 }
3739
3740 /// Returns true if this is an Objective-C, C++11, or
3741 /// Microsoft-style enumeration with a fixed underlying type.
3742 bool isFixed() const { return EnumDeclBits.IsFixed; }
3743
3744 unsigned getODRHash();
3745
3746 /// Returns true if this can be considered a complete type.
3747 bool isComplete() const {
3748 // IntegerType is set for fixed type enums and non-fixed but implicitly
3749 // int-sized Microsoft enums.
3750 return isCompleteDefinition() || IntegerType;
3751 }
3752
3753 /// Returns true if this enum is either annotated with
3754 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3755 bool isClosed() const;
3756
3757 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3758 /// with enum_extensibility(open).
3759 bool isClosedFlag() const;
3760
3761 /// Returns true if this enum is annotated with neither flag_enum nor
3762 /// enum_extensibility(open).
3763 bool isClosedNonFlag() const;
3764
3765 /// Retrieve the enum definition from which this enumeration could
3766 /// be instantiated, if it is an instantiation (rather than a non-template).
3767 EnumDecl *getTemplateInstantiationPattern() const;
3768
3769 /// Returns the enumeration (declared within the template)
3770 /// from which this enumeration type was instantiated, or NULL if
3771 /// this enumeration was not instantiated from any template.
3772 EnumDecl *getInstantiatedFromMemberEnum() const;
3773
3774 /// If this enumeration is a member of a specialization of a
3775 /// templated class, determine what kind of template specialization
3776 /// or instantiation this is.
3777 TemplateSpecializationKind getTemplateSpecializationKind() const;
3778
3779 /// For an enumeration member that was instantiated from a member
3780 /// enumeration of a templated class, set the template specialiation kind.
3781 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3782 SourceLocation PointOfInstantiation = SourceLocation());
3783
3784 /// If this enumeration is an instantiation of a member enumeration of
3785 /// a class template specialization, retrieves the member specialization
3786 /// information.
3787 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3788 return SpecializationInfo;
3789 }
3790
3791 /// Specify that this enumeration is an instantiation of the
3792 /// member enumeration ED.
3793 void setInstantiationOfMemberEnum(EnumDecl *ED,
3794 TemplateSpecializationKind TSK) {
3795 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3796 }
3797
3798 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3799 static bool classofKind(Kind K) { return K == Enum; }
3800};
3801
3802/// Represents a struct/union/class. For example:
3803/// struct X; // Forward declaration, no "body".
3804/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3805/// This decl will be marked invalid if *any* members are invalid.
3806class RecordDecl : public TagDecl {
3807 // This class stores some data in DeclContext::RecordDeclBits
3808 // to save some space. Use the provided accessors to access it.
3809public:
3810 friend class DeclContext;
3811 /// Enum that represents the different ways arguments are passed to and
3812 /// returned from function calls. This takes into account the target-specific
3813 /// and version-specific rules along with the rules determined by the
3814 /// language.
3815 enum ArgPassingKind : unsigned {
3816 /// The argument of this type can be passed directly in registers.
3817 APK_CanPassInRegs,
3818
3819 /// The argument of this type cannot be passed directly in registers.
3820 /// Records containing this type as a subobject are not forced to be passed
3821 /// indirectly. This value is used only in C++. This value is required by
3822 /// C++ because, in uncommon situations, it is possible for a class to have
3823 /// only trivial copy/move constructors even when one of its subobjects has
3824 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3825 /// constructor in the derived class is deleted).
3826 APK_CannotPassInRegs,
3827
3828 /// The argument of this type cannot be passed directly in registers.
3829 /// Records containing this type as a subobject are forced to be passed
3830 /// indirectly.
3831 APK_CanNeverPassInRegs
3832 };
3833
3834protected:
3835 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3836 SourceLocation StartLoc, SourceLocation IdLoc,
3837 IdentifierInfo *Id, RecordDecl *PrevDecl);
3838
3839public:
3840 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3841 SourceLocation StartLoc, SourceLocation IdLoc,
3842 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3843 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3844
3845 RecordDecl *getPreviousDecl() {
3846 return cast_or_null<RecordDecl>(
3847 static_cast<TagDecl *>(this)->getPreviousDecl());
3848 }
3849 const RecordDecl *getPreviousDecl() const {
3850 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3851 }
3852
3853 RecordDecl *getMostRecentDecl() {
3854 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3855 }
3856 const RecordDecl *getMostRecentDecl() const {
3857 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3858 }
3859
3860 bool hasFlexibleArrayMember() const {
3861 return RecordDeclBits.HasFlexibleArrayMember;
3862 }
3863
3864 void setHasFlexibleArrayMember(bool V) {
3865 RecordDeclBits.HasFlexibleArrayMember = V;
3866 }
3867
3868 /// Whether this is an anonymous struct or union. To be an anonymous
3869 /// struct or union, it must have been declared without a name and
3870 /// there must be no objects of this type declared, e.g.,
3871 /// @code
3872 /// union { int i; float f; };
3873 /// @endcode
3874 /// is an anonymous union but neither of the following are:
3875 /// @code
3876 /// union X { int i; float f; };
3877 /// union { int i; float f; } obj;
3878 /// @endcode
3879 bool isAnonymousStructOrUnion() const {
3880 return RecordDeclBits.AnonymousStructOrUnion;
3881 }
3882
3883 void setAnonymousStructOrUnion(bool Anon) {
3884 RecordDeclBits.AnonymousStructOrUnion = Anon;
3885 }
3886
3887 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3888 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3889
3890 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3891
3892 void setHasVolatileMember(bool val) {
3893 RecordDeclBits.HasVolatileMember = val;
3894 }
3895
3896 bool hasLoadedFieldsFromExternalStorage() const {
3897 return RecordDeclBits.LoadedFieldsFromExternalStorage;
3898 }
3899
3900 void setHasLoadedFieldsFromExternalStorage(bool val) const {
3901 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3902 }
3903
3904 /// Functions to query basic properties of non-trivial C structs.
3905 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3906 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3907 }
3908
3909 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3910 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3911 }
3912
3913 bool isNonTrivialToPrimitiveCopy() const {
3914 return RecordDeclBits.NonTrivialToPrimitiveCopy;
3915 }
3916
3917 void setNonTrivialToPrimitiveCopy(bool V) {
3918 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3919 }
3920
3921 bool isNonTrivialToPrimitiveDestroy() const {
3922 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3923 }
3924
3925 void setNonTrivialToPrimitiveDestroy(bool V) {
3926 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3927 }
3928
3929 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
3930 return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
3931 }
3932
3933 void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
3934 RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
3935 }
3936
3937 bool hasNonTrivialToPrimitiveDestructCUnion() const {
3938 return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
3939 }
3940
3941 void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
3942 RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
3943 }
3944
3945 bool hasNonTrivialToPrimitiveCopyCUnion() const {
3946 return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
3947 }
3948
3949 void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
3950 RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
3951 }
3952
3953 /// Determine whether this class can be passed in registers. In C++ mode,
3954 /// it must have at least one trivial, non-deleted copy or move constructor.
3955 /// FIXME: This should be set as part of completeDefinition.
3956 bool canPassInRegisters() const {
3957 return getArgPassingRestrictions() == APK_CanPassInRegs;
3958 }
3959
3960 ArgPassingKind getArgPassingRestrictions() const {
3961 return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3962 }
3963
3964 void setArgPassingRestrictions(ArgPassingKind Kind) {
3965 RecordDeclBits.ArgPassingRestrictions = Kind;
3966 }
3967
3968 bool isParamDestroyedInCallee() const {
3969 return RecordDeclBits.ParamDestroyedInCallee;
3970 }
3971
3972 void setParamDestroyedInCallee(bool V) {
3973 RecordDeclBits.ParamDestroyedInCallee = V;
3974 }
3975
3976 /// Determines whether this declaration represents the
3977 /// injected class name.
3978 ///
3979 /// The injected class name in C++ is the name of the class that
3980 /// appears inside the class itself. For example:
3981 ///
3982 /// \code
3983 /// struct C {
3984 /// // C is implicitly declared here as a synonym for the class name.
3985 /// };
3986 ///
3987 /// C::C c; // same as "C c;"
3988 /// \endcode
3989 bool isInjectedClassName() const;
3990
3991 /// Determine whether this record is a class describing a lambda
3992 /// function object.
3993 bool isLambda() const;
3994
3995 /// Determine whether this record is a record for captured variables in
3996 /// CapturedStmt construct.
3997 bool isCapturedRecord() const;
3998
3999 /// Mark the record as a record for captured variables in CapturedStmt
4000 /// construct.
4001 void setCapturedRecord();
4002
4003 /// Returns the RecordDecl that actually defines
4004 /// this struct/union/class. When determining whether or not a
4005 /// struct/union/class is completely defined, one should use this
4006 /// method as opposed to 'isCompleteDefinition'.
4007 /// 'isCompleteDefinition' indicates whether or not a specific
4008 /// RecordDecl is a completed definition, not whether or not the
4009 /// record type is defined. This method returns NULL if there is
4010 /// no RecordDecl that defines the struct/union/tag.
4011 RecordDecl *getDefinition() const {
4012 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
4013 }
4014
4015 /// Returns whether this record is a union, or contains (at any nesting level)
4016 /// a union member. This is used by CMSE to warn about possible information
4017 /// leaks.
4018 bool isOrContainsUnion() const;
4019
4020 // Iterator access to field members. The field iterator only visits
4021 // the non-static data members of this class, ignoring any static
4022 // data members, functions, constructors, destructors, etc.
4023 using field_iterator = specific_decl_iterator<FieldDecl>;
4024 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
4025
4026 field_range fields() const { return field_range(field_begin(), field_end()); }
4027 field_iterator field_begin() const;
4028
4029 field_iterator field_end() const {
4030 return field_iterator(decl_iterator());
4031 }
4032
4033 // Whether there are any fields (non-static data members) in this record.
4034 bool field_empty() const {
4035 return field_begin() == field_end();
4036 }
4037
4038 /// Note that the definition of this type is now complete.
4039 virtual void completeDefinition();
4040
4041 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4042 static bool classofKind(Kind K) {
4043 return K >= firstRecord && K <= lastRecord;
4044 }
4045
4046 /// Get whether or not this is an ms_struct which can
4047 /// be turned on with an attribute, pragma, or -mms-bitfields
4048 /// commandline option.
4049 bool isMsStruct(const ASTContext &C) const;
4050
4051 /// Whether we are allowed to insert extra padding between fields.
4052 /// These padding are added to help AddressSanitizer detect
4053 /// intra-object-overflow bugs.
4054 bool mayInsertExtraPadding(bool EmitRemark = false) const;
4055
4056 /// Finds the first data member which has a name.
4057 /// nullptr is returned if no named data member exists.
4058 const FieldDecl *findFirstNamedDataMember() const;
4059
4060private:
4061 /// Deserialize just the fields.
4062 void LoadFieldsFromExternalStorage() const;
4063};
4064
4065class FileScopeAsmDecl : public Decl {
4066 StringLiteral *AsmString;
4067 SourceLocation RParenLoc;
4068
4069 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
4070 SourceLocation StartL, SourceLocation EndL)
4071 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
4072
4073 virtual void anchor();
4074
4075public:
4076 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
4077 StringLiteral *Str, SourceLocation AsmLoc,
4078 SourceLocation RParenLoc);
4079
4080 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4081
4082 SourceLocation getAsmLoc() const { return getLocation(); }
4083 SourceLocation getRParenLoc() const { return RParenLoc; }
4084 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4085 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4086 return SourceRange(getAsmLoc(), getRParenLoc());
4087 }
4088
4089 const StringLiteral *getAsmString() const { return AsmString; }
4090 StringLiteral *getAsmString() { return AsmString; }
4091 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
4092
4093 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4094 static bool classofKind(Kind K) { return K == FileScopeAsm; }
4095};
4096
4097/// Represents a block literal declaration, which is like an
4098/// unnamed FunctionDecl. For example:
4099/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4100class BlockDecl : public Decl, public DeclContext {
4101 // This class stores some data in DeclContext::BlockDeclBits
4102 // to save some space. Use the provided accessors to access it.
4103public:
4104 /// A class which contains all the information about a particular
4105 /// captured value.
4106 class Capture {
4107 enum {
4108 flag_isByRef = 0x1,
4109 flag_isNested = 0x2
4110 };
4111
4112 /// The variable being captured.
4113 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
4114
4115 /// The copy expression, expressed in terms of a DeclRef (or
4116 /// BlockDeclRef) to the captured variable. Only required if the
4117 /// variable has a C++ class type.
4118 Expr *CopyExpr;
4119
4120 public:
4121 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
4122 : VariableAndFlags(variable,
4123 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
4124 CopyExpr(copy) {}
4125
4126 /// The variable being captured.
4127 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
4128
4129 /// Whether this is a "by ref" capture, i.e. a capture of a __block
4130 /// variable.
4131 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
4132
4133 bool isEscapingByref() const {
4134 return getVariable()->isEscapingByref();
4135 }
4136
4137 bool isNonEscapingByref() const {
4138 return getVariable()->isNonEscapingByref();
4139 }
4140
4141 /// Whether this is a nested capture, i.e. the variable captured
4142 /// is not from outside the immediately enclosing function/block.
4143 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
4144
4145 bool hasCopyExpr() const { return CopyExpr != nullptr; }
4146 Expr *getCopyExpr() const { return CopyExpr; }
4147 void setCopyExpr(Expr *e) { CopyExpr = e; }
4148 };
4149
4150private:
4151 /// A new[]'d array of pointers to ParmVarDecls for the formal
4152 /// parameters of this function. This is null if a prototype or if there are
4153 /// no formals.
4154 ParmVarDecl **ParamInfo = nullptr;
4155 unsigned NumParams = 0;
4156
4157 Stmt *Body = nullptr;
4158 TypeSourceInfo *SignatureAsWritten = nullptr;
4159
4160 const Capture *Captures = nullptr;
4161 unsigned NumCaptures = 0;
4162
4163 unsigned ManglingNumber = 0;
4164 Decl *ManglingContextDecl = nullptr;
4165
4166protected:
4167 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4168
4169public:
4170 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4171 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4172
4173 SourceLocation getCaretLocation() const { return getLocation(); }
4174
4175 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4176 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4177
4178 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4179 Stmt *getBody() const override { return (Stmt*) Body; }
4180 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4181
4182 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4183 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4184
4185 // ArrayRef access to formal parameters.
4186 ArrayRef<ParmVarDecl *> parameters() const {
4187 return {ParamInfo, getNumParams()};
4188 }
4189 MutableArrayRef<ParmVarDecl *> parameters() {
4190 return {ParamInfo, getNumParams()};
4191 }
4192
4193 // Iterator access to formal parameters.
4194 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4195 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4196
4197 bool param_empty() const { return parameters().empty(); }
4198 param_iterator param_begin() { return parameters().begin(); }
4199 param_iterator param_end() { return parameters().end(); }
4200 param_const_iterator param_begin() const { return parameters().begin(); }
4201 param_const_iterator param_end() const { return parameters().end(); }
4202 size_t param_size() const { return parameters().size(); }
4203
4204 unsigned getNumParams() const { return NumParams; }
4205
4206 const ParmVarDecl *getParamDecl(unsigned i) const {
4207 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4207, __PRETTY_FUNCTION__))
;
4208 return ParamInfo[i];
4209 }
4210 ParmVarDecl *getParamDecl(unsigned i) {
4211 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4211, __PRETTY_FUNCTION__))
;
4212 return ParamInfo[i];
4213 }
4214
4215 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4216
4217 /// True if this block (or its nested blocks) captures
4218 /// anything of local storage from its enclosing scopes.
4219 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4220
4221 /// Returns the number of captured variables.
4222 /// Does not include an entry for 'this'.
4223 unsigned getNumCaptures() const { return NumCaptures; }
4224
4225 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4226
4227 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4228
4229 capture_const_iterator capture_begin() const { return captures().begin(); }
4230 capture_const_iterator capture_end() const { return captures().end(); }
4231
4232 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4233 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4234
4235 bool blockMissingReturnType() const {
4236 return BlockDeclBits.BlockMissingReturnType;
4237 }
4238
4239 void setBlockMissingReturnType(bool val = true) {
4240 BlockDeclBits.BlockMissingReturnType = val;
4241 }
4242
4243 bool isConversionFromLambda() const {
4244 return BlockDeclBits.IsConversionFromLambda;
4245 }
4246
4247 void setIsConversionFromLambda(bool val = true) {
4248 BlockDeclBits.IsConversionFromLambda = val;
4249 }
4250
4251 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4252 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4253
4254 bool canAvoidCopyToHeap() const {
4255 return BlockDeclBits.CanAvoidCopyToHeap;
4256 }
4257 void setCanAvoidCopyToHeap(bool B = true) {
4258 BlockDeclBits.CanAvoidCopyToHeap = B;
4259 }
4260
4261 bool capturesVariable(const VarDecl *var) const;
4262
4263 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4264 bool CapturesCXXThis);
4265
4266 unsigned getBlockManglingNumber() const { return ManglingNumber; }
4267
4268 Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
4269
4270 void setBlockMangling(unsigned Number, Decl *Ctx) {
4271 ManglingNumber = Number;
4272 ManglingContextDecl = Ctx;
4273 }
4274
4275 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4276
4277 // Implement isa/cast/dyncast/etc.
4278 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4279 static bool classofKind(Kind K) { return K == Block; }
4280 static DeclContext *castToDeclContext(const BlockDecl *D) {
4281 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4282 }
4283 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4284 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4285 }
4286};
4287
4288/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4289class CapturedDecl final
4290 : public Decl,
4291 public DeclContext,
4292 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4293protected:
4294 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4295 return NumParams;
4296 }
4297
4298private:
4299 /// The number of parameters to the outlined function.
4300 unsigned NumParams;
4301
4302 /// The position of context parameter in list of parameters.
4303 unsigned ContextParam;
4304
4305 /// The body of the outlined function.
4306 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4307
4308 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4309
4310 ImplicitParamDecl *const *getParams() const {
4311 return getTrailingObjects<ImplicitParamDecl *>();
4312 }
4313
4314 ImplicitParamDecl **getParams() {
4315 return getTrailingObjects<ImplicitParamDecl *>();
4316 }
4317
4318public:
4319 friend class ASTDeclReader;
4320 friend class ASTDeclWriter;
4321 friend TrailingObjects;
4322
4323 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4324 unsigned NumParams);
4325 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4326 unsigned NumParams);
4327
4328 Stmt *getBody() const override;
4329 void setBody(Stmt *B);
4330
4331 bool isNothrow() const;
4332 void setNothrow(bool Nothrow = true);
4333
4334 unsigned getNumParams() const { return NumParams; }
4335
4336 ImplicitParamDecl *getParam(unsigned i) const {
4337 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4337, __PRETTY_FUNCTION__))
;
4338 return getParams()[i];
4339 }
4340 void setParam(unsigned i, ImplicitParamDecl *P) {
4341 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4341, __PRETTY_FUNCTION__))
;
4342 getParams()[i] = P;
4343 }
4344
4345 // ArrayRef interface to parameters.
4346 ArrayRef<ImplicitParamDecl *> parameters() const {
4347 return {getParams(), getNumParams()};
4348 }
4349 MutableArrayRef<ImplicitParamDecl *> parameters() {
4350 return {getParams(), getNumParams()};
4351 }
4352
4353 /// Retrieve the parameter containing captured variables.
4354 ImplicitParamDecl *getContextParam() const {
4355 assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) :
__assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4355, __PRETTY_FUNCTION__))
;
4356 return getParam(ContextParam);
4357 }
4358 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4359 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4359, __PRETTY_FUNCTION__))
;
4360 ContextParam = i;
4361 setParam(i, P);
4362 }
4363 unsigned getContextParamPosition() const { return ContextParam; }
4364
4365 using param_iterator = ImplicitParamDecl *const *;
4366 using param_range = llvm::iterator_range<param_iterator>;
4367
4368 /// Retrieve an iterator pointing to the first parameter decl.
4369 param_iterator param_begin() const { return getParams(); }
4370 /// Retrieve an iterator one past the last parameter decl.
4371 param_iterator param_end() const { return getParams() + NumParams; }
4372
4373 // Implement isa/cast/dyncast/etc.
4374 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4375 static bool classofKind(Kind K) { return K == Captured; }
4376 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4377 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4378 }
4379 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4380 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4381 }
4382};
4383
4384/// Describes a module import declaration, which makes the contents
4385/// of the named module visible in the current translation unit.
4386///
4387/// An import declaration imports the named module (or submodule). For example:
4388/// \code
4389/// @import std.vector;
4390/// \endcode
4391///
4392/// Import declarations can also be implicitly generated from
4393/// \#include/\#import directives.
4394class ImportDecl final : public Decl,
4395 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4396 friend class ASTContext;
4397 friend class ASTDeclReader;
4398 friend class ASTReader;
4399 friend TrailingObjects;
4400
4401 /// The imported module.
4402 Module *ImportedModule = nullptr;
4403
4404 /// The next import in the list of imports local to the translation
4405 /// unit being parsed (not loaded from an AST file).
4406 ///
4407 /// Includes a bit that indicates whether we have source-location information
4408 /// for each identifier in the module name.
4409 ///
4410 /// When the bit is false, we only have a single source location for the
4411 /// end of the import declaration.
4412 llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete;
4413
4414 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4415 ArrayRef<SourceLocation> IdentifierLocs);
4416
4417 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4418 SourceLocation EndLoc);
4419
4420 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4421
4422 bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); }
4423
4424 void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); }
4425
4426 /// The next import in the list of imports local to the translation
4427 /// unit being parsed (not loaded from an AST file).
4428 ImportDecl *getNextLocalImport() const {
4429 return NextLocalImportAndComplete.getPointer();
4430 }
4431
4432 void setNextLocalImport(ImportDecl *Import) {
4433 NextLocalImportAndComplete.setPointer(Import);
4434 }
4435
4436public:
4437 /// Create a new module import declaration.
4438 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4439 SourceLocation StartLoc, Module *Imported,
4440 ArrayRef<SourceLocation> IdentifierLocs);
4441
4442 /// Create a new module import declaration for an implicitly-generated
4443 /// import.
4444 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4445 SourceLocation StartLoc, Module *Imported,
4446 SourceLocation EndLoc);
4447
4448 /// Create a new, deserialized module import declaration.
4449 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4450 unsigned NumLocations);
4451
4452 /// Retrieve the module that was imported by the import declaration.
4453 Module *getImportedModule() const { return ImportedModule; }
4454
4455 /// Retrieves the locations of each of the identifiers that make up
4456 /// the complete module name in the import declaration.
4457 ///
4458 /// This will return an empty array if the locations of the individual
4459 /// identifiers aren't available.
4460 ArrayRef<SourceLocation> getIdentifierLocs() const;
4461
4462 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4463
4464 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4465 static bool classofKind(Kind K) { return K == Import; }
4466};
4467
4468/// Represents a C++ Modules TS module export declaration.
4469///
4470/// For example:
4471/// \code
4472/// export void foo();
4473/// \endcode
4474class ExportDecl final : public Decl, public DeclContext {
4475 virtual void anchor();
4476
4477private:
4478 friend class ASTDeclReader;
4479
4480 /// The source location for the right brace (if valid).
4481 SourceLocation RBraceLoc;
4482
4483 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4484 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4485 RBraceLoc(SourceLocation()) {}
4486
4487public:
4488 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4489 SourceLocation ExportLoc);
4490 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4491
4492 SourceLocation getExportLoc() const { return getLocation(); }
4493 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4494 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4495
4496 bool hasBraces() const { return RBraceLoc.isValid(); }
4497
4498 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4499 if (hasBraces())
4500 return RBraceLoc;
4501 // No braces: get the end location of the (only) declaration in context
4502 // (if present).
4503 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4504 }
4505
4506 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4507 return SourceRange(getLocation(), getEndLoc());
4508 }
4509
4510 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4511 static bool classofKind(Kind K) { return K == Export; }
4512 static DeclContext *castToDeclContext(const ExportDecl *D) {
4513 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4514 }
4515 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4516 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4517 }
4518};
4519
4520/// Represents an empty-declaration.
4521class EmptyDecl : public Decl {
4522 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4523
4524 virtual void anchor();
4525
4526public:
4527 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4528 SourceLocation L);
4529 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4530
4531 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4532 static bool classofKind(Kind K) { return K == Empty; }
4533};
4534
4535/// Insertion operator for diagnostics. This allows sending NamedDecl's
4536/// into a diagnostic with <<.
4537inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
4538 const NamedDecl *ND) {
4539 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4540 DiagnosticsEngine::ak_nameddecl);
4541 return PD;
4542}
4543
4544template<typename decl_type>
4545void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4546 // Note: This routine is implemented here because we need both NamedDecl
4547 // and Redeclarable to be defined.
4548 assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4549, __PRETTY_FUNCTION__))
4549 "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4549, __PRETTY_FUNCTION__))
;
4550
4551 if (PrevDecl) {
4552 // Point to previous. Make sure that this is actually the most recent
4553 // redeclaration, or we can build invalid chains. If the most recent
4554 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4555 First = PrevDecl->getFirstDecl();
4556 assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first")
? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4556, __PRETTY_FUNCTION__))
;
4557 decl_type *MostRecent = First->getNextRedeclaration();
4558 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4559
4560 // If the declaration was previously visible, a redeclaration of it remains
4561 // visible even if it wouldn't be visible by itself.
4562 static_cast<decl_type*>(this)->IdentifierNamespace |=
4563 MostRecent->getIdentifierNamespace() &
4564 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4565 } else {
4566 // Make this first.
4567 First = static_cast<decl_type*>(this);
4568 }
4569
4570 // First one will point to this one as latest.
4571 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4572
4573 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4574, __PRETTY_FUNCTION__))
4574 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/clang/include/clang/AST/Decl.h"
, 4574, __PRETTY_FUNCTION__))
;
4575}
4576
4577// Inline function definitions.
4578
4579/// Check if the given decl is complete.
4580///
4581/// We use this function to break a cycle between the inline definitions in
4582/// Type.h and Decl.h.
4583inline bool IsEnumDeclComplete(EnumDecl *ED) {
4584 return ED->isComplete();
4585}
4586
4587/// Check if the given decl is scoped.
4588///
4589/// We use this function to break a cycle between the inline definitions in
4590/// Type.h and Decl.h.
4591inline bool IsEnumDeclScoped(EnumDecl *ED) {
4592 return ED->isScoped();
4593}
4594
4595/// OpenMP variants are mangled early based on their OpenMP context selector.
4596/// The new name looks likes this:
4597/// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context>
4598static constexpr StringRef getOpenMPVariantManglingSeparatorStr() {
4599 return "$ompvariant";
4600}
4601
4602} // namespace clang
4603
4604#endif // LLVM_CLANG_AST_DECL_H