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