Bug Summary

File:build/source/clang/lib/Sema/SemaLambda.cpp
Warning:line 1241, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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