Bug Summary

File:build/source/clang/lib/Sema/SemaLambda.cpp
Warning:line 1281, column 26
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaLambda.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaLambda.cpp

/build/source/clang/lib/Sema/SemaLambda.cpp

1//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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++ lambda expressions.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Sema/DeclSpec.h"
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Scope.h"
20#include "clang/Sema/ScopeInfo.h"
21#include "clang/Sema/SemaInternal.h"
22#include "clang/Sema/SemaLambda.h"
23#include "llvm/ADT/STLExtras.h"
24#include <optional>
25using namespace clang;
26using namespace sema;
27
28/// Examines the FunctionScopeInfo stack to determine the nearest
29/// enclosing lambda (to the current lambda) that is 'capture-ready' for
30/// the variable referenced in the current lambda (i.e. \p VarToCapture).
31/// If successful, returns the index into Sema's FunctionScopeInfo stack
32/// of the capture-ready lambda's LambdaScopeInfo.
33///
34/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
35/// lambda - is on top) to determine the index of the nearest enclosing/outer
36/// lambda that is ready to capture the \p VarToCapture being referenced in
37/// the current lambda.
38/// As we climb down the stack, we want the index of the first such lambda -
39/// that is the lambda with the highest index that is 'capture-ready'.
40///
41/// A lambda 'L' is capture-ready for 'V' (var or this) if:
42/// - its enclosing context is non-dependent
43/// - and if the chain of lambdas between L and the lambda in which
44/// V is potentially used (i.e. the lambda at the top of the scope info
45/// stack), can all capture or have already captured V.
46/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
47///
48/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
49/// for whether it is 'capture-capable' (see
50/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
51/// capture.
52///
53/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
54/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
55/// is at the top of the stack and has the highest index.
56/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
57///
58/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
59/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
60/// lambda which is capture-ready. If the return value evaluates to 'false'
61/// then no lambda is capture-ready for \p VarToCapture.
62
63static inline std::optional<unsigned>
64getStackIndexOfNearestEnclosingCaptureReadyLambda(
65 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
66 ValueDecl *VarToCapture) {
67 // Label failure to capture.
68 const std::optional<unsigned> NoLambdaIsCaptureReady;
69
70 // Ignore all inner captured regions.
71 unsigned CurScopeIndex = FunctionScopes.size() - 1;
72 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
73 FunctionScopes[CurScopeIndex]))
74 --CurScopeIndex;
75 assert((static_cast <bool> (isa<clang::sema::LambdaScopeInfo
>(FunctionScopes[CurScopeIndex]) && "The function on the top of sema's function-info stack must be a lambda"
) ? void (0) : __assert_fail ("isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && \"The function on the top of sema's function-info stack must be a lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 77, __extension__ __PRETTY_FUNCTION__
))
76 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&(static_cast <bool> (isa<clang::sema::LambdaScopeInfo
>(FunctionScopes[CurScopeIndex]) && "The function on the top of sema's function-info stack must be a lambda"
) ? void (0) : __assert_fail ("isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && \"The function on the top of sema's function-info stack must be a lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 77, __extension__ __PRETTY_FUNCTION__
))
77 "The function on the top of sema's function-info stack must be a lambda")(static_cast <bool> (isa<clang::sema::LambdaScopeInfo
>(FunctionScopes[CurScopeIndex]) && "The function on the top of sema's function-info stack must be a lambda"
) ? void (0) : __assert_fail ("isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && \"The function on the top of sema's function-info stack must be a lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 77, __extension__ __PRETTY_FUNCTION__
))
;
78
79 // If VarToCapture is null, we are attempting to capture 'this'.
80 const bool IsCapturingThis = !VarToCapture;
81 const bool IsCapturingVariable = !IsCapturingThis;
82
83 // Start with the current lambda at the top of the stack (highest index).
84 DeclContext *EnclosingDC =
85 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
86
87 do {
88 const clang::sema::LambdaScopeInfo *LSI =
89 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
90 // IF we have climbed down to an intervening enclosing lambda that contains
91 // the variable declaration - it obviously can/must not capture the
92 // variable.
93 // Since its enclosing DC is dependent, all the lambdas between it and the
94 // innermost nested lambda are dependent (otherwise we wouldn't have
95 // arrived here) - so we don't yet have a lambda that can capture the
96 // variable.
97 if (IsCapturingVariable &&
98 VarToCapture->getDeclContext()->Equals(EnclosingDC))
99 return NoLambdaIsCaptureReady;
100
101 // For an enclosing lambda to be capture ready for an entity, all
102 // intervening lambda's have to be able to capture that entity. If even
103 // one of the intervening lambda's is not capable of capturing the entity
104 // then no enclosing lambda can ever capture that entity.
105 // For e.g.
106 // const int x = 10;
107 // [=](auto a) { #1
108 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
109 // [=](auto c) { #3
110 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
111 // }; }; };
112 // If they do not have a default implicit capture, check to see
113 // if the entity has already been explicitly captured.
114 // If even a single dependent enclosing lambda lacks the capability
115 // to ever capture this variable, there is no further enclosing
116 // non-dependent lambda that can capture this variable.
117 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
118 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
119 return NoLambdaIsCaptureReady;
120 if (IsCapturingThis && !LSI->isCXXThisCaptured())
121 return NoLambdaIsCaptureReady;
122 }
123 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
124
125 assert(CurScopeIndex)(static_cast <bool> (CurScopeIndex) ? void (0) : __assert_fail
("CurScopeIndex", "clang/lib/Sema/SemaLambda.cpp", 125, __extension__
__PRETTY_FUNCTION__))
;
126 --CurScopeIndex;
127 } while (!EnclosingDC->isTranslationUnit() &&
128 EnclosingDC->isDependentContext() &&
129 isLambdaCallOperator(EnclosingDC));
130
131 assert(CurScopeIndex < (FunctionScopes.size() - 1))(static_cast <bool> (CurScopeIndex < (FunctionScopes
.size() - 1)) ? void (0) : __assert_fail ("CurScopeIndex < (FunctionScopes.size() - 1)"
, "clang/lib/Sema/SemaLambda.cpp", 131, __extension__ __PRETTY_FUNCTION__
))
;
132 // If the enclosingDC is not dependent, then the immediately nested lambda
133 // (one index above) is capture-ready.
134 if (!EnclosingDC->isDependentContext())
135 return CurScopeIndex + 1;
136 return NoLambdaIsCaptureReady;
137}
138
139/// Examines the FunctionScopeInfo stack to determine the nearest
140/// enclosing lambda (to the current lambda) that is 'capture-capable' for
141/// the variable referenced in the current lambda (i.e. \p VarToCapture).
142/// If successful, returns the index into Sema's FunctionScopeInfo stack
143/// of the capture-capable lambda's LambdaScopeInfo.
144///
145/// Given the current stack of lambdas being processed by Sema and
146/// the variable of interest, to identify the nearest enclosing lambda (to the
147/// current lambda at the top of the stack) that can truly capture
148/// a variable, it has to have the following two properties:
149/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
150/// - climb down the stack (i.e. starting from the innermost and examining
151/// each outer lambda step by step) checking if each enclosing
152/// lambda can either implicitly or explicitly capture the variable.
153/// Record the first such lambda that is enclosed in a non-dependent
154/// context. If no such lambda currently exists return failure.
155/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
156/// capture the variable by checking all its enclosing lambdas:
157/// - check if all outer lambdas enclosing the 'capture-ready' lambda
158/// identified above in 'a' can also capture the variable (this is done
159/// via tryCaptureVariable for variables and CheckCXXThisCapture for
160/// 'this' by passing in the index of the Lambda identified in step 'a')
161///
162/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
163/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
164/// is at the top of the stack.
165///
166/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
167///
168///
169/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
170/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
171/// lambda which is capture-capable. If the return value evaluates to 'false'
172/// then no lambda is capture-capable for \p VarToCapture.
173
174std::optional<unsigned>
175clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
176 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
177 ValueDecl *VarToCapture, Sema &S) {
178
179 const std::optional<unsigned> NoLambdaIsCaptureCapable;
180
181 const std::optional<unsigned> OptionalStackIndex =
182 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
183 VarToCapture);
184 if (!OptionalStackIndex)
185 return NoLambdaIsCaptureCapable;
186
187 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
188 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 191, __extension__ __PRETTY_FUNCTION__
))
189 S.getCurGenericLambda()) &&(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 191, __extension__ __PRETTY_FUNCTION__
))
190 "The capture ready lambda for a potential capture can only be the "(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 191, __extension__ __PRETTY_FUNCTION__
))
191 "current lambda if it is a generic lambda")(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 191, __extension__ __PRETTY_FUNCTION__
))
;
192
193 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
194 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
195
196 // If VarToCapture is null, we are attempting to capture 'this'
197 const bool IsCapturingThis = !VarToCapture;
198 const bool IsCapturingVariable = !IsCapturingThis;
199
200 if (IsCapturingVariable) {
201 // Check if the capture-ready lambda can truly capture the variable, by
202 // checking whether all enclosing lambdas of the capture-ready lambda allow
203 // the capture - i.e. make sure it is capture-capable.
204 QualType CaptureType, DeclRefType;
205 const bool CanCaptureVariable =
206 !S.tryCaptureVariable(VarToCapture,
207 /*ExprVarIsUsedInLoc*/ SourceLocation(),
208 clang::Sema::TryCapture_Implicit,
209 /*EllipsisLoc*/ SourceLocation(),
210 /*BuildAndDiagnose*/ false, CaptureType,
211 DeclRefType, &IndexOfCaptureReadyLambda);
212 if (!CanCaptureVariable)
213 return NoLambdaIsCaptureCapable;
214 } else {
215 // Check if the capture-ready lambda can truly capture 'this' by checking
216 // whether all enclosing lambdas of the capture-ready lambda can capture
217 // 'this'.
218 const bool CanCaptureThis =
219 !S.CheckCXXThisCapture(
220 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
221 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
222 &IndexOfCaptureReadyLambda);
223 if (!CanCaptureThis)
224 return NoLambdaIsCaptureCapable;
225 }
226 return IndexOfCaptureReadyLambda;
227}
228
229static inline TemplateParameterList *
230getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
231 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
232 LSI->GLTemplateParameterList = TemplateParameterList::Create(
233 SemaRef.Context,
234 /*Template kw loc*/ SourceLocation(),
235 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
236 LSI->TemplateParams,
237 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
238 LSI->RequiresClause.get());
239 }
240 return LSI->GLTemplateParameterList;
241}
242
243CXXRecordDecl *
244Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
245 unsigned LambdaDependencyKind,
246 LambdaCaptureDefault CaptureDefault) {
247 DeclContext *DC = CurContext;
248 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
249 DC = DC->getParent();
250
251 bool IsGenericLambda =
252 Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this);
253 // Start constructing the lambda class.
254 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
255 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
256 IsGenericLambda, CaptureDefault);
257 DC->addDecl(Class);
258
259 return Class;
260}
261
262/// Determine whether the given context is or is enclosed in an inline
263/// function.
264static bool isInInlineFunction(const DeclContext *DC) {
265 while (!DC->isFileContext()) {
266 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
267 if (FD->isInlined())
268 return true;
269
270 DC = DC->getLexicalParent();
271 }
272
273 return false;
274}
275
276std::tuple<MangleNumberingContext *, Decl *>
277Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
278 // Compute the context for allocating mangling numbers in the current
279 // expression, if the ABI requires them.
280 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
281
282 enum ContextKind {
283 Normal,
284 DefaultArgument,
285 DataMember,
286 InlineVariable,
287 TemplatedVariable,
288 Concept
289 } Kind = Normal;
290
291 bool IsInNonspecializedTemplate =
292 inTemplateInstantiation() || CurContext->isDependentContext();
293
294 // Default arguments of member function parameters that appear in a class
295 // definition, as well as the initializers of data members, receive special
296 // treatment. Identify them.
297 if (ManglingContextDecl) {
298 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
299 if (const DeclContext *LexicalDC
300 = Param->getDeclContext()->getLexicalParent())
301 if (LexicalDC->isRecord())
302 Kind = DefaultArgument;
303 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
304 if (Var->getMostRecentDecl()->isInline())
305 Kind = InlineVariable;
306 else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
307 Kind = TemplatedVariable;
308 else if (Var->getDescribedVarTemplate())
309 Kind = TemplatedVariable;
310 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
311 if (!VTS->isExplicitSpecialization())
312 Kind = TemplatedVariable;
313 }
314 } else if (isa<FieldDecl>(ManglingContextDecl)) {
315 Kind = DataMember;
316 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
317 Kind = Concept;
318 }
319 }
320
321 // Itanium ABI [5.1.7]:
322 // In the following contexts [...] the one-definition rule requires closure
323 // types in different translation units to "correspond":
324 switch (Kind) {
325 case Normal: {
326 // -- the bodies of inline or templated functions
327 if ((IsInNonspecializedTemplate &&
328 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
329 isInInlineFunction(CurContext)) {
330 while (auto *CD = dyn_cast<CapturedDecl>(DC))
331 DC = CD->getParent();
332 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
333 }
334
335 return std::make_tuple(nullptr, nullptr);
336 }
337
338 case Concept:
339 // Concept definitions aren't code generated and thus aren't mangled,
340 // however the ManglingContextDecl is important for the purposes of
341 // re-forming the template argument list of the lambda for constraint
342 // evaluation.
343 case DataMember:
344 // -- default member initializers
345 case DefaultArgument:
346 // -- default arguments appearing in class definitions
347 case InlineVariable:
348 case TemplatedVariable:
349 // -- the initializers of inline or templated variables
350 return std::make_tuple(
351 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
352 ManglingContextDecl),
353 ManglingContextDecl);
354 }
355
356 llvm_unreachable("unexpected context")::llvm::llvm_unreachable_internal("unexpected context", "clang/lib/Sema/SemaLambda.cpp"
, 356)
;
357}
358
359static QualType
360buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class,
361 TemplateParameterList *TemplateParams,
362 TypeSourceInfo *MethodTypeInfo) {
363 assert(MethodTypeInfo && "expected a non null type")(static_cast <bool> (MethodTypeInfo && "expected a non null type"
) ? void (0) : __assert_fail ("MethodTypeInfo && \"expected a non null type\""
, "clang/lib/Sema/SemaLambda.cpp", 363, __extension__ __PRETTY_FUNCTION__
))
;
364
365 QualType MethodType = MethodTypeInfo->getType();
366 // If a lambda appears in a dependent context or is a generic lambda (has
367 // template parameters) and has an 'auto' return type, deduce it to a
368 // dependent type.
369 if (Class->isDependentContext() || TemplateParams) {
370 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
371 QualType Result = FPT->getReturnType();
372 if (Result->isUndeducedType()) {
373 Result = S.SubstAutoTypeDependent(Result);
374 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
375 FPT->getExtProtoInfo());
376 }
377 }
378 return MethodType;
379}
380
381void Sema::handleLambdaNumbering(
382 CXXRecordDecl *Class, CXXMethodDecl *Method,
383 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
384 if (NumberingOverride) {
385 Class->setLambdaNumbering(*NumberingOverride);
386 return;
387 }
388
389 ContextRAII ManglingContext(*this, Class->getDeclContext());
390
391 auto getMangleNumberingContext =
392 [this](CXXRecordDecl *Class,
393 Decl *ManglingContextDecl) -> MangleNumberingContext * {
394 // Get mangle numbering context if there's any extra decl context.
395 if (ManglingContextDecl)
396 return &Context.getManglingNumberContext(
397 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
398 // Otherwise, from that lambda's decl context.
399 auto DC = Class->getDeclContext();
400 while (auto *CD = dyn_cast<CapturedDecl>(DC))
401 DC = CD->getParent();
402 return &Context.getManglingNumberContext(DC);
403 };
404
405 CXXRecordDecl::LambdaNumbering Numbering;
406 MangleNumberingContext *MCtx;
407 std::tie(MCtx, Numbering.ContextDecl) =
408 getCurrentMangleNumberContext(Class->getDeclContext());
409 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
410 getLangOpts().SYCLIsHost)) {
411 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
412 // ODR. Both device- and host-compilation need to have a consistent naming
413 // on kernel functions. As lambdas are potential part of these `__global__`
414 // function names, they needs numbering following ODR.
415 // Also force for SYCL, since we need this for the
416 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
417 // mangling.
418 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
419 assert(MCtx && "Retrieving mangle numbering context failed!")(static_cast <bool> (MCtx && "Retrieving mangle numbering context failed!"
) ? void (0) : __assert_fail ("MCtx && \"Retrieving mangle numbering context failed!\""
, "clang/lib/Sema/SemaLambda.cpp", 419, __extension__ __PRETTY_FUNCTION__
))
;
420 Numbering.HasKnownInternalLinkage = true;
421 }
422 if (MCtx) {
423 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
424 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
425 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
426 Class->setLambdaNumbering(Numbering);
427
428 if (auto *Source =
429 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
430 Source->AssignedLambdaNumbering(Class);
431 }
432}
433
434static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI,
435 CXXMethodDecl *CallOperator,
436 bool ExplicitResultType) {
437 if (ExplicitResultType) {
438 LSI->HasImplicitReturnType = false;
439 LSI->ReturnType = CallOperator->getReturnType();
440 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
441 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
442 diag::err_lambda_incomplete_result);
443 } else {
444 LSI->HasImplicitReturnType = true;
445 }
446}
447
448void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
449 SourceRange IntroducerRange,
450 LambdaCaptureDefault CaptureDefault,
451 SourceLocation CaptureDefaultLoc,
452 bool ExplicitParams, bool Mutable) {
453 LSI->CallOperator = CallOperator;
454 CXXRecordDecl *LambdaClass = CallOperator->getParent();
455 LSI->Lambda = LambdaClass;
456 if (CaptureDefault == LCD_ByCopy)
457 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
458 else if (CaptureDefault == LCD_ByRef)
459 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
460 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
461 LSI->IntroducerRange = IntroducerRange;
462 LSI->ExplicitParams = ExplicitParams;
463 LSI->Mutable = Mutable;
464}
465
466void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
467 LSI->finishedExplicitCaptures();
468}
469
470void Sema::ActOnLambdaExplicitTemplateParameterList(
471 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
472 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
473 ExprResult RequiresClause) {
474 LambdaScopeInfo *LSI = getCurLambda();
475 assert(LSI && "Expected a lambda scope")(static_cast <bool> (LSI && "Expected a lambda scope"
) ? void (0) : __assert_fail ("LSI && \"Expected a lambda scope\""
, "clang/lib/Sema/SemaLambda.cpp", 475, __extension__ __PRETTY_FUNCTION__
))
;
476 assert(LSI->NumExplicitTemplateParams == 0 &&(static_cast <bool> (LSI->NumExplicitTemplateParams ==
0 && "Already acted on explicit template parameters"
) ? void (0) : __assert_fail ("LSI->NumExplicitTemplateParams == 0 && \"Already acted on explicit template parameters\""
, "clang/lib/Sema/SemaLambda.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
477 "Already acted on explicit template parameters")(static_cast <bool> (LSI->NumExplicitTemplateParams ==
0 && "Already acted on explicit template parameters"
) ? void (0) : __assert_fail ("LSI->NumExplicitTemplateParams == 0 && \"Already acted on explicit template parameters\""
, "clang/lib/Sema/SemaLambda.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
;
478 assert(LSI->TemplateParams.empty() &&(static_cast <bool> (LSI->TemplateParams.empty() &&
"Explicit template parameters should come " "before invented (auto) ones"
) ? void (0) : __assert_fail ("LSI->TemplateParams.empty() && \"Explicit template parameters should come \" \"before invented (auto) ones\""
, "clang/lib/Sema/SemaLambda.cpp", 480, __extension__ __PRETTY_FUNCTION__
))
479 "Explicit template parameters should come "(static_cast <bool> (LSI->TemplateParams.empty() &&
"Explicit template parameters should come " "before invented (auto) ones"
) ? void (0) : __assert_fail ("LSI->TemplateParams.empty() && \"Explicit template parameters should come \" \"before invented (auto) ones\""
, "clang/lib/Sema/SemaLambda.cpp", 480, __extension__ __PRETTY_FUNCTION__
))
480 "before invented (auto) ones")(static_cast <bool> (LSI->TemplateParams.empty() &&
"Explicit template parameters should come " "before invented (auto) ones"
) ? void (0) : __assert_fail ("LSI->TemplateParams.empty() && \"Explicit template parameters should come \" \"before invented (auto) ones\""
, "clang/lib/Sema/SemaLambda.cpp", 480, __extension__ __PRETTY_FUNCTION__
))
;
481 assert(!TParams.empty() &&(static_cast <bool> (!TParams.empty() && "No template parameters to act on"
) ? void (0) : __assert_fail ("!TParams.empty() && \"No template parameters to act on\""
, "clang/lib/Sema/SemaLambda.cpp", 482, __extension__ __PRETTY_FUNCTION__
))
482 "No template parameters to act on")(static_cast <bool> (!TParams.empty() && "No template parameters to act on"
) ? void (0) : __assert_fail ("!TParams.empty() && \"No template parameters to act on\""
, "clang/lib/Sema/SemaLambda.cpp", 482, __extension__ __PRETTY_FUNCTION__
))
;
483 LSI->TemplateParams.append(TParams.begin(), TParams.end());
484 LSI->NumExplicitTemplateParams = TParams.size();
485 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
486 LSI->RequiresClause = RequiresClause;
487}
488
489/// If this expression is an enumerator-like expression of some type
490/// T, return the type T; otherwise, return null.
491///
492/// Pointer comparisons on the result here should always work because
493/// it's derived from either the parent of an EnumConstantDecl
494/// (i.e. the definition) or the declaration returned by
495/// EnumType::getDecl() (i.e. the definition).
496static EnumDecl *findEnumForBlockReturn(Expr *E) {
497 // An expression is an enumerator-like expression of type T if,
498 // ignoring parens and parens-like expressions:
499 E = E->IgnoreParens();
500
501 // - it is an enumerator whose enum type is T or
502 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
503 if (EnumConstantDecl *D
504 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
505 return cast<EnumDecl>(D->getDeclContext());
506 }
507 return nullptr;
508 }
509
510 // - it is a comma expression whose RHS is an enumerator-like
511 // expression of type T or
512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
513 if (BO->getOpcode() == BO_Comma)
514 return findEnumForBlockReturn(BO->getRHS());
515 return nullptr;
516 }
517
518 // - it is a statement-expression whose value expression is an
519 // enumerator-like expression of type T or
520 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
521 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
522 return findEnumForBlockReturn(last);
523 return nullptr;
524 }
525
526 // - it is a ternary conditional operator (not the GNU ?:
527 // extension) whose second and third operands are
528 // enumerator-like expressions of type T or
529 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
530 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
531 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
532 return ED;
533 return nullptr;
534 }
535
536 // (implicitly:)
537 // - it is an implicit integral conversion applied to an
538 // enumerator-like expression of type T or
539 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
540 // We can sometimes see integral conversions in valid
541 // enumerator-like expressions.
542 if (ICE->getCastKind() == CK_IntegralCast)
543 return findEnumForBlockReturn(ICE->getSubExpr());
544
545 // Otherwise, just rely on the type.
546 }
547
548 // - it is an expression of that formal enum type.
549 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
550 return ET->getDecl();
551 }
552
553 // Otherwise, nope.
554 return nullptr;
555}
556
557/// Attempt to find a type T for which the returned expression of the
558/// given statement is an enumerator-like expression of that type.
559static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
560 if (Expr *retValue = ret->getRetValue())
561 return findEnumForBlockReturn(retValue);
562 return nullptr;
563}
564
565/// Attempt to find a common type T for which all of the returned
566/// expressions in a block are enumerator-like expressions of that
567/// type.
568static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
569 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
570
571 // Try to find one for the first return.
572 EnumDecl *ED = findEnumForBlockReturn(*i);
573 if (!ED) return nullptr;
574
575 // Check that the rest of the returns have the same enum.
576 for (++i; i != e; ++i) {
577 if (findEnumForBlockReturn(*i) != ED)
578 return nullptr;
579 }
580
581 // Never infer an anonymous enum type.
582 if (!ED->hasNameForLinkage()) return nullptr;
583
584 return ED;
585}
586
587/// Adjust the given return statements so that they formally return
588/// the given type. It should require, at most, an IntegralCast.
589static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
590 QualType returnType) {
591 for (ArrayRef<ReturnStmt*>::iterator
592 i = returns.begin(), e = returns.end(); i != e; ++i) {
593 ReturnStmt *ret = *i;
594 Expr *retValue = ret->getRetValue();
595 if (S.Context.hasSameType(retValue->getType(), returnType))
596 continue;
597
598 // Right now we only support integral fixup casts.
599 assert(returnType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (returnType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("returnType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaLambda.cpp", 599, __extension__ __PRETTY_FUNCTION__
))
;
600 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (retValue->getType()->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("retValue->getType()->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaLambda.cpp", 600, __extension__ __PRETTY_FUNCTION__
))
;
601
602 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
603
604 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
605 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
606 /*base path*/ nullptr, VK_PRValue,
607 FPOptionsOverride());
608 if (cleanups) {
609 cleanups->setSubExpr(E);
610 } else {
611 ret->setRetValue(E);
612 }
613 }
614}
615
616void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
617 assert(CSI.HasImplicitReturnType)(static_cast <bool> (CSI.HasImplicitReturnType) ? void (
0) : __assert_fail ("CSI.HasImplicitReturnType", "clang/lib/Sema/SemaLambda.cpp"
, 617, __extension__ __PRETTY_FUNCTION__))
;
618 // If it was ever a placeholder, it had to been deduced to DependentTy.
619 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType())(static_cast <bool> (CSI.ReturnType.isNull() || !CSI.ReturnType
->isUndeducedType()) ? void (0) : __assert_fail ("CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()"
, "clang/lib/Sema/SemaLambda.cpp", 619, __extension__ __PRETTY_FUNCTION__
))
;
620 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!isa<LambdaScopeInfo>(CSI) ||
!getLangOpts().CPlusPlus14) && "lambda expressions use auto deduction in C++14 onwards"
) ? void (0) : __assert_fail ("(!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && \"lambda expressions use auto deduction in C++14 onwards\""
, "clang/lib/Sema/SemaLambda.cpp", 621, __extension__ __PRETTY_FUNCTION__
))
621 "lambda expressions use auto deduction in C++14 onwards")(static_cast <bool> ((!isa<LambdaScopeInfo>(CSI) ||
!getLangOpts().CPlusPlus14) && "lambda expressions use auto deduction in C++14 onwards"
) ? void (0) : __assert_fail ("(!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && \"lambda expressions use auto deduction in C++14 onwards\""
, "clang/lib/Sema/SemaLambda.cpp", 621, __extension__ __PRETTY_FUNCTION__
))
;
622
623 // C++ core issue 975:
624 // If a lambda-expression does not include a trailing-return-type,
625 // it is as if the trailing-return-type denotes the following type:
626 // - if there are no return statements in the compound-statement,
627 // or all return statements return either an expression of type
628 // void or no expression or braced-init-list, the type void;
629 // - otherwise, if all return statements return an expression
630 // and the types of the returned expressions after
631 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
632 // array-to-pointer conversion (4.2 [conv.array]), and
633 // function-to-pointer conversion (4.3 [conv.func]) are the
634 // same, that common type;
635 // - otherwise, the program is ill-formed.
636 //
637 // C++ core issue 1048 additionally removes top-level cv-qualifiers
638 // from the types of returned expressions to match the C++14 auto
639 // deduction rules.
640 //
641 // In addition, in blocks in non-C++ modes, if all of the return
642 // statements are enumerator-like expressions of some type T, where
643 // T has a name for linkage, then we infer the return type of the
644 // block to be that type.
645
646 // First case: no return statements, implicit void return type.
647 ASTContext &Ctx = getASTContext();
648 if (CSI.Returns.empty()) {
649 // It's possible there were simply no /valid/ return statements.
650 // In this case, the first one we found may have at least given us a type.
651 if (CSI.ReturnType.isNull())
652 CSI.ReturnType = Ctx.VoidTy;
653 return;
654 }
655
656 // Second case: at least one return statement has dependent type.
657 // Delay type checking until instantiation.
658 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.")(static_cast <bool> (!CSI.ReturnType.isNull() &&
"We should have a tentative return type.") ? void (0) : __assert_fail
("!CSI.ReturnType.isNull() && \"We should have a tentative return type.\""
, "clang/lib/Sema/SemaLambda.cpp", 658, __extension__ __PRETTY_FUNCTION__
))
;
659 if (CSI.ReturnType->isDependentType())
660 return;
661
662 // Try to apply the enum-fuzz rule.
663 if (!getLangOpts().CPlusPlus) {
664 assert(isa<BlockScopeInfo>(CSI))(static_cast <bool> (isa<BlockScopeInfo>(CSI)) ? void
(0) : __assert_fail ("isa<BlockScopeInfo>(CSI)", "clang/lib/Sema/SemaLambda.cpp"
, 664, __extension__ __PRETTY_FUNCTION__))
;
665 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
666 if (ED) {
667 CSI.ReturnType = Context.getTypeDeclType(ED);
668 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
669 return;
670 }
671 }
672
673 // Third case: only one return statement. Don't bother doing extra work!
674 if (CSI.Returns.size() == 1)
675 return;
676
677 // General case: many return statements.
678 // Check that they all have compatible return types.
679
680 // We require the return types to strictly match here.
681 // Note that we've already done the required promotions as part of
682 // processing the return statement.
683 for (const ReturnStmt *RS : CSI.Returns) {
684 const Expr *RetE = RS->getRetValue();
685
686 QualType ReturnType =
687 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
688 if (Context.getCanonicalFunctionResultType(ReturnType) ==
689 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
690 // Use the return type with the strictest possible nullability annotation.
691 auto RetTyNullability = ReturnType->getNullability();
692 auto BlockNullability = CSI.ReturnType->getNullability();
693 if (BlockNullability &&
694 (!RetTyNullability ||
695 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
696 CSI.ReturnType = ReturnType;
697 continue;
698 }
699
700 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
701 // TODO: It's possible that the *first* return is the divergent one.
702 Diag(RS->getBeginLoc(),
703 diag::err_typecheck_missing_return_type_incompatible)
704 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
705 // Continue iterating so that we keep emitting diagnostics.
706 }
707}
708
709QualType Sema::buildLambdaInitCaptureInitialization(
710 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
711 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
712 bool IsDirectInit, Expr *&Init) {
713 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
714 // deduce against.
715 QualType DeductType = Context.getAutoDeductType();
716 TypeLocBuilder TLB;
717 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
718 TL.setNameLoc(Loc);
719 if (ByRef) {
720 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
721 assert(!DeductType.isNull() && "can't build reference to auto")(static_cast <bool> (!DeductType.isNull() && "can't build reference to auto"
) ? void (0) : __assert_fail ("!DeductType.isNull() && \"can't build reference to auto\""
, "clang/lib/Sema/SemaLambda.cpp", 721, __extension__ __PRETTY_FUNCTION__
))
;
722 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
723 }
724 if (EllipsisLoc.isValid()) {
725 if (Init->containsUnexpandedParameterPack()) {
726 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
727 ? diag::warn_cxx17_compat_init_capture_pack
728 : diag::ext_init_capture_pack);
729 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
730 /*ExpectPackInType=*/false);
731 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
732 } else {
733 // Just ignore the ellipsis for now and form a non-pack variable. We'll
734 // diagnose this later when we try to capture it.
735 }
736 }
737 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
738
739 // Deduce the type of the init capture.
740 QualType DeducedType = deduceVarTypeFromInitializer(
741 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
742 SourceRange(Loc, Loc), IsDirectInit, Init);
743 if (DeducedType.isNull())
744 return QualType();
745
746 // Are we a non-list direct initialization?
747 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
748
749 // Perform initialization analysis and ensure any implicit conversions
750 // (such as lvalue-to-rvalue) are enforced.
751 InitializedEntity Entity =
752 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
753 InitializationKind Kind =
754 IsDirectInit
755 ? (CXXDirectInit ? InitializationKind::CreateDirect(
756 Loc, Init->getBeginLoc(), Init->getEndLoc())
757 : InitializationKind::CreateDirectList(Loc))
758 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
759
760 MultiExprArg Args = Init;
761 if (CXXDirectInit)
762 Args =
763 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
764 QualType DclT;
765 InitializationSequence InitSeq(*this, Entity, Kind, Args);
766 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
767
768 if (Result.isInvalid())
769 return QualType();
770
771 Init = Result.getAs<Expr>();
772 return DeducedType;
773}
774
775VarDecl *Sema::createLambdaInitCaptureVarDecl(
776 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
777 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
778 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
779 // rather than reconstructing it here.
780 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
781 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
782 PETL.setEllipsisLoc(EllipsisLoc);
783
784 // Create a dummy variable representing the init-capture. This is not actually
785 // used as a variable, and only exists as a way to name and refer to the
786 // init-capture.
787 // FIXME: Pass in separate source locations for '&' and identifier.
788 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
789 InitCaptureType, TSI, SC_Auto);
790 NewVD->setInitCapture(true);
791 NewVD->setReferenced(true);
792 // FIXME: Pass in a VarDecl::InitializationStyle.
793 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
794 NewVD->markUsed(Context);
795 NewVD->setInit(Init);
796 if (NewVD->isParameterPack())
797 getCurLambda()->LocalPacks.push_back(NewVD);
798 return NewVD;
799}
800
801void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var,
802 bool isReferenceType) {
803 assert(Var->isInitCapture() && "init capture flag should be set")(static_cast <bool> (Var->isInitCapture() &&
"init capture flag should be set") ? void (0) : __assert_fail
("Var->isInitCapture() && \"init capture flag should be set\""
, "clang/lib/Sema/SemaLambda.cpp", 803, __extension__ __PRETTY_FUNCTION__
))
;
804 LSI->addCapture(Var, /*isBlock*/ false, isReferenceType,
805 /*isNested*/ false, Var->getLocation(), SourceLocation(),
806 Var->getType(), /*Invalid*/ false);
807}
808
809// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
810// check that the current lambda is in a consistent or fully constructed state.
811static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) {
812 assert(!S.FunctionScopes.empty())(static_cast <bool> (!S.FunctionScopes.empty()) ? void (
0) : __assert_fail ("!S.FunctionScopes.empty()", "clang/lib/Sema/SemaLambda.cpp"
, 812, __extension__ __PRETTY_FUNCTION__))
;
813 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
814}
815
816static TypeSourceInfo *
817getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) {
818 // C++11 [expr.prim.lambda]p4:
819 // If a lambda-expression does not include a lambda-declarator, it is as
820 // if the lambda-declarator were ().
821 FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention(
822 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
823 EPI.HasTrailingReturn = true;
824 EPI.TypeQuals.addConst();
825 LangAS AS = S.getDefaultCXXMethodAddrSpace();
826 if (AS != LangAS::Default)
827 EPI.TypeQuals.addAddressSpace(AS);
828
829 // C++1y [expr.prim.lambda]:
830 // The lambda return type is 'auto', which is replaced by the
831 // trailing-return type if provided and/or deduced from 'return'
832 // statements
833 // We don't do this before C++1y, because we don't support deduced return
834 // types there.
835 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
836 ? S.Context.getAutoDeductType()
837 : S.Context.DependentTy;
838 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
839 std::nullopt, EPI);
840 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
841}
842
843static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro,
844 Declarator &ParamInfo, Scope *CurScope,
845 SourceLocation Loc,
846 bool &ExplicitResultType) {
847
848 ExplicitResultType = false;
849
850 assert((static_cast <bool> ((ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_static) && "Unexpected storage specifier"
) ? void (0) : __assert_fail ("(ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && \"Unexpected storage specifier\""
, "clang/lib/Sema/SemaLambda.cpp", 854, __extension__ __PRETTY_FUNCTION__
))
851 (ParamInfo.getDeclSpec().getStorageClassSpec() ==(static_cast <bool> ((ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_static) && "Unexpected storage specifier"
) ? void (0) : __assert_fail ("(ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && \"Unexpected storage specifier\""
, "clang/lib/Sema/SemaLambda.cpp", 854, __extension__ __PRETTY_FUNCTION__
))
852 DeclSpec::SCS_unspecified ||(static_cast <bool> ((ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_static) && "Unexpected storage specifier"
) ? void (0) : __assert_fail ("(ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && \"Unexpected storage specifier\""
, "clang/lib/Sema/SemaLambda.cpp", 854, __extension__ __PRETTY_FUNCTION__
))
853 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) &&(static_cast <bool> ((ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_static) && "Unexpected storage specifier"
) ? void (0) : __assert_fail ("(ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && \"Unexpected storage specifier\""
, "clang/lib/Sema/SemaLambda.cpp", 854, __extension__ __PRETTY_FUNCTION__
))
854 "Unexpected storage specifier")(static_cast <bool> ((ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec
() == DeclSpec::SCS_static) && "Unexpected storage specifier"
) ? void (0) : __assert_fail ("(ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_unspecified || ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && \"Unexpected storage specifier\""
, "clang/lib/Sema/SemaLambda.cpp", 854, __extension__ __PRETTY_FUNCTION__
))
;
855 bool IsLambdaStatic =
856 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
857
858 TypeSourceInfo *MethodTyInfo;
859
860 if (ParamInfo.getNumTypeObjects() == 0) {
861 MethodTyInfo = getDummyLambdaType(S, Loc);
862 } else {
863 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
864 ExplicitResultType = FTI.hasTrailingReturnType();
865 if (!FTI.hasMutableQualifier() && !IsLambdaStatic)
866 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, Loc);
867
868 if (ExplicitResultType && S.getLangOpts().HLSL) {
869 QualType RetTy = FTI.getTrailingReturnType().get();
870 if (!RetTy.isNull()) {
871 // HLSL does not support specifying an address space on a lambda return
872 // type.
873 LangAS AddressSpace = RetTy.getAddressSpace();
874 if (AddressSpace != LangAS::Default)
875 S.Diag(FTI.getTrailingReturnTypeLoc(),
876 diag::err_return_value_with_address_space);
877 }
878 }
879
880 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo, CurScope);
881 assert(MethodTyInfo && "no type from lambda-declarator")(static_cast <bool> (MethodTyInfo && "no type from lambda-declarator"
) ? void (0) : __assert_fail ("MethodTyInfo && \"no type from lambda-declarator\""
, "clang/lib/Sema/SemaLambda.cpp", 881, __extension__ __PRETTY_FUNCTION__
))
;
882
883 // Check for unexpanded parameter packs in the method type.
884 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
885 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
886 S.UPPC_DeclarationType);
887 }
888 return MethodTyInfo;
889}
890
891CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange,
892 CXXRecordDecl *Class) {
893
894 // C++20 [expr.prim.lambda.closure]p3:
895 // The closure type for a lambda-expression has a public inline function
896 // call operator (for a non-generic lambda) or function call operator
897 // template (for a generic lambda) whose parameters and return type are
898 // described by the lambda-expression's parameter-declaration-clause
899 // and trailing-return-type respectively.
900 DeclarationName MethodName =
901 Context.DeclarationNames.getCXXOperatorName(OO_Call);
902 DeclarationNameLoc MethodNameLoc =
903 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange.getBegin());
904 CXXMethodDecl *Method = CXXMethodDecl::Create(
905 Context, Class, SourceLocation(),
906 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
907 MethodNameLoc),
908 QualType(), /*Tinfo=*/nullptr, SC_None,
909 getCurFPFeatures().isFPConstrained(),
910 /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),
911 /*TrailingRequiresClause=*/nullptr);
912 Method->setAccess(AS_public);
913 return Method;
914}
915
916void Sema::CompleteLambdaCallOperator(
917 CXXMethodDecl *Method, SourceLocation LambdaLoc,
918 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
919 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
920 StorageClass SC, ArrayRef<ParmVarDecl *> Params,
921 bool HasExplicitResultType) {
922
923 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
924
925 if (TrailingRequiresClause)
926 Method->setTrailingRequiresClause(TrailingRequiresClause);
927
928 TemplateParameterList *TemplateParams =
929 getGenericLambdaTemplateParameterList(LSI, *this);
930
931 DeclContext *DC = Method->getLexicalDeclContext();
932 Method->setLexicalDeclContext(LSI->Lambda);
933 if (TemplateParams) {
934 FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create(
935 Context, LSI->Lambda, Method->getLocation(), Method->getDeclName(),
936 TemplateParams, Method);
937 TemplateMethod->setAccess(AS_public);
938 Method->setDescribedFunctionTemplate(TemplateMethod);
939 LSI->Lambda->addDecl(TemplateMethod);
940 TemplateMethod->setLexicalDeclContext(DC);
941 } else {
942 LSI->Lambda->addDecl(Method);
943 }
944 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
945 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
946
947 Method->setLexicalDeclContext(DC);
948 Method->setLocation(LambdaLoc);
949 Method->setInnerLocStart(CallOperatorLoc);
950 Method->setTypeSourceInfo(MethodTyInfo);
951 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
952 TemplateParams, MethodTyInfo));
953 Method->setConstexprKind(ConstexprKind);
954 Method->setStorageClass(SC);
955 if (!Params.empty()) {
956 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
957 Method->setParams(Params);
958 for (auto P : Method->parameters()) {
959 assert(P && "null in a parameter list")(static_cast <bool> (P && "null in a parameter list"
) ? void (0) : __assert_fail ("P && \"null in a parameter list\""
, "clang/lib/Sema/SemaLambda.cpp", 959, __extension__ __PRETTY_FUNCTION__
))
;
960 P->setOwningFunction(Method);
961 }
962 }
963
964 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
965}
966
967void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
968 Scope *CurrentScope) {
969
970 LambdaScopeInfo *LSI = getCurLambda();
971 assert(LSI && "LambdaScopeInfo should be on stack!")(static_cast <bool> (LSI && "LambdaScopeInfo should be on stack!"
) ? void (0) : __assert_fail ("LSI && \"LambdaScopeInfo should be on stack!\""
, "clang/lib/Sema/SemaLambda.cpp", 971, __extension__ __PRETTY_FUNCTION__
))
;
972
973 if (Intro.Default == LCD_ByCopy)
974 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
975 else if (Intro.Default == LCD_ByRef)
976 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
977 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
978 LSI->IntroducerRange = Intro.Range;
979 LSI->AfterParameterList = false;
980
981 assert(LSI->NumExplicitTemplateParams == 0)(static_cast <bool> (LSI->NumExplicitTemplateParams ==
0) ? void (0) : __assert_fail ("LSI->NumExplicitTemplateParams == 0"
, "clang/lib/Sema/SemaLambda.cpp", 981, __extension__ __PRETTY_FUNCTION__
))
;
982
983 // Determine if we're within a context where we know that the lambda will
984 // be dependent, because there are template parameters in scope.
985 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
986 CXXRecordDecl::LDK_Unknown;
987 if (LSI->NumExplicitTemplateParams > 0) {
988 Scope *TemplateParamScope = CurScope->getTemplateParamParent();
989 assert(TemplateParamScope &&(static_cast <bool> (TemplateParamScope && "Lambda with explicit template param list should establish a "
"template param scope") ? void (0) : __assert_fail ("TemplateParamScope && \"Lambda with explicit template param list should establish a \" \"template param scope\""
, "clang/lib/Sema/SemaLambda.cpp", 991, __extension__ __PRETTY_FUNCTION__
))
990 "Lambda with explicit template param list should establish a "(static_cast <bool> (TemplateParamScope && "Lambda with explicit template param list should establish a "
"template param scope") ? void (0) : __assert_fail ("TemplateParamScope && \"Lambda with explicit template param list should establish a \" \"template param scope\""
, "clang/lib/Sema/SemaLambda.cpp", 991, __extension__ __PRETTY_FUNCTION__
))
991 "template param scope")(static_cast <bool> (TemplateParamScope && "Lambda with explicit template param list should establish a "
"template param scope") ? void (0) : __assert_fail ("TemplateParamScope && \"Lambda with explicit template param list should establish a \" \"template param scope\""
, "clang/lib/Sema/SemaLambda.cpp", 991, __extension__ __PRETTY_FUNCTION__
))
;
992 assert(TemplateParamScope->getParent())(static_cast <bool> (TemplateParamScope->getParent()
) ? void (0) : __assert_fail ("TemplateParamScope->getParent()"
, "clang/lib/Sema/SemaLambda.cpp", 992, __extension__ __PRETTY_FUNCTION__
))
;
993 if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
994 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
995 } else if (CurScope->getTemplateParamParent() != nullptr) {
996 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
997 }
998
999 CXXRecordDecl *Class = createLambdaClosureType(
1000 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1001 LSI->Lambda = Class;
1002
1003 CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class);
1004 LSI->CallOperator = Method;
1005 Method->setLexicalDeclContext(CurContext);
1006
1007 PushDeclContext(CurScope, Method);
1008
1009 bool ContainsUnexpandedParameterPack = false;
1010
1011 // Distinct capture names, for diagnostics.
1012 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1013
1014 // Handle explicit captures.
1015 SourceLocation PrevCaptureLoc =
1016 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1017 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1018 PrevCaptureLoc = C->Loc, ++C) {
1019 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1020 if (C->Kind == LCK_StarThis)
1021 Diag(C->Loc, !getLangOpts().CPlusPlus17
1022 ? diag::ext_star_this_lambda_capture_cxx17
1023 : diag::warn_cxx14_compat_star_this_lambda_capture);
1024
1025 // C++11 [expr.prim.lambda]p8:
1026 // An identifier or this shall not appear more than once in a
1027 // lambda-capture.
1028 if (LSI->isCXXThisCaptured()) {
1029 Diag(C->Loc, diag::err_capture_more_than_once)
1030 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1031 << FixItHint::CreateRemoval(
1032 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1033 continue;
1034 }
1035
1036 // C++20 [expr.prim.lambda]p8:
1037 // If a lambda-capture includes a capture-default that is =,
1038 // each simple-capture of that lambda-capture shall be of the form
1039 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1040 // redundant but accepted for compatibility with ISO C++14. --end note ]
1041 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1042 Diag(C->Loc, !getLangOpts().CPlusPlus20
1043 ? diag::ext_equals_this_lambda_capture_cxx20
1044 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1045
1046 // C++11 [expr.prim.lambda]p12:
1047 // If this is captured by a local lambda expression, its nearest
1048 // enclosing function shall be a non-static member function.
1049 QualType ThisCaptureType = getCurrentThisType();
1050 if (ThisCaptureType.isNull()) {
1051 Diag(C->Loc, diag::err_this_capture) << true;
1052 continue;
1053 }
1054
1055 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1056 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1057 C->Kind == LCK_StarThis);
1058 if (!LSI->Captures.empty())
1059 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1060 continue;
1061 }
1062
1063 assert(C->Id && "missing identifier for capture")(static_cast <bool> (C->Id && "missing identifier for capture"
) ? void (0) : __assert_fail ("C->Id && \"missing identifier for capture\""
, "clang/lib/Sema/SemaLambda.cpp", 1063, __extension__ __PRETTY_FUNCTION__
))
;
1064
1065 if (C->Init.isInvalid())
1066 continue;
1067
1068 ValueDecl *Var = nullptr;
1069 if (C->Init.isUsable()) {
1070 Diag(C->Loc, getLangOpts().CPlusPlus14
1071 ? diag::warn_cxx11_compat_init_capture
1072 : diag::ext_init_capture);
1073
1074 // If the initializer expression is usable, but the InitCaptureType
1075 // is not, then an error has occurred - so ignore the capture for now.
1076 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1077 // FIXME: we should create the init capture variable and mark it invalid
1078 // in this case.
1079 if (C->InitCaptureType.get().isNull())
1080 continue;
1081
1082 if (C->Init.get()->containsUnexpandedParameterPack() &&
1083 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1084 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1085
1086 unsigned InitStyle;
1087 switch (C->InitKind) {
1088 case LambdaCaptureInitKind::NoInit:
1089 llvm_unreachable("not an init-capture?")::llvm::llvm_unreachable_internal("not an init-capture?", "clang/lib/Sema/SemaLambda.cpp"
, 1089)
;
1090 case LambdaCaptureInitKind::CopyInit:
1091 InitStyle = VarDecl::CInit;
1092 break;
1093 case LambdaCaptureInitKind::DirectInit:
1094 InitStyle = VarDecl::CallInit;
1095 break;
1096 case LambdaCaptureInitKind::ListInit:
1097 InitStyle = VarDecl::ListInit;
1098 break;
1099 }
1100 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1101 C->EllipsisLoc, C->Id, InitStyle,
1102 C->Init.get(), Method);
1103 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?")(static_cast <bool> (Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?"
) ? void (0) : __assert_fail ("Var && \"createLambdaInitCaptureVarDecl returned a null VarDecl?\""
, "clang/lib/Sema/SemaLambda.cpp", 1103, __extension__ __PRETTY_FUNCTION__
))
;
1104 if (auto *V = dyn_cast<VarDecl>(Var))
1105 CheckShadow(CurrentScope, V);
1106 PushOnScopeChains(Var, CurrentScope, false);
1107 } else {
1108 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&(static_cast <bool> (C->InitKind == LambdaCaptureInitKind
::NoInit && "init capture has valid but null init?") ?
void (0) : __assert_fail ("C->InitKind == LambdaCaptureInitKind::NoInit && \"init capture has valid but null init?\""
, "clang/lib/Sema/SemaLambda.cpp", 1109, __extension__ __PRETTY_FUNCTION__
))
1109 "init capture has valid but null init?")(static_cast <bool> (C->InitKind == LambdaCaptureInitKind
::NoInit && "init capture has valid but null init?") ?
void (0) : __assert_fail ("C->InitKind == LambdaCaptureInitKind::NoInit && \"init capture has valid but null init?\""
, "clang/lib/Sema/SemaLambda.cpp", 1109, __extension__ __PRETTY_FUNCTION__
))
;
1110
1111 // C++11 [expr.prim.lambda]p8:
1112 // If a lambda-capture includes a capture-default that is &, the
1113 // identifiers in the lambda-capture shall not be preceded by &.
1114 // If a lambda-capture includes a capture-default that is =, [...]
1115 // each identifier it contains shall be preceded by &.
1116 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1117 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1118 << FixItHint::CreateRemoval(
1119 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1120 continue;
1121 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1122 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1123 << FixItHint::CreateRemoval(
1124 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1125 continue;
1126 }
1127
1128 // C++11 [expr.prim.lambda]p10:
1129 // The identifiers in a capture-list are looked up using the usual
1130 // rules for unqualified name lookup (3.4.1)
1131 DeclarationNameInfo Name(C->Id, C->Loc);
1132 LookupResult R(*this, Name, LookupOrdinaryName);
1133 LookupName(R, CurScope);
1134 if (R.isAmbiguous())
1135 continue;
1136 if (R.empty()) {
1137 // FIXME: Disable corrections that would add qualification?
1138 CXXScopeSpec ScopeSpec;
1139 DeclFilterCCC<VarDecl> Validator{};
1140 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1141 continue;
1142 }
1143
1144 if (auto *BD = R.getAsSingle<BindingDecl>())
1145 Var = BD;
1146 else
1147 Var = R.getAsSingle<VarDecl>();
1148 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1149 continue;
1150 }
1151
1152 // C++11 [expr.prim.lambda]p10:
1153 // [...] each such lookup shall find a variable with automatic storage
1154 // duration declared in the reaching scope of the local lambda expression.
1155 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1156 if (!Var) {
1157 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1158 continue;
1159 }
1160
1161 // C++11 [expr.prim.lambda]p8:
1162 // An identifier or this shall not appear more than once in a
1163 // lambda-capture.
1164 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1165 !Inserted) {
1166 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1167 !Var->isInitCapture()) {
1168 Diag(C->Loc, diag::err_capture_more_than_once)
1169 << C->Id << It->second->getBeginLoc()
1170 << FixItHint::CreateRemoval(
1171 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1172 } else
1173 // Previous capture captured something different (one or both was
1174 // an init-capture): no fixit.
1175 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1176 continue;
1177 }
1178
1179 // Ignore invalid decls; they'll just confuse the code later.
1180 if (Var->isInvalidDecl())
1181 continue;
1182
1183 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1184
1185 if (!Underlying->hasLocalStorage()) {
1186 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1187 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1188 continue;
1189 }
1190
1191 // C++11 [expr.prim.lambda]p23:
1192 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1193 SourceLocation EllipsisLoc;
1194 if (C->EllipsisLoc.isValid()) {
1195 if (Var->isParameterPack()) {
1196 EllipsisLoc = C->EllipsisLoc;
1197 } else {
1198 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1199 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1200 : SourceRange(C->Loc));
1201
1202 // Just ignore the ellipsis.
1203 }
1204 } else if (Var->isParameterPack()) {
1205 ContainsUnexpandedParameterPack = true;
1206 }
1207
1208 if (C->Init.isUsable()) {
1209 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1210 PushOnScopeChains(Var, CurScope, false);
1211 } else {
1212 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef
1213 : TryCapture_ExplicitByVal;
1214 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1215 }
1216 if (!LSI->Captures.empty())
1217 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1218 }
1219 finishLambdaExplicitCaptures(LSI);
1220 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1221 PopDeclContext();
1222}
1223
1224void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
1225 SourceLocation MutableLoc) {
1226
1227 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
1228 LSI->Mutable = MutableLoc.isValid();
1229 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1230
1231 // C++11 [expr.prim.lambda]p9:
1232 // A lambda-expression whose smallest enclosing scope is a block scope is a
1233 // local lambda expression; any other lambda expression shall not have a
1234 // capture-default or simple-capture in its lambda-introducer.
1235 //
1236 // For simple-captures, this is covered by the check below that any named
1237 // entity is a variable that can be captured.
1238 //
1239 // For DR1632, we also allow a capture-default in any context where we can
1240 // odr-use 'this' (in particular, in a default initializer for a non-static
1241 // data member).
1242 if (Intro.Default != LCD_None &&
1243 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1244 (getCurrentThisType().isNull() ||
1245 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1246 /*BuildAndDiagnose=*/false)))
1247 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1248}
1249
1250void Sema::ActOnLambdaClosureParameters(
1251 Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) {
1252 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
1253 PushDeclContext(LambdaScope, LSI->CallOperator);
1254
1255 for (const DeclaratorChunk::ParamInfo &P : Params) {
1256 auto *Param = cast<ParmVarDecl>(P.Param);
1257 Param->setOwningFunction(LSI->CallOperator);
1258 if (Param->getIdentifier())
1259 PushOnScopeChains(Param, LambdaScope, false);
1260 }
1261
1262 LSI->AfterParameterList = true;
1263}
1264
1265void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
1266 Declarator &ParamInfo,
1267 const DeclSpec &DS) {
1268
1269 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
1270 LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier());
1271
1272 SmallVector<ParmVarDecl *, 8> Params;
1273 bool ExplicitResultType;
1274
1275 SourceLocation TypeLoc, CallOperatorLoc;
1276 if (ParamInfo.getNumTypeObjects() == 0) {
1
Assuming the condition is false
2
Taking false branch
1277 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1278 } else {
1279 unsigned Index;
3
'Index' declared without an initial value
1280 ParamInfo.isFunctionDeclarator(Index);
4
Calling 'Declarator::isFunctionDeclarator'
8
Returning from 'Declarator::isFunctionDeclarator'
1281 const auto &Object = ParamInfo.getTypeObject(Index);
9
1st function call argument is an uninitialized value
1282 TypeLoc =
1283 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1284 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1285 }
1286
1287 CXXRecordDecl *Class = LSI->Lambda;
1288 CXXMethodDecl *Method = LSI->CallOperator;
1289
1290 TypeSourceInfo *MethodTyInfo = getLambdaType(
1291 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1292
1293 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1294
1295 if (ParamInfo.isFunctionDeclarator() != 0 &&
1296 !FTIHasSingleVoidParameter(ParamInfo.getFunctionTypeInfo())) {
1297 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1298 Params.reserve(Params.size());
1299 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1300 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1301 Param->setScopeInfo(0, Params.size());
1302 Params.push_back(Param);
1303 }
1304 }
1305
1306 bool IsLambdaStatic =
1307 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
1308
1309 CompleteLambdaCallOperator(
1310 Method, Intro.Range.getBegin(), CallOperatorLoc,
1311 ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1312 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1313 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1314
1315 CheckCXXDefaultArguments(Method);
1316
1317 // This represents the function body for the lambda function, check if we
1318 // have to apply optnone due to a pragma.
1319 AddRangeBasedOptnone(Method);
1320
1321 // code_seg attribute on lambda apply to the method.
1322 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(
1323 Method, /*IsDefinition=*/true))
1324 Method->addAttr(A);
1325
1326 // Attributes on the lambda apply to the method.
1327 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1328
1329 // CUDA lambdas get implicit host and device attributes.
1330 if (getLangOpts().CUDA)
1331 CUDASetLambdaAttrs(Method);
1332
1333 // OpenMP lambdas might get assumumption attributes.
1334 if (LangOpts.OpenMP)
1335 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1336
1337 handleLambdaNumbering(Class, Method);
1338
1339 for (auto &&C : LSI->Captures) {
1340 if (!C.isVariableCapture())
1341 continue;
1342 ValueDecl *Var = C.getVariable();
1343 if (Var && Var->isInitCapture()) {
1344 PushOnScopeChains(Var, CurScope, false);
1345 }
1346 }
1347
1348 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1349 for (const auto &Capture : Intro.Captures) {
1350 if (Capture.Id == Param->getIdentifier()) {
1351 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1352 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1353 << Capture.Id << true;
1354 return false;
1355 }
1356 }
1357 return true;
1358 };
1359
1360 for (ParmVarDecl *P : Params) {
1361 if (!P->getIdentifier())
1362 continue;
1363 if (CheckRedefinition(P))
1364 CheckShadow(CurScope, P);
1365 PushOnScopeChains(P, CurScope);
1366 }
1367
1368 // C++23 [expr.prim.lambda.capture]p5:
1369 // If an identifier in a capture appears as the declarator-id of a parameter
1370 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1371 // template parameter of the lambda-expression's template-parameter-list, the
1372 // program is ill-formed.
1373 TemplateParameterList *TemplateParams =
1374 getGenericLambdaTemplateParameterList(LSI, *this);
1375 if (TemplateParams) {
1376 for (const auto *TP : TemplateParams->asArray()) {
1377 if (!TP->getIdentifier())
1378 continue;
1379 for (const auto &Capture : Intro.Captures) {
1380 if (Capture.Id == TP->getIdentifier()) {
1381 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1382 Diag(TP->getLocation(), diag::note_template_param_here);
1383 }
1384 }
1385 }
1386 }
1387
1388 // C++20: dcl.decl.general p4:
1389 // The optional requires-clause ([temp.pre]) in an init-declarator or
1390 // member-declarator shall be present only if the declarator declares a
1391 // templated function ([dcl.fct]).
1392 if (Expr *TRC = Method->getTrailingRequiresClause()) {
1393 // [temp.pre]/8:
1394 // An entity is templated if it is
1395 // - a template,
1396 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1397 // templated entity,
1398 // - a member of a templated entity,
1399 // - an enumerator for an enumeration that is a templated entity, or
1400 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1401 // appearing in the declaration of a templated entity. [Note 6: A local
1402 // class, a local or block variable, or a friend function defined in a
1403 // templated entity is a templated entity. — end note]
1404 //
1405 // A templated function is a function template or a function that is
1406 // templated. A templated class is a class template or a class that is
1407 // templated. A templated variable is a variable template or a variable
1408 // that is templated.
1409
1410 // Note: we only have to check if this is defined in a template entity, OR
1411 // if we are a template, since the rest don't apply. The requires clause
1412 // applies to the call operator, which we already know is a member function,
1413 // AND defined.
1414 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1415 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1416 }
1417 }
1418
1419 // Enter a new evaluation context to insulate the lambda from any
1420 // cleanups from the enclosing full-expression.
1421 PushExpressionEvaluationContext(
1422 LSI->CallOperator->isConsteval()
1423 ? ExpressionEvaluationContext::ImmediateFunctionContext
1424 : ExpressionEvaluationContext::PotentiallyEvaluated);
1425}
1426
1427void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1428 bool IsInstantiation) {
1429 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1430
1431 // Leave the expression-evaluation context.
1432 DiscardCleanupsInEvaluationContext();
1433 PopExpressionEvaluationContext();
1434
1435 // Leave the context of the lambda.
1436 if (!IsInstantiation)
1437 PopDeclContext();
1438
1439 // Finalize the lambda.
1440 CXXRecordDecl *Class = LSI->Lambda;
1441 Class->setInvalidDecl();
1442 SmallVector<Decl*, 4> Fields(Class->fields());
1443 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1444 SourceLocation(), ParsedAttributesView());
1445 CheckCompletedCXXClass(nullptr, Class);
1446
1447 PopFunctionScopeInfo();
1448}
1449
1450template <typename Func>
1451static void repeatForLambdaConversionFunctionCallingConvs(
1452 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1453 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1454 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1455 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1456 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1457 CallingConv CallOpCC = CallOpProto.getCallConv();
1458
1459 /// Implement emitting a version of the operator for many of the calling
1460 /// conventions for MSVC, as described here:
1461 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1462 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1463 /// vectorcall are generated by MSVC when it is supported by the target.
1464 /// Additionally, we are ensuring that the default-free/default-member and
1465 /// call-operator calling convention are generated as well.
1466 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1467 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1468 /// that someone who intentionally places 'thiscall' on the lambda call
1469 /// operator will still get that overload, since we don't have the a way of
1470 /// detecting the attribute by the time we get here.
1471 if (S.getLangOpts().MSVCCompat) {
1472 CallingConv Convs[] = {
1473 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1474 DefaultFree, DefaultMember, CallOpCC};
1475 llvm::sort(Convs);
1476 llvm::iterator_range<CallingConv *> Range(
1477 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1478 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1479
1480 for (CallingConv C : Range) {
1481 if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
1482 F(C);
1483 }
1484 return;
1485 }
1486
1487 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1488 F(DefaultFree);
1489 F(DefaultMember);
1490 } else {
1491 F(CallOpCC);
1492 }
1493}
1494
1495// Returns the 'standard' calling convention to be used for the lambda
1496// conversion function, that is, the 'free' function calling convention unless
1497// it is overridden by a non-default calling convention attribute.
1498static CallingConv
1499getLambdaConversionFunctionCallConv(Sema &S,
1500 const FunctionProtoType *CallOpProto) {
1501 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1502 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1503 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1504 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1505 CallingConv CallOpCC = CallOpProto->getCallConv();
1506
1507 // If the call-operator hasn't been changed, return both the 'free' and
1508 // 'member' function calling convention.
1509 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1510 return DefaultFree;
1511 return CallOpCC;
1512}
1513
1514QualType Sema::getLambdaConversionFunctionResultType(
1515 const FunctionProtoType *CallOpProto, CallingConv CC) {
1516 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1517 CallOpProto->getExtProtoInfo();
1518 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1519 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1520 InvokerExtInfo.TypeQuals = Qualifiers();
1521 assert(InvokerExtInfo.RefQualifier == RQ_None &&(static_cast <bool> (InvokerExtInfo.RefQualifier == RQ_None
&& "Lambda's call operator should not have a reference qualifier"
) ? void (0) : __assert_fail ("InvokerExtInfo.RefQualifier == RQ_None && \"Lambda's call operator should not have a reference qualifier\""
, "clang/lib/Sema/SemaLambda.cpp", 1522, __extension__ __PRETTY_FUNCTION__
))
1522 "Lambda's call operator should not have a reference qualifier")(static_cast <bool> (InvokerExtInfo.RefQualifier == RQ_None
&& "Lambda's call operator should not have a reference qualifier"
) ? void (0) : __assert_fail ("InvokerExtInfo.RefQualifier == RQ_None && \"Lambda's call operator should not have a reference qualifier\""
, "clang/lib/Sema/SemaLambda.cpp", 1522, __extension__ __PRETTY_FUNCTION__
))
;
1523 return Context.getFunctionType(CallOpProto->getReturnType(),
1524 CallOpProto->getParamTypes(), InvokerExtInfo);
1525}
1526
1527/// Add a lambda's conversion to function pointer, as described in
1528/// C++11 [expr.prim.lambda]p6.
1529static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1530 CXXRecordDecl *Class,
1531 CXXMethodDecl *CallOperator,
1532 QualType InvokerFunctionTy) {
1533 // This conversion is explicitly disabled if the lambda's function has
1534 // pass_object_size attributes on any of its parameters.
1535 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1536 return P->hasAttr<PassObjectSizeAttr>();
1537 };
1538 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1539 return;
1540
1541 // Add the conversion to function pointer.
1542 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1543
1544 // Create the type of the conversion function.
1545 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1546 S.Context.getDefaultCallingConvention(
1547 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1548 // The conversion function is always const and noexcept.
1549 ConvExtInfo.TypeQuals = Qualifiers();
1550 ConvExtInfo.TypeQuals.addConst();
1551 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1552 QualType ConvTy =
1553 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1554
1555 SourceLocation Loc = IntroducerRange.getBegin();
1556 DeclarationName ConversionName
1557 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1558 S.Context.getCanonicalType(PtrToFunctionTy));
1559 // Construct a TypeSourceInfo for the conversion function, and wire
1560 // all the parameters appropriately for the FunctionProtoTypeLoc
1561 // so that everything works during transformation/instantiation of
1562 // generic lambdas.
1563 // The main reason for wiring up the parameters of the conversion
1564 // function with that of the call operator is so that constructs
1565 // like the following work:
1566 // auto L = [](auto b) { <-- 1
1567 // return [](auto a) -> decltype(a) { <-- 2
1568 // return a;
1569 // };
1570 // };
1571 // int (*fp)(int) = L(5);
1572 // Because the trailing return type can contain DeclRefExprs that refer
1573 // to the original call operator's variables, we hijack the call
1574 // operators ParmVarDecls below.
1575 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1576 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1577 DeclarationNameLoc ConvNameLoc =
1578 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1579
1580 // The conversion function is a conversion to a pointer-to-function.
1581 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1582 FunctionProtoTypeLoc ConvTL =
1583 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1584 // Get the result of the conversion function which is a pointer-to-function.
1585 PointerTypeLoc PtrToFunctionTL =
1586 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1587 // Do the same for the TypeSourceInfo that is used to name the conversion
1588 // operator.
1589 PointerTypeLoc ConvNamePtrToFunctionTL =
1590 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1591
1592 // Get the underlying function types that the conversion function will
1593 // be converting to (should match the type of the call operator).
1594 FunctionProtoTypeLoc CallOpConvTL =
1595 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1596 FunctionProtoTypeLoc CallOpConvNameTL =
1597 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1598
1599 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1600 // These parameter's are essentially used to transform the name and
1601 // the type of the conversion operator. By using the same parameters
1602 // as the call operator's we don't have to fix any back references that
1603 // the trailing return type of the call operator's uses (such as
1604 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1605 // - we can simply use the return type of the call operator, and
1606 // everything should work.
1607 SmallVector<ParmVarDecl *, 4> InvokerParams;
1608 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1609 ParmVarDecl *From = CallOperator->getParamDecl(I);
1610
1611 InvokerParams.push_back(ParmVarDecl::Create(
1612 S.Context,
1613 // Temporarily add to the TU. This is set to the invoker below.
1614 S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1615 From->getLocation(), From->getIdentifier(), From->getType(),
1616 From->getTypeSourceInfo(), From->getStorageClass(),
1617 /*DefArg=*/nullptr));
1618 CallOpConvTL.setParam(I, From);
1619 CallOpConvNameTL.setParam(I, From);
1620 }
1621
1622 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1623 S.Context, Class, Loc,
1624 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1625 S.getCurFPFeatures().isFPConstrained(),
1626 /*isInline=*/true, ExplicitSpecifier(),
1627 S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1628 : ConstexprSpecKind::Unspecified,
1629 CallOperator->getBody()->getEndLoc());
1630 Conversion->setAccess(AS_public);
1631 Conversion->setImplicit(true);
1632
1633 if (Class->isGenericLambda()) {
1634 // Create a template version of the conversion operator, using the template
1635 // parameter list of the function call operator.
1636 FunctionTemplateDecl *TemplateCallOperator =
1637 CallOperator->getDescribedFunctionTemplate();
1638 FunctionTemplateDecl *ConversionTemplate =
1639 FunctionTemplateDecl::Create(S.Context, Class,
1640 Loc, ConversionName,
1641 TemplateCallOperator->getTemplateParameters(),
1642 Conversion);
1643 ConversionTemplate->setAccess(AS_public);
1644 ConversionTemplate->setImplicit(true);
1645 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1646 Class->addDecl(ConversionTemplate);
1647 } else
1648 Class->addDecl(Conversion);
1649
1650 // If the lambda is not static, we need to add a static member
1651 // function that will be the result of the conversion with a
1652 // certain unique ID.
1653 // When it is static we just return the static call operator instead.
1654 if (CallOperator->isInstance()) {
1655 DeclarationName InvokerName =
1656 &S.Context.Idents.get(getLambdaStaticInvokerName());
1657 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1658 // we should get a prebuilt TrivialTypeSourceInfo from Context
1659 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1660 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1661 // loop below and then use its Params to set Invoke->setParams(...) below.
1662 // This would avoid the 'const' qualifier of the calloperator from
1663 // contaminating the type of the invoker, which is currently adjusted
1664 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1665 // trailing return type of the invoker would require a visitor to rebuild
1666 // the trailing return type and adjusting all back DeclRefExpr's to refer
1667 // to the new static invoker parameters - not the call operator's.
1668 CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1669 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1670 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1671 S.getCurFPFeatures().isFPConstrained(),
1672 /*isInline=*/true, CallOperator->getConstexprKind(),
1673 CallOperator->getBody()->getEndLoc());
1674 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1675 InvokerParams[I]->setOwningFunction(Invoke);
1676 Invoke->setParams(InvokerParams);
1677 Invoke->setAccess(AS_private);
1678 Invoke->setImplicit(true);
1679 if (Class->isGenericLambda()) {
1680 FunctionTemplateDecl *TemplateCallOperator =
1681 CallOperator->getDescribedFunctionTemplate();
1682 FunctionTemplateDecl *StaticInvokerTemplate =
1683 FunctionTemplateDecl::Create(
1684 S.Context, Class, Loc, InvokerName,
1685 TemplateCallOperator->getTemplateParameters(), Invoke);
1686 StaticInvokerTemplate->setAccess(AS_private);
1687 StaticInvokerTemplate->setImplicit(true);
1688 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1689 Class->addDecl(StaticInvokerTemplate);
1690 } else
1691 Class->addDecl(Invoke);
1692 }
1693}
1694
1695/// Add a lambda's conversion to function pointers, as described in
1696/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1697/// single pointer conversion. In the event that the default calling convention
1698/// for free and member functions is different, it will emit both conventions.
1699static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1700 CXXRecordDecl *Class,
1701 CXXMethodDecl *CallOperator) {
1702 const FunctionProtoType *CallOpProto =
1703 CallOperator->getType()->castAs<FunctionProtoType>();
1704
1705 repeatForLambdaConversionFunctionCallingConvs(
1706 S, *CallOpProto, [&](CallingConv CC) {
1707 QualType InvokerFunctionTy =
1708 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1709 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1710 InvokerFunctionTy);
1711 });
1712}
1713
1714/// Add a lambda's conversion to block pointer.
1715static void addBlockPointerConversion(Sema &S,
1716 SourceRange IntroducerRange,
1717 CXXRecordDecl *Class,
1718 CXXMethodDecl *CallOperator) {
1719 const FunctionProtoType *CallOpProto =
1720 CallOperator->getType()->castAs<FunctionProtoType>();
1721 QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1722 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1723 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1724
1725 FunctionProtoType::ExtProtoInfo ConversionEPI(
1726 S.Context.getDefaultCallingConvention(
1727 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1728 ConversionEPI.TypeQuals = Qualifiers();
1729 ConversionEPI.TypeQuals.addConst();
1730 QualType ConvTy =
1731 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1732
1733 SourceLocation Loc = IntroducerRange.getBegin();
1734 DeclarationName Name
1735 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1736 S.Context.getCanonicalType(BlockPtrTy));
1737 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1738 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1739 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1740 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1741 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1742 S.getCurFPFeatures().isFPConstrained(),
1743 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
1744 CallOperator->getBody()->getEndLoc());
1745 Conversion->setAccess(AS_public);
1746 Conversion->setImplicit(true);
1747 Class->addDecl(Conversion);
1748}
1749
1750ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1751 SourceLocation ImplicitCaptureLoc,
1752 bool IsOpenMPMapping) {
1753 // VLA captures don't have a stored initialization expression.
1754 if (Cap.isVLATypeCapture())
1755 return ExprResult();
1756
1757 // An init-capture is initialized directly from its stored initializer.
1758 if (Cap.isInitCapture())
1759 return cast<VarDecl>(Cap.getVariable())->getInit();
1760
1761 // For anything else, build an initialization expression. For an implicit
1762 // capture, the capture notionally happens at the capture-default, so use
1763 // that location here.
1764 SourceLocation Loc =
1765 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1766
1767 // C++11 [expr.prim.lambda]p21:
1768 // When the lambda-expression is evaluated, the entities that
1769 // are captured by copy are used to direct-initialize each
1770 // corresponding non-static data member of the resulting closure
1771 // object. (For array members, the array elements are
1772 // direct-initialized in increasing subscript order.) These
1773 // initializations are performed in the (unspecified) order in
1774 // which the non-static data members are declared.
1775
1776 // C++ [expr.prim.lambda]p12:
1777 // An entity captured by a lambda-expression is odr-used (3.2) in
1778 // the scope containing the lambda-expression.
1779 ExprResult Init;
1780 IdentifierInfo *Name = nullptr;
1781 if (Cap.isThisCapture()) {
1782 QualType ThisTy = getCurrentThisType();
1783 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1784 if (Cap.isCopyCapture())
1785 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1786 else
1787 Init = This;
1788 } else {
1789 assert(Cap.isVariableCapture() && "unknown kind of capture")(static_cast <bool> (Cap.isVariableCapture() &&
"unknown kind of capture") ? void (0) : __assert_fail ("Cap.isVariableCapture() && \"unknown kind of capture\""
, "clang/lib/Sema/SemaLambda.cpp", 1789, __extension__ __PRETTY_FUNCTION__
))
;
1790 ValueDecl *Var = Cap.getVariable();
1791 Name = Var->getIdentifier();
1792 Init = BuildDeclarationNameExpr(
1793 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1794 }
1795
1796 // In OpenMP, the capture kind doesn't actually describe how to capture:
1797 // variables are "mapped" onto the device in a process that does not formally
1798 // make a copy, even for a "copy capture".
1799 if (IsOpenMPMapping)
1800 return Init;
1801
1802 if (Init.isInvalid())
1803 return ExprError();
1804
1805 Expr *InitExpr = Init.get();
1806 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1807 Name, Cap.getCaptureType(), Loc);
1808 InitializationKind InitKind =
1809 InitializationKind::CreateDirect(Loc, Loc, Loc);
1810 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1811 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1812}
1813
1814ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1815 Scope *CurScope) {
1816 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1817 ActOnFinishFunctionBody(LSI.CallOperator, Body);
1818 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1819}
1820
1821static LambdaCaptureDefault
1822mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1823 switch (ICS) {
1824 case CapturingScopeInfo::ImpCap_None:
1825 return LCD_None;
1826 case CapturingScopeInfo::ImpCap_LambdaByval:
1827 return LCD_ByCopy;
1828 case CapturingScopeInfo::ImpCap_CapturedRegion:
1829 case CapturingScopeInfo::ImpCap_LambdaByref:
1830 return LCD_ByRef;
1831 case CapturingScopeInfo::ImpCap_Block:
1832 llvm_unreachable("block capture in lambda")::llvm::llvm_unreachable_internal("block capture in lambda", "clang/lib/Sema/SemaLambda.cpp"
, 1832)
;
1833 }
1834 llvm_unreachable("Unknown implicit capture style")::llvm::llvm_unreachable_internal("Unknown implicit capture style"
, "clang/lib/Sema/SemaLambda.cpp", 1834)
;
1835}
1836
1837bool Sema::CaptureHasSideEffects(const Capture &From) {
1838 if (From.isInitCapture()) {
1839 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1840 if (Init && Init->HasSideEffects(Context))
1841 return true;
1842 }
1843
1844 if (!From.isCopyCapture())
1845 return false;
1846
1847 const QualType T = From.isThisCapture()
1848 ? getCurrentThisType()->getPointeeType()
1849 : From.getCaptureType();
1850
1851 if (T.isVolatileQualified())
1852 return true;
1853
1854 const Type *BaseT = T->getBaseElementTypeUnsafe();
1855 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1856 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1857 !RD->hasTrivialDestructor();
1858
1859 return false;
1860}
1861
1862bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1863 const Capture &From) {
1864 if (CaptureHasSideEffects(From))
1865 return false;
1866
1867 if (From.isVLATypeCapture())
1868 return false;
1869
1870 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1871 if (From.isThisCapture())
1872 diag << "'this'";
1873 else
1874 diag << From.getVariable();
1875 diag << From.isNonODRUsed();
1876 diag << FixItHint::CreateRemoval(CaptureRange);
1877 return true;
1878}
1879
1880/// Create a field within the lambda class or captured statement record for the
1881/// given capture.
1882FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1883 const sema::Capture &Capture) {
1884 SourceLocation Loc = Capture.getLocation();
1885 QualType FieldType = Capture.getCaptureType();
1886
1887 TypeSourceInfo *TSI = nullptr;
1888 if (Capture.isVariableCapture()) {
1889 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
1890 if (Var && Var->isInitCapture())
1891 TSI = Var->getTypeSourceInfo();
1892 }
1893
1894 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1895 // appropriate, at least for an implicit capture.
1896 if (!TSI)
1897 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1898
1899 // Build the non-static data member.
1900 FieldDecl *Field =
1901 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1902 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1903 /*Mutable=*/false, ICIS_NoInit);
1904 // If the variable being captured has an invalid type, mark the class as
1905 // invalid as well.
1906 if (!FieldType->isDependentType()) {
1907 if (RequireCompleteSizedType(Loc, FieldType,
1908 diag::err_field_incomplete_or_sizeless)) {
1909 RD->setInvalidDecl();
1910 Field->setInvalidDecl();
1911 } else {
1912 NamedDecl *Def;
1913 FieldType->isIncompleteType(&Def);
1914 if (Def && Def->isInvalidDecl()) {
1915 RD->setInvalidDecl();
1916 Field->setInvalidDecl();
1917 }
1918 }
1919 }
1920 Field->setImplicit(true);
1921 Field->setAccess(AS_private);
1922 RD->addDecl(Field);
1923
1924 if (Capture.isVLATypeCapture())
1925 Field->setCapturedVLAType(Capture.getCapturedVLAType());
1926
1927 return Field;
1928}
1929
1930ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1931 LambdaScopeInfo *LSI) {
1932 // Collect information from the lambda scope.
1933 SmallVector<LambdaCapture, 4> Captures;
1934 SmallVector<Expr *, 4> CaptureInits;
1935 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1936 LambdaCaptureDefault CaptureDefault =
1937 mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1938 CXXRecordDecl *Class;
1939 CXXMethodDecl *CallOperator;
1940 SourceRange IntroducerRange;
1941 bool ExplicitParams;
1942 bool ExplicitResultType;
1943 CleanupInfo LambdaCleanup;
1944 bool ContainsUnexpandedParameterPack;
1945 bool IsGenericLambda;
1946 {
1947 CallOperator = LSI->CallOperator;
1948 Class = LSI->Lambda;
1949 IntroducerRange = LSI->IntroducerRange;
1950 ExplicitParams = LSI->ExplicitParams;
1951 ExplicitResultType = !LSI->HasImplicitReturnType;
1952 LambdaCleanup = LSI->Cleanup;
1953 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1954 IsGenericLambda = Class->isGenericLambda();
1955
1956 CallOperator->setLexicalDeclContext(Class);
1957 Decl *TemplateOrNonTemplateCallOperatorDecl =
1958 CallOperator->getDescribedFunctionTemplate()
1959 ? CallOperator->getDescribedFunctionTemplate()
1960 : cast<Decl>(CallOperator);
1961
1962 // FIXME: Is this really the best choice? Keeping the lexical decl context
1963 // set as CurContext seems more faithful to the source.
1964 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1965
1966 PopExpressionEvaluationContext();
1967
1968 // True if the current capture has a used capture or default before it.
1969 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1970 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1971 CaptureDefaultLoc : IntroducerRange.getBegin();
1972
1973 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1974 const Capture &From = LSI->Captures[I];
1975
1976 if (From.isInvalid())
1977 return ExprError();
1978
1979 assert(!From.isBlockCapture() && "Cannot capture __block variables")(static_cast <bool> (!From.isBlockCapture() && "Cannot capture __block variables"
) ? void (0) : __assert_fail ("!From.isBlockCapture() && \"Cannot capture __block variables\""
, "clang/lib/Sema/SemaLambda.cpp", 1979, __extension__ __PRETTY_FUNCTION__
))
;
1980 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1981 SourceLocation ImplicitCaptureLoc =
1982 IsImplicit ? CaptureDefaultLoc : SourceLocation();
1983
1984 // Use source ranges of explicit captures for fixits where available.
1985 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1986
1987 // Warn about unused explicit captures.
1988 bool IsCaptureUsed = true;
1989 if (!CurContext->isDependentContext() && !IsImplicit &&
1990 !From.isODRUsed()) {
1991 // Initialized captures that are non-ODR used may not be eliminated.
1992 // FIXME: Where did the IsGenericLambda here come from?
1993 bool NonODRUsedInitCapture =
1994 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
1995 if (!NonODRUsedInitCapture) {
1996 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1997 SourceRange FixItRange;
1998 if (CaptureRange.isValid()) {
1999 if (!CurHasPreviousCapture && !IsLast) {
2000 // If there are no captures preceding this capture, remove the
2001 // following comma.
2002 FixItRange = SourceRange(CaptureRange.getBegin(),
2003 getLocForEndOfToken(CaptureRange.getEnd()));
2004 } else {
2005 // Otherwise, remove the comma since the last used capture.
2006 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2007 CaptureRange.getEnd());
2008 }
2009 }
2010
2011 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2012 }
2013 }
2014
2015 if (CaptureRange.isValid()) {
2016 CurHasPreviousCapture |= IsCaptureUsed;
2017 PrevCaptureLoc = CaptureRange.getEnd();
2018 }
2019
2020 // Map the capture to our AST representation.
2021 LambdaCapture Capture = [&] {
2022 if (From.isThisCapture()) {
2023 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2024 // because it results in a reference capture. Don't warn prior to
2025 // C++2a; there's nothing that can be done about it before then.
2026 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2027 CaptureDefault == LCD_ByCopy) {
2028 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2029 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2030 << FixItHint::CreateInsertion(
2031 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2032 }
2033 return LambdaCapture(From.getLocation(), IsImplicit,
2034 From.isCopyCapture() ? LCK_StarThis : LCK_This);
2035 } else if (From.isVLATypeCapture()) {
2036 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2037 } else {
2038 assert(From.isVariableCapture() && "unknown kind of capture")(static_cast <bool> (From.isVariableCapture() &&
"unknown kind of capture") ? void (0) : __assert_fail ("From.isVariableCapture() && \"unknown kind of capture\""
, "clang/lib/Sema/SemaLambda.cpp", 2038, __extension__ __PRETTY_FUNCTION__
))
;
2039 ValueDecl *Var = From.getVariable();
2040 LambdaCaptureKind Kind =
2041 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
2042 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2043 From.getEllipsisLoc());
2044 }
2045 }();
2046
2047 // Form the initializer for the capture field.
2048 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2049
2050 // FIXME: Skip this capture if the capture is not used, the initializer
2051 // has no side-effects, the type of the capture is trivial, and the
2052 // lambda is not externally visible.
2053
2054 // Add a FieldDecl for the capture and form its initializer.
2055 BuildCaptureField(Class, From);
2056 Captures.push_back(Capture);
2057 CaptureInits.push_back(Init.get());
2058
2059 if (LangOpts.CUDA)
2060 CUDACheckLambdaCapture(CallOperator, From);
2061 }
2062
2063 Class->setCaptures(Context, Captures);
2064
2065 // C++11 [expr.prim.lambda]p6:
2066 // The closure type for a lambda-expression with no lambda-capture
2067 // has a public non-virtual non-explicit const conversion function
2068 // to pointer to function having the same parameter and return
2069 // types as the closure type's function call operator.
2070 if (Captures.empty() && CaptureDefault == LCD_None)
2071 addFunctionPointerConversions(*this, IntroducerRange, Class,
2072 CallOperator);
2073
2074 // Objective-C++:
2075 // The closure type for a lambda-expression has a public non-virtual
2076 // non-explicit const conversion function to a block pointer having the
2077 // same parameter and return types as the closure type's function call
2078 // operator.
2079 // FIXME: Fix generic lambda to block conversions.
2080 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2081 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2082
2083 // Finalize the lambda class.
2084 SmallVector<Decl*, 4> Fields(Class->fields());
2085 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2086 SourceLocation(), ParsedAttributesView());
2087 CheckCompletedCXXClass(nullptr, Class);
2088 }
2089
2090 Cleanup.mergeFrom(LambdaCleanup);
2091
2092 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2093 CaptureDefault, CaptureDefaultLoc,
2094 ExplicitParams, ExplicitResultType,
2095 CaptureInits, EndLoc,
2096 ContainsUnexpandedParameterPack);
2097 // If the lambda expression's call operator is not explicitly marked constexpr
2098 // and we are not in a dependent context, analyze the call operator to infer
2099 // its constexpr-ness, suppressing diagnostics while doing so.
2100 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2101 !CallOperator->isConstexpr() &&
2102 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2103 !Class->getDeclContext()->isDependentContext()) {
2104 CallOperator->setConstexprKind(
2105 CheckConstexprFunctionDefinition(CallOperator,
2106 CheckConstexprKind::CheckValid)
2107 ? ConstexprSpecKind::Constexpr
2108 : ConstexprSpecKind::Unspecified);
2109 }
2110
2111 // Emit delayed shadowing warnings now that the full capture list is known.
2112 DiagnoseShadowingLambdaDecls(LSI);
2113
2114 if (!CurContext->isDependentContext()) {
2115 switch (ExprEvalContexts.back().Context) {
2116 // C++11 [expr.prim.lambda]p2:
2117 // A lambda-expression shall not appear in an unevaluated operand
2118 // (Clause 5).
2119 case ExpressionEvaluationContext::Unevaluated:
2120 case ExpressionEvaluationContext::UnevaluatedList:
2121 case ExpressionEvaluationContext::UnevaluatedAbstract:
2122 // C++1y [expr.const]p2:
2123 // A conditional-expression e is a core constant expression unless the
2124 // evaluation of e, following the rules of the abstract machine, would
2125 // evaluate [...] a lambda-expression.
2126 //
2127 // This is technically incorrect, there are some constant evaluated contexts
2128 // where this should be allowed. We should probably fix this when DR1607 is
2129 // ratified, it lays out the exact set of conditions where we shouldn't
2130 // allow a lambda-expression.
2131 case ExpressionEvaluationContext::ConstantEvaluated:
2132 case ExpressionEvaluationContext::ImmediateFunctionContext:
2133 // We don't actually diagnose this case immediately, because we
2134 // could be within a context where we might find out later that
2135 // the expression is potentially evaluated (e.g., for typeid).
2136 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2137 break;
2138
2139 case ExpressionEvaluationContext::DiscardedStatement:
2140 case ExpressionEvaluationContext::PotentiallyEvaluated:
2141 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
2142 break;
2143 }
2144 }
2145
2146 return MaybeBindToTemporary(Lambda);
2147}
2148
2149ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
2150 SourceLocation ConvLocation,
2151 CXXConversionDecl *Conv,
2152 Expr *Src) {
2153 // Make sure that the lambda call operator is marked used.
2154 CXXRecordDecl *Lambda = Conv->getParent();
2155 CXXMethodDecl *CallOperator
2156 = cast<CXXMethodDecl>(
2157 Lambda->lookup(
2158 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
2159 CallOperator->setReferenced();
2160 CallOperator->markUsed(Context);
2161
2162 ExprResult Init = PerformCopyInitialization(
2163 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
2164 CurrentLocation, Src);
2165 if (!Init.isInvalid())
2166 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2167
2168 if (Init.isInvalid())
2169 return ExprError();
2170
2171 // Create the new block to be returned.
2172 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
2173
2174 // Set the type information.
2175 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2176 Block->setIsVariadic(CallOperator->isVariadic());
2177 Block->setBlockMissingReturnType(false);
2178
2179 // Add parameters.
2180 SmallVector<ParmVarDecl *, 4> BlockParams;
2181 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2182 ParmVarDecl *From = CallOperator->getParamDecl(I);
2183 BlockParams.push_back(ParmVarDecl::Create(
2184 Context, Block, From->getBeginLoc(), From->getLocation(),
2185 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2186 From->getStorageClass(),
2187 /*DefArg=*/nullptr));
2188 }
2189 Block->setParams(BlockParams);
2190
2191 Block->setIsConversionFromLambda(true);
2192
2193 // Add capture. The capture uses a fake variable, which doesn't correspond
2194 // to any actual memory location. However, the initializer copy-initializes
2195 // the lambda object.
2196 TypeSourceInfo *CapVarTSI =
2197 Context.getTrivialTypeSourceInfo(Src->getType());
2198 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2199 ConvLocation, nullptr,
2200 Src->getType(), CapVarTSI,
2201 SC_None);
2202 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2203 /*nested=*/false, /*copy=*/Init.get());
2204 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2205
2206 // Add a fake function body to the block. IR generation is responsible
2207 // for filling in the actual body, which cannot be expressed as an AST.
2208 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2209
2210 // Create the block literal expression.
2211 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2212 ExprCleanupObjects.push_back(Block);
2213 Cleanup.setExprNeedsCleanups(true);
2214
2215 return BuildBlock;
2216}

/build/source/clang/include/clang/Sema/DeclSpec.h

1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- 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/// \file
10/// This file defines the classes used to store parsed information about
11/// declaration-specifiers and declarators.
12///
13/// \verbatim
14/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
15/// ------------------------- - -- ---------------------------
16/// declaration-specifiers \ | /
17/// declarators
18/// \endverbatim
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23#define LLVM_CLANG_SEMA_DECLSPEC_H
24
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjCCommon.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/Basic/ExceptionSpecificationType.h"
29#include "clang/Basic/Lambda.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Lex/Token.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/ParsedAttr.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/SmallVector.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/ErrorHandling.h"
39
40namespace clang {
41 class ASTContext;
42 class CXXRecordDecl;
43 class TypeLoc;
44 class LangOptions;
45 class IdentifierInfo;
46 class NamespaceAliasDecl;
47 class NamespaceDecl;
48 class ObjCDeclSpec;
49 class Sema;
50 class Declarator;
51 struct TemplateIdAnnotation;
52
53/// Represents a C++ nested-name-specifier or a global scope specifier.
54///
55/// These can be in 3 states:
56/// 1) Not present, identified by isEmpty()
57/// 2) Present, identified by isNotEmpty()
58/// 2.a) Valid, identified by isValid()
59/// 2.b) Invalid, identified by isInvalid().
60///
61/// isSet() is deprecated because it mostly corresponded to "valid" but was
62/// often used as if it meant "present".
63///
64/// The actual scope is described by getScopeRep().
65///
66/// If the kind of getScopeRep() is TypeSpec then TemplateParamLists may be empty
67/// or contain the template parameter lists attached to the current declaration.
68/// Consider the following example:
69/// template <class T> void SomeType<T>::some_method() {}
70/// If CXXScopeSpec refers to SomeType<T> then TemplateParamLists will contain
71/// a single element referring to template <class T>.
72
73class CXXScopeSpec {
74 SourceRange Range;
75 NestedNameSpecifierLocBuilder Builder;
76 ArrayRef<TemplateParameterList *> TemplateParamLists;
77
78public:
79 SourceRange getRange() const { return Range; }
80 void setRange(SourceRange R) { Range = R; }
81 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
82 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
83 SourceLocation getBeginLoc() const { return Range.getBegin(); }
84 SourceLocation getEndLoc() const { return Range.getEnd(); }
85
86 void setTemplateParamLists(ArrayRef<TemplateParameterList *> L) {
87 TemplateParamLists = L;
88 }
89 ArrayRef<TemplateParameterList *> getTemplateParamLists() const {
90 return TemplateParamLists;
91 }
92
93 /// Retrieve the representation of the nested-name-specifier.
94 NestedNameSpecifier *getScopeRep() const {
95 return Builder.getRepresentation();
96 }
97
98 /// Extend the current nested-name-specifier by another
99 /// nested-name-specifier component of the form 'type::'.
100 ///
101 /// \param Context The AST context in which this nested-name-specifier
102 /// resides.
103 ///
104 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
105 ///
106 /// \param TL The TypeLoc that describes the type preceding the '::'.
107 ///
108 /// \param ColonColonLoc The location of the trailing '::'.
109 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
110 SourceLocation ColonColonLoc);
111
112 /// Extend the current nested-name-specifier by another
113 /// nested-name-specifier component of the form 'identifier::'.
114 ///
115 /// \param Context The AST context in which this nested-name-specifier
116 /// resides.
117 ///
118 /// \param Identifier The identifier.
119 ///
120 /// \param IdentifierLoc The location of the identifier.
121 ///
122 /// \param ColonColonLoc The location of the trailing '::'.
123 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
124 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
125
126 /// Extend the current nested-name-specifier by another
127 /// nested-name-specifier component of the form 'namespace::'.
128 ///
129 /// \param Context The AST context in which this nested-name-specifier
130 /// resides.
131 ///
132 /// \param Namespace The namespace.
133 ///
134 /// \param NamespaceLoc The location of the namespace name.
135 ///
136 /// \param ColonColonLoc The location of the trailing '::'.
137 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
138 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
139
140 /// Extend the current nested-name-specifier by another
141 /// nested-name-specifier component of the form 'namespace-alias::'.
142 ///
143 /// \param Context The AST context in which this nested-name-specifier
144 /// resides.
145 ///
146 /// \param Alias The namespace alias.
147 ///
148 /// \param AliasLoc The location of the namespace alias
149 /// name.
150 ///
151 /// \param ColonColonLoc The location of the trailing '::'.
152 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
153 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
154
155 /// Turn this (empty) nested-name-specifier into the global
156 /// nested-name-specifier '::'.
157 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
158
159 /// Turns this (empty) nested-name-specifier into '__super'
160 /// nested-name-specifier.
161 ///
162 /// \param Context The AST context in which this nested-name-specifier
163 /// resides.
164 ///
165 /// \param RD The declaration of the class in which nested-name-specifier
166 /// appeared.
167 ///
168 /// \param SuperLoc The location of the '__super' keyword.
169 /// name.
170 ///
171 /// \param ColonColonLoc The location of the trailing '::'.
172 void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
173 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
174
175 /// Make a new nested-name-specifier from incomplete source-location
176 /// information.
177 ///
178 /// FIXME: This routine should be used very, very rarely, in cases where we
179 /// need to synthesize a nested-name-specifier. Most code should instead use
180 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
181 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
182 SourceRange R);
183
184 /// Adopt an existing nested-name-specifier (with source-range
185 /// information).
186 void Adopt(NestedNameSpecifierLoc Other);
187
188 /// Retrieve a nested-name-specifier with location information, copied
189 /// into the given AST context.
190 ///
191 /// \param Context The context into which this nested-name-specifier will be
192 /// copied.
193 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
194
195 /// Retrieve the location of the name in the last qualifier
196 /// in this nested name specifier.
197 ///
198 /// For example, the location of \c bar
199 /// in
200 /// \verbatim
201 /// \::foo::bar<0>::
202 /// ^~~
203 /// \endverbatim
204 SourceLocation getLastQualifierNameLoc() const;
205
206 /// No scope specifier.
207 bool isEmpty() const { return Range.isInvalid() && getScopeRep() == nullptr; }
208 /// A scope specifier is present, but may be valid or invalid.
209 bool isNotEmpty() const { return !isEmpty(); }
210
211 /// An error occurred during parsing of the scope specifier.
212 bool isInvalid() const { return Range.isValid() && getScopeRep() == nullptr; }
213 /// A scope specifier is present, and it refers to a real scope.
214 bool isValid() const { return getScopeRep() != nullptr; }
215
216 /// Indicate that this nested-name-specifier is invalid.
217 void SetInvalid(SourceRange R) {
218 assert(R.isValid() && "Must have a valid source range")(static_cast <bool> (R.isValid() && "Must have a valid source range"
) ? void (0) : __assert_fail ("R.isValid() && \"Must have a valid source range\""
, "clang/include/clang/Sema/DeclSpec.h", 218, __extension__ __PRETTY_FUNCTION__
))
;
219 if (Range.getBegin().isInvalid())
220 Range.setBegin(R.getBegin());
221 Range.setEnd(R.getEnd());
222 Builder.Clear();
223 }
224
225 /// Deprecated. Some call sites intend isNotEmpty() while others intend
226 /// isValid().
227 bool isSet() const { return getScopeRep() != nullptr; }
228
229 void clear() {
230 Range = SourceRange();
231 Builder.Clear();
232 }
233
234 /// Retrieve the data associated with the source-location information.
235 char *location_data() const { return Builder.getBuffer().first; }
236
237 /// Retrieve the size of the data associated with source-location
238 /// information.
239 unsigned location_size() const { return Builder.getBuffer().second; }
240};
241
242/// Captures information about "declaration specifiers".
243///
244/// "Declaration specifiers" encompasses storage-class-specifiers,
245/// type-specifiers, type-qualifiers, and function-specifiers.
246class DeclSpec {
247public:
248 /// storage-class-specifier
249 /// \note The order of these enumerators is important for diagnostics.
250 enum SCS {
251 SCS_unspecified = 0,
252 SCS_typedef,
253 SCS_extern,
254 SCS_static,
255 SCS_auto,
256 SCS_register,
257 SCS_private_extern,
258 SCS_mutable
259 };
260
261 // Import thread storage class specifier enumeration and constants.
262 // These can be combined with SCS_extern and SCS_static.
263 typedef ThreadStorageClassSpecifier TSCS;
264 static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
265 static const TSCS TSCS___thread = clang::TSCS___thread;
266 static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
267 static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
268
269 enum TSC {
270 TSC_unspecified,
271 TSC_imaginary,
272 TSC_complex
273 };
274
275 // Import type specifier type enumeration and constants.
276 typedef TypeSpecifierType TST;
277 static const TST TST_unspecified = clang::TST_unspecified;
278 static const TST TST_void = clang::TST_void;
279 static const TST TST_char = clang::TST_char;
280 static const TST TST_wchar = clang::TST_wchar;
281 static const TST TST_char8 = clang::TST_char8;
282 static const TST TST_char16 = clang::TST_char16;
283 static const TST TST_char32 = clang::TST_char32;
284 static const TST TST_int = clang::TST_int;
285 static const TST TST_int128 = clang::TST_int128;
286 static const TST TST_bitint = clang::TST_bitint;
287 static const TST TST_half = clang::TST_half;
288 static const TST TST_BFloat16 = clang::TST_BFloat16;
289 static const TST TST_float = clang::TST_float;
290 static const TST TST_double = clang::TST_double;
291 static const TST TST_float16 = clang::TST_Float16;
292 static const TST TST_accum = clang::TST_Accum;
293 static const TST TST_fract = clang::TST_Fract;
294 static const TST TST_float128 = clang::TST_float128;
295 static const TST TST_ibm128 = clang::TST_ibm128;
296 static const TST TST_bool = clang::TST_bool;
297 static const TST TST_decimal32 = clang::TST_decimal32;
298 static const TST TST_decimal64 = clang::TST_decimal64;
299 static const TST TST_decimal128 = clang::TST_decimal128;
300 static const TST TST_enum = clang::TST_enum;
301 static const TST TST_union = clang::TST_union;
302 static const TST TST_struct = clang::TST_struct;
303 static const TST TST_interface = clang::TST_interface;
304 static const TST TST_class = clang::TST_class;
305 static const TST TST_typename = clang::TST_typename;
306 static const TST TST_typeofType = clang::TST_typeofType;
307 static const TST TST_typeofExpr = clang::TST_typeofExpr;
308 static const TST TST_typeof_unqualType = clang::TST_typeof_unqualType;
309 static const TST TST_typeof_unqualExpr = clang::TST_typeof_unqualExpr;
310 static const TST TST_decltype = clang::TST_decltype;
311 static const TST TST_decltype_auto = clang::TST_decltype_auto;
312#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
313 static const TST TST_##Trait = clang::TST_##Trait;
314#include "clang/Basic/TransformTypeTraits.def"
315 static const TST TST_auto = clang::TST_auto;
316 static const TST TST_auto_type = clang::TST_auto_type;
317 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
318 static const TST TST_atomic = clang::TST_atomic;
319#define GENERIC_IMAGE_TYPE(ImgType, Id) \
320 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
321#include "clang/Basic/OpenCLImageTypes.def"
322 static const TST TST_error = clang::TST_error;
323
324 // type-qualifiers
325 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
326 TQ_unspecified = 0,
327 TQ_const = 1,
328 TQ_restrict = 2,
329 TQ_volatile = 4,
330 TQ_unaligned = 8,
331 // This has no corresponding Qualifiers::TQ value, because it's not treated
332 // as a qualifier in our type system.
333 TQ_atomic = 16
334 };
335
336 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
337 /// returned by getParsedSpecifiers.
338 enum ParsedSpecifiers {
339 PQ_None = 0,
340 PQ_StorageClassSpecifier = 1,
341 PQ_TypeSpecifier = 2,
342 PQ_TypeQualifier = 4,
343 PQ_FunctionSpecifier = 8
344 // FIXME: Attributes should be included here.
345 };
346
347 enum FriendSpecified : bool {
348 No,
349 Yes,
350 };
351
352private:
353 // storage-class-specifier
354 /*SCS*/unsigned StorageClassSpec : 3;
355 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
356 unsigned SCS_extern_in_linkage_spec : 1;
357
358 // type-specifier
359 /*TypeSpecifierWidth*/ unsigned TypeSpecWidth : 2;
360 /*TSC*/unsigned TypeSpecComplex : 2;
361 /*TSS*/unsigned TypeSpecSign : 2;
362 /*TST*/unsigned TypeSpecType : 7;
363 unsigned TypeAltiVecVector : 1;
364 unsigned TypeAltiVecPixel : 1;
365 unsigned TypeAltiVecBool : 1;
366 unsigned TypeSpecOwned : 1;
367 unsigned TypeSpecPipe : 1;
368 unsigned TypeSpecSat : 1;
369 unsigned ConstrainedAuto : 1;
370
371 // type-qualifiers
372 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
373
374 // function-specifier
375 unsigned FS_inline_specified : 1;
376 unsigned FS_forceinline_specified: 1;
377 unsigned FS_virtual_specified : 1;
378 unsigned FS_noreturn_specified : 1;
379
380 // friend-specifier
381 unsigned Friend_specified : 1;
382
383 // constexpr-specifier
384 unsigned ConstexprSpecifier : 2;
385
386 union {
387 UnionParsedType TypeRep;
388 Decl *DeclRep;
389 Expr *ExprRep;
390 TemplateIdAnnotation *TemplateIdRep;
391 };
392
393 /// ExplicitSpecifier - Store information about explicit spicifer.
394 ExplicitSpecifier FS_explicit_specifier;
395
396 // attributes.
397 ParsedAttributes Attrs;
398
399 // Scope specifier for the type spec, if applicable.
400 CXXScopeSpec TypeScope;
401
402 // SourceLocation info. These are null if the item wasn't specified or if
403 // the setting was synthesized.
404 SourceRange Range;
405
406 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
407 SourceRange TSWRange;
408 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc;
409 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
410 /// typename, then this is the location of the named type (if present);
411 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
412 /// TSTNameLoc provides source range info for tag types.
413 SourceLocation TSTNameLoc;
414 SourceRange TypeofParensRange;
415 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
416 TQ_unalignedLoc;
417 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
418 SourceLocation FS_explicitCloseParenLoc;
419 SourceLocation FS_forceinlineLoc;
420 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
421 SourceLocation TQ_pipeLoc;
422
423 WrittenBuiltinSpecs writtenBS;
424 void SaveWrittenBuiltinSpecs();
425
426 ObjCDeclSpec *ObjCQualifiers;
427
428 static bool isTypeRep(TST T) {
429 return T == TST_atomic || T == TST_typename || T == TST_typeofType ||
430 T == TST_typeof_unqualType || isTransformTypeTrait(T);
431 }
432 static bool isExprRep(TST T) {
433 return T == TST_typeofExpr || T == TST_typeof_unqualExpr ||
434 T == TST_decltype || T == TST_bitint;
435 }
436 static bool isTemplateIdRep(TST T) {
437 return (T == TST_auto || T == TST_decltype_auto);
438 }
439
440 DeclSpec(const DeclSpec &) = delete;
441 void operator=(const DeclSpec &) = delete;
442public:
443 static bool isDeclRep(TST T) {
444 return (T == TST_enum || T == TST_struct ||
445 T == TST_interface || T == TST_union ||
446 T == TST_class);
447 }
448 static bool isTransformTypeTrait(TST T) {
449 constexpr std::array<TST, 16> Traits = {
450#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
451#include "clang/Basic/TransformTypeTraits.def"
452 };
453
454 return T >= Traits.front() && T <= Traits.back();
455 }
456
457 DeclSpec(AttributeFactory &attrFactory)
458 : StorageClassSpec(SCS_unspecified),
459 ThreadStorageClassSpec(TSCS_unspecified),
460 SCS_extern_in_linkage_spec(false),
461 TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)),
462 TypeSpecComplex(TSC_unspecified),
463 TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)),
464 TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
465 TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
466 TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
467 TypeQualifiers(TQ_unspecified), FS_inline_specified(false),
468 FS_forceinline_specified(false), FS_virtual_specified(false),
469 FS_noreturn_specified(false), Friend_specified(false),
470 ConstexprSpecifier(
471 static_cast<unsigned>(ConstexprSpecKind::Unspecified)),
472 Attrs(attrFactory), writtenBS(), ObjCQualifiers(nullptr) {}
473
474 // storage-class-specifier
475 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
476 TSCS getThreadStorageClassSpec() const {
477 return (TSCS)ThreadStorageClassSpec;
478 }
479 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
480 void setExternInLinkageSpec(bool Value) {
481 SCS_extern_in_linkage_spec = Value;
482 }
483
484 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
485 SourceLocation getThreadStorageClassSpecLoc() const {
486 return ThreadStorageClassSpecLoc;
487 }
488
489 void ClearStorageClassSpecs() {
490 StorageClassSpec = DeclSpec::SCS_unspecified;
491 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
492 SCS_extern_in_linkage_spec = false;
493 StorageClassSpecLoc = SourceLocation();
494 ThreadStorageClassSpecLoc = SourceLocation();
495 }
496
497 void ClearTypeSpecType() {
498 TypeSpecType = DeclSpec::TST_unspecified;
499 TypeSpecOwned = false;
500 TSTLoc = SourceLocation();
501 }
502
503 // type-specifier
504 TypeSpecifierWidth getTypeSpecWidth() const {
505 return static_cast<TypeSpecifierWidth>(TypeSpecWidth);
506 }
507 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
508 TypeSpecifierSign getTypeSpecSign() const {
509 return static_cast<TypeSpecifierSign>(TypeSpecSign);
510 }
511 TST getTypeSpecType() const { return (TST)TypeSpecType; }
512 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
513 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
514 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
515 bool isTypeSpecOwned() const { return TypeSpecOwned; }
516 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
517 bool isTypeSpecPipe() const { return TypeSpecPipe; }
518 bool isTypeSpecSat() const { return TypeSpecSat; }
519 bool isConstrainedAuto() const { return ConstrainedAuto; }
520
521 ParsedType getRepAsType() const {
522 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type")(static_cast <bool> (isTypeRep((TST) TypeSpecType) &&
"DeclSpec does not store a type") ? void (0) : __assert_fail
("isTypeRep((TST) TypeSpecType) && \"DeclSpec does not store a type\""
, "clang/include/clang/Sema/DeclSpec.h", 522, __extension__ __PRETTY_FUNCTION__
))
;
523 return TypeRep;
524 }
525 Decl *getRepAsDecl() const {
526 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl")(static_cast <bool> (isDeclRep((TST) TypeSpecType) &&
"DeclSpec does not store a decl") ? void (0) : __assert_fail
("isDeclRep((TST) TypeSpecType) && \"DeclSpec does not store a decl\""
, "clang/include/clang/Sema/DeclSpec.h", 526, __extension__ __PRETTY_FUNCTION__
))
;
527 return DeclRep;
528 }
529 Expr *getRepAsExpr() const {
530 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr")(static_cast <bool> (isExprRep((TST) TypeSpecType) &&
"DeclSpec does not store an expr") ? void (0) : __assert_fail
("isExprRep((TST) TypeSpecType) && \"DeclSpec does not store an expr\""
, "clang/include/clang/Sema/DeclSpec.h", 530, __extension__ __PRETTY_FUNCTION__
))
;
531 return ExprRep;
532 }
533 TemplateIdAnnotation *getRepAsTemplateId() const {
534 assert(isTemplateIdRep((TST) TypeSpecType) &&(static_cast <bool> (isTemplateIdRep((TST) TypeSpecType
) && "DeclSpec does not store a template id") ? void (
0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\""
, "clang/include/clang/Sema/DeclSpec.h", 535, __extension__ __PRETTY_FUNCTION__
))
535 "DeclSpec does not store a template id")(static_cast <bool> (isTemplateIdRep((TST) TypeSpecType
) && "DeclSpec does not store a template id") ? void (
0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\""
, "clang/include/clang/Sema/DeclSpec.h", 535, __extension__ __PRETTY_FUNCTION__
))
;
536 return TemplateIdRep;
537 }
538 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
539 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
540
541 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
542 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
543 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
544
545 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
546 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
547 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
548 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
549 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
550 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
551 SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
552
553 SourceLocation getTypeSpecTypeNameLoc() const {
554 assert(isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) ||(static_cast <bool> (isDeclRep((TST)TypeSpecType) || isTypeRep
((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)) ? void (
0) : __assert_fail ("isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)"
, "clang/include/clang/Sema/DeclSpec.h", 555, __extension__ __PRETTY_FUNCTION__
))
555 isExprRep((TST)TypeSpecType))(static_cast <bool> (isDeclRep((TST)TypeSpecType) || isTypeRep
((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)) ? void (
0) : __assert_fail ("isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)"
, "clang/include/clang/Sema/DeclSpec.h", 555, __extension__ __PRETTY_FUNCTION__
))
;
556 return TSTNameLoc;
557 }
558
559 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
560 void setTypeArgumentRange(SourceRange range) { TypeofParensRange = range; }
561
562 bool hasAutoTypeSpec() const {
563 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
564 TypeSpecType == TST_decltype_auto);
565 }
566
567 bool hasTagDefinition() const;
568
569 /// Turn a type-specifier-type into a string like "_Bool" or "union".
570 static const char *getSpecifierName(DeclSpec::TST T,
571 const PrintingPolicy &Policy);
572 static const char *getSpecifierName(DeclSpec::TQ Q);
573 static const char *getSpecifierName(TypeSpecifierSign S);
574 static const char *getSpecifierName(DeclSpec::TSC C);
575 static const char *getSpecifierName(TypeSpecifierWidth W);
576 static const char *getSpecifierName(DeclSpec::SCS S);
577 static const char *getSpecifierName(DeclSpec::TSCS S);
578 static const char *getSpecifierName(ConstexprSpecKind C);
579
580 // type-qualifiers
581
582 /// getTypeQualifiers - Return a set of TQs.
583 unsigned getTypeQualifiers() const { return TypeQualifiers; }
584 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
585 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
586 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
587 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
588 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
589 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
590
591 /// Clear out all of the type qualifiers.
592 void ClearTypeQualifiers() {
593 TypeQualifiers = 0;
594 TQ_constLoc = SourceLocation();
595 TQ_restrictLoc = SourceLocation();
596 TQ_volatileLoc = SourceLocation();
597 TQ_atomicLoc = SourceLocation();
598 TQ_unalignedLoc = SourceLocation();
599 TQ_pipeLoc = SourceLocation();
600 }
601
602 // function-specifier
603 bool isInlineSpecified() const {
604 return FS_inline_specified | FS_forceinline_specified;
605 }
606 SourceLocation getInlineSpecLoc() const {
607 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
608 }
609
610 ExplicitSpecifier getExplicitSpecifier() const {
611 return FS_explicit_specifier;
612 }
613
614 bool isVirtualSpecified() const { return FS_virtual_specified; }
615 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
616
617 bool hasExplicitSpecifier() const {
618 return FS_explicit_specifier.isSpecified();
619 }
620 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
621 SourceRange getExplicitSpecRange() const {
622 return FS_explicit_specifier.getExpr()
623 ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
624 : SourceRange(FS_explicitLoc);
625 }
626
627 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
628 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
629
630 void ClearFunctionSpecs() {
631 FS_inline_specified = false;
632 FS_inlineLoc = SourceLocation();
633 FS_forceinline_specified = false;
634 FS_forceinlineLoc = SourceLocation();
635 FS_virtual_specified = false;
636 FS_virtualLoc = SourceLocation();
637 FS_explicit_specifier = ExplicitSpecifier();
638 FS_explicitLoc = SourceLocation();
639 FS_explicitCloseParenLoc = SourceLocation();
640 FS_noreturn_specified = false;
641 FS_noreturnLoc = SourceLocation();
642 }
643
644 /// This method calls the passed in handler on each CVRU qual being
645 /// set.
646 /// Handle - a handler to be invoked.
647 void forEachCVRUQualifier(
648 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
649
650 /// This method calls the passed in handler on each qual being
651 /// set.
652 /// Handle - a handler to be invoked.
653 void forEachQualifier(
654 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
655
656 /// Return true if any type-specifier has been found.
657 bool hasTypeSpecifier() const {
658 return getTypeSpecType() != DeclSpec::TST_unspecified ||
659 getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
660 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
661 getTypeSpecSign() != TypeSpecifierSign::Unspecified;
662 }
663
664 /// Return a bitmask of which flavors of specifiers this
665 /// DeclSpec includes.
666 unsigned getParsedSpecifiers() const;
667
668 /// isEmpty - Return true if this declaration specifier is completely empty:
669 /// no tokens were parsed in the production of it.
670 bool isEmpty() const {
671 return getParsedSpecifiers() == DeclSpec::PQ_None;
672 }
673
674 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
675 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
676
677 /// These methods set the specified attribute of the DeclSpec and
678 /// return false if there was no error. If an error occurs (for
679 /// example, if we tried to set "auto" on a spec with "extern"
680 /// already set), they return true and set PrevSpec and DiagID
681 /// such that
682 /// Diag(Loc, DiagID) << PrevSpec;
683 /// will yield a useful result.
684 ///
685 /// TODO: use a more general approach that still allows these
686 /// diagnostics to be ignored when desired.
687 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
688 const char *&PrevSpec, unsigned &DiagID,
689 const PrintingPolicy &Policy);
690 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
691 const char *&PrevSpec, unsigned &DiagID);
692 bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
693 const char *&PrevSpec, unsigned &DiagID,
694 const PrintingPolicy &Policy);
695 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
696 unsigned &DiagID);
697 bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
698 const char *&PrevSpec, unsigned &DiagID);
699 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
700 unsigned &DiagID, const PrintingPolicy &Policy);
701 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
702 unsigned &DiagID, ParsedType Rep,
703 const PrintingPolicy &Policy);
704 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
705 unsigned &DiagID, TypeResult Rep,
706 const PrintingPolicy &Policy) {
707 if (Rep.isInvalid())
708 return SetTypeSpecError();
709 return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep.get(), Policy);
710 }
711 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
712 unsigned &DiagID, Decl *Rep, bool Owned,
713 const PrintingPolicy &Policy);
714 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
715 SourceLocation TagNameLoc, const char *&PrevSpec,
716 unsigned &DiagID, ParsedType Rep,
717 const PrintingPolicy &Policy);
718 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
719 SourceLocation TagNameLoc, const char *&PrevSpec,
720 unsigned &DiagID, Decl *Rep, bool Owned,
721 const PrintingPolicy &Policy);
722 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
723 unsigned &DiagID, TemplateIdAnnotation *Rep,
724 const PrintingPolicy &Policy);
725
726 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
727 unsigned &DiagID, Expr *Rep,
728 const PrintingPolicy &policy);
729 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
730 const char *&PrevSpec, unsigned &DiagID,
731 const PrintingPolicy &Policy);
732 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
733 const char *&PrevSpec, unsigned &DiagID,
734 const PrintingPolicy &Policy);
735 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
736 const char *&PrevSpec, unsigned &DiagID,
737 const PrintingPolicy &Policy);
738 bool SetTypePipe(bool isPipe, SourceLocation Loc,
739 const char *&PrevSpec, unsigned &DiagID,
740 const PrintingPolicy &Policy);
741 bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth,
742 const char *&PrevSpec, unsigned &DiagID,
743 const PrintingPolicy &Policy);
744 bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
745 unsigned &DiagID);
746 bool SetTypeSpecError();
747 void UpdateDeclRep(Decl *Rep) {
748 assert(isDeclRep((TST) TypeSpecType))(static_cast <bool> (isDeclRep((TST) TypeSpecType)) ? void
(0) : __assert_fail ("isDeclRep((TST) TypeSpecType)", "clang/include/clang/Sema/DeclSpec.h"
, 748, __extension__ __PRETTY_FUNCTION__))
;
749 DeclRep = Rep;
750 }
751 void UpdateTypeRep(ParsedType Rep) {
752 assert(isTypeRep((TST) TypeSpecType))(static_cast <bool> (isTypeRep((TST) TypeSpecType)) ? void
(0) : __assert_fail ("isTypeRep((TST) TypeSpecType)", "clang/include/clang/Sema/DeclSpec.h"
, 752, __extension__ __PRETTY_FUNCTION__))
;
753 TypeRep = Rep;
754 }
755 void UpdateExprRep(Expr *Rep) {
756 assert(isExprRep((TST) TypeSpecType))(static_cast <bool> (isExprRep((TST) TypeSpecType)) ? void
(0) : __assert_fail ("isExprRep((TST) TypeSpecType)", "clang/include/clang/Sema/DeclSpec.h"
, 756, __extension__ __PRETTY_FUNCTION__))
;
757 ExprRep = Rep;
758 }
759
760 bool SetTypeQual(TQ T, SourceLocation Loc);
761
762 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
763 unsigned &DiagID, const LangOptions &Lang);
764
765 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
766 unsigned &DiagID);
767 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
768 unsigned &DiagID);
769 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
770 unsigned &DiagID);
771 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
772 unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
773 SourceLocation CloseParenLoc);
774 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
775 unsigned &DiagID);
776
777 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
778 unsigned &DiagID);
779 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
780 unsigned &DiagID);
781 bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
782 const char *&PrevSpec, unsigned &DiagID);
783
784 FriendSpecified isFriendSpecified() const {
785 return static_cast<FriendSpecified>(Friend_specified);
786 }
787
788 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
789
790 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
791 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
792
793 ConstexprSpecKind getConstexprSpecifier() const {
794 return ConstexprSpecKind(ConstexprSpecifier);
795 }
796
797 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
798 bool hasConstexprSpecifier() const {
799 return getConstexprSpecifier() != ConstexprSpecKind::Unspecified;
800 }
801
802 void ClearConstexprSpec() {
803 ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified);
804 ConstexprLoc = SourceLocation();
805 }
806
807 AttributePool &getAttributePool() const {
808 return Attrs.getPool();
809 }
810
811 /// Concatenates two attribute lists.
812 ///
813 /// The GCC attribute syntax allows for the following:
814 ///
815 /// \code
816 /// short __attribute__(( unused, deprecated ))
817 /// int __attribute__(( may_alias, aligned(16) )) var;
818 /// \endcode
819 ///
820 /// This declares 4 attributes using 2 lists. The following syntax is
821 /// also allowed and equivalent to the previous declaration.
822 ///
823 /// \code
824 /// short __attribute__((unused)) __attribute__((deprecated))
825 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
826 /// \endcode
827 ///
828 void addAttributes(const ParsedAttributesView &AL) {
829 Attrs.addAll(AL.begin(), AL.end());
830 }
831
832 bool hasAttributes() const { return !Attrs.empty(); }
833
834 ParsedAttributes &getAttributes() { return Attrs; }
835 const ParsedAttributes &getAttributes() const { return Attrs; }
836
837 void takeAttributesFrom(ParsedAttributes &attrs) {
838 Attrs.takeAllFrom(attrs);
839 }
840
841 /// Finish - This does final analysis of the declspec, issuing diagnostics for
842 /// things like "_Imaginary" (lacking an FP type). After calling this method,
843 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
844 void Finish(Sema &S, const PrintingPolicy &Policy);
845
846 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
847 return writtenBS;
848 }
849
850 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
851 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
852
853 /// Checks if this DeclSpec can stand alone, without a Declarator.
854 ///
855 /// Only tag declspecs can stand alone.
856 bool isMissingDeclaratorOk();
857};
858
859/// Captures information about "declaration specifiers" specific to
860/// Objective-C.
861class ObjCDeclSpec {
862public:
863 /// ObjCDeclQualifier - Qualifier used on types in method
864 /// declarations. Not all combinations are sensible. Parameters
865 /// can be one of { in, out, inout } with one of { bycopy, byref }.
866 /// Returns can either be { oneway } or not.
867 ///
868 /// This should be kept in sync with Decl::ObjCDeclQualifier.
869 enum ObjCDeclQualifier {
870 DQ_None = 0x0,
871 DQ_In = 0x1,
872 DQ_Inout = 0x2,
873 DQ_Out = 0x4,
874 DQ_Bycopy = 0x8,
875 DQ_Byref = 0x10,
876 DQ_Oneway = 0x20,
877 DQ_CSNullability = 0x40
878 };
879
880 ObjCDeclSpec()
881 : objcDeclQualifier(DQ_None),
882 PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0),
883 GetterName(nullptr), SetterName(nullptr) {}
884
885 ObjCDeclQualifier getObjCDeclQualifier() const {
886 return (ObjCDeclQualifier)objcDeclQualifier;
887 }
888 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
889 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
890 }
891 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
892 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
893 }
894
895 ObjCPropertyAttribute::Kind getPropertyAttributes() const {
896 return ObjCPropertyAttribute::Kind(PropertyAttributes);
897 }
898 void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) {
899 PropertyAttributes =
900 (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal);
901 }
902
903 NullabilityKind getNullability() const {
904 assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__
))
905 ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__
))
906 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__
))
907 "Objective-C declspec doesn't have nullability")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__
))
;
908 return static_cast<NullabilityKind>(Nullability);
909 }
910
911 SourceLocation getNullabilityLoc() const {
912 assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__
))
913 ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__
))
914 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__
))
915 "Objective-C declspec doesn't have nullability")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__
))
;
916 return NullabilityLoc;
917 }
918
919 void setNullability(SourceLocation loc, NullabilityKind kind) {
920 assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__
))
921 ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__
))
922 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__
))
923 "Set the nullability declspec or property attribute first")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__
))
;
924 Nullability = static_cast<unsigned>(kind);
925 NullabilityLoc = loc;
926 }
927
928 const IdentifierInfo *getGetterName() const { return GetterName; }
929 IdentifierInfo *getGetterName() { return GetterName; }
930 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
931 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
932 GetterName = name;
933 GetterNameLoc = loc;
934 }
935
936 const IdentifierInfo *getSetterName() const { return SetterName; }
937 IdentifierInfo *getSetterName() { return SetterName; }
938 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
939 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
940 SetterName = name;
941 SetterNameLoc = loc;
942 }
943
944private:
945 // FIXME: These two are unrelated and mutually exclusive. So perhaps
946 // we can put them in a union to reflect their mutual exclusivity
947 // (space saving is negligible).
948 unsigned objcDeclQualifier : 7;
949
950 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind
951 unsigned PropertyAttributes : NumObjCPropertyAttrsBits;
952
953 unsigned Nullability : 2;
954
955 SourceLocation NullabilityLoc;
956
957 IdentifierInfo *GetterName; // getter name or NULL if no getter
958 IdentifierInfo *SetterName; // setter name or NULL if no setter
959 SourceLocation GetterNameLoc; // location of the getter attribute's value
960 SourceLocation SetterNameLoc; // location of the setter attribute's value
961
962};
963
964/// Describes the kind of unqualified-id parsed.
965enum class UnqualifiedIdKind {
966 /// An identifier.
967 IK_Identifier,
968 /// An overloaded operator name, e.g., operator+.
969 IK_OperatorFunctionId,
970 /// A conversion function name, e.g., operator int.
971 IK_ConversionFunctionId,
972 /// A user-defined literal name, e.g., operator "" _i.
973 IK_LiteralOperatorId,
974 /// A constructor name.
975 IK_ConstructorName,
976 /// A constructor named via a template-id.
977 IK_ConstructorTemplateId,
978 /// A destructor name.
979 IK_DestructorName,
980 /// A template-id, e.g., f<int>.
981 IK_TemplateId,
982 /// An implicit 'self' parameter
983 IK_ImplicitSelfParam,
984 /// A deduction-guide name (a template-name)
985 IK_DeductionGuideName
986};
987
988/// Represents a C++ unqualified-id that has been parsed.
989class UnqualifiedId {
990private:
991 UnqualifiedId(const UnqualifiedId &Other) = delete;
992 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
993
994 /// Describes the kind of unqualified-id parsed.
995 UnqualifiedIdKind Kind;
996
997public:
998 struct OFI {
999 /// The kind of overloaded operator.
1000 OverloadedOperatorKind Operator;
1001
1002 /// The source locations of the individual tokens that name
1003 /// the operator, e.g., the "new", "[", and "]" tokens in
1004 /// operator new [].
1005 ///
1006 /// Different operators have different numbers of tokens in their name,
1007 /// up to three. Any remaining source locations in this array will be
1008 /// set to an invalid value for operators with fewer than three tokens.
1009 SourceLocation SymbolLocations[3];
1010 };
1011
1012 /// Anonymous union that holds extra data associated with the
1013 /// parsed unqualified-id.
1014 union {
1015 /// When Kind == IK_Identifier, the parsed identifier, or when
1016 /// Kind == IK_UserLiteralId, the identifier suffix.
1017 IdentifierInfo *Identifier;
1018
1019 /// When Kind == IK_OperatorFunctionId, the overloaded operator
1020 /// that we parsed.
1021 struct OFI OperatorFunctionId;
1022
1023 /// When Kind == IK_ConversionFunctionId, the type that the
1024 /// conversion function names.
1025 UnionParsedType ConversionFunctionId;
1026
1027 /// When Kind == IK_ConstructorName, the class-name of the type
1028 /// whose constructor is being referenced.
1029 UnionParsedType ConstructorName;
1030
1031 /// When Kind == IK_DestructorName, the type referred to by the
1032 /// class-name.
1033 UnionParsedType DestructorName;
1034
1035 /// When Kind == IK_DeductionGuideName, the parsed template-name.
1036 UnionParsedTemplateTy TemplateName;
1037
1038 /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
1039 /// the template-id annotation that contains the template name and
1040 /// template arguments.
1041 TemplateIdAnnotation *TemplateId;
1042 };
1043
1044 /// The location of the first token that describes this unqualified-id,
1045 /// which will be the location of the identifier, "operator" keyword,
1046 /// tilde (for a destructor), or the template name of a template-id.
1047 SourceLocation StartLocation;
1048
1049 /// The location of the last token that describes this unqualified-id.
1050 SourceLocation EndLocation;
1051
1052 UnqualifiedId()
1053 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1054
1055 /// Clear out this unqualified-id, setting it to default (invalid)
1056 /// state.
1057 void clear() {
1058 Kind = UnqualifiedIdKind::IK_Identifier;
1059 Identifier = nullptr;
1060 StartLocation = SourceLocation();
1061 EndLocation = SourceLocation();
1062 }
1063
1064 /// Determine whether this unqualified-id refers to a valid name.
1065 bool isValid() const { return StartLocation.isValid(); }
1066
1067 /// Determine whether this unqualified-id refers to an invalid name.
1068 bool isInvalid() const { return !isValid(); }
1069
1070 /// Determine what kind of name we have.
1071 UnqualifiedIdKind getKind() const { return Kind; }
1072
1073 /// Specify that this unqualified-id was parsed as an identifier.
1074 ///
1075 /// \param Id the parsed identifier.
1076 /// \param IdLoc the location of the parsed identifier.
1077 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1078 Kind = UnqualifiedIdKind::IK_Identifier;
1079 Identifier = const_cast<IdentifierInfo *>(Id);
1080 StartLocation = EndLocation = IdLoc;
1081 }
1082
1083 /// Specify that this unqualified-id was parsed as an
1084 /// operator-function-id.
1085 ///
1086 /// \param OperatorLoc the location of the 'operator' keyword.
1087 ///
1088 /// \param Op the overloaded operator.
1089 ///
1090 /// \param SymbolLocations the locations of the individual operator symbols
1091 /// in the operator.
1092 void setOperatorFunctionId(SourceLocation OperatorLoc,
1093 OverloadedOperatorKind Op,
1094 SourceLocation SymbolLocations[3]);
1095
1096 /// Specify that this unqualified-id was parsed as a
1097 /// conversion-function-id.
1098 ///
1099 /// \param OperatorLoc the location of the 'operator' keyword.
1100 ///
1101 /// \param Ty the type to which this conversion function is converting.
1102 ///
1103 /// \param EndLoc the location of the last token that makes up the type name.
1104 void setConversionFunctionId(SourceLocation OperatorLoc,
1105 ParsedType Ty,
1106 SourceLocation EndLoc) {
1107 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1108 StartLocation = OperatorLoc;
1109 EndLocation = EndLoc;
1110 ConversionFunctionId = Ty;
1111 }
1112
1113 /// Specific that this unqualified-id was parsed as a
1114 /// literal-operator-id.
1115 ///
1116 /// \param Id the parsed identifier.
1117 ///
1118 /// \param OpLoc the location of the 'operator' keyword.
1119 ///
1120 /// \param IdLoc the location of the identifier.
1121 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1122 SourceLocation IdLoc) {
1123 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1124 Identifier = const_cast<IdentifierInfo *>(Id);
1125 StartLocation = OpLoc;
1126 EndLocation = IdLoc;
1127 }
1128
1129 /// Specify that this unqualified-id was parsed as a constructor name.
1130 ///
1131 /// \param ClassType the class type referred to by the constructor name.
1132 ///
1133 /// \param ClassNameLoc the location of the class name.
1134 ///
1135 /// \param EndLoc the location of the last token that makes up the type name.
1136 void setConstructorName(ParsedType ClassType,
1137 SourceLocation ClassNameLoc,
1138 SourceLocation EndLoc) {
1139 Kind = UnqualifiedIdKind::IK_ConstructorName;
1140 StartLocation = ClassNameLoc;
1141 EndLocation = EndLoc;
1142 ConstructorName = ClassType;
1143 }
1144
1145 /// Specify that this unqualified-id was parsed as a
1146 /// template-id that names a constructor.
1147 ///
1148 /// \param TemplateId the template-id annotation that describes the parsed
1149 /// template-id. This UnqualifiedId instance will take ownership of the
1150 /// \p TemplateId and will free it on destruction.
1151 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1152
1153 /// Specify that this unqualified-id was parsed as a destructor name.
1154 ///
1155 /// \param TildeLoc the location of the '~' that introduces the destructor
1156 /// name.
1157 ///
1158 /// \param ClassType the name of the class referred to by the destructor name.
1159 void setDestructorName(SourceLocation TildeLoc,
1160 ParsedType ClassType,
1161 SourceLocation EndLoc) {
1162 Kind = UnqualifiedIdKind::IK_DestructorName;
1163 StartLocation = TildeLoc;
1164 EndLocation = EndLoc;
1165 DestructorName = ClassType;
1166 }
1167
1168 /// Specify that this unqualified-id was parsed as a template-id.
1169 ///
1170 /// \param TemplateId the template-id annotation that describes the parsed
1171 /// template-id. This UnqualifiedId instance will take ownership of the
1172 /// \p TemplateId and will free it on destruction.
1173 void setTemplateId(TemplateIdAnnotation *TemplateId);
1174
1175 /// Specify that this unqualified-id was parsed as a template-name for
1176 /// a deduction-guide.
1177 ///
1178 /// \param Template The parsed template-name.
1179 /// \param TemplateLoc The location of the parsed template-name.
1180 void setDeductionGuideName(ParsedTemplateTy Template,
1181 SourceLocation TemplateLoc) {
1182 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1183 TemplateName = Template;
1184 StartLocation = EndLocation = TemplateLoc;
1185 }
1186
1187 /// Specify that this unqualified-id is an implicit 'self'
1188 /// parameter.
1189 ///
1190 /// \param Id the identifier.
1191 void setImplicitSelfParam(const IdentifierInfo *Id) {
1192 Kind = UnqualifiedIdKind::IK_ImplicitSelfParam;
1193 Identifier = const_cast<IdentifierInfo *>(Id);
1194 StartLocation = EndLocation = SourceLocation();
1195 }
1196
1197 /// Return the source range that covers this unqualified-id.
1198 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
1199 return SourceRange(StartLocation, EndLocation);
1200 }
1201 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return StartLocation; }
1202 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EndLocation; }
1203};
1204
1205/// A set of tokens that has been cached for later parsing.
1206typedef SmallVector<Token, 4> CachedTokens;
1207
1208/// One instance of this struct is used for each type in a
1209/// declarator that is parsed.
1210///
1211/// This is intended to be a small value object.
1212struct DeclaratorChunk {
1213 DeclaratorChunk() {};
1214
1215 enum {
1216 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1217 } Kind;
1218
1219 /// Loc - The place where this type was defined.
1220 SourceLocation Loc;
1221 /// EndLoc - If valid, the place where this chunck ends.
1222 SourceLocation EndLoc;
1223
1224 SourceRange getSourceRange() const {
1225 if (EndLoc.isInvalid())
1226 return SourceRange(Loc, Loc);
1227 return SourceRange(Loc, EndLoc);
1228 }
1229
1230 ParsedAttributesView AttrList;
1231
1232 struct PointerTypeInfo {
1233 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1234 unsigned TypeQuals : 5;
1235
1236 /// The location of the const-qualifier, if any.
1237 SourceLocation ConstQualLoc;
1238
1239 /// The location of the volatile-qualifier, if any.
1240 SourceLocation VolatileQualLoc;
1241
1242 /// The location of the restrict-qualifier, if any.
1243 SourceLocation RestrictQualLoc;
1244
1245 /// The location of the _Atomic-qualifier, if any.
1246 SourceLocation AtomicQualLoc;
1247
1248 /// The location of the __unaligned-qualifier, if any.
1249 SourceLocation UnalignedQualLoc;
1250
1251 void destroy() {
1252 }
1253 };
1254
1255 struct ReferenceTypeInfo {
1256 /// The type qualifier: restrict. [GNU] C++ extension
1257 bool HasRestrict : 1;
1258 /// True if this is an lvalue reference, false if it's an rvalue reference.
1259 bool LValueRef : 1;
1260 void destroy() {
1261 }
1262 };
1263
1264 struct ArrayTypeInfo {
1265 /// The type qualifiers for the array:
1266 /// const/volatile/restrict/__unaligned/_Atomic.
1267 unsigned TypeQuals : 5;
1268
1269 /// True if this dimension included the 'static' keyword.
1270 unsigned hasStatic : 1;
1271
1272 /// True if this dimension was [*]. In this case, NumElts is null.
1273 unsigned isStar : 1;
1274
1275 /// This is the size of the array, or null if [] or [*] was specified.
1276 /// Since the parser is multi-purpose, and we don't want to impose a root
1277 /// expression class on all clients, NumElts is untyped.
1278 Expr *NumElts;
1279
1280 void destroy() {}
1281 };
1282
1283 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1284 /// declarator is parsed. There are two interesting styles of parameters
1285 /// here:
1286 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1287 /// lists will have information about the identifier, but no type information.
1288 /// Parameter type lists will have type info (if the actions module provides
1289 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1290 struct ParamInfo {
1291 IdentifierInfo *Ident;
1292 SourceLocation IdentLoc;
1293 Decl *Param;
1294
1295 /// DefaultArgTokens - When the parameter's default argument
1296 /// cannot be parsed immediately (because it occurs within the
1297 /// declaration of a member function), it will be stored here as a
1298 /// sequence of tokens to be parsed once the class definition is
1299 /// complete. Non-NULL indicates that there is a default argument.
1300 std::unique_ptr<CachedTokens> DefaultArgTokens;
1301
1302 ParamInfo() = default;
1303 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1304 Decl *param,
1305 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1306 : Ident(ident), IdentLoc(iloc), Param(param),
1307 DefaultArgTokens(std::move(DefArgTokens)) {}
1308 };
1309
1310 struct TypeAndRange {
1311 ParsedType Ty;
1312 SourceRange Range;
1313 };
1314
1315 struct FunctionTypeInfo {
1316 /// hasPrototype - This is true if the function had at least one typed
1317 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1318 /// and is treated as a K&R-style function.
1319 unsigned hasPrototype : 1;
1320
1321 /// isVariadic - If this function has a prototype, and if that
1322 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1323 /// contains the location of the ellipsis.
1324 unsigned isVariadic : 1;
1325
1326 /// Can this declaration be a constructor-style initializer?
1327 unsigned isAmbiguous : 1;
1328
1329 /// Whether the ref-qualifier (if any) is an lvalue reference.
1330 /// Otherwise, it's an rvalue reference.
1331 unsigned RefQualifierIsLValueRef : 1;
1332
1333 /// ExceptionSpecType - An ExceptionSpecificationType value.
1334 unsigned ExceptionSpecType : 4;
1335
1336 /// DeleteParams - If this is true, we need to delete[] Params.
1337 unsigned DeleteParams : 1;
1338
1339 /// HasTrailingReturnType - If this is true, a trailing return type was
1340 /// specified.
1341 unsigned HasTrailingReturnType : 1;
1342
1343 /// The location of the left parenthesis in the source.
1344 SourceLocation LParenLoc;
1345
1346 /// When isVariadic is true, the location of the ellipsis in the source.
1347 SourceLocation EllipsisLoc;
1348
1349 /// The location of the right parenthesis in the source.
1350 SourceLocation RParenLoc;
1351
1352 /// NumParams - This is the number of formal parameters specified by the
1353 /// declarator.
1354 unsigned NumParams;
1355
1356 /// NumExceptionsOrDecls - This is the number of types in the
1357 /// dynamic-exception-decl, if the function has one. In C, this is the
1358 /// number of declarations in the function prototype.
1359 unsigned NumExceptionsOrDecls;
1360
1361 /// The location of the ref-qualifier, if any.
1362 ///
1363 /// If this is an invalid location, there is no ref-qualifier.
1364 SourceLocation RefQualifierLoc;
1365
1366 /// The location of the 'mutable' qualifer in a lambda-declarator, if
1367 /// any.
1368 SourceLocation MutableLoc;
1369
1370 /// The beginning location of the exception specification, if any.
1371 SourceLocation ExceptionSpecLocBeg;
1372
1373 /// The end location of the exception specification, if any.
1374 SourceLocation ExceptionSpecLocEnd;
1375
1376 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1377 /// describe the parameters specified by this function declarator. null if
1378 /// there are no parameters specified.
1379 ParamInfo *Params;
1380
1381 /// DeclSpec for the function with the qualifier related info.
1382 DeclSpec *MethodQualifiers;
1383
1384 /// AttributeFactory for the MethodQualifiers.
1385 AttributeFactory *QualAttrFactory;
1386
1387 union {
1388 /// Pointer to a new[]'d array of TypeAndRange objects that
1389 /// contain the types in the function's dynamic exception specification
1390 /// and their locations, if there is one.
1391 TypeAndRange *Exceptions;
1392
1393 /// Pointer to the expression in the noexcept-specifier of this
1394 /// function, if it has one.
1395 Expr *NoexceptExpr;
1396
1397 /// Pointer to the cached tokens for an exception-specification
1398 /// that has not yet been parsed.
1399 CachedTokens *ExceptionSpecTokens;
1400
1401 /// Pointer to a new[]'d array of declarations that need to be available
1402 /// for lookup inside the function body, if one exists. Does not exist in
1403 /// C++.
1404 NamedDecl **DeclsInPrototype;
1405 };
1406
1407 /// If HasTrailingReturnType is true, this is the trailing return
1408 /// type specified.
1409 UnionParsedType TrailingReturnType;
1410
1411 /// If HasTrailingReturnType is true, this is the location of the trailing
1412 /// return type.
1413 SourceLocation TrailingReturnTypeLoc;
1414
1415 /// Reset the parameter list to having zero parameters.
1416 ///
1417 /// This is used in various places for error recovery.
1418 void freeParams() {
1419 for (unsigned I = 0; I < NumParams; ++I)
1420 Params[I].DefaultArgTokens.reset();
1421 if (DeleteParams) {
1422 delete[] Params;
1423 DeleteParams = false;
1424 }
1425 NumParams = 0;
1426 }
1427
1428 void destroy() {
1429 freeParams();
1430 delete QualAttrFactory;
1431 delete MethodQualifiers;
1432 switch (getExceptionSpecType()) {
1433 default:
1434 break;
1435 case EST_Dynamic:
1436 delete[] Exceptions;
1437 break;
1438 case EST_Unparsed:
1439 delete ExceptionSpecTokens;
1440 break;
1441 case EST_None:
1442 if (NumExceptionsOrDecls != 0)
1443 delete[] DeclsInPrototype;
1444 break;
1445 }
1446 }
1447
1448 DeclSpec &getOrCreateMethodQualifiers() {
1449 if (!MethodQualifiers) {
1450 QualAttrFactory = new AttributeFactory();
1451 MethodQualifiers = new DeclSpec(*QualAttrFactory);
1452 }
1453 return *MethodQualifiers;
1454 }
1455
1456 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1457 /// like "void foo(a,b,c)". In a function definition, this will be followed
1458 /// by the parameter type definitions.
1459 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1460
1461 SourceLocation getLParenLoc() const { return LParenLoc; }
1462
1463 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1464
1465 SourceLocation getRParenLoc() const { return RParenLoc; }
1466
1467 SourceLocation getExceptionSpecLocBeg() const {
1468 return ExceptionSpecLocBeg;
1469 }
1470
1471 SourceLocation getExceptionSpecLocEnd() const {
1472 return ExceptionSpecLocEnd;
1473 }
1474
1475 SourceRange getExceptionSpecRange() const {
1476 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1477 }
1478
1479 /// Retrieve the location of the ref-qualifier, if any.
1480 SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; }
1481
1482 /// Retrieve the location of the 'const' qualifier.
1483 SourceLocation getConstQualifierLoc() const {
1484 assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail
("MethodQualifiers", "clang/include/clang/Sema/DeclSpec.h", 1484
, __extension__ __PRETTY_FUNCTION__))
;
1485 return MethodQualifiers->getConstSpecLoc();
1486 }
1487
1488 /// Retrieve the location of the 'volatile' qualifier.
1489 SourceLocation getVolatileQualifierLoc() const {
1490 assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail
("MethodQualifiers", "clang/include/clang/Sema/DeclSpec.h", 1490
, __extension__ __PRETTY_FUNCTION__))
;
1491 return MethodQualifiers->getVolatileSpecLoc();
1492 }
1493
1494 /// Retrieve the location of the 'restrict' qualifier.
1495 SourceLocation getRestrictQualifierLoc() const {
1496 assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail
("MethodQualifiers", "clang/include/clang/Sema/DeclSpec.h", 1496
, __extension__ __PRETTY_FUNCTION__))
;
1497 return MethodQualifiers->getRestrictSpecLoc();
1498 }
1499
1500 /// Retrieve the location of the 'mutable' qualifier, if any.
1501 SourceLocation getMutableLoc() const { return MutableLoc; }
1502
1503 /// Determine whether this function declaration contains a
1504 /// ref-qualifier.
1505 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1506
1507 /// Determine whether this lambda-declarator contains a 'mutable'
1508 /// qualifier.
1509 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1510
1511 /// Determine whether this method has qualifiers.
1512 bool hasMethodTypeQualifiers() const {
1513 return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1514 MethodQualifiers->getAttributes().size());
1515 }
1516
1517 /// Get the type of exception specification this function has.
1518 ExceptionSpecificationType getExceptionSpecType() const {
1519 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1520 }
1521
1522 /// Get the number of dynamic exception specifications.
1523 unsigned getNumExceptions() const {
1524 assert(ExceptionSpecType != EST_None)(static_cast <bool> (ExceptionSpecType != EST_None) ? void
(0) : __assert_fail ("ExceptionSpecType != EST_None", "clang/include/clang/Sema/DeclSpec.h"
, 1524, __extension__ __PRETTY_FUNCTION__))
;
1525 return NumExceptionsOrDecls;
1526 }
1527
1528 /// Get the non-parameter decls defined within this function
1529 /// prototype. Typically these are tag declarations.
1530 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1531 assert(ExceptionSpecType == EST_None)(static_cast <bool> (ExceptionSpecType == EST_None) ? void
(0) : __assert_fail ("ExceptionSpecType == EST_None", "clang/include/clang/Sema/DeclSpec.h"
, 1531, __extension__ __PRETTY_FUNCTION__))
;
1532 return llvm::ArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1533 }
1534
1535 /// Determine whether this function declarator had a
1536 /// trailing-return-type.
1537 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1538
1539 /// Get the trailing-return-type for this function declarator.
1540 ParsedType getTrailingReturnType() const {
1541 assert(HasTrailingReturnType)(static_cast <bool> (HasTrailingReturnType) ? void (0) :
__assert_fail ("HasTrailingReturnType", "clang/include/clang/Sema/DeclSpec.h"
, 1541, __extension__ __PRETTY_FUNCTION__))
;
1542 return TrailingReturnType;
1543 }
1544
1545 /// Get the trailing-return-type location for this function declarator.
1546 SourceLocation getTrailingReturnTypeLoc() const {
1547 assert(HasTrailingReturnType)(static_cast <bool> (HasTrailingReturnType) ? void (0) :
__assert_fail ("HasTrailingReturnType", "clang/include/clang/Sema/DeclSpec.h"
, 1547, __extension__ __PRETTY_FUNCTION__))
;
1548 return TrailingReturnTypeLoc;
1549 }
1550 };
1551
1552 struct BlockPointerTypeInfo {
1553 /// For now, sema will catch these as invalid.
1554 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1555 unsigned TypeQuals : 5;
1556
1557 void destroy() {
1558 }
1559 };
1560
1561 struct MemberPointerTypeInfo {
1562 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1563 unsigned TypeQuals : 5;
1564 /// Location of the '*' token.
1565 SourceLocation StarLoc;
1566 // CXXScopeSpec has a constructor, so it can't be a direct member.
1567 // So we need some pointer-aligned storage and a bit of trickery.
1568 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1569 CXXScopeSpec &Scope() {
1570 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1571 }
1572 const CXXScopeSpec &Scope() const {
1573 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1574 }
1575 void destroy() {
1576 Scope().~CXXScopeSpec();
1577 }
1578 };
1579
1580 struct PipeTypeInfo {
1581 /// The access writes.
1582 unsigned AccessWrites : 3;
1583
1584 void destroy() {}
1585 };
1586
1587 union {
1588 PointerTypeInfo Ptr;
1589 ReferenceTypeInfo Ref;
1590 ArrayTypeInfo Arr;
1591 FunctionTypeInfo Fun;
1592 BlockPointerTypeInfo Cls;
1593 MemberPointerTypeInfo Mem;
1594 PipeTypeInfo PipeInfo;
1595 };
1596
1597 void destroy() {
1598 switch (Kind) {
1599 case DeclaratorChunk::Function: return Fun.destroy();
1600 case DeclaratorChunk::Pointer: return Ptr.destroy();
1601 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1602 case DeclaratorChunk::Reference: return Ref.destroy();
1603 case DeclaratorChunk::Array: return Arr.destroy();
1604 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1605 case DeclaratorChunk::Paren: return;
1606 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1607 }
1608 }
1609
1610 /// If there are attributes applied to this declaratorchunk, return
1611 /// them.
1612 const ParsedAttributesView &getAttrs() const { return AttrList; }
1613 ParsedAttributesView &getAttrs() { return AttrList; }
1614
1615 /// Return a DeclaratorChunk for a pointer.
1616 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1617 SourceLocation ConstQualLoc,
1618 SourceLocation VolatileQualLoc,
1619 SourceLocation RestrictQualLoc,
1620 SourceLocation AtomicQualLoc,
1621 SourceLocation UnalignedQualLoc) {
1622 DeclaratorChunk I;
1623 I.Kind = Pointer;
1624 I.Loc = Loc;
1625 new (&I.Ptr) PointerTypeInfo;
1626 I.Ptr.TypeQuals = TypeQuals;
1627 I.Ptr.ConstQualLoc = ConstQualLoc;
1628 I.Ptr.VolatileQualLoc = VolatileQualLoc;
1629 I.Ptr.RestrictQualLoc = RestrictQualLoc;
1630 I.Ptr.AtomicQualLoc = AtomicQualLoc;
1631 I.Ptr.UnalignedQualLoc = UnalignedQualLoc;
1632 return I;
1633 }
1634
1635 /// Return a DeclaratorChunk for a reference.
1636 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1637 bool lvalue) {
1638 DeclaratorChunk I;
1639 I.Kind = Reference;
1640 I.Loc = Loc;
1641 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1642 I.Ref.LValueRef = lvalue;
1643 return I;
1644 }
1645
1646 /// Return a DeclaratorChunk for an array.
1647 static DeclaratorChunk getArray(unsigned TypeQuals,
1648 bool isStatic, bool isStar, Expr *NumElts,
1649 SourceLocation LBLoc, SourceLocation RBLoc) {
1650 DeclaratorChunk I;
1651 I.Kind = Array;
1652 I.Loc = LBLoc;
1653 I.EndLoc = RBLoc;
1654 I.Arr.TypeQuals = TypeQuals;
1655 I.Arr.hasStatic = isStatic;
1656 I.Arr.isStar = isStar;
1657 I.Arr.NumElts = NumElts;
1658 return I;
1659 }
1660
1661 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1662 /// "TheDeclarator" is the declarator that this will be added to.
1663 static DeclaratorChunk getFunction(bool HasProto,
1664 bool IsAmbiguous,
1665 SourceLocation LParenLoc,
1666 ParamInfo *Params, unsigned NumParams,
1667 SourceLocation EllipsisLoc,
1668 SourceLocation RParenLoc,
1669 bool RefQualifierIsLvalueRef,
1670 SourceLocation RefQualifierLoc,
1671 SourceLocation MutableLoc,
1672 ExceptionSpecificationType ESpecType,
1673 SourceRange ESpecRange,
1674 ParsedType *Exceptions,
1675 SourceRange *ExceptionRanges,
1676 unsigned NumExceptions,
1677 Expr *NoexceptExpr,
1678 CachedTokens *ExceptionSpecTokens,
1679 ArrayRef<NamedDecl *> DeclsInPrototype,
1680 SourceLocation LocalRangeBegin,
1681 SourceLocation LocalRangeEnd,
1682 Declarator &TheDeclarator,
1683 TypeResult TrailingReturnType =
1684 TypeResult(),
1685 SourceLocation TrailingReturnTypeLoc =
1686 SourceLocation(),
1687 DeclSpec *MethodQualifiers = nullptr);
1688
1689 /// Return a DeclaratorChunk for a block.
1690 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1691 SourceLocation Loc) {
1692 DeclaratorChunk I;
1693 I.Kind = BlockPointer;
1694 I.Loc = Loc;
1695 I.Cls.TypeQuals = TypeQuals;
1696 return I;
1697 }
1698
1699 /// Return a DeclaratorChunk for a block.
1700 static DeclaratorChunk getPipe(unsigned TypeQuals,
1701 SourceLocation Loc) {
1702 DeclaratorChunk I;
1703 I.Kind = Pipe;
1704 I.Loc = Loc;
1705 I.Cls.TypeQuals = TypeQuals;
1706 return I;
1707 }
1708
1709 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1710 unsigned TypeQuals,
1711 SourceLocation StarLoc,
1712 SourceLocation EndLoc) {
1713 DeclaratorChunk I;
1714 I.Kind = MemberPointer;
1715 I.Loc = SS.getBeginLoc();
1716 I.EndLoc = EndLoc;
1717 new (&I.Mem) MemberPointerTypeInfo;
1718 I.Mem.StarLoc = StarLoc;
1719 I.Mem.TypeQuals = TypeQuals;
1720 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1721 return I;
1722 }
1723
1724 /// Return a DeclaratorChunk for a paren.
1725 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1726 SourceLocation RParenLoc) {
1727 DeclaratorChunk I;
1728 I.Kind = Paren;
1729 I.Loc = LParenLoc;
1730 I.EndLoc = RParenLoc;
1731 return I;
1732 }
1733
1734 bool isParen() const {
1735 return Kind == Paren;
1736 }
1737};
1738
1739/// A parsed C++17 decomposition declarator of the form
1740/// '[' identifier-list ']'
1741class DecompositionDeclarator {
1742public:
1743 struct Binding {
1744 IdentifierInfo *Name;
1745 SourceLocation NameLoc;
1746 };
1747
1748private:
1749 /// The locations of the '[' and ']' tokens.
1750 SourceLocation LSquareLoc, RSquareLoc;
1751
1752 /// The bindings.
1753 Binding *Bindings;
1754 unsigned NumBindings : 31;
1755 unsigned DeleteBindings : 1;
1756
1757 friend class Declarator;
1758
1759public:
1760 DecompositionDeclarator()
1761 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1762 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1763 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1764 ~DecompositionDeclarator() {
1765 if (DeleteBindings)
1766 delete[] Bindings;
1767 }
1768
1769 void clear() {
1770 LSquareLoc = RSquareLoc = SourceLocation();
1771 if (DeleteBindings)
1772 delete[] Bindings;
1773 Bindings = nullptr;
1774 NumBindings = 0;
1775 DeleteBindings = false;
1776 }
1777
1778 ArrayRef<Binding> bindings() const {
1779 return llvm::ArrayRef(Bindings, NumBindings);
1780 }
1781
1782 bool isSet() const { return LSquareLoc.isValid(); }
1783
1784 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1785 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1786 SourceRange getSourceRange() const {
1787 return SourceRange(LSquareLoc, RSquareLoc);
1788 }
1789};
1790
1791/// Described the kind of function definition (if any) provided for
1792/// a function.
1793enum class FunctionDefinitionKind {
1794 Declaration,
1795 Definition,
1796 Defaulted,
1797 Deleted
1798};
1799
1800enum class DeclaratorContext {
1801 File, // File scope declaration.
1802 Prototype, // Within a function prototype.
1803 ObjCResult, // An ObjC method result type.
1804 ObjCParameter, // An ObjC method parameter type.
1805 KNRTypeList, // K&R type definition list for formals.
1806 TypeName, // Abstract declarator for types.
1807 FunctionalCast, // Type in a C++ functional cast expression.
1808 Member, // Struct/Union field.
1809 Block, // Declaration within a block in a function.
1810 ForInit, // Declaration within first part of a for loop.
1811 SelectionInit, // Declaration within optional init stmt of if/switch.
1812 Condition, // Condition declaration in a C++ if/switch/while/for.
1813 TemplateParam, // Within a template parameter list.
1814 CXXNew, // C++ new-expression.
1815 CXXCatch, // C++ catch exception-declaration
1816 ObjCCatch, // Objective-C catch exception-declaration
1817 BlockLiteral, // Block literal declarator.
1818 LambdaExpr, // Lambda-expression declarator.
1819 LambdaExprParameter, // Lambda-expression parameter declarator.
1820 ConversionId, // C++ conversion-type-id.
1821 TrailingReturn, // C++11 trailing-type-specifier.
1822 TrailingReturnVar, // C++11 trailing-type-specifier for variable.
1823 TemplateArg, // Any template argument (in template argument list).
1824 TemplateTypeArg, // Template type argument (in default argument).
1825 AliasDecl, // C++11 alias-declaration.
1826 AliasTemplate, // C++11 alias-declaration template.
1827 RequiresExpr, // C++2a requires-expression.
1828 Association // C11 _Generic selection expression association.
1829};
1830
1831// Describes whether the current context is a context where an implicit
1832// typename is allowed (C++2a [temp.res]p5]).
1833enum class ImplicitTypenameContext {
1834 No,
1835 Yes,
1836};
1837
1838/// Information about one declarator, including the parsed type
1839/// information and the identifier.
1840///
1841/// When the declarator is fully formed, this is turned into the appropriate
1842/// Decl object.
1843///
1844/// Declarators come in two types: normal declarators and abstract declarators.
1845/// Abstract declarators are used when parsing types, and don't have an
1846/// identifier. Normal declarators do have ID's.
1847///
1848/// Instances of this class should be a transient object that lives on the
1849/// stack, not objects that are allocated in large quantities on the heap.
1850class Declarator {
1851
1852private:
1853 const DeclSpec &DS;
1854 CXXScopeSpec SS;
1855 UnqualifiedId Name;
1856 SourceRange Range;
1857
1858 /// Where we are parsing this declarator.
1859 DeclaratorContext Context;
1860
1861 /// The C++17 structured binding, if any. This is an alternative to a Name.
1862 DecompositionDeclarator BindingGroup;
1863
1864 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1865 /// parsed. This is pushed from the identifier out, which means that element
1866 /// #0 will be the most closely bound to the identifier, and
1867 /// DeclTypeInfo.back() will be the least closely bound.
1868 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1869
1870 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1871 unsigned InvalidType : 1;
1872
1873 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1874 unsigned GroupingParens : 1;
1875
1876 /// FunctionDefinition - Is this Declarator for a function or member
1877 /// definition and, if so, what kind?
1878 ///
1879 /// Actually a FunctionDefinitionKind.
1880 unsigned FunctionDefinition : 2;
1881
1882 /// Is this Declarator a redeclaration?
1883 unsigned Redeclaration : 1;
1884
1885 /// true if the declaration is preceded by \c __extension__.
1886 unsigned Extension : 1;
1887
1888 /// Indicates whether this is an Objective-C instance variable.
1889 unsigned ObjCIvar : 1;
1890
1891 /// Indicates whether this is an Objective-C 'weak' property.
1892 unsigned ObjCWeakProperty : 1;
1893
1894 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1895 unsigned InlineStorageUsed : 1;
1896
1897 /// Indicates whether this declarator has an initializer.
1898 unsigned HasInitializer : 1;
1899
1900 /// Attributes attached to the declarator.
1901 ParsedAttributes Attrs;
1902
1903 /// Attributes attached to the declaration. See also documentation for the
1904 /// corresponding constructor parameter.
1905 const ParsedAttributesView &DeclarationAttrs;
1906
1907 /// The asm label, if specified.
1908 Expr *AsmLabel;
1909
1910 /// \brief The constraint-expression specified by the trailing
1911 /// requires-clause, or null if no such clause was specified.
1912 Expr *TrailingRequiresClause;
1913
1914 /// If this declarator declares a template, its template parameter lists.
1915 ArrayRef<TemplateParameterList *> TemplateParameterLists;
1916
1917 /// If the declarator declares an abbreviated function template, the innermost
1918 /// template parameter list containing the invented and explicit template
1919 /// parameters (if any).
1920 TemplateParameterList *InventedTemplateParameterList;
1921
1922#ifndef _MSC_VER
1923 union {
1924#endif
1925 /// InlineParams - This is a local array used for the first function decl
1926 /// chunk to avoid going to the heap for the common case when we have one
1927 /// function chunk in the declarator.
1928 DeclaratorChunk::ParamInfo InlineParams[16];
1929 DecompositionDeclarator::Binding InlineBindings[16];
1930#ifndef _MSC_VER
1931 };
1932#endif
1933
1934 /// If this is the second or subsequent declarator in this declaration,
1935 /// the location of the comma before this declarator.
1936 SourceLocation CommaLoc;
1937
1938 /// If provided, the source location of the ellipsis used to describe
1939 /// this declarator as a parameter pack.
1940 SourceLocation EllipsisLoc;
1941
1942 friend struct DeclaratorChunk;
1943
1944public:
1945 /// `DS` and `DeclarationAttrs` must outlive the `Declarator`. In particular,
1946 /// take care not to pass temporary objects for these parameters.
1947 ///
1948 /// `DeclarationAttrs` contains [[]] attributes from the
1949 /// attribute-specifier-seq at the beginning of a declaration, which appertain
1950 /// to the declared entity itself. Attributes with other syntax (e.g. GNU)
1951 /// should not be placed in this attribute list; if they occur at the
1952 /// beginning of a declaration, they apply to the `DeclSpec` and should be
1953 /// attached to that instead.
1954 ///
1955 /// Here is an example of an attribute associated with a declaration:
1956 ///
1957 /// [[deprecated]] int x, y;
1958 ///
1959 /// This attribute appertains to all of the entities declared in the
1960 /// declaration, i.e. `x` and `y` in this case.
1961 Declarator(const DeclSpec &DS, const ParsedAttributesView &DeclarationAttrs,
1962 DeclaratorContext C)
1963 : DS(DS), Range(DS.getSourceRange()), Context(C),
1964 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1965 GroupingParens(false), FunctionDefinition(static_cast<unsigned>(
1966 FunctionDefinitionKind::Declaration)),
1967 Redeclaration(false), Extension(false), ObjCIvar(false),
1968 ObjCWeakProperty(false), InlineStorageUsed(false),
1969 HasInitializer(false), Attrs(DS.getAttributePool().getFactory()),
1970 DeclarationAttrs(DeclarationAttrs), AsmLabel(nullptr),
1971 TrailingRequiresClause(nullptr),
1972 InventedTemplateParameterList(nullptr) {
1973 assert(llvm::all_of(DeclarationAttrs,(static_cast <bool> (llvm::all_of(DeclarationAttrs, [](
const ParsedAttr &AL) { return AL.isStandardAttributeSyntax
(); }) && "DeclarationAttrs may only contain [[]] attributes"
) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\""
, "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__
))
1974 [](const ParsedAttr &AL) {(static_cast <bool> (llvm::all_of(DeclarationAttrs, [](
const ParsedAttr &AL) { return AL.isStandardAttributeSyntax
(); }) && "DeclarationAttrs may only contain [[]] attributes"
) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\""
, "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__
))
1975 return AL.isStandardAttributeSyntax();(static_cast <bool> (llvm::all_of(DeclarationAttrs, [](
const ParsedAttr &AL) { return AL.isStandardAttributeSyntax
(); }) && "DeclarationAttrs may only contain [[]] attributes"
) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\""
, "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__
))
1976 }) &&(static_cast <bool> (llvm::all_of(DeclarationAttrs, [](
const ParsedAttr &AL) { return AL.isStandardAttributeSyntax
(); }) && "DeclarationAttrs may only contain [[]] attributes"
) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\""
, "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__
))
1977 "DeclarationAttrs may only contain [[]] attributes")(static_cast <bool> (llvm::all_of(DeclarationAttrs, [](
const ParsedAttr &AL) { return AL.isStandardAttributeSyntax
(); }) && "DeclarationAttrs may only contain [[]] attributes"
) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\""
, "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__
))
;
1978 }
1979
1980 ~Declarator() {
1981 clear();
1982 }
1983 /// getDeclSpec - Return the declaration-specifier that this declarator was
1984 /// declared with.
1985 const DeclSpec &getDeclSpec() const { return DS; }
1986
1987 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1988 /// should be used with extreme care: declspecs can often be shared between
1989 /// multiple declarators, so mutating the DeclSpec affects all of the
1990 /// Declarators. This should only be done when the declspec is known to not
1991 /// be shared or when in error recovery etc.
1992 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1993
1994 AttributePool &getAttributePool() const {
1995 return Attrs.getPool();
1996 }
1997
1998 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1999 /// nested-name-specifier) that is part of the declarator-id.
2000 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
2001 CXXScopeSpec &getCXXScopeSpec() { return SS; }
2002
2003 /// Retrieve the name specified by this declarator.
2004 UnqualifiedId &getName() { return Name; }
2005
2006 const DecompositionDeclarator &getDecompositionDeclarator() const {
2007 return BindingGroup;
2008 }
2009
2010 DeclaratorContext getContext() const { return Context; }
2011
2012 bool isPrototypeContext() const {
2013 return (Context == DeclaratorContext::Prototype ||
2014 Context == DeclaratorContext::ObjCParameter ||
2015 Context == DeclaratorContext::ObjCResult ||
2016 Context == DeclaratorContext::LambdaExprParameter);
2017 }
2018
2019 /// Get the source range that spans this declarator.
2020 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
2021 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
2022 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
2023
2024 void SetSourceRange(SourceRange R) { Range = R; }
2025 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
2026 /// invalid.
2027 void SetRangeBegin(SourceLocation Loc) {
2028 if (!Loc.isInvalid())
2029 Range.setBegin(Loc);
2030 }
2031 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
2032 void SetRangeEnd(SourceLocation Loc) {
2033 if (!Loc.isInvalid())
2034 Range.setEnd(Loc);
2035 }
2036 /// ExtendWithDeclSpec - Extend the declarator source range to include the
2037 /// given declspec, unless its location is invalid. Adopts the range start if
2038 /// the current range start is invalid.
2039 void ExtendWithDeclSpec(const DeclSpec &DS) {
2040 SourceRange SR = DS.getSourceRange();
2041 if (Range.getBegin().isInvalid())
2042 Range.setBegin(SR.getBegin());
2043 if (!SR.getEnd().isInvalid())
2044 Range.setEnd(SR.getEnd());
2045 }
2046
2047 /// Reset the contents of this Declarator.
2048 void clear() {
2049 SS.clear();
2050 Name.clear();
2051 Range = DS.getSourceRange();
2052 BindingGroup.clear();
2053
2054 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
2055 DeclTypeInfo[i].destroy();
2056 DeclTypeInfo.clear();
2057 Attrs.clear();
2058 AsmLabel = nullptr;
2059 InlineStorageUsed = false;
2060 HasInitializer = false;
2061 ObjCIvar = false;
2062 ObjCWeakProperty = false;
2063 CommaLoc = SourceLocation();
2064 EllipsisLoc = SourceLocation();
2065 }
2066
2067 /// mayOmitIdentifier - Return true if the identifier is either optional or
2068 /// not allowed. This is true for typenames, prototypes, and template
2069 /// parameter lists.
2070 bool mayOmitIdentifier() const {
2071 switch (Context) {
2072 case DeclaratorContext::File:
2073 case DeclaratorContext::KNRTypeList:
2074 case DeclaratorContext::Member:
2075 case DeclaratorContext::Block:
2076 case DeclaratorContext::ForInit:
2077 case DeclaratorContext::SelectionInit:
2078 case DeclaratorContext::Condition:
2079 return false;
2080
2081 case DeclaratorContext::TypeName:
2082 case DeclaratorContext::FunctionalCast:
2083 case DeclaratorContext::AliasDecl:
2084 case DeclaratorContext::AliasTemplate:
2085 case DeclaratorContext::Prototype:
2086 case DeclaratorContext::LambdaExprParameter:
2087 case DeclaratorContext::ObjCParameter:
2088 case DeclaratorContext::ObjCResult:
2089 case DeclaratorContext::TemplateParam:
2090 case DeclaratorContext::CXXNew:
2091 case DeclaratorContext::CXXCatch:
2092 case DeclaratorContext::ObjCCatch:
2093 case DeclaratorContext::BlockLiteral:
2094 case DeclaratorContext::LambdaExpr:
2095 case DeclaratorContext::ConversionId:
2096 case DeclaratorContext::TemplateArg:
2097 case DeclaratorContext::TemplateTypeArg:
2098 case DeclaratorContext::TrailingReturn:
2099 case DeclaratorContext::TrailingReturnVar:
2100 case DeclaratorContext::RequiresExpr:
2101 case DeclaratorContext::Association:
2102 return true;
2103 }
2104 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h"
, 2104)
;
2105 }
2106
2107 /// mayHaveIdentifier - Return true if the identifier is either optional or
2108 /// required. This is true for normal declarators and prototypes, but not
2109 /// typenames.
2110 bool mayHaveIdentifier() const {
2111 switch (Context) {
2112 case DeclaratorContext::File:
2113 case DeclaratorContext::KNRTypeList:
2114 case DeclaratorContext::Member:
2115 case DeclaratorContext::Block:
2116 case DeclaratorContext::ForInit:
2117 case DeclaratorContext::SelectionInit:
2118 case DeclaratorContext::Condition:
2119 case DeclaratorContext::Prototype:
2120 case DeclaratorContext::LambdaExprParameter:
2121 case DeclaratorContext::TemplateParam:
2122 case DeclaratorContext::CXXCatch:
2123 case DeclaratorContext::ObjCCatch:
2124 case DeclaratorContext::RequiresExpr:
2125 return true;
2126
2127 case DeclaratorContext::TypeName:
2128 case DeclaratorContext::FunctionalCast:
2129 case DeclaratorContext::CXXNew:
2130 case DeclaratorContext::AliasDecl:
2131 case DeclaratorContext::AliasTemplate:
2132 case DeclaratorContext::ObjCParameter:
2133 case DeclaratorContext::ObjCResult:
2134 case DeclaratorContext::BlockLiteral:
2135 case DeclaratorContext::LambdaExpr:
2136 case DeclaratorContext::ConversionId:
2137 case DeclaratorContext::TemplateArg:
2138 case DeclaratorContext::TemplateTypeArg:
2139 case DeclaratorContext::TrailingReturn:
2140 case DeclaratorContext::TrailingReturnVar:
2141 case DeclaratorContext::Association:
2142 return false;
2143 }
2144 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h"
, 2144)
;
2145 }
2146
2147 /// Return true if the context permits a C++17 decomposition declarator.
2148 bool mayHaveDecompositionDeclarator() const {
2149 switch (Context) {
2150 case DeclaratorContext::File:
2151 // FIXME: It's not clear that the proposal meant to allow file-scope
2152 // structured bindings, but it does.
2153 case DeclaratorContext::Block:
2154 case DeclaratorContext::ForInit:
2155 case DeclaratorContext::SelectionInit:
2156 case DeclaratorContext::Condition:
2157 return true;
2158
2159 case DeclaratorContext::Member:
2160 case DeclaratorContext::Prototype:
2161 case DeclaratorContext::TemplateParam:
2162 case DeclaratorContext::RequiresExpr:
2163 // Maybe one day...
2164 return false;
2165
2166 // These contexts don't allow any kind of non-abstract declarator.
2167 case DeclaratorContext::KNRTypeList:
2168 case DeclaratorContext::TypeName:
2169 case DeclaratorContext::FunctionalCast:
2170 case DeclaratorContext::AliasDecl:
2171 case DeclaratorContext::AliasTemplate:
2172 case DeclaratorContext::LambdaExprParameter:
2173 case DeclaratorContext::ObjCParameter:
2174 case DeclaratorContext::ObjCResult:
2175 case DeclaratorContext::CXXNew:
2176 case DeclaratorContext::CXXCatch:
2177 case DeclaratorContext::ObjCCatch:
2178 case DeclaratorContext::BlockLiteral:
2179 case DeclaratorContext::LambdaExpr:
2180 case DeclaratorContext::ConversionId:
2181 case DeclaratorContext::TemplateArg:
2182 case DeclaratorContext::TemplateTypeArg:
2183 case DeclaratorContext::TrailingReturn:
2184 case DeclaratorContext::TrailingReturnVar:
2185 case DeclaratorContext::Association:
2186 return false;
2187 }
2188 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h"
, 2188)
;
2189 }
2190
2191 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2192 /// followed by a C++ direct initializer, e.g. "int x(1);".
2193 bool mayBeFollowedByCXXDirectInit() const {
2194 if (hasGroupingParens()) return false;
2195
2196 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2197 return false;
2198
2199 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2200 Context != DeclaratorContext::File)
2201 return false;
2202
2203 // Special names can't have direct initializers.
2204 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2205 return false;
2206
2207 switch (Context) {
2208 case DeclaratorContext::File:
2209 case DeclaratorContext::Block:
2210 case DeclaratorContext::ForInit:
2211 case DeclaratorContext::SelectionInit:
2212 case DeclaratorContext::TrailingReturnVar:
2213 return true;
2214
2215 case DeclaratorContext::Condition:
2216 // This may not be followed by a direct initializer, but it can't be a
2217 // function declaration either, and we'd prefer to perform a tentative
2218 // parse in order to produce the right diagnostic.
2219 return true;
2220
2221 case DeclaratorContext::KNRTypeList:
2222 case DeclaratorContext::Member:
2223 case DeclaratorContext::Prototype:
2224 case DeclaratorContext::LambdaExprParameter:
2225 case DeclaratorContext::ObjCParameter:
2226 case DeclaratorContext::ObjCResult:
2227 case DeclaratorContext::TemplateParam:
2228 case DeclaratorContext::CXXCatch:
2229 case DeclaratorContext::ObjCCatch:
2230 case DeclaratorContext::TypeName:
2231 case DeclaratorContext::FunctionalCast: // FIXME
2232 case DeclaratorContext::CXXNew:
2233 case DeclaratorContext::AliasDecl:
2234 case DeclaratorContext::AliasTemplate:
2235 case DeclaratorContext::BlockLiteral:
2236 case DeclaratorContext::LambdaExpr:
2237 case DeclaratorContext::ConversionId:
2238 case DeclaratorContext::TemplateArg:
2239 case DeclaratorContext::TemplateTypeArg:
2240 case DeclaratorContext::TrailingReturn:
2241 case DeclaratorContext::RequiresExpr:
2242 case DeclaratorContext::Association:
2243 return false;
2244 }
2245 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h"
, 2245)
;
2246 }
2247
2248 /// isPastIdentifier - Return true if we have parsed beyond the point where
2249 /// the name would appear. (This may happen even if we haven't actually parsed
2250 /// a name, perhaps because this context doesn't require one.)
2251 bool isPastIdentifier() const { return Name.isValid(); }
2252
2253 /// hasName - Whether this declarator has a name, which might be an
2254 /// identifier (accessible via getIdentifier()) or some kind of
2255 /// special C++ name (constructor, destructor, etc.), or a structured
2256 /// binding (which is not exactly a name, but occupies the same position).
2257 bool hasName() const {
2258 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2259 Name.Identifier || isDecompositionDeclarator();
2260 }
2261
2262 /// Return whether this declarator is a decomposition declarator.
2263 bool isDecompositionDeclarator() const {
2264 return BindingGroup.isSet();
2265 }
2266
2267 IdentifierInfo *getIdentifier() const {
2268 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2269 return Name.Identifier;
2270
2271 return nullptr;
2272 }
2273 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2274
2275 /// Set the name of this declarator to be the given identifier.
2276 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2277 Name.setIdentifier(Id, IdLoc);
2278 }
2279
2280 /// Set the decomposition bindings for this declarator.
2281 void
2282 setDecompositionBindings(SourceLocation LSquareLoc,
2283 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2284 SourceLocation RSquareLoc);
2285
2286 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2287 /// EndLoc, which should be the last token of the chunk.
2288 /// This function takes attrs by R-Value reference because it takes ownership
2289 /// of those attributes from the parameter.
2290 void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2291 SourceLocation EndLoc) {
2292 DeclTypeInfo.push_back(TI);
2293 DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2294 getAttributePool().takeAllFrom(attrs.getPool());
2295
2296 if (!EndLoc.isInvalid())
2297 SetRangeEnd(EndLoc);
2298 }
2299
2300 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2301 /// EndLoc, which should be the last token of the chunk.
2302 void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2303 DeclTypeInfo.push_back(TI);
2304
2305 if (!EndLoc.isInvalid())
2306 SetRangeEnd(EndLoc);
2307 }
2308
2309 /// Add a new innermost chunk to this declarator.
2310 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2311 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2312 }
2313
2314 /// Return the number of types applied to this declarator.
2315 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2316
2317 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2318 /// closest to the identifier.
2319 const DeclaratorChunk &getTypeObject(unsigned i) const {
2320 assert(i < DeclTypeInfo.size() && "Invalid type chunk")(static_cast <bool> (i < DeclTypeInfo.size() &&
"Invalid type chunk") ? void (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "clang/include/clang/Sema/DeclSpec.h", 2320, __extension__ __PRETTY_FUNCTION__
))
;
2321 return DeclTypeInfo[i];
2322 }
2323 DeclaratorChunk &getTypeObject(unsigned i) {
2324 assert(i < DeclTypeInfo.size() && "Invalid type chunk")(static_cast <bool> (i < DeclTypeInfo.size() &&
"Invalid type chunk") ? void (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "clang/include/clang/Sema/DeclSpec.h", 2324, __extension__ __PRETTY_FUNCTION__
))
;
2325 return DeclTypeInfo[i];
2326 }
2327
2328 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2329 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2330
2331 /// Returns the range of type objects, from the identifier outwards.
2332 type_object_range type_objects() const {
2333 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2334 }
2335
2336 void DropFirstTypeObject() {
2337 assert(!DeclTypeInfo.empty() && "No type chunks to drop.")(static_cast <bool> (!DeclTypeInfo.empty() && "No type chunks to drop."
) ? void (0) : __assert_fail ("!DeclTypeInfo.empty() && \"No type chunks to drop.\""
, "clang/include/clang/Sema/DeclSpec.h", 2337, __extension__ __PRETTY_FUNCTION__
))
;
2338 DeclTypeInfo.front().destroy();
2339 DeclTypeInfo.erase(DeclTypeInfo.begin());
2340 }
2341
2342 /// Return the innermost (closest to the declarator) chunk of this
2343 /// declarator that is not a parens chunk, or null if there are no
2344 /// non-parens chunks.
2345 const DeclaratorChunk *getInnermostNonParenChunk() const {
2346 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2347 if (!DeclTypeInfo[i].isParen())
2348 return &DeclTypeInfo[i];
2349 }
2350 return nullptr;
2351 }
2352
2353 /// Return the outermost (furthest from the declarator) chunk of
2354 /// this declarator that is not a parens chunk, or null if there are
2355 /// no non-parens chunks.
2356 const DeclaratorChunk *getOutermostNonParenChunk() const {
2357 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2358 if (!DeclTypeInfo[i-1].isParen())
2359 return &DeclTypeInfo[i-1];
2360 }
2361 return nullptr;
2362 }
2363
2364 /// isArrayOfUnknownBound - This method returns true if the declarator
2365 /// is a declarator for an array of unknown bound (looking through
2366 /// parentheses).
2367 bool isArrayOfUnknownBound() const {
2368 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2369 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2370 !chunk->Arr.NumElts);
2371 }
2372
2373 /// isFunctionDeclarator - This method returns true if the declarator
2374 /// is a function declarator (looking through parentheses).
2375 /// If true is returned, then the reference type parameter idx is
2376 /// assigned with the index of the declaration chunk.
2377 bool isFunctionDeclarator(unsigned& idx) const {
2378 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i
4.1
'i' is < 'i_end'
4.1
'i' is < 'i_end'
< i_end; ++i) {
5
Loop condition is true. Entering loop body
2379 switch (DeclTypeInfo[i].Kind) {
6
Control jumps to 'case Pipe:' at line 2390
2380 case DeclaratorChunk::Function:
2381 idx = i;
2382 return true;
2383 case DeclaratorChunk::Paren:
2384 continue;
2385 case DeclaratorChunk::Pointer:
2386 case DeclaratorChunk::Reference:
2387 case DeclaratorChunk::Array:
2388 case DeclaratorChunk::BlockPointer:
2389 case DeclaratorChunk::MemberPointer:
2390 case DeclaratorChunk::Pipe:
2391 return false;
7
Returning without writing to 'idx'
2392 }
2393 llvm_unreachable("Invalid type chunk")::llvm::llvm_unreachable_internal("Invalid type chunk", "clang/include/clang/Sema/DeclSpec.h"
, 2393)
;
2394 }
2395 return false;
2396 }
2397
2398 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2399 /// this method returns true if the identifier is a function declarator
2400 /// (looking through parentheses).
2401 bool isFunctionDeclarator() const {
2402 unsigned index;
2403 return isFunctionDeclarator(index);
2404 }
2405
2406 /// getFunctionTypeInfo - Retrieves the function type info object
2407 /// (looking through parentheses).
2408 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2409 assert(isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (isFunctionDeclarator() && "Not a function declarator!"
) ? void (0) : __assert_fail ("isFunctionDeclarator() && \"Not a function declarator!\""
, "clang/include/clang/Sema/DeclSpec.h", 2409, __extension__ __PRETTY_FUNCTION__
))
;
2410 unsigned index = 0;
2411 isFunctionDeclarator(index);
2412 return DeclTypeInfo[index].Fun;
2413 }
2414
2415 /// getFunctionTypeInfo - Retrieves the function type info object
2416 /// (looking through parentheses).
2417 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2418 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2419 }
2420
2421 /// Determine whether the declaration that will be produced from
2422 /// this declaration will be a function.
2423 ///
2424 /// A declaration can declare a function even if the declarator itself
2425 /// isn't a function declarator, if the type specifier refers to a function
2426 /// type. This routine checks for both cases.
2427 bool isDeclarationOfFunction() const;
2428
2429 /// Return true if this declaration appears in a context where a
2430 /// function declarator would be a function declaration.
2431 bool isFunctionDeclarationContext() const {
2432 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2433 return false;
2434
2435 switch (Context) {
2436 case DeclaratorContext::File:
2437 case DeclaratorContext::Member:
2438 case DeclaratorContext::Block:
2439 case DeclaratorContext::ForInit:
2440 case DeclaratorContext::SelectionInit:
2441 return true;
2442
2443 case DeclaratorContext::Condition:
2444 case DeclaratorContext::KNRTypeList:
2445 case DeclaratorContext::TypeName:
2446 case DeclaratorContext::FunctionalCast:
2447 case DeclaratorContext::AliasDecl:
2448 case DeclaratorContext::AliasTemplate:
2449 case DeclaratorContext::Prototype:
2450 case DeclaratorContext::LambdaExprParameter:
2451 case DeclaratorContext::ObjCParameter:
2452 case DeclaratorContext::ObjCResult:
2453 case DeclaratorContext::TemplateParam:
2454 case DeclaratorContext::CXXNew:
2455 case DeclaratorContext::CXXCatch:
2456 case DeclaratorContext::ObjCCatch:
2457 case DeclaratorContext::BlockLiteral:
2458 case DeclaratorContext::LambdaExpr:
2459 case DeclaratorContext::ConversionId:
2460 case DeclaratorContext::TemplateArg:
2461 case DeclaratorContext::TemplateTypeArg:
2462 case DeclaratorContext::TrailingReturn:
2463 case DeclaratorContext::TrailingReturnVar:
2464 case DeclaratorContext::RequiresExpr:
2465 case DeclaratorContext::Association:
2466 return false;
2467 }
2468 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h"
, 2468)
;
2469 }
2470
2471 /// Determine whether this declaration appears in a context where an
2472 /// expression could appear.
2473 bool isExpressionContext() const {
2474 switch (Context) {
2475 case DeclaratorContext::File:
2476 case DeclaratorContext::KNRTypeList:
2477 case DeclaratorContext::Member:
2478
2479 // FIXME: sizeof(...) permits an expression.
2480 case DeclaratorContext::TypeName:
2481
2482 case DeclaratorContext::FunctionalCast:
2483 case DeclaratorContext::AliasDecl:
2484 case DeclaratorContext::AliasTemplate:
2485 case DeclaratorContext::Prototype:
2486 case DeclaratorContext::LambdaExprParameter:
2487 case DeclaratorContext::ObjCParameter:
2488 case DeclaratorContext::ObjCResult:
2489 case DeclaratorContext::TemplateParam:
2490 case DeclaratorContext::CXXNew:
2491 case DeclaratorContext::CXXCatch:
2492 case DeclaratorContext::ObjCCatch:
2493 case DeclaratorContext::BlockLiteral:
2494 case DeclaratorContext::LambdaExpr:
2495 case DeclaratorContext::ConversionId:
2496 case DeclaratorContext::TrailingReturn:
2497 case DeclaratorContext::TrailingReturnVar:
2498 case DeclaratorContext::TemplateTypeArg:
2499 case DeclaratorContext::RequiresExpr:
2500 case DeclaratorContext::Association:
2501 return false;
2502
2503 case DeclaratorContext::Block:
2504 case DeclaratorContext::ForInit:
2505 case DeclaratorContext::SelectionInit:
2506 case DeclaratorContext::Condition:
2507 case DeclaratorContext::TemplateArg:
2508 return true;
2509 }
2510
2511 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h"
, 2511)
;
2512 }
2513
2514 /// Return true if a function declarator at this position would be a
2515 /// function declaration.
2516 bool isFunctionDeclaratorAFunctionDeclaration() const {
2517 if (!isFunctionDeclarationContext())
2518 return false;
2519
2520 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2521 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2522 return false;
2523
2524 return true;
2525 }
2526
2527 /// Determine whether a trailing return type was written (at any
2528 /// level) within this declarator.
2529 bool hasTrailingReturnType() const {
2530 for (const auto &Chunk : type_objects())
2531 if (Chunk.Kind == DeclaratorChunk::Function &&
2532 Chunk.Fun.hasTrailingReturnType())
2533 return true;
2534 return false;
2535 }
2536 /// Get the trailing return type appearing (at any level) within this
2537 /// declarator.
2538 ParsedType getTrailingReturnType() const {
2539 for (const auto &Chunk : type_objects())
2540 if (Chunk.Kind == DeclaratorChunk::Function &&
2541 Chunk.Fun.hasTrailingReturnType())
2542 return Chunk.Fun.getTrailingReturnType();
2543 return ParsedType();
2544 }
2545
2546 /// \brief Sets a trailing requires clause for this declarator.
2547 void setTrailingRequiresClause(Expr *TRC) {
2548 TrailingRequiresClause = TRC;
2549
2550 SetRangeEnd(TRC->getEndLoc());
2551 }
2552
2553 /// \brief Sets a trailing requires clause for this declarator.
2554 Expr *getTrailingRequiresClause() {
2555 return TrailingRequiresClause;
2556 }
2557
2558 /// \brief Determine whether a trailing requires clause was written in this
2559 /// declarator.
2560 bool hasTrailingRequiresClause() const {
2561 return TrailingRequiresClause != nullptr;
2562 }
2563
2564 /// Sets the template parameter lists that preceded the declarator.
2565 void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) {
2566 TemplateParameterLists = TPLs;
2567 }
2568
2569 /// The template parameter lists that preceded the declarator.
2570 ArrayRef<TemplateParameterList *> getTemplateParameterLists() const {
2571 return TemplateParameterLists;
2572 }
2573
2574 /// Sets the template parameter list generated from the explicit template
2575 /// parameters along with any invented template parameters from
2576 /// placeholder-typed parameters.
2577 void setInventedTemplateParameterList(TemplateParameterList *Invented) {
2578 InventedTemplateParameterList = Invented;
2579 }
2580
2581 /// The template parameter list generated from the explicit template
2582 /// parameters along with any invented template parameters from
2583 /// placeholder-typed parameters, if there were any such parameters.
2584 TemplateParameterList * getInventedTemplateParameterList() const {
2585 return InventedTemplateParameterList;
2586 }
2587
2588 /// takeAttributes - Takes attributes from the given parsed-attributes
2589 /// set and add them to this declarator.
2590 ///
2591 /// These examples both add 3 attributes to "var":
2592 /// short int var __attribute__((aligned(16),common,deprecated));
2593 /// short int x, __attribute__((aligned(16)) var
2594 /// __attribute__((common,deprecated));
2595 ///
2596 /// Also extends the range of the declarator.
2597 void takeAttributes(ParsedAttributes &attrs) {
2598 Attrs.takeAllFrom(attrs);
2599
2600 if (attrs.Range.getEnd().isValid())
2601 SetRangeEnd(attrs.Range.getEnd());
2602 }
2603
2604 const ParsedAttributes &getAttributes() const { return Attrs; }
2605 ParsedAttributes &getAttributes() { return Attrs; }
2606
2607 const ParsedAttributesView &getDeclarationAttributes() const {
2608 return DeclarationAttrs;
2609 }
2610
2611 /// hasAttributes - do we contain any attributes?
2612 bool hasAttributes() const {
2613 if (!getAttributes().empty() || !getDeclarationAttributes().empty() ||
2614 getDeclSpec().hasAttributes())
2615 return true;
2616 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2617 if (!getTypeObject(i).getAttrs().empty())
2618 return true;
2619 return false;
2620 }
2621
2622 /// Return a source range list of C++11 attributes associated
2623 /// with the declarator.
2624 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2625 for (const ParsedAttr &AL : Attrs)
2626 if (AL.isCXX11Attribute())
2627 Ranges.push_back(AL.getRange());
2628 }
2629
2630 void setAsmLabel(Expr *E) { AsmLabel = E; }
2631 Expr *getAsmLabel() const { return AsmLabel; }
2632
2633 void setExtension(bool Val = true) { Extension = Val; }
2634 bool getExtension() const { return Extension; }
2635
2636 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2637 bool isObjCIvar() const { return ObjCIvar; }
2638
2639 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2640 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2641
2642 void setInvalidType(bool Val = true) { InvalidType = Val; }
2643 bool isInvalidType() const {
2644 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2645 }
2646
2647 void setGroupingParens(bool flag) { GroupingParens = flag; }
2648 bool hasGroupingParens() const { return GroupingParens; }
2649
2650 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2651 SourceLocation getCommaLoc() const { return CommaLoc; }
2652 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2653
2654 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2655 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2656 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2657
2658 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2659 FunctionDefinition = static_cast<unsigned>(Val);
2660 }
2661
2662 bool isFunctionDefinition() const {
2663 return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration;
2664 }
2665
2666 FunctionDefinitionKind getFunctionDefinitionKind() const {
2667 return (FunctionDefinitionKind)FunctionDefinition;
2668 }
2669
2670 void setHasInitializer(bool Val = true) { HasInitializer = Val; }
2671 bool hasInitializer() const { return HasInitializer; }
2672
2673 /// Returns true if this declares a real member and not a friend.
2674 bool isFirstDeclarationOfMember() {
2675 return getContext() == DeclaratorContext::Member &&
2676 !getDeclSpec().isFriendSpecified();
2677 }
2678
2679 /// Returns true if this declares a static member. This cannot be called on a
2680 /// declarator outside of a MemberContext because we won't know until
2681 /// redeclaration time if the decl is static.
2682 bool isStaticMember();
2683
2684 /// Returns true if this declares a constructor or a destructor.
2685 bool isCtorOrDtor();
2686
2687 void setRedeclaration(bool Val) { Redeclaration = Val; }
2688 bool isRedeclaration() const { return Redeclaration; }
2689};
2690
2691/// This little struct is used to capture information about
2692/// structure field declarators, which is basically just a bitfield size.
2693struct FieldDeclarator {
2694 Declarator D;
2695 Expr *BitfieldSize;
2696 explicit FieldDeclarator(const DeclSpec &DS,
2697 const ParsedAttributes &DeclarationAttrs)
2698 : D(DS, DeclarationAttrs, DeclaratorContext::Member),
2699 BitfieldSize(nullptr) {}
2700};
2701
2702/// Represents a C++11 virt-specifier-seq.
2703class VirtSpecifiers {
2704public:
2705 enum Specifier {
2706 VS_None = 0,
2707 VS_Override = 1,
2708 VS_Final = 2,
2709 VS_Sealed = 4,
2710 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2711 VS_GNU_Final = 8,
2712 VS_Abstract = 16
2713 };
2714
2715 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2716
2717 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2718 const char *&PrevSpec);
2719
2720 bool isUnset() const { return Specifiers == 0; }
2721
2722 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2723 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2724
2725 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2726 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2727 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2728 SourceLocation getAbstractLoc() const { return VS_abstractLoc; }
2729
2730 void clear() { Specifiers = 0; }
2731
2732 static const char *getSpecifierName(Specifier VS);
2733
2734 SourceLocation getFirstLocation() const { return FirstLocation; }
2735 SourceLocation getLastLocation() const { return LastLocation; }
2736 Specifier getLastSpecifier() const { return LastSpecifier; }
2737
2738private:
2739 unsigned Specifiers;
2740 Specifier LastSpecifier;
2741
2742 SourceLocation VS_overrideLoc, VS_finalLoc, VS_abstractLoc;
2743 SourceLocation FirstLocation;
2744 SourceLocation LastLocation;
2745};
2746
2747enum class LambdaCaptureInitKind {
2748 NoInit, //!< [a]
2749 CopyInit, //!< [a = b], [a = {b}]
2750 DirectInit, //!< [a(b)]
2751 ListInit //!< [a{b}]
2752};
2753
2754/// Represents a complete lambda introducer.
2755struct LambdaIntroducer {
2756 /// An individual capture in a lambda introducer.
2757 struct LambdaCapture {
2758 LambdaCaptureKind Kind;
2759 SourceLocation Loc;
2760 IdentifierInfo *Id;
2761 SourceLocation EllipsisLoc;
2762 LambdaCaptureInitKind InitKind;
2763 ExprResult Init;
2764 ParsedType InitCaptureType;
2765 SourceRange ExplicitRange;
2766
2767 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2768 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2769 LambdaCaptureInitKind InitKind, ExprResult Init,
2770 ParsedType InitCaptureType,
2771 SourceRange ExplicitRange)
2772 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2773 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2774 ExplicitRange(ExplicitRange) {}
2775 };
2776
2777 SourceRange Range;
2778 SourceLocation DefaultLoc;
2779 LambdaCaptureDefault Default;
2780 SmallVector<LambdaCapture, 4> Captures;
2781
2782 LambdaIntroducer()
2783 : Default(LCD_None) {}
2784
2785 bool hasLambdaCapture() const {
2786 return Captures.size() > 0 || Default != LCD_None;
2787 }
2788
2789 /// Append a capture in a lambda introducer.
2790 void addCapture(LambdaCaptureKind Kind,
2791 SourceLocation Loc,
2792 IdentifierInfo* Id,
2793 SourceLocation EllipsisLoc,
2794 LambdaCaptureInitKind InitKind,
2795 ExprResult Init,
2796 ParsedType InitCaptureType,
2797 SourceRange ExplicitRange) {
2798 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2799 InitCaptureType, ExplicitRange));
2800 }
2801};
2802
2803struct InventedTemplateParameterInfo {
2804 /// The number of parameters in the template parameter list that were
2805 /// explicitly specified by the user, as opposed to being invented by use
2806 /// of an auto parameter.
2807 unsigned NumExplicitTemplateParams = 0;
2808
2809 /// If this is a generic lambda or abbreviated function template, use this
2810 /// as the depth of each 'auto' parameter, during initial AST construction.
2811 unsigned AutoTemplateParameterDepth = 0;
2812
2813 /// Store the list of the template parameters for a generic lambda or an
2814 /// abbreviated function template.
2815 /// If this is a generic lambda or abbreviated function template, this holds
2816 /// the explicit template parameters followed by the auto parameters
2817 /// converted into TemplateTypeParmDecls.
2818 /// It can be used to construct the generic lambda or abbreviated template's
2819 /// template parameter list during initial AST construction.
2820 SmallVector<NamedDecl*, 4> TemplateParams;
2821};
2822
2823} // end namespace clang
2824
2825#endif // LLVM_CLANG_SEMA_DECLSPEC_H