Bug Summary

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

/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