1*67e74705SXin Li //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements semantic analysis for C++ lambda expressions.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
14*67e74705SXin Li #include "TypeLocBuilder.h"
15*67e74705SXin Li #include "clang/AST/ASTLambda.h"
16*67e74705SXin Li #include "clang/AST/ExprCXX.h"
17*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
18*67e74705SXin Li #include "clang/Sema/Initialization.h"
19*67e74705SXin Li #include "clang/Sema/Lookup.h"
20*67e74705SXin Li #include "clang/Sema/Scope.h"
21*67e74705SXin Li #include "clang/Sema/ScopeInfo.h"
22*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
23*67e74705SXin Li #include "clang/Sema/SemaLambda.h"
24*67e74705SXin Li using namespace clang;
25*67e74705SXin Li using namespace sema;
26*67e74705SXin Li
27*67e74705SXin Li /// \brief Examines the FunctionScopeInfo stack to determine the nearest
28*67e74705SXin Li /// enclosing lambda (to the current lambda) that is 'capture-ready' for
29*67e74705SXin Li /// the variable referenced in the current lambda (i.e. \p VarToCapture).
30*67e74705SXin Li /// If successful, returns the index into Sema's FunctionScopeInfo stack
31*67e74705SXin Li /// of the capture-ready lambda's LambdaScopeInfo.
32*67e74705SXin Li ///
33*67e74705SXin Li /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34*67e74705SXin Li /// lambda - is on top) to determine the index of the nearest enclosing/outer
35*67e74705SXin Li /// lambda that is ready to capture the \p VarToCapture being referenced in
36*67e74705SXin Li /// the current lambda.
37*67e74705SXin Li /// As we climb down the stack, we want the index of the first such lambda -
38*67e74705SXin Li /// that is the lambda with the highest index that is 'capture-ready'.
39*67e74705SXin Li ///
40*67e74705SXin Li /// A lambda 'L' is capture-ready for 'V' (var or this) if:
41*67e74705SXin Li /// - its enclosing context is non-dependent
42*67e74705SXin Li /// - and if the chain of lambdas between L and the lambda in which
43*67e74705SXin Li /// V is potentially used (i.e. the lambda at the top of the scope info
44*67e74705SXin Li /// stack), can all capture or have already captured V.
45*67e74705SXin Li /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46*67e74705SXin Li ///
47*67e74705SXin Li /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48*67e74705SXin Li /// for whether it is 'capture-capable' (see
49*67e74705SXin Li /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50*67e74705SXin Li /// capture.
51*67e74705SXin Li ///
52*67e74705SXin Li /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53*67e74705SXin Li /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
54*67e74705SXin Li /// is at the top of the stack and has the highest index.
55*67e74705SXin Li /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
56*67e74705SXin Li ///
57*67e74705SXin Li /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58*67e74705SXin Li /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59*67e74705SXin Li /// which is capture-ready. If the return value evaluates to 'false' then
60*67e74705SXin Li /// no lambda is capture-ready for \p VarToCapture.
61*67e74705SXin Li
62*67e74705SXin Li static inline Optional<unsigned>
getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef<const clang::sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture)63*67e74705SXin Li getStackIndexOfNearestEnclosingCaptureReadyLambda(
64*67e74705SXin Li ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65*67e74705SXin Li VarDecl *VarToCapture) {
66*67e74705SXin Li // Label failure to capture.
67*67e74705SXin Li const Optional<unsigned> NoLambdaIsCaptureReady;
68*67e74705SXin Li
69*67e74705SXin Li assert(
70*67e74705SXin Li isa<clang::sema::LambdaScopeInfo>(
71*67e74705SXin Li FunctionScopes[FunctionScopes.size() - 1]) &&
72*67e74705SXin Li "The function on the top of sema's function-info stack must be a lambda");
73*67e74705SXin Li
74*67e74705SXin Li // If VarToCapture is null, we are attempting to capture 'this'.
75*67e74705SXin Li const bool IsCapturingThis = !VarToCapture;
76*67e74705SXin Li const bool IsCapturingVariable = !IsCapturingThis;
77*67e74705SXin Li
78*67e74705SXin Li // Start with the current lambda at the top of the stack (highest index).
79*67e74705SXin Li unsigned CurScopeIndex = FunctionScopes.size() - 1;
80*67e74705SXin Li DeclContext *EnclosingDC =
81*67e74705SXin Li cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
82*67e74705SXin Li
83*67e74705SXin Li do {
84*67e74705SXin Li const clang::sema::LambdaScopeInfo *LSI =
85*67e74705SXin Li cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
86*67e74705SXin Li // IF we have climbed down to an intervening enclosing lambda that contains
87*67e74705SXin Li // the variable declaration - it obviously can/must not capture the
88*67e74705SXin Li // variable.
89*67e74705SXin Li // Since its enclosing DC is dependent, all the lambdas between it and the
90*67e74705SXin Li // innermost nested lambda are dependent (otherwise we wouldn't have
91*67e74705SXin Li // arrived here) - so we don't yet have a lambda that can capture the
92*67e74705SXin Li // variable.
93*67e74705SXin Li if (IsCapturingVariable &&
94*67e74705SXin Li VarToCapture->getDeclContext()->Equals(EnclosingDC))
95*67e74705SXin Li return NoLambdaIsCaptureReady;
96*67e74705SXin Li
97*67e74705SXin Li // For an enclosing lambda to be capture ready for an entity, all
98*67e74705SXin Li // intervening lambda's have to be able to capture that entity. If even
99*67e74705SXin Li // one of the intervening lambda's is not capable of capturing the entity
100*67e74705SXin Li // then no enclosing lambda can ever capture that entity.
101*67e74705SXin Li // For e.g.
102*67e74705SXin Li // const int x = 10;
103*67e74705SXin Li // [=](auto a) { #1
104*67e74705SXin Li // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
105*67e74705SXin Li // [=](auto c) { #3
106*67e74705SXin Li // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
107*67e74705SXin Li // }; }; };
108*67e74705SXin Li // If they do not have a default implicit capture, check to see
109*67e74705SXin Li // if the entity has already been explicitly captured.
110*67e74705SXin Li // If even a single dependent enclosing lambda lacks the capability
111*67e74705SXin Li // to ever capture this variable, there is no further enclosing
112*67e74705SXin Li // non-dependent lambda that can capture this variable.
113*67e74705SXin Li if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
114*67e74705SXin Li if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
115*67e74705SXin Li return NoLambdaIsCaptureReady;
116*67e74705SXin Li if (IsCapturingThis && !LSI->isCXXThisCaptured())
117*67e74705SXin Li return NoLambdaIsCaptureReady;
118*67e74705SXin Li }
119*67e74705SXin Li EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
120*67e74705SXin Li
121*67e74705SXin Li assert(CurScopeIndex);
122*67e74705SXin Li --CurScopeIndex;
123*67e74705SXin Li } while (!EnclosingDC->isTranslationUnit() &&
124*67e74705SXin Li EnclosingDC->isDependentContext() &&
125*67e74705SXin Li isLambdaCallOperator(EnclosingDC));
126*67e74705SXin Li
127*67e74705SXin Li assert(CurScopeIndex < (FunctionScopes.size() - 1));
128*67e74705SXin Li // If the enclosingDC is not dependent, then the immediately nested lambda
129*67e74705SXin Li // (one index above) is capture-ready.
130*67e74705SXin Li if (!EnclosingDC->isDependentContext())
131*67e74705SXin Li return CurScopeIndex + 1;
132*67e74705SXin Li return NoLambdaIsCaptureReady;
133*67e74705SXin Li }
134*67e74705SXin Li
135*67e74705SXin Li /// \brief Examines the FunctionScopeInfo stack to determine the nearest
136*67e74705SXin Li /// enclosing lambda (to the current lambda) that is 'capture-capable' for
137*67e74705SXin Li /// the variable referenced in the current lambda (i.e. \p VarToCapture).
138*67e74705SXin Li /// If successful, returns the index into Sema's FunctionScopeInfo stack
139*67e74705SXin Li /// of the capture-capable lambda's LambdaScopeInfo.
140*67e74705SXin Li ///
141*67e74705SXin Li /// Given the current stack of lambdas being processed by Sema and
142*67e74705SXin Li /// the variable of interest, to identify the nearest enclosing lambda (to the
143*67e74705SXin Li /// current lambda at the top of the stack) that can truly capture
144*67e74705SXin Li /// a variable, it has to have the following two properties:
145*67e74705SXin Li /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
146*67e74705SXin Li /// - climb down the stack (i.e. starting from the innermost and examining
147*67e74705SXin Li /// each outer lambda step by step) checking if each enclosing
148*67e74705SXin Li /// lambda can either implicitly or explicitly capture the variable.
149*67e74705SXin Li /// Record the first such lambda that is enclosed in a non-dependent
150*67e74705SXin Li /// context. If no such lambda currently exists return failure.
151*67e74705SXin Li /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
152*67e74705SXin Li /// capture the variable by checking all its enclosing lambdas:
153*67e74705SXin Li /// - check if all outer lambdas enclosing the 'capture-ready' lambda
154*67e74705SXin Li /// identified above in 'a' can also capture the variable (this is done
155*67e74705SXin Li /// via tryCaptureVariable for variables and CheckCXXThisCapture for
156*67e74705SXin Li /// 'this' by passing in the index of the Lambda identified in step 'a')
157*67e74705SXin Li ///
158*67e74705SXin Li /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
159*67e74705SXin Li /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
160*67e74705SXin Li /// is at the top of the stack.
161*67e74705SXin Li ///
162*67e74705SXin Li /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
163*67e74705SXin Li ///
164*67e74705SXin Li ///
165*67e74705SXin Li /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
166*67e74705SXin Li /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
167*67e74705SXin Li /// which is capture-capable. If the return value evaluates to 'false' then
168*67e74705SXin Li /// no lambda is capture-capable for \p VarToCapture.
169*67e74705SXin Li
getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef<const sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture,Sema & S)170*67e74705SXin Li Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
171*67e74705SXin Li ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
172*67e74705SXin Li VarDecl *VarToCapture, Sema &S) {
173*67e74705SXin Li
174*67e74705SXin Li const Optional<unsigned> NoLambdaIsCaptureCapable;
175*67e74705SXin Li
176*67e74705SXin Li const Optional<unsigned> OptionalStackIndex =
177*67e74705SXin Li getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
178*67e74705SXin Li VarToCapture);
179*67e74705SXin Li if (!OptionalStackIndex)
180*67e74705SXin Li return NoLambdaIsCaptureCapable;
181*67e74705SXin Li
182*67e74705SXin Li const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
183*67e74705SXin Li assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
184*67e74705SXin Li S.getCurGenericLambda()) &&
185*67e74705SXin Li "The capture ready lambda for a potential capture can only be the "
186*67e74705SXin Li "current lambda if it is a generic lambda");
187*67e74705SXin Li
188*67e74705SXin Li const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
189*67e74705SXin Li cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
190*67e74705SXin Li
191*67e74705SXin Li // If VarToCapture is null, we are attempting to capture 'this'
192*67e74705SXin Li const bool IsCapturingThis = !VarToCapture;
193*67e74705SXin Li const bool IsCapturingVariable = !IsCapturingThis;
194*67e74705SXin Li
195*67e74705SXin Li if (IsCapturingVariable) {
196*67e74705SXin Li // Check if the capture-ready lambda can truly capture the variable, by
197*67e74705SXin Li // checking whether all enclosing lambdas of the capture-ready lambda allow
198*67e74705SXin Li // the capture - i.e. make sure it is capture-capable.
199*67e74705SXin Li QualType CaptureType, DeclRefType;
200*67e74705SXin Li const bool CanCaptureVariable =
201*67e74705SXin Li !S.tryCaptureVariable(VarToCapture,
202*67e74705SXin Li /*ExprVarIsUsedInLoc*/ SourceLocation(),
203*67e74705SXin Li clang::Sema::TryCapture_Implicit,
204*67e74705SXin Li /*EllipsisLoc*/ SourceLocation(),
205*67e74705SXin Li /*BuildAndDiagnose*/ false, CaptureType,
206*67e74705SXin Li DeclRefType, &IndexOfCaptureReadyLambda);
207*67e74705SXin Li if (!CanCaptureVariable)
208*67e74705SXin Li return NoLambdaIsCaptureCapable;
209*67e74705SXin Li } else {
210*67e74705SXin Li // Check if the capture-ready lambda can truly capture 'this' by checking
211*67e74705SXin Li // whether all enclosing lambdas of the capture-ready lambda can capture
212*67e74705SXin Li // 'this'.
213*67e74705SXin Li const bool CanCaptureThis =
214*67e74705SXin Li !S.CheckCXXThisCapture(
215*67e74705SXin Li CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
216*67e74705SXin Li /*Explicit*/ false, /*BuildAndDiagnose*/ false,
217*67e74705SXin Li &IndexOfCaptureReadyLambda);
218*67e74705SXin Li if (!CanCaptureThis)
219*67e74705SXin Li return NoLambdaIsCaptureCapable;
220*67e74705SXin Li }
221*67e74705SXin Li return IndexOfCaptureReadyLambda;
222*67e74705SXin Li }
223*67e74705SXin Li
224*67e74705SXin Li static inline TemplateParameterList *
getGenericLambdaTemplateParameterList(LambdaScopeInfo * LSI,Sema & SemaRef)225*67e74705SXin Li getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
226*67e74705SXin Li if (LSI->GLTemplateParameterList)
227*67e74705SXin Li return LSI->GLTemplateParameterList;
228*67e74705SXin Li
229*67e74705SXin Li if (!LSI->AutoTemplateParams.empty()) {
230*67e74705SXin Li SourceRange IntroRange = LSI->IntroducerRange;
231*67e74705SXin Li SourceLocation LAngleLoc = IntroRange.getBegin();
232*67e74705SXin Li SourceLocation RAngleLoc = IntroRange.getEnd();
233*67e74705SXin Li LSI->GLTemplateParameterList = TemplateParameterList::Create(
234*67e74705SXin Li SemaRef.Context,
235*67e74705SXin Li /*Template kw loc*/ SourceLocation(), LAngleLoc,
236*67e74705SXin Li llvm::makeArrayRef((NamedDecl *const *)LSI->AutoTemplateParams.data(),
237*67e74705SXin Li LSI->AutoTemplateParams.size()),
238*67e74705SXin Li RAngleLoc);
239*67e74705SXin Li }
240*67e74705SXin Li return LSI->GLTemplateParameterList;
241*67e74705SXin Li }
242*67e74705SXin Li
createLambdaClosureType(SourceRange IntroducerRange,TypeSourceInfo * Info,bool KnownDependent,LambdaCaptureDefault CaptureDefault)243*67e74705SXin Li CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
244*67e74705SXin Li TypeSourceInfo *Info,
245*67e74705SXin Li bool KnownDependent,
246*67e74705SXin Li LambdaCaptureDefault CaptureDefault) {
247*67e74705SXin Li DeclContext *DC = CurContext;
248*67e74705SXin Li while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
249*67e74705SXin Li DC = DC->getParent();
250*67e74705SXin Li bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
251*67e74705SXin Li *this);
252*67e74705SXin Li // Start constructing the lambda class.
253*67e74705SXin Li CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
254*67e74705SXin Li IntroducerRange.getBegin(),
255*67e74705SXin Li KnownDependent,
256*67e74705SXin Li IsGenericLambda,
257*67e74705SXin Li CaptureDefault);
258*67e74705SXin Li DC->addDecl(Class);
259*67e74705SXin Li
260*67e74705SXin Li return Class;
261*67e74705SXin Li }
262*67e74705SXin Li
263*67e74705SXin Li /// \brief Determine whether the given context is or is enclosed in an inline
264*67e74705SXin Li /// function.
isInInlineFunction(const DeclContext * DC)265*67e74705SXin Li static bool isInInlineFunction(const DeclContext *DC) {
266*67e74705SXin Li while (!DC->isFileContext()) {
267*67e74705SXin Li if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
268*67e74705SXin Li if (FD->isInlined())
269*67e74705SXin Li return true;
270*67e74705SXin Li
271*67e74705SXin Li DC = DC->getLexicalParent();
272*67e74705SXin Li }
273*67e74705SXin Li
274*67e74705SXin Li return false;
275*67e74705SXin Li }
276*67e74705SXin Li
277*67e74705SXin Li MangleNumberingContext *
getCurrentMangleNumberContext(const DeclContext * DC,Decl * & ManglingContextDecl)278*67e74705SXin Li Sema::getCurrentMangleNumberContext(const DeclContext *DC,
279*67e74705SXin Li Decl *&ManglingContextDecl) {
280*67e74705SXin Li // Compute the context for allocating mangling numbers in the current
281*67e74705SXin Li // expression, if the ABI requires them.
282*67e74705SXin Li ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
283*67e74705SXin Li
284*67e74705SXin Li enum ContextKind {
285*67e74705SXin Li Normal,
286*67e74705SXin Li DefaultArgument,
287*67e74705SXin Li DataMember,
288*67e74705SXin Li StaticDataMember
289*67e74705SXin Li } Kind = Normal;
290*67e74705SXin Li
291*67e74705SXin Li // Default arguments of member function parameters that appear in a class
292*67e74705SXin Li // definition, as well as the initializers of data members, receive special
293*67e74705SXin Li // treatment. Identify them.
294*67e74705SXin Li if (ManglingContextDecl) {
295*67e74705SXin Li if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
296*67e74705SXin Li if (const DeclContext *LexicalDC
297*67e74705SXin Li = Param->getDeclContext()->getLexicalParent())
298*67e74705SXin Li if (LexicalDC->isRecord())
299*67e74705SXin Li Kind = DefaultArgument;
300*67e74705SXin Li } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
301*67e74705SXin Li if (Var->getDeclContext()->isRecord())
302*67e74705SXin Li Kind = StaticDataMember;
303*67e74705SXin Li } else if (isa<FieldDecl>(ManglingContextDecl)) {
304*67e74705SXin Li Kind = DataMember;
305*67e74705SXin Li }
306*67e74705SXin Li }
307*67e74705SXin Li
308*67e74705SXin Li // Itanium ABI [5.1.7]:
309*67e74705SXin Li // In the following contexts [...] the one-definition rule requires closure
310*67e74705SXin Li // types in different translation units to "correspond":
311*67e74705SXin Li bool IsInNonspecializedTemplate =
312*67e74705SXin Li !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
313*67e74705SXin Li switch (Kind) {
314*67e74705SXin Li case Normal:
315*67e74705SXin Li // -- the bodies of non-exported nonspecialized template functions
316*67e74705SXin Li // -- the bodies of inline functions
317*67e74705SXin Li if ((IsInNonspecializedTemplate &&
318*67e74705SXin Li !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
319*67e74705SXin Li isInInlineFunction(CurContext)) {
320*67e74705SXin Li ManglingContextDecl = nullptr;
321*67e74705SXin Li return &Context.getManglingNumberContext(DC);
322*67e74705SXin Li }
323*67e74705SXin Li
324*67e74705SXin Li ManglingContextDecl = nullptr;
325*67e74705SXin Li return nullptr;
326*67e74705SXin Li
327*67e74705SXin Li case StaticDataMember:
328*67e74705SXin Li // -- the initializers of nonspecialized static members of template classes
329*67e74705SXin Li if (!IsInNonspecializedTemplate) {
330*67e74705SXin Li ManglingContextDecl = nullptr;
331*67e74705SXin Li return nullptr;
332*67e74705SXin Li }
333*67e74705SXin Li // Fall through to get the current context.
334*67e74705SXin Li
335*67e74705SXin Li case DataMember:
336*67e74705SXin Li // -- the in-class initializers of class members
337*67e74705SXin Li case DefaultArgument:
338*67e74705SXin Li // -- default arguments appearing in class definitions
339*67e74705SXin Li return &ExprEvalContexts.back().getMangleNumberingContext(Context);
340*67e74705SXin Li }
341*67e74705SXin Li
342*67e74705SXin Li llvm_unreachable("unexpected context");
343*67e74705SXin Li }
344*67e74705SXin Li
345*67e74705SXin Li MangleNumberingContext &
getMangleNumberingContext(ASTContext & Ctx)346*67e74705SXin Li Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
347*67e74705SXin Li ASTContext &Ctx) {
348*67e74705SXin Li assert(ManglingContextDecl && "Need to have a context declaration");
349*67e74705SXin Li if (!MangleNumbering)
350*67e74705SXin Li MangleNumbering = Ctx.createMangleNumberingContext();
351*67e74705SXin Li return *MangleNumbering;
352*67e74705SXin Li }
353*67e74705SXin Li
startLambdaDefinition(CXXRecordDecl * Class,SourceRange IntroducerRange,TypeSourceInfo * MethodTypeInfo,SourceLocation EndLoc,ArrayRef<ParmVarDecl * > Params,const bool IsConstexprSpecified)354*67e74705SXin Li CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
355*67e74705SXin Li SourceRange IntroducerRange,
356*67e74705SXin Li TypeSourceInfo *MethodTypeInfo,
357*67e74705SXin Li SourceLocation EndLoc,
358*67e74705SXin Li ArrayRef<ParmVarDecl *> Params,
359*67e74705SXin Li const bool IsConstexprSpecified) {
360*67e74705SXin Li QualType MethodType = MethodTypeInfo->getType();
361*67e74705SXin Li TemplateParameterList *TemplateParams =
362*67e74705SXin Li getGenericLambdaTemplateParameterList(getCurLambda(), *this);
363*67e74705SXin Li // If a lambda appears in a dependent context or is a generic lambda (has
364*67e74705SXin Li // template parameters) and has an 'auto' return type, deduce it to a
365*67e74705SXin Li // dependent type.
366*67e74705SXin Li if (Class->isDependentContext() || TemplateParams) {
367*67e74705SXin Li const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
368*67e74705SXin Li QualType Result = FPT->getReturnType();
369*67e74705SXin Li if (Result->isUndeducedType()) {
370*67e74705SXin Li Result = SubstAutoType(Result, Context.DependentTy);
371*67e74705SXin Li MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
372*67e74705SXin Li FPT->getExtProtoInfo());
373*67e74705SXin Li }
374*67e74705SXin Li }
375*67e74705SXin Li
376*67e74705SXin Li // C++11 [expr.prim.lambda]p5:
377*67e74705SXin Li // The closure type for a lambda-expression has a public inline function
378*67e74705SXin Li // call operator (13.5.4) whose parameters and return type are described by
379*67e74705SXin Li // the lambda-expression's parameter-declaration-clause and
380*67e74705SXin Li // trailing-return-type respectively.
381*67e74705SXin Li DeclarationName MethodName
382*67e74705SXin Li = Context.DeclarationNames.getCXXOperatorName(OO_Call);
383*67e74705SXin Li DeclarationNameLoc MethodNameLoc;
384*67e74705SXin Li MethodNameLoc.CXXOperatorName.BeginOpNameLoc
385*67e74705SXin Li = IntroducerRange.getBegin().getRawEncoding();
386*67e74705SXin Li MethodNameLoc.CXXOperatorName.EndOpNameLoc
387*67e74705SXin Li = IntroducerRange.getEnd().getRawEncoding();
388*67e74705SXin Li CXXMethodDecl *Method
389*67e74705SXin Li = CXXMethodDecl::Create(Context, Class, EndLoc,
390*67e74705SXin Li DeclarationNameInfo(MethodName,
391*67e74705SXin Li IntroducerRange.getBegin(),
392*67e74705SXin Li MethodNameLoc),
393*67e74705SXin Li MethodType, MethodTypeInfo,
394*67e74705SXin Li SC_None,
395*67e74705SXin Li /*isInline=*/true,
396*67e74705SXin Li IsConstexprSpecified,
397*67e74705SXin Li EndLoc);
398*67e74705SXin Li Method->setAccess(AS_public);
399*67e74705SXin Li
400*67e74705SXin Li // Temporarily set the lexical declaration context to the current
401*67e74705SXin Li // context, so that the Scope stack matches the lexical nesting.
402*67e74705SXin Li Method->setLexicalDeclContext(CurContext);
403*67e74705SXin Li // Create a function template if we have a template parameter list
404*67e74705SXin Li FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
405*67e74705SXin Li FunctionTemplateDecl::Create(Context, Class,
406*67e74705SXin Li Method->getLocation(), MethodName,
407*67e74705SXin Li TemplateParams,
408*67e74705SXin Li Method) : nullptr;
409*67e74705SXin Li if (TemplateMethod) {
410*67e74705SXin Li TemplateMethod->setLexicalDeclContext(CurContext);
411*67e74705SXin Li TemplateMethod->setAccess(AS_public);
412*67e74705SXin Li Method->setDescribedFunctionTemplate(TemplateMethod);
413*67e74705SXin Li }
414*67e74705SXin Li
415*67e74705SXin Li // Add parameters.
416*67e74705SXin Li if (!Params.empty()) {
417*67e74705SXin Li Method->setParams(Params);
418*67e74705SXin Li CheckParmsForFunctionDef(Params,
419*67e74705SXin Li /*CheckParameterNames=*/false);
420*67e74705SXin Li
421*67e74705SXin Li for (auto P : Method->parameters())
422*67e74705SXin Li P->setOwningFunction(Method);
423*67e74705SXin Li }
424*67e74705SXin Li
425*67e74705SXin Li Decl *ManglingContextDecl;
426*67e74705SXin Li if (MangleNumberingContext *MCtx =
427*67e74705SXin Li getCurrentMangleNumberContext(Class->getDeclContext(),
428*67e74705SXin Li ManglingContextDecl)) {
429*67e74705SXin Li unsigned ManglingNumber = MCtx->getManglingNumber(Method);
430*67e74705SXin Li Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
431*67e74705SXin Li }
432*67e74705SXin Li
433*67e74705SXin Li return Method;
434*67e74705SXin Li }
435*67e74705SXin Li
buildLambdaScope(LambdaScopeInfo * LSI,CXXMethodDecl * CallOperator,SourceRange IntroducerRange,LambdaCaptureDefault CaptureDefault,SourceLocation CaptureDefaultLoc,bool ExplicitParams,bool ExplicitResultType,bool Mutable)436*67e74705SXin Li void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
437*67e74705SXin Li CXXMethodDecl *CallOperator,
438*67e74705SXin Li SourceRange IntroducerRange,
439*67e74705SXin Li LambdaCaptureDefault CaptureDefault,
440*67e74705SXin Li SourceLocation CaptureDefaultLoc,
441*67e74705SXin Li bool ExplicitParams,
442*67e74705SXin Li bool ExplicitResultType,
443*67e74705SXin Li bool Mutable) {
444*67e74705SXin Li LSI->CallOperator = CallOperator;
445*67e74705SXin Li CXXRecordDecl *LambdaClass = CallOperator->getParent();
446*67e74705SXin Li LSI->Lambda = LambdaClass;
447*67e74705SXin Li if (CaptureDefault == LCD_ByCopy)
448*67e74705SXin Li LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
449*67e74705SXin Li else if (CaptureDefault == LCD_ByRef)
450*67e74705SXin Li LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
451*67e74705SXin Li LSI->CaptureDefaultLoc = CaptureDefaultLoc;
452*67e74705SXin Li LSI->IntroducerRange = IntroducerRange;
453*67e74705SXin Li LSI->ExplicitParams = ExplicitParams;
454*67e74705SXin Li LSI->Mutable = Mutable;
455*67e74705SXin Li
456*67e74705SXin Li if (ExplicitResultType) {
457*67e74705SXin Li LSI->ReturnType = CallOperator->getReturnType();
458*67e74705SXin Li
459*67e74705SXin Li if (!LSI->ReturnType->isDependentType() &&
460*67e74705SXin Li !LSI->ReturnType->isVoidType()) {
461*67e74705SXin Li if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
462*67e74705SXin Li diag::err_lambda_incomplete_result)) {
463*67e74705SXin Li // Do nothing.
464*67e74705SXin Li }
465*67e74705SXin Li }
466*67e74705SXin Li } else {
467*67e74705SXin Li LSI->HasImplicitReturnType = true;
468*67e74705SXin Li }
469*67e74705SXin Li }
470*67e74705SXin Li
finishLambdaExplicitCaptures(LambdaScopeInfo * LSI)471*67e74705SXin Li void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
472*67e74705SXin Li LSI->finishedExplicitCaptures();
473*67e74705SXin Li }
474*67e74705SXin Li
addLambdaParameters(CXXMethodDecl * CallOperator,Scope * CurScope)475*67e74705SXin Li void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
476*67e74705SXin Li // Introduce our parameters into the function scope
477*67e74705SXin Li for (unsigned p = 0, NumParams = CallOperator->getNumParams();
478*67e74705SXin Li p < NumParams; ++p) {
479*67e74705SXin Li ParmVarDecl *Param = CallOperator->getParamDecl(p);
480*67e74705SXin Li
481*67e74705SXin Li // If this has an identifier, add it to the scope stack.
482*67e74705SXin Li if (CurScope && Param->getIdentifier()) {
483*67e74705SXin Li CheckShadow(CurScope, Param);
484*67e74705SXin Li
485*67e74705SXin Li PushOnScopeChains(Param, CurScope);
486*67e74705SXin Li }
487*67e74705SXin Li }
488*67e74705SXin Li }
489*67e74705SXin Li
490*67e74705SXin Li /// If this expression is an enumerator-like expression of some type
491*67e74705SXin Li /// T, return the type T; otherwise, return null.
492*67e74705SXin Li ///
493*67e74705SXin Li /// Pointer comparisons on the result here should always work because
494*67e74705SXin Li /// it's derived from either the parent of an EnumConstantDecl
495*67e74705SXin Li /// (i.e. the definition) or the declaration returned by
496*67e74705SXin Li /// EnumType::getDecl() (i.e. the definition).
findEnumForBlockReturn(Expr * E)497*67e74705SXin Li static EnumDecl *findEnumForBlockReturn(Expr *E) {
498*67e74705SXin Li // An expression is an enumerator-like expression of type T if,
499*67e74705SXin Li // ignoring parens and parens-like expressions:
500*67e74705SXin Li E = E->IgnoreParens();
501*67e74705SXin Li
502*67e74705SXin Li // - it is an enumerator whose enum type is T or
503*67e74705SXin Li if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
504*67e74705SXin Li if (EnumConstantDecl *D
505*67e74705SXin Li = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
506*67e74705SXin Li return cast<EnumDecl>(D->getDeclContext());
507*67e74705SXin Li }
508*67e74705SXin Li return nullptr;
509*67e74705SXin Li }
510*67e74705SXin Li
511*67e74705SXin Li // - it is a comma expression whose RHS is an enumerator-like
512*67e74705SXin Li // expression of type T or
513*67e74705SXin Li if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
514*67e74705SXin Li if (BO->getOpcode() == BO_Comma)
515*67e74705SXin Li return findEnumForBlockReturn(BO->getRHS());
516*67e74705SXin Li return nullptr;
517*67e74705SXin Li }
518*67e74705SXin Li
519*67e74705SXin Li // - it is a statement-expression whose value expression is an
520*67e74705SXin Li // enumerator-like expression of type T or
521*67e74705SXin Li if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
522*67e74705SXin Li if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
523*67e74705SXin Li return findEnumForBlockReturn(last);
524*67e74705SXin Li return nullptr;
525*67e74705SXin Li }
526*67e74705SXin Li
527*67e74705SXin Li // - it is a ternary conditional operator (not the GNU ?:
528*67e74705SXin Li // extension) whose second and third operands are
529*67e74705SXin Li // enumerator-like expressions of type T or
530*67e74705SXin Li if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
531*67e74705SXin Li if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
532*67e74705SXin Li if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
533*67e74705SXin Li return ED;
534*67e74705SXin Li return nullptr;
535*67e74705SXin Li }
536*67e74705SXin Li
537*67e74705SXin Li // (implicitly:)
538*67e74705SXin Li // - it is an implicit integral conversion applied to an
539*67e74705SXin Li // enumerator-like expression of type T or
540*67e74705SXin Li if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
541*67e74705SXin Li // We can sometimes see integral conversions in valid
542*67e74705SXin Li // enumerator-like expressions.
543*67e74705SXin Li if (ICE->getCastKind() == CK_IntegralCast)
544*67e74705SXin Li return findEnumForBlockReturn(ICE->getSubExpr());
545*67e74705SXin Li
546*67e74705SXin Li // Otherwise, just rely on the type.
547*67e74705SXin Li }
548*67e74705SXin Li
549*67e74705SXin Li // - it is an expression of that formal enum type.
550*67e74705SXin Li if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
551*67e74705SXin Li return ET->getDecl();
552*67e74705SXin Li }
553*67e74705SXin Li
554*67e74705SXin Li // Otherwise, nope.
555*67e74705SXin Li return nullptr;
556*67e74705SXin Li }
557*67e74705SXin Li
558*67e74705SXin Li /// Attempt to find a type T for which the returned expression of the
559*67e74705SXin Li /// given statement is an enumerator-like expression of that type.
findEnumForBlockReturn(ReturnStmt * ret)560*67e74705SXin Li static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
561*67e74705SXin Li if (Expr *retValue = ret->getRetValue())
562*67e74705SXin Li return findEnumForBlockReturn(retValue);
563*67e74705SXin Li return nullptr;
564*67e74705SXin Li }
565*67e74705SXin Li
566*67e74705SXin Li /// Attempt to find a common type T for which all of the returned
567*67e74705SXin Li /// expressions in a block are enumerator-like expressions of that
568*67e74705SXin Li /// type.
findCommonEnumForBlockReturns(ArrayRef<ReturnStmt * > returns)569*67e74705SXin Li static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
570*67e74705SXin Li ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
571*67e74705SXin Li
572*67e74705SXin Li // Try to find one for the first return.
573*67e74705SXin Li EnumDecl *ED = findEnumForBlockReturn(*i);
574*67e74705SXin Li if (!ED) return nullptr;
575*67e74705SXin Li
576*67e74705SXin Li // Check that the rest of the returns have the same enum.
577*67e74705SXin Li for (++i; i != e; ++i) {
578*67e74705SXin Li if (findEnumForBlockReturn(*i) != ED)
579*67e74705SXin Li return nullptr;
580*67e74705SXin Li }
581*67e74705SXin Li
582*67e74705SXin Li // Never infer an anonymous enum type.
583*67e74705SXin Li if (!ED->hasNameForLinkage()) return nullptr;
584*67e74705SXin Li
585*67e74705SXin Li return ED;
586*67e74705SXin Li }
587*67e74705SXin Li
588*67e74705SXin Li /// Adjust the given return statements so that they formally return
589*67e74705SXin Li /// the given type. It should require, at most, an IntegralCast.
adjustBlockReturnsToEnum(Sema & S,ArrayRef<ReturnStmt * > returns,QualType returnType)590*67e74705SXin Li static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
591*67e74705SXin Li QualType returnType) {
592*67e74705SXin Li for (ArrayRef<ReturnStmt*>::iterator
593*67e74705SXin Li i = returns.begin(), e = returns.end(); i != e; ++i) {
594*67e74705SXin Li ReturnStmt *ret = *i;
595*67e74705SXin Li Expr *retValue = ret->getRetValue();
596*67e74705SXin Li if (S.Context.hasSameType(retValue->getType(), returnType))
597*67e74705SXin Li continue;
598*67e74705SXin Li
599*67e74705SXin Li // Right now we only support integral fixup casts.
600*67e74705SXin Li assert(returnType->isIntegralOrUnscopedEnumerationType());
601*67e74705SXin Li assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
602*67e74705SXin Li
603*67e74705SXin Li ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
604*67e74705SXin Li
605*67e74705SXin Li Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
606*67e74705SXin Li E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
607*67e74705SXin Li E, /*base path*/ nullptr, VK_RValue);
608*67e74705SXin Li if (cleanups) {
609*67e74705SXin Li cleanups->setSubExpr(E);
610*67e74705SXin Li } else {
611*67e74705SXin Li ret->setRetValue(E);
612*67e74705SXin Li }
613*67e74705SXin Li }
614*67e74705SXin Li }
615*67e74705SXin Li
deduceClosureReturnType(CapturingScopeInfo & CSI)616*67e74705SXin Li void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
617*67e74705SXin Li assert(CSI.HasImplicitReturnType);
618*67e74705SXin Li // If it was ever a placeholder, it had to been deduced to DependentTy.
619*67e74705SXin Li assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
620*67e74705SXin Li assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
621*67e74705SXin Li "lambda expressions use auto deduction in C++14 onwards");
622*67e74705SXin Li
623*67e74705SXin Li // C++ core issue 975:
624*67e74705SXin Li // If a lambda-expression does not include a trailing-return-type,
625*67e74705SXin Li // it is as if the trailing-return-type denotes the following type:
626*67e74705SXin Li // - if there are no return statements in the compound-statement,
627*67e74705SXin Li // or all return statements return either an expression of type
628*67e74705SXin Li // void or no expression or braced-init-list, the type void;
629*67e74705SXin Li // - otherwise, if all return statements return an expression
630*67e74705SXin Li // and the types of the returned expressions after
631*67e74705SXin Li // lvalue-to-rvalue conversion (4.1 [conv.lval]),
632*67e74705SXin Li // array-to-pointer conversion (4.2 [conv.array]), and
633*67e74705SXin Li // function-to-pointer conversion (4.3 [conv.func]) are the
634*67e74705SXin Li // same, that common type;
635*67e74705SXin Li // - otherwise, the program is ill-formed.
636*67e74705SXin Li //
637*67e74705SXin Li // C++ core issue 1048 additionally removes top-level cv-qualifiers
638*67e74705SXin Li // from the types of returned expressions to match the C++14 auto
639*67e74705SXin Li // deduction rules.
640*67e74705SXin Li //
641*67e74705SXin Li // In addition, in blocks in non-C++ modes, if all of the return
642*67e74705SXin Li // statements are enumerator-like expressions of some type T, where
643*67e74705SXin Li // T has a name for linkage, then we infer the return type of the
644*67e74705SXin Li // block to be that type.
645*67e74705SXin Li
646*67e74705SXin Li // First case: no return statements, implicit void return type.
647*67e74705SXin Li ASTContext &Ctx = getASTContext();
648*67e74705SXin Li if (CSI.Returns.empty()) {
649*67e74705SXin Li // It's possible there were simply no /valid/ return statements.
650*67e74705SXin Li // In this case, the first one we found may have at least given us a type.
651*67e74705SXin Li if (CSI.ReturnType.isNull())
652*67e74705SXin Li CSI.ReturnType = Ctx.VoidTy;
653*67e74705SXin Li return;
654*67e74705SXin Li }
655*67e74705SXin Li
656*67e74705SXin Li // Second case: at least one return statement has dependent type.
657*67e74705SXin Li // Delay type checking until instantiation.
658*67e74705SXin Li assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
659*67e74705SXin Li if (CSI.ReturnType->isDependentType())
660*67e74705SXin Li return;
661*67e74705SXin Li
662*67e74705SXin Li // Try to apply the enum-fuzz rule.
663*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
664*67e74705SXin Li assert(isa<BlockScopeInfo>(CSI));
665*67e74705SXin Li const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
666*67e74705SXin Li if (ED) {
667*67e74705SXin Li CSI.ReturnType = Context.getTypeDeclType(ED);
668*67e74705SXin Li adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
669*67e74705SXin Li return;
670*67e74705SXin Li }
671*67e74705SXin Li }
672*67e74705SXin Li
673*67e74705SXin Li // Third case: only one return statement. Don't bother doing extra work!
674*67e74705SXin Li SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
675*67e74705SXin Li E = CSI.Returns.end();
676*67e74705SXin Li if (I+1 == E)
677*67e74705SXin Li return;
678*67e74705SXin Li
679*67e74705SXin Li // General case: many return statements.
680*67e74705SXin Li // Check that they all have compatible return types.
681*67e74705SXin Li
682*67e74705SXin Li // We require the return types to strictly match here.
683*67e74705SXin Li // Note that we've already done the required promotions as part of
684*67e74705SXin Li // processing the return statement.
685*67e74705SXin Li for (; I != E; ++I) {
686*67e74705SXin Li const ReturnStmt *RS = *I;
687*67e74705SXin Li const Expr *RetE = RS->getRetValue();
688*67e74705SXin Li
689*67e74705SXin Li QualType ReturnType =
690*67e74705SXin Li (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
691*67e74705SXin Li if (Context.getCanonicalFunctionResultType(ReturnType) ==
692*67e74705SXin Li Context.getCanonicalFunctionResultType(CSI.ReturnType))
693*67e74705SXin Li continue;
694*67e74705SXin Li
695*67e74705SXin Li // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
696*67e74705SXin Li // TODO: It's possible that the *first* return is the divergent one.
697*67e74705SXin Li Diag(RS->getLocStart(),
698*67e74705SXin Li diag::err_typecheck_missing_return_type_incompatible)
699*67e74705SXin Li << ReturnType << CSI.ReturnType
700*67e74705SXin Li << isa<LambdaScopeInfo>(CSI);
701*67e74705SXin Li // Continue iterating so that we keep emitting diagnostics.
702*67e74705SXin Li }
703*67e74705SXin Li }
704*67e74705SXin Li
buildLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,IdentifierInfo * Id,bool IsDirectInit,Expr * & Init)705*67e74705SXin Li QualType Sema::buildLambdaInitCaptureInitialization(SourceLocation Loc,
706*67e74705SXin Li bool ByRef,
707*67e74705SXin Li IdentifierInfo *Id,
708*67e74705SXin Li bool IsDirectInit,
709*67e74705SXin Li Expr *&Init) {
710*67e74705SXin Li // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
711*67e74705SXin Li // deduce against.
712*67e74705SXin Li QualType DeductType = Context.getAutoDeductType();
713*67e74705SXin Li TypeLocBuilder TLB;
714*67e74705SXin Li TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
715*67e74705SXin Li if (ByRef) {
716*67e74705SXin Li DeductType = BuildReferenceType(DeductType, true, Loc, Id);
717*67e74705SXin Li assert(!DeductType.isNull() && "can't build reference to auto");
718*67e74705SXin Li TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
719*67e74705SXin Li }
720*67e74705SXin Li TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
721*67e74705SXin Li
722*67e74705SXin Li // Deduce the type of the init capture.
723*67e74705SXin Li QualType DeducedType = deduceVarTypeFromInitializer(
724*67e74705SXin Li /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
725*67e74705SXin Li SourceRange(Loc, Loc), IsDirectInit, Init);
726*67e74705SXin Li if (DeducedType.isNull())
727*67e74705SXin Li return QualType();
728*67e74705SXin Li
729*67e74705SXin Li // Are we a non-list direct initialization?
730*67e74705SXin Li ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
731*67e74705SXin Li
732*67e74705SXin Li // Perform initialization analysis and ensure any implicit conversions
733*67e74705SXin Li // (such as lvalue-to-rvalue) are enforced.
734*67e74705SXin Li InitializedEntity Entity =
735*67e74705SXin Li InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
736*67e74705SXin Li InitializationKind Kind =
737*67e74705SXin Li IsDirectInit
738*67e74705SXin Li ? (CXXDirectInit ? InitializationKind::CreateDirect(
739*67e74705SXin Li Loc, Init->getLocStart(), Init->getLocEnd())
740*67e74705SXin Li : InitializationKind::CreateDirectList(Loc))
741*67e74705SXin Li : InitializationKind::CreateCopy(Loc, Init->getLocStart());
742*67e74705SXin Li
743*67e74705SXin Li MultiExprArg Args = Init;
744*67e74705SXin Li if (CXXDirectInit)
745*67e74705SXin Li Args =
746*67e74705SXin Li MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
747*67e74705SXin Li QualType DclT;
748*67e74705SXin Li InitializationSequence InitSeq(*this, Entity, Kind, Args);
749*67e74705SXin Li ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
750*67e74705SXin Li
751*67e74705SXin Li if (Result.isInvalid())
752*67e74705SXin Li return QualType();
753*67e74705SXin Li Init = Result.getAs<Expr>();
754*67e74705SXin Li
755*67e74705SXin Li // The init-capture initialization is a full-expression that must be
756*67e74705SXin Li // processed as one before we enter the declcontext of the lambda's
757*67e74705SXin Li // call-operator.
758*67e74705SXin Li Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
759*67e74705SXin Li /*IsConstexpr*/ false,
760*67e74705SXin Li /*IsLambdaInitCaptureInitalizer*/ true);
761*67e74705SXin Li if (Result.isInvalid())
762*67e74705SXin Li return QualType();
763*67e74705SXin Li
764*67e74705SXin Li Init = Result.getAs<Expr>();
765*67e74705SXin Li return DeducedType;
766*67e74705SXin Li }
767*67e74705SXin Li
createLambdaInitCaptureVarDecl(SourceLocation Loc,QualType InitCaptureType,IdentifierInfo * Id,unsigned InitStyle,Expr * Init)768*67e74705SXin Li VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
769*67e74705SXin Li QualType InitCaptureType,
770*67e74705SXin Li IdentifierInfo *Id,
771*67e74705SXin Li unsigned InitStyle, Expr *Init) {
772*67e74705SXin Li TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
773*67e74705SXin Li Loc);
774*67e74705SXin Li // Create a dummy variable representing the init-capture. This is not actually
775*67e74705SXin Li // used as a variable, and only exists as a way to name and refer to the
776*67e74705SXin Li // init-capture.
777*67e74705SXin Li // FIXME: Pass in separate source locations for '&' and identifier.
778*67e74705SXin Li VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
779*67e74705SXin Li Loc, Id, InitCaptureType, TSI, SC_Auto);
780*67e74705SXin Li NewVD->setInitCapture(true);
781*67e74705SXin Li NewVD->setReferenced(true);
782*67e74705SXin Li // FIXME: Pass in a VarDecl::InitializationStyle.
783*67e74705SXin Li NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
784*67e74705SXin Li NewVD->markUsed(Context);
785*67e74705SXin Li NewVD->setInit(Init);
786*67e74705SXin Li return NewVD;
787*67e74705SXin Li }
788*67e74705SXin Li
buildInitCaptureField(LambdaScopeInfo * LSI,VarDecl * Var)789*67e74705SXin Li FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
790*67e74705SXin Li FieldDecl *Field = FieldDecl::Create(
791*67e74705SXin Li Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
792*67e74705SXin Li nullptr, Var->getType(), Var->getTypeSourceInfo(), nullptr, false,
793*67e74705SXin Li ICIS_NoInit);
794*67e74705SXin Li Field->setImplicit(true);
795*67e74705SXin Li Field->setAccess(AS_private);
796*67e74705SXin Li LSI->Lambda->addDecl(Field);
797*67e74705SXin Li
798*67e74705SXin Li LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
799*67e74705SXin Li /*isNested*/false, Var->getLocation(), SourceLocation(),
800*67e74705SXin Li Var->getType(), Var->getInit());
801*67e74705SXin Li return Field;
802*67e74705SXin Li }
803*67e74705SXin Li
ActOnStartOfLambdaDefinition(LambdaIntroducer & Intro,Declarator & ParamInfo,Scope * CurScope)804*67e74705SXin Li void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
805*67e74705SXin Li Declarator &ParamInfo,
806*67e74705SXin Li Scope *CurScope) {
807*67e74705SXin Li // Determine if we're within a context where we know that the lambda will
808*67e74705SXin Li // be dependent, because there are template parameters in scope.
809*67e74705SXin Li bool KnownDependent = false;
810*67e74705SXin Li LambdaScopeInfo *const LSI = getCurLambda();
811*67e74705SXin Li assert(LSI && "LambdaScopeInfo should be on stack!");
812*67e74705SXin Li
813*67e74705SXin Li // The lambda-expression's closure type might be dependent even if its
814*67e74705SXin Li // semantic context isn't, if it appears within a default argument of a
815*67e74705SXin Li // function template.
816*67e74705SXin Li if (CurScope->getTemplateParamParent())
817*67e74705SXin Li KnownDependent = true;
818*67e74705SXin Li
819*67e74705SXin Li // Determine the signature of the call operator.
820*67e74705SXin Li TypeSourceInfo *MethodTyInfo;
821*67e74705SXin Li bool ExplicitParams = true;
822*67e74705SXin Li bool ExplicitResultType = true;
823*67e74705SXin Li bool ContainsUnexpandedParameterPack = false;
824*67e74705SXin Li SourceLocation EndLoc;
825*67e74705SXin Li SmallVector<ParmVarDecl *, 8> Params;
826*67e74705SXin Li if (ParamInfo.getNumTypeObjects() == 0) {
827*67e74705SXin Li // C++11 [expr.prim.lambda]p4:
828*67e74705SXin Li // If a lambda-expression does not include a lambda-declarator, it is as
829*67e74705SXin Li // if the lambda-declarator were ().
830*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
831*67e74705SXin Li /*IsVariadic=*/false, /*IsCXXMethod=*/true));
832*67e74705SXin Li EPI.HasTrailingReturn = true;
833*67e74705SXin Li EPI.TypeQuals |= DeclSpec::TQ_const;
834*67e74705SXin Li // C++1y [expr.prim.lambda]:
835*67e74705SXin Li // The lambda return type is 'auto', which is replaced by the
836*67e74705SXin Li // trailing-return type if provided and/or deduced from 'return'
837*67e74705SXin Li // statements
838*67e74705SXin Li // We don't do this before C++1y, because we don't support deduced return
839*67e74705SXin Li // types there.
840*67e74705SXin Li QualType DefaultTypeForNoTrailingReturn =
841*67e74705SXin Li getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
842*67e74705SXin Li : Context.DependentTy;
843*67e74705SXin Li QualType MethodTy =
844*67e74705SXin Li Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
845*67e74705SXin Li MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
846*67e74705SXin Li ExplicitParams = false;
847*67e74705SXin Li ExplicitResultType = false;
848*67e74705SXin Li EndLoc = Intro.Range.getEnd();
849*67e74705SXin Li } else {
850*67e74705SXin Li assert(ParamInfo.isFunctionDeclarator() &&
851*67e74705SXin Li "lambda-declarator is a function");
852*67e74705SXin Li DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
853*67e74705SXin Li
854*67e74705SXin Li // C++11 [expr.prim.lambda]p5:
855*67e74705SXin Li // This function call operator is declared const (9.3.1) if and only if
856*67e74705SXin Li // the lambda-expression's parameter-declaration-clause is not followed
857*67e74705SXin Li // by mutable. It is neither virtual nor declared volatile. [...]
858*67e74705SXin Li if (!FTI.hasMutableQualifier())
859*67e74705SXin Li FTI.TypeQuals |= DeclSpec::TQ_const;
860*67e74705SXin Li
861*67e74705SXin Li MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
862*67e74705SXin Li assert(MethodTyInfo && "no type from lambda-declarator");
863*67e74705SXin Li EndLoc = ParamInfo.getSourceRange().getEnd();
864*67e74705SXin Li
865*67e74705SXin Li ExplicitResultType = FTI.hasTrailingReturnType();
866*67e74705SXin Li
867*67e74705SXin Li if (FTIHasNonVoidParameters(FTI)) {
868*67e74705SXin Li Params.reserve(FTI.NumParams);
869*67e74705SXin Li for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
870*67e74705SXin Li Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
871*67e74705SXin Li }
872*67e74705SXin Li
873*67e74705SXin Li // Check for unexpanded parameter packs in the method type.
874*67e74705SXin Li if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
875*67e74705SXin Li ContainsUnexpandedParameterPack = true;
876*67e74705SXin Li }
877*67e74705SXin Li
878*67e74705SXin Li CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
879*67e74705SXin Li KnownDependent, Intro.Default);
880*67e74705SXin Li
881*67e74705SXin Li CXXMethodDecl *Method =
882*67e74705SXin Li startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
883*67e74705SXin Li ParamInfo.getDeclSpec().isConstexprSpecified());
884*67e74705SXin Li if (ExplicitParams)
885*67e74705SXin Li CheckCXXDefaultArguments(Method);
886*67e74705SXin Li
887*67e74705SXin Li // Attributes on the lambda apply to the method.
888*67e74705SXin Li ProcessDeclAttributes(CurScope, Method, ParamInfo);
889*67e74705SXin Li
890*67e74705SXin Li // Introduce the function call operator as the current declaration context.
891*67e74705SXin Li PushDeclContext(CurScope, Method);
892*67e74705SXin Li
893*67e74705SXin Li // Build the lambda scope.
894*67e74705SXin Li buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
895*67e74705SXin Li ExplicitParams, ExplicitResultType, !Method->isConst());
896*67e74705SXin Li
897*67e74705SXin Li // C++11 [expr.prim.lambda]p9:
898*67e74705SXin Li // A lambda-expression whose smallest enclosing scope is a block scope is a
899*67e74705SXin Li // local lambda expression; any other lambda expression shall not have a
900*67e74705SXin Li // capture-default or simple-capture in its lambda-introducer.
901*67e74705SXin Li //
902*67e74705SXin Li // For simple-captures, this is covered by the check below that any named
903*67e74705SXin Li // entity is a variable that can be captured.
904*67e74705SXin Li //
905*67e74705SXin Li // For DR1632, we also allow a capture-default in any context where we can
906*67e74705SXin Li // odr-use 'this' (in particular, in a default initializer for a non-static
907*67e74705SXin Li // data member).
908*67e74705SXin Li if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
909*67e74705SXin Li (getCurrentThisType().isNull() ||
910*67e74705SXin Li CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
911*67e74705SXin Li /*BuildAndDiagnose*/false)))
912*67e74705SXin Li Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
913*67e74705SXin Li
914*67e74705SXin Li // Distinct capture names, for diagnostics.
915*67e74705SXin Li llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
916*67e74705SXin Li
917*67e74705SXin Li // Handle explicit captures.
918*67e74705SXin Li SourceLocation PrevCaptureLoc
919*67e74705SXin Li = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
920*67e74705SXin Li for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
921*67e74705SXin Li PrevCaptureLoc = C->Loc, ++C) {
922*67e74705SXin Li if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
923*67e74705SXin Li if (C->Kind == LCK_StarThis)
924*67e74705SXin Li Diag(C->Loc, !getLangOpts().CPlusPlus1z
925*67e74705SXin Li ? diag::ext_star_this_lambda_capture_cxx1z
926*67e74705SXin Li : diag::warn_cxx14_compat_star_this_lambda_capture);
927*67e74705SXin Li
928*67e74705SXin Li // C++11 [expr.prim.lambda]p8:
929*67e74705SXin Li // An identifier or this shall not appear more than once in a
930*67e74705SXin Li // lambda-capture.
931*67e74705SXin Li if (LSI->isCXXThisCaptured()) {
932*67e74705SXin Li Diag(C->Loc, diag::err_capture_more_than_once)
933*67e74705SXin Li << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
934*67e74705SXin Li << FixItHint::CreateRemoval(
935*67e74705SXin Li SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
936*67e74705SXin Li continue;
937*67e74705SXin Li }
938*67e74705SXin Li
939*67e74705SXin Li // C++1z [expr.prim.lambda]p8:
940*67e74705SXin Li // If a lambda-capture includes a capture-default that is =, each
941*67e74705SXin Li // simple-capture of that lambda-capture shall be of the form "&
942*67e74705SXin Li // identifier" or "* this". [ Note: The form [&,this] is redundant but
943*67e74705SXin Li // accepted for compatibility with ISO C++14. --end note ]
944*67e74705SXin Li if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis) {
945*67e74705SXin Li Diag(C->Loc, diag::err_this_capture_with_copy_default)
946*67e74705SXin Li << FixItHint::CreateRemoval(
947*67e74705SXin Li SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
948*67e74705SXin Li continue;
949*67e74705SXin Li }
950*67e74705SXin Li
951*67e74705SXin Li // C++11 [expr.prim.lambda]p12:
952*67e74705SXin Li // If this is captured by a local lambda expression, its nearest
953*67e74705SXin Li // enclosing function shall be a non-static member function.
954*67e74705SXin Li QualType ThisCaptureType = getCurrentThisType();
955*67e74705SXin Li if (ThisCaptureType.isNull()) {
956*67e74705SXin Li Diag(C->Loc, diag::err_this_capture) << true;
957*67e74705SXin Li continue;
958*67e74705SXin Li }
959*67e74705SXin Li
960*67e74705SXin Li CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
961*67e74705SXin Li /*FunctionScopeIndexToStopAtPtr*/ nullptr,
962*67e74705SXin Li C->Kind == LCK_StarThis);
963*67e74705SXin Li continue;
964*67e74705SXin Li }
965*67e74705SXin Li
966*67e74705SXin Li assert(C->Id && "missing identifier for capture");
967*67e74705SXin Li
968*67e74705SXin Li if (C->Init.isInvalid())
969*67e74705SXin Li continue;
970*67e74705SXin Li
971*67e74705SXin Li VarDecl *Var = nullptr;
972*67e74705SXin Li if (C->Init.isUsable()) {
973*67e74705SXin Li Diag(C->Loc, getLangOpts().CPlusPlus14
974*67e74705SXin Li ? diag::warn_cxx11_compat_init_capture
975*67e74705SXin Li : diag::ext_init_capture);
976*67e74705SXin Li
977*67e74705SXin Li if (C->Init.get()->containsUnexpandedParameterPack())
978*67e74705SXin Li ContainsUnexpandedParameterPack = true;
979*67e74705SXin Li // If the initializer expression is usable, but the InitCaptureType
980*67e74705SXin Li // is not, then an error has occurred - so ignore the capture for now.
981*67e74705SXin Li // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
982*67e74705SXin Li // FIXME: we should create the init capture variable and mark it invalid
983*67e74705SXin Li // in this case.
984*67e74705SXin Li if (C->InitCaptureType.get().isNull())
985*67e74705SXin Li continue;
986*67e74705SXin Li
987*67e74705SXin Li unsigned InitStyle;
988*67e74705SXin Li switch (C->InitKind) {
989*67e74705SXin Li case LambdaCaptureInitKind::NoInit:
990*67e74705SXin Li llvm_unreachable("not an init-capture?");
991*67e74705SXin Li case LambdaCaptureInitKind::CopyInit:
992*67e74705SXin Li InitStyle = VarDecl::CInit;
993*67e74705SXin Li break;
994*67e74705SXin Li case LambdaCaptureInitKind::DirectInit:
995*67e74705SXin Li InitStyle = VarDecl::CallInit;
996*67e74705SXin Li break;
997*67e74705SXin Li case LambdaCaptureInitKind::ListInit:
998*67e74705SXin Li InitStyle = VarDecl::ListInit;
999*67e74705SXin Li break;
1000*67e74705SXin Li }
1001*67e74705SXin Li Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1002*67e74705SXin Li C->Id, InitStyle, C->Init.get());
1003*67e74705SXin Li // C++1y [expr.prim.lambda]p11:
1004*67e74705SXin Li // An init-capture behaves as if it declares and explicitly
1005*67e74705SXin Li // captures a variable [...] whose declarative region is the
1006*67e74705SXin Li // lambda-expression's compound-statement
1007*67e74705SXin Li if (Var)
1008*67e74705SXin Li PushOnScopeChains(Var, CurScope, false);
1009*67e74705SXin Li } else {
1010*67e74705SXin Li assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1011*67e74705SXin Li "init capture has valid but null init?");
1012*67e74705SXin Li
1013*67e74705SXin Li // C++11 [expr.prim.lambda]p8:
1014*67e74705SXin Li // If a lambda-capture includes a capture-default that is &, the
1015*67e74705SXin Li // identifiers in the lambda-capture shall not be preceded by &.
1016*67e74705SXin Li // If a lambda-capture includes a capture-default that is =, [...]
1017*67e74705SXin Li // each identifier it contains shall be preceded by &.
1018*67e74705SXin Li if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1019*67e74705SXin Li Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1020*67e74705SXin Li << FixItHint::CreateRemoval(
1021*67e74705SXin Li SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1022*67e74705SXin Li continue;
1023*67e74705SXin Li } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1024*67e74705SXin Li Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1025*67e74705SXin Li << FixItHint::CreateRemoval(
1026*67e74705SXin Li SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1027*67e74705SXin Li continue;
1028*67e74705SXin Li }
1029*67e74705SXin Li
1030*67e74705SXin Li // C++11 [expr.prim.lambda]p10:
1031*67e74705SXin Li // The identifiers in a capture-list are looked up using the usual
1032*67e74705SXin Li // rules for unqualified name lookup (3.4.1)
1033*67e74705SXin Li DeclarationNameInfo Name(C->Id, C->Loc);
1034*67e74705SXin Li LookupResult R(*this, Name, LookupOrdinaryName);
1035*67e74705SXin Li LookupName(R, CurScope);
1036*67e74705SXin Li if (R.isAmbiguous())
1037*67e74705SXin Li continue;
1038*67e74705SXin Li if (R.empty()) {
1039*67e74705SXin Li // FIXME: Disable corrections that would add qualification?
1040*67e74705SXin Li CXXScopeSpec ScopeSpec;
1041*67e74705SXin Li if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R,
1042*67e74705SXin Li llvm::make_unique<DeclFilterCCC<VarDecl>>()))
1043*67e74705SXin Li continue;
1044*67e74705SXin Li }
1045*67e74705SXin Li
1046*67e74705SXin Li Var = R.getAsSingle<VarDecl>();
1047*67e74705SXin Li if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1048*67e74705SXin Li continue;
1049*67e74705SXin Li }
1050*67e74705SXin Li
1051*67e74705SXin Li // C++11 [expr.prim.lambda]p8:
1052*67e74705SXin Li // An identifier or this shall not appear more than once in a
1053*67e74705SXin Li // lambda-capture.
1054*67e74705SXin Li if (!CaptureNames.insert(C->Id).second) {
1055*67e74705SXin Li if (Var && LSI->isCaptured(Var)) {
1056*67e74705SXin Li Diag(C->Loc, diag::err_capture_more_than_once)
1057*67e74705SXin Li << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1058*67e74705SXin Li << FixItHint::CreateRemoval(
1059*67e74705SXin Li SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1060*67e74705SXin Li } else
1061*67e74705SXin Li // Previous capture captured something different (one or both was
1062*67e74705SXin Li // an init-cpature): no fixit.
1063*67e74705SXin Li Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1064*67e74705SXin Li continue;
1065*67e74705SXin Li }
1066*67e74705SXin Li
1067*67e74705SXin Li // C++11 [expr.prim.lambda]p10:
1068*67e74705SXin Li // [...] each such lookup shall find a variable with automatic storage
1069*67e74705SXin Li // duration declared in the reaching scope of the local lambda expression.
1070*67e74705SXin Li // Note that the 'reaching scope' check happens in tryCaptureVariable().
1071*67e74705SXin Li if (!Var) {
1072*67e74705SXin Li Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1073*67e74705SXin Li continue;
1074*67e74705SXin Li }
1075*67e74705SXin Li
1076*67e74705SXin Li // Ignore invalid decls; they'll just confuse the code later.
1077*67e74705SXin Li if (Var->isInvalidDecl())
1078*67e74705SXin Li continue;
1079*67e74705SXin Li
1080*67e74705SXin Li if (!Var->hasLocalStorage()) {
1081*67e74705SXin Li Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1082*67e74705SXin Li Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1083*67e74705SXin Li continue;
1084*67e74705SXin Li }
1085*67e74705SXin Li
1086*67e74705SXin Li // C++11 [expr.prim.lambda]p23:
1087*67e74705SXin Li // A capture followed by an ellipsis is a pack expansion (14.5.3).
1088*67e74705SXin Li SourceLocation EllipsisLoc;
1089*67e74705SXin Li if (C->EllipsisLoc.isValid()) {
1090*67e74705SXin Li if (Var->isParameterPack()) {
1091*67e74705SXin Li EllipsisLoc = C->EllipsisLoc;
1092*67e74705SXin Li } else {
1093*67e74705SXin Li Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1094*67e74705SXin Li << SourceRange(C->Loc);
1095*67e74705SXin Li
1096*67e74705SXin Li // Just ignore the ellipsis.
1097*67e74705SXin Li }
1098*67e74705SXin Li } else if (Var->isParameterPack()) {
1099*67e74705SXin Li ContainsUnexpandedParameterPack = true;
1100*67e74705SXin Li }
1101*67e74705SXin Li
1102*67e74705SXin Li if (C->Init.isUsable()) {
1103*67e74705SXin Li buildInitCaptureField(LSI, Var);
1104*67e74705SXin Li } else {
1105*67e74705SXin Li TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1106*67e74705SXin Li TryCapture_ExplicitByVal;
1107*67e74705SXin Li tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1108*67e74705SXin Li }
1109*67e74705SXin Li }
1110*67e74705SXin Li finishLambdaExplicitCaptures(LSI);
1111*67e74705SXin Li
1112*67e74705SXin Li LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1113*67e74705SXin Li
1114*67e74705SXin Li // Add lambda parameters into scope.
1115*67e74705SXin Li addLambdaParameters(Method, CurScope);
1116*67e74705SXin Li
1117*67e74705SXin Li // Enter a new evaluation context to insulate the lambda from any
1118*67e74705SXin Li // cleanups from the enclosing full-expression.
1119*67e74705SXin Li PushExpressionEvaluationContext(PotentiallyEvaluated);
1120*67e74705SXin Li }
1121*67e74705SXin Li
ActOnLambdaError(SourceLocation StartLoc,Scope * CurScope,bool IsInstantiation)1122*67e74705SXin Li void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1123*67e74705SXin Li bool IsInstantiation) {
1124*67e74705SXin Li LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1125*67e74705SXin Li
1126*67e74705SXin Li // Leave the expression-evaluation context.
1127*67e74705SXin Li DiscardCleanupsInEvaluationContext();
1128*67e74705SXin Li PopExpressionEvaluationContext();
1129*67e74705SXin Li
1130*67e74705SXin Li // Leave the context of the lambda.
1131*67e74705SXin Li if (!IsInstantiation)
1132*67e74705SXin Li PopDeclContext();
1133*67e74705SXin Li
1134*67e74705SXin Li // Finalize the lambda.
1135*67e74705SXin Li CXXRecordDecl *Class = LSI->Lambda;
1136*67e74705SXin Li Class->setInvalidDecl();
1137*67e74705SXin Li SmallVector<Decl*, 4> Fields(Class->fields());
1138*67e74705SXin Li ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1139*67e74705SXin Li SourceLocation(), nullptr);
1140*67e74705SXin Li CheckCompletedCXXClass(Class);
1141*67e74705SXin Li
1142*67e74705SXin Li PopFunctionScopeInfo();
1143*67e74705SXin Li }
1144*67e74705SXin Li
1145*67e74705SXin Li /// \brief Add a lambda's conversion to function pointer, as described in
1146*67e74705SXin Li /// C++11 [expr.prim.lambda]p6.
addFunctionPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1147*67e74705SXin Li static void addFunctionPointerConversion(Sema &S,
1148*67e74705SXin Li SourceRange IntroducerRange,
1149*67e74705SXin Li CXXRecordDecl *Class,
1150*67e74705SXin Li CXXMethodDecl *CallOperator) {
1151*67e74705SXin Li // This conversion is explicitly disabled if the lambda's function has
1152*67e74705SXin Li // pass_object_size attributes on any of its parameters.
1153*67e74705SXin Li if (llvm::any_of(CallOperator->parameters(),
1154*67e74705SXin Li std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)))
1155*67e74705SXin Li return;
1156*67e74705SXin Li
1157*67e74705SXin Li // Add the conversion to function pointer.
1158*67e74705SXin Li const FunctionProtoType *CallOpProto =
1159*67e74705SXin Li CallOperator->getType()->getAs<FunctionProtoType>();
1160*67e74705SXin Li const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1161*67e74705SXin Li CallOpProto->getExtProtoInfo();
1162*67e74705SXin Li QualType PtrToFunctionTy;
1163*67e74705SXin Li QualType InvokerFunctionTy;
1164*67e74705SXin Li {
1165*67e74705SXin Li FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1166*67e74705SXin Li CallingConv CC = S.Context.getDefaultCallingConvention(
1167*67e74705SXin Li CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1168*67e74705SXin Li InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1169*67e74705SXin Li InvokerExtInfo.TypeQuals = 0;
1170*67e74705SXin Li assert(InvokerExtInfo.RefQualifier == RQ_None &&
1171*67e74705SXin Li "Lambda's call operator should not have a reference qualifier");
1172*67e74705SXin Li InvokerFunctionTy =
1173*67e74705SXin Li S.Context.getFunctionType(CallOpProto->getReturnType(),
1174*67e74705SXin Li CallOpProto->getParamTypes(), InvokerExtInfo);
1175*67e74705SXin Li PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1176*67e74705SXin Li }
1177*67e74705SXin Li
1178*67e74705SXin Li // Create the type of the conversion function.
1179*67e74705SXin Li FunctionProtoType::ExtProtoInfo ConvExtInfo(
1180*67e74705SXin Li S.Context.getDefaultCallingConvention(
1181*67e74705SXin Li /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1182*67e74705SXin Li // The conversion function is always const.
1183*67e74705SXin Li ConvExtInfo.TypeQuals = Qualifiers::Const;
1184*67e74705SXin Li QualType ConvTy =
1185*67e74705SXin Li S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1186*67e74705SXin Li
1187*67e74705SXin Li SourceLocation Loc = IntroducerRange.getBegin();
1188*67e74705SXin Li DeclarationName ConversionName
1189*67e74705SXin Li = S.Context.DeclarationNames.getCXXConversionFunctionName(
1190*67e74705SXin Li S.Context.getCanonicalType(PtrToFunctionTy));
1191*67e74705SXin Li DeclarationNameLoc ConvNameLoc;
1192*67e74705SXin Li // Construct a TypeSourceInfo for the conversion function, and wire
1193*67e74705SXin Li // all the parameters appropriately for the FunctionProtoTypeLoc
1194*67e74705SXin Li // so that everything works during transformation/instantiation of
1195*67e74705SXin Li // generic lambdas.
1196*67e74705SXin Li // The main reason for wiring up the parameters of the conversion
1197*67e74705SXin Li // function with that of the call operator is so that constructs
1198*67e74705SXin Li // like the following work:
1199*67e74705SXin Li // auto L = [](auto b) { <-- 1
1200*67e74705SXin Li // return [](auto a) -> decltype(a) { <-- 2
1201*67e74705SXin Li // return a;
1202*67e74705SXin Li // };
1203*67e74705SXin Li // };
1204*67e74705SXin Li // int (*fp)(int) = L(5);
1205*67e74705SXin Li // Because the trailing return type can contain DeclRefExprs that refer
1206*67e74705SXin Li // to the original call operator's variables, we hijack the call
1207*67e74705SXin Li // operators ParmVarDecls below.
1208*67e74705SXin Li TypeSourceInfo *ConvNamePtrToFunctionTSI =
1209*67e74705SXin Li S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1210*67e74705SXin Li ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1211*67e74705SXin Li
1212*67e74705SXin Li // The conversion function is a conversion to a pointer-to-function.
1213*67e74705SXin Li TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1214*67e74705SXin Li FunctionProtoTypeLoc ConvTL =
1215*67e74705SXin Li ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1216*67e74705SXin Li // Get the result of the conversion function which is a pointer-to-function.
1217*67e74705SXin Li PointerTypeLoc PtrToFunctionTL =
1218*67e74705SXin Li ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1219*67e74705SXin Li // Do the same for the TypeSourceInfo that is used to name the conversion
1220*67e74705SXin Li // operator.
1221*67e74705SXin Li PointerTypeLoc ConvNamePtrToFunctionTL =
1222*67e74705SXin Li ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1223*67e74705SXin Li
1224*67e74705SXin Li // Get the underlying function types that the conversion function will
1225*67e74705SXin Li // be converting to (should match the type of the call operator).
1226*67e74705SXin Li FunctionProtoTypeLoc CallOpConvTL =
1227*67e74705SXin Li PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1228*67e74705SXin Li FunctionProtoTypeLoc CallOpConvNameTL =
1229*67e74705SXin Li ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1230*67e74705SXin Li
1231*67e74705SXin Li // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1232*67e74705SXin Li // These parameter's are essentially used to transform the name and
1233*67e74705SXin Li // the type of the conversion operator. By using the same parameters
1234*67e74705SXin Li // as the call operator's we don't have to fix any back references that
1235*67e74705SXin Li // the trailing return type of the call operator's uses (such as
1236*67e74705SXin Li // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1237*67e74705SXin Li // - we can simply use the return type of the call operator, and
1238*67e74705SXin Li // everything should work.
1239*67e74705SXin Li SmallVector<ParmVarDecl *, 4> InvokerParams;
1240*67e74705SXin Li for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1241*67e74705SXin Li ParmVarDecl *From = CallOperator->getParamDecl(I);
1242*67e74705SXin Li
1243*67e74705SXin Li InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1244*67e74705SXin Li // Temporarily add to the TU. This is set to the invoker below.
1245*67e74705SXin Li S.Context.getTranslationUnitDecl(),
1246*67e74705SXin Li From->getLocStart(),
1247*67e74705SXin Li From->getLocation(),
1248*67e74705SXin Li From->getIdentifier(),
1249*67e74705SXin Li From->getType(),
1250*67e74705SXin Li From->getTypeSourceInfo(),
1251*67e74705SXin Li From->getStorageClass(),
1252*67e74705SXin Li /*DefaultArg=*/nullptr));
1253*67e74705SXin Li CallOpConvTL.setParam(I, From);
1254*67e74705SXin Li CallOpConvNameTL.setParam(I, From);
1255*67e74705SXin Li }
1256*67e74705SXin Li
1257*67e74705SXin Li CXXConversionDecl *Conversion
1258*67e74705SXin Li = CXXConversionDecl::Create(S.Context, Class, Loc,
1259*67e74705SXin Li DeclarationNameInfo(ConversionName,
1260*67e74705SXin Li Loc, ConvNameLoc),
1261*67e74705SXin Li ConvTy,
1262*67e74705SXin Li ConvTSI,
1263*67e74705SXin Li /*isInline=*/true, /*isExplicit=*/false,
1264*67e74705SXin Li /*isConstexpr=*/false,
1265*67e74705SXin Li CallOperator->getBody()->getLocEnd());
1266*67e74705SXin Li Conversion->setAccess(AS_public);
1267*67e74705SXin Li Conversion->setImplicit(true);
1268*67e74705SXin Li
1269*67e74705SXin Li if (Class->isGenericLambda()) {
1270*67e74705SXin Li // Create a template version of the conversion operator, using the template
1271*67e74705SXin Li // parameter list of the function call operator.
1272*67e74705SXin Li FunctionTemplateDecl *TemplateCallOperator =
1273*67e74705SXin Li CallOperator->getDescribedFunctionTemplate();
1274*67e74705SXin Li FunctionTemplateDecl *ConversionTemplate =
1275*67e74705SXin Li FunctionTemplateDecl::Create(S.Context, Class,
1276*67e74705SXin Li Loc, ConversionName,
1277*67e74705SXin Li TemplateCallOperator->getTemplateParameters(),
1278*67e74705SXin Li Conversion);
1279*67e74705SXin Li ConversionTemplate->setAccess(AS_public);
1280*67e74705SXin Li ConversionTemplate->setImplicit(true);
1281*67e74705SXin Li Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1282*67e74705SXin Li Class->addDecl(ConversionTemplate);
1283*67e74705SXin Li } else
1284*67e74705SXin Li Class->addDecl(Conversion);
1285*67e74705SXin Li // Add a non-static member function that will be the result of
1286*67e74705SXin Li // the conversion with a certain unique ID.
1287*67e74705SXin Li DeclarationName InvokerName = &S.Context.Idents.get(
1288*67e74705SXin Li getLambdaStaticInvokerName());
1289*67e74705SXin Li // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1290*67e74705SXin Li // we should get a prebuilt TrivialTypeSourceInfo from Context
1291*67e74705SXin Li // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1292*67e74705SXin Li // then rewire the parameters accordingly, by hoisting up the InvokeParams
1293*67e74705SXin Li // loop below and then use its Params to set Invoke->setParams(...) below.
1294*67e74705SXin Li // This would avoid the 'const' qualifier of the calloperator from
1295*67e74705SXin Li // contaminating the type of the invoker, which is currently adjusted
1296*67e74705SXin Li // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1297*67e74705SXin Li // trailing return type of the invoker would require a visitor to rebuild
1298*67e74705SXin Li // the trailing return type and adjusting all back DeclRefExpr's to refer
1299*67e74705SXin Li // to the new static invoker parameters - not the call operator's.
1300*67e74705SXin Li CXXMethodDecl *Invoke
1301*67e74705SXin Li = CXXMethodDecl::Create(S.Context, Class, Loc,
1302*67e74705SXin Li DeclarationNameInfo(InvokerName, Loc),
1303*67e74705SXin Li InvokerFunctionTy,
1304*67e74705SXin Li CallOperator->getTypeSourceInfo(),
1305*67e74705SXin Li SC_Static, /*IsInline=*/true,
1306*67e74705SXin Li /*IsConstexpr=*/false,
1307*67e74705SXin Li CallOperator->getBody()->getLocEnd());
1308*67e74705SXin Li for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1309*67e74705SXin Li InvokerParams[I]->setOwningFunction(Invoke);
1310*67e74705SXin Li Invoke->setParams(InvokerParams);
1311*67e74705SXin Li Invoke->setAccess(AS_private);
1312*67e74705SXin Li Invoke->setImplicit(true);
1313*67e74705SXin Li if (Class->isGenericLambda()) {
1314*67e74705SXin Li FunctionTemplateDecl *TemplateCallOperator =
1315*67e74705SXin Li CallOperator->getDescribedFunctionTemplate();
1316*67e74705SXin Li FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1317*67e74705SXin Li S.Context, Class, Loc, InvokerName,
1318*67e74705SXin Li TemplateCallOperator->getTemplateParameters(),
1319*67e74705SXin Li Invoke);
1320*67e74705SXin Li StaticInvokerTemplate->setAccess(AS_private);
1321*67e74705SXin Li StaticInvokerTemplate->setImplicit(true);
1322*67e74705SXin Li Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1323*67e74705SXin Li Class->addDecl(StaticInvokerTemplate);
1324*67e74705SXin Li } else
1325*67e74705SXin Li Class->addDecl(Invoke);
1326*67e74705SXin Li }
1327*67e74705SXin Li
1328*67e74705SXin Li /// \brief Add a lambda's conversion to block pointer.
addBlockPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1329*67e74705SXin Li static void addBlockPointerConversion(Sema &S,
1330*67e74705SXin Li SourceRange IntroducerRange,
1331*67e74705SXin Li CXXRecordDecl *Class,
1332*67e74705SXin Li CXXMethodDecl *CallOperator) {
1333*67e74705SXin Li const FunctionProtoType *Proto =
1334*67e74705SXin Li CallOperator->getType()->getAs<FunctionProtoType>();
1335*67e74705SXin Li
1336*67e74705SXin Li // The function type inside the block pointer type is the same as the call
1337*67e74705SXin Li // operator with some tweaks. The calling convention is the default free
1338*67e74705SXin Li // function convention, and the type qualifications are lost.
1339*67e74705SXin Li FunctionProtoType::ExtProtoInfo BlockEPI = Proto->getExtProtoInfo();
1340*67e74705SXin Li BlockEPI.ExtInfo =
1341*67e74705SXin Li BlockEPI.ExtInfo.withCallingConv(S.Context.getDefaultCallingConvention(
1342*67e74705SXin Li Proto->isVariadic(), /*IsCXXMethod=*/false));
1343*67e74705SXin Li BlockEPI.TypeQuals = 0;
1344*67e74705SXin Li QualType FunctionTy = S.Context.getFunctionType(
1345*67e74705SXin Li Proto->getReturnType(), Proto->getParamTypes(), BlockEPI);
1346*67e74705SXin Li QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1347*67e74705SXin Li
1348*67e74705SXin Li FunctionProtoType::ExtProtoInfo ConversionEPI(
1349*67e74705SXin Li S.Context.getDefaultCallingConvention(
1350*67e74705SXin Li /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1351*67e74705SXin Li ConversionEPI.TypeQuals = Qualifiers::Const;
1352*67e74705SXin Li QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1353*67e74705SXin Li
1354*67e74705SXin Li SourceLocation Loc = IntroducerRange.getBegin();
1355*67e74705SXin Li DeclarationName Name
1356*67e74705SXin Li = S.Context.DeclarationNames.getCXXConversionFunctionName(
1357*67e74705SXin Li S.Context.getCanonicalType(BlockPtrTy));
1358*67e74705SXin Li DeclarationNameLoc NameLoc;
1359*67e74705SXin Li NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1360*67e74705SXin Li CXXConversionDecl *Conversion
1361*67e74705SXin Li = CXXConversionDecl::Create(S.Context, Class, Loc,
1362*67e74705SXin Li DeclarationNameInfo(Name, Loc, NameLoc),
1363*67e74705SXin Li ConvTy,
1364*67e74705SXin Li S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1365*67e74705SXin Li /*isInline=*/true, /*isExplicit=*/false,
1366*67e74705SXin Li /*isConstexpr=*/false,
1367*67e74705SXin Li CallOperator->getBody()->getLocEnd());
1368*67e74705SXin Li Conversion->setAccess(AS_public);
1369*67e74705SXin Li Conversion->setImplicit(true);
1370*67e74705SXin Li Class->addDecl(Conversion);
1371*67e74705SXin Li }
1372*67e74705SXin Li
performLambdaVarCaptureInitialization(Sema & S,LambdaScopeInfo::Capture & Capture,FieldDecl * Field,SmallVectorImpl<VarDecl * > & ArrayIndexVars,SmallVectorImpl<unsigned> & ArrayIndexStarts)1373*67e74705SXin Li static ExprResult performLambdaVarCaptureInitialization(
1374*67e74705SXin Li Sema &S, LambdaScopeInfo::Capture &Capture,
1375*67e74705SXin Li FieldDecl *Field,
1376*67e74705SXin Li SmallVectorImpl<VarDecl *> &ArrayIndexVars,
1377*67e74705SXin Li SmallVectorImpl<unsigned> &ArrayIndexStarts) {
1378*67e74705SXin Li assert(Capture.isVariableCapture() && "not a variable capture");
1379*67e74705SXin Li
1380*67e74705SXin Li auto *Var = Capture.getVariable();
1381*67e74705SXin Li SourceLocation Loc = Capture.getLocation();
1382*67e74705SXin Li
1383*67e74705SXin Li // C++11 [expr.prim.lambda]p21:
1384*67e74705SXin Li // When the lambda-expression is evaluated, the entities that
1385*67e74705SXin Li // are captured by copy are used to direct-initialize each
1386*67e74705SXin Li // corresponding non-static data member of the resulting closure
1387*67e74705SXin Li // object. (For array members, the array elements are
1388*67e74705SXin Li // direct-initialized in increasing subscript order.) These
1389*67e74705SXin Li // initializations are performed in the (unspecified) order in
1390*67e74705SXin Li // which the non-static data members are declared.
1391*67e74705SXin Li
1392*67e74705SXin Li // C++ [expr.prim.lambda]p12:
1393*67e74705SXin Li // An entity captured by a lambda-expression is odr-used (3.2) in
1394*67e74705SXin Li // the scope containing the lambda-expression.
1395*67e74705SXin Li ExprResult RefResult = S.BuildDeclarationNameExpr(
1396*67e74705SXin Li CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1397*67e74705SXin Li if (RefResult.isInvalid())
1398*67e74705SXin Li return ExprError();
1399*67e74705SXin Li Expr *Ref = RefResult.get();
1400*67e74705SXin Li
1401*67e74705SXin Li QualType FieldType = Field->getType();
1402*67e74705SXin Li
1403*67e74705SXin Li // When the variable has array type, create index variables for each
1404*67e74705SXin Li // dimension of the array. We use these index variables to subscript
1405*67e74705SXin Li // the source array, and other clients (e.g., CodeGen) will perform
1406*67e74705SXin Li // the necessary iteration with these index variables.
1407*67e74705SXin Li //
1408*67e74705SXin Li // FIXME: This is dumb. Add a proper AST representation for array
1409*67e74705SXin Li // copy-construction and use it here.
1410*67e74705SXin Li SmallVector<VarDecl *, 4> IndexVariables;
1411*67e74705SXin Li QualType BaseType = FieldType;
1412*67e74705SXin Li QualType SizeType = S.Context.getSizeType();
1413*67e74705SXin Li ArrayIndexStarts.push_back(ArrayIndexVars.size());
1414*67e74705SXin Li while (const ConstantArrayType *Array
1415*67e74705SXin Li = S.Context.getAsConstantArrayType(BaseType)) {
1416*67e74705SXin Li // Create the iteration variable for this array index.
1417*67e74705SXin Li IdentifierInfo *IterationVarName = nullptr;
1418*67e74705SXin Li {
1419*67e74705SXin Li SmallString<8> Str;
1420*67e74705SXin Li llvm::raw_svector_ostream OS(Str);
1421*67e74705SXin Li OS << "__i" << IndexVariables.size();
1422*67e74705SXin Li IterationVarName = &S.Context.Idents.get(OS.str());
1423*67e74705SXin Li }
1424*67e74705SXin Li VarDecl *IterationVar = VarDecl::Create(
1425*67e74705SXin Li S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
1426*67e74705SXin Li S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
1427*67e74705SXin Li IterationVar->setImplicit();
1428*67e74705SXin Li IndexVariables.push_back(IterationVar);
1429*67e74705SXin Li ArrayIndexVars.push_back(IterationVar);
1430*67e74705SXin Li
1431*67e74705SXin Li // Create a reference to the iteration variable.
1432*67e74705SXin Li ExprResult IterationVarRef =
1433*67e74705SXin Li S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
1434*67e74705SXin Li assert(!IterationVarRef.isInvalid() &&
1435*67e74705SXin Li "Reference to invented variable cannot fail!");
1436*67e74705SXin Li IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
1437*67e74705SXin Li assert(!IterationVarRef.isInvalid() &&
1438*67e74705SXin Li "Conversion of invented variable cannot fail!");
1439*67e74705SXin Li
1440*67e74705SXin Li // Subscript the array with this iteration variable.
1441*67e74705SXin Li ExprResult Subscript =
1442*67e74705SXin Li S.CreateBuiltinArraySubscriptExpr(Ref, Loc, IterationVarRef.get(), Loc);
1443*67e74705SXin Li if (Subscript.isInvalid())
1444*67e74705SXin Li return ExprError();
1445*67e74705SXin Li
1446*67e74705SXin Li Ref = Subscript.get();
1447*67e74705SXin Li BaseType = Array->getElementType();
1448*67e74705SXin Li }
1449*67e74705SXin Li
1450*67e74705SXin Li // Construct the entity that we will be initializing. For an array, this
1451*67e74705SXin Li // will be first element in the array, which may require several levels
1452*67e74705SXin Li // of array-subscript entities.
1453*67e74705SXin Li SmallVector<InitializedEntity, 4> Entities;
1454*67e74705SXin Li Entities.reserve(1 + IndexVariables.size());
1455*67e74705SXin Li Entities.push_back(InitializedEntity::InitializeLambdaCapture(
1456*67e74705SXin Li Var->getIdentifier(), FieldType, Loc));
1457*67e74705SXin Li for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1458*67e74705SXin Li Entities.push_back(
1459*67e74705SXin Li InitializedEntity::InitializeElement(S.Context, 0, Entities.back()));
1460*67e74705SXin Li
1461*67e74705SXin Li InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1462*67e74705SXin Li InitializationSequence Init(S, Entities.back(), InitKind, Ref);
1463*67e74705SXin Li return Init.Perform(S, Entities.back(), InitKind, Ref);
1464*67e74705SXin Li }
1465*67e74705SXin Li
ActOnLambdaExpr(SourceLocation StartLoc,Stmt * Body,Scope * CurScope)1466*67e74705SXin Li ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1467*67e74705SXin Li Scope *CurScope) {
1468*67e74705SXin Li LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1469*67e74705SXin Li ActOnFinishFunctionBody(LSI.CallOperator, Body);
1470*67e74705SXin Li return BuildLambdaExpr(StartLoc, Body->getLocEnd(), &LSI);
1471*67e74705SXin Li }
1472*67e74705SXin Li
1473*67e74705SXin Li static LambdaCaptureDefault
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)1474*67e74705SXin Li mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1475*67e74705SXin Li switch (ICS) {
1476*67e74705SXin Li case CapturingScopeInfo::ImpCap_None:
1477*67e74705SXin Li return LCD_None;
1478*67e74705SXin Li case CapturingScopeInfo::ImpCap_LambdaByval:
1479*67e74705SXin Li return LCD_ByCopy;
1480*67e74705SXin Li case CapturingScopeInfo::ImpCap_CapturedRegion:
1481*67e74705SXin Li case CapturingScopeInfo::ImpCap_LambdaByref:
1482*67e74705SXin Li return LCD_ByRef;
1483*67e74705SXin Li case CapturingScopeInfo::ImpCap_Block:
1484*67e74705SXin Li llvm_unreachable("block capture in lambda");
1485*67e74705SXin Li }
1486*67e74705SXin Li llvm_unreachable("Unknown implicit capture style");
1487*67e74705SXin Li }
1488*67e74705SXin Li
BuildLambdaExpr(SourceLocation StartLoc,SourceLocation EndLoc,LambdaScopeInfo * LSI)1489*67e74705SXin Li ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1490*67e74705SXin Li LambdaScopeInfo *LSI) {
1491*67e74705SXin Li // Collect information from the lambda scope.
1492*67e74705SXin Li SmallVector<LambdaCapture, 4> Captures;
1493*67e74705SXin Li SmallVector<Expr *, 4> CaptureInits;
1494*67e74705SXin Li SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1495*67e74705SXin Li LambdaCaptureDefault CaptureDefault =
1496*67e74705SXin Li mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1497*67e74705SXin Li CXXRecordDecl *Class;
1498*67e74705SXin Li CXXMethodDecl *CallOperator;
1499*67e74705SXin Li SourceRange IntroducerRange;
1500*67e74705SXin Li bool ExplicitParams;
1501*67e74705SXin Li bool ExplicitResultType;
1502*67e74705SXin Li CleanupInfo LambdaCleanup;
1503*67e74705SXin Li bool ContainsUnexpandedParameterPack;
1504*67e74705SXin Li SmallVector<VarDecl *, 4> ArrayIndexVars;
1505*67e74705SXin Li SmallVector<unsigned, 4> ArrayIndexStarts;
1506*67e74705SXin Li {
1507*67e74705SXin Li CallOperator = LSI->CallOperator;
1508*67e74705SXin Li Class = LSI->Lambda;
1509*67e74705SXin Li IntroducerRange = LSI->IntroducerRange;
1510*67e74705SXin Li ExplicitParams = LSI->ExplicitParams;
1511*67e74705SXin Li ExplicitResultType = !LSI->HasImplicitReturnType;
1512*67e74705SXin Li LambdaCleanup = LSI->Cleanup;
1513*67e74705SXin Li ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1514*67e74705SXin Li
1515*67e74705SXin Li CallOperator->setLexicalDeclContext(Class);
1516*67e74705SXin Li Decl *TemplateOrNonTemplateCallOperatorDecl =
1517*67e74705SXin Li CallOperator->getDescribedFunctionTemplate()
1518*67e74705SXin Li ? CallOperator->getDescribedFunctionTemplate()
1519*67e74705SXin Li : cast<Decl>(CallOperator);
1520*67e74705SXin Li
1521*67e74705SXin Li TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1522*67e74705SXin Li Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1523*67e74705SXin Li
1524*67e74705SXin Li PopExpressionEvaluationContext();
1525*67e74705SXin Li
1526*67e74705SXin Li // Translate captures.
1527*67e74705SXin Li auto CurField = Class->field_begin();
1528*67e74705SXin Li for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I, ++CurField) {
1529*67e74705SXin Li LambdaScopeInfo::Capture From = LSI->Captures[I];
1530*67e74705SXin Li assert(!From.isBlockCapture() && "Cannot capture __block variables");
1531*67e74705SXin Li bool IsImplicit = I >= LSI->NumExplicitCaptures;
1532*67e74705SXin Li
1533*67e74705SXin Li // Handle 'this' capture.
1534*67e74705SXin Li if (From.isThisCapture()) {
1535*67e74705SXin Li Captures.push_back(
1536*67e74705SXin Li LambdaCapture(From.getLocation(), IsImplicit,
1537*67e74705SXin Li From.isCopyCapture() ? LCK_StarThis : LCK_This));
1538*67e74705SXin Li CaptureInits.push_back(From.getInitExpr());
1539*67e74705SXin Li ArrayIndexStarts.push_back(ArrayIndexVars.size());
1540*67e74705SXin Li continue;
1541*67e74705SXin Li }
1542*67e74705SXin Li if (From.isVLATypeCapture()) {
1543*67e74705SXin Li Captures.push_back(
1544*67e74705SXin Li LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType));
1545*67e74705SXin Li CaptureInits.push_back(nullptr);
1546*67e74705SXin Li ArrayIndexStarts.push_back(ArrayIndexVars.size());
1547*67e74705SXin Li continue;
1548*67e74705SXin Li }
1549*67e74705SXin Li
1550*67e74705SXin Li VarDecl *Var = From.getVariable();
1551*67e74705SXin Li LambdaCaptureKind Kind = From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
1552*67e74705SXin Li Captures.push_back(LambdaCapture(From.getLocation(), IsImplicit, Kind,
1553*67e74705SXin Li Var, From.getEllipsisLoc()));
1554*67e74705SXin Li Expr *Init = From.getInitExpr();
1555*67e74705SXin Li if (!Init) {
1556*67e74705SXin Li auto InitResult = performLambdaVarCaptureInitialization(
1557*67e74705SXin Li *this, From, *CurField, ArrayIndexVars, ArrayIndexStarts);
1558*67e74705SXin Li if (InitResult.isInvalid())
1559*67e74705SXin Li return ExprError();
1560*67e74705SXin Li Init = InitResult.get();
1561*67e74705SXin Li } else {
1562*67e74705SXin Li ArrayIndexStarts.push_back(ArrayIndexVars.size());
1563*67e74705SXin Li }
1564*67e74705SXin Li CaptureInits.push_back(Init);
1565*67e74705SXin Li }
1566*67e74705SXin Li
1567*67e74705SXin Li // C++11 [expr.prim.lambda]p6:
1568*67e74705SXin Li // The closure type for a lambda-expression with no lambda-capture
1569*67e74705SXin Li // has a public non-virtual non-explicit const conversion function
1570*67e74705SXin Li // to pointer to function having the same parameter and return
1571*67e74705SXin Li // types as the closure type's function call operator.
1572*67e74705SXin Li if (Captures.empty() && CaptureDefault == LCD_None)
1573*67e74705SXin Li addFunctionPointerConversion(*this, IntroducerRange, Class,
1574*67e74705SXin Li CallOperator);
1575*67e74705SXin Li
1576*67e74705SXin Li // Objective-C++:
1577*67e74705SXin Li // The closure type for a lambda-expression has a public non-virtual
1578*67e74705SXin Li // non-explicit const conversion function to a block pointer having the
1579*67e74705SXin Li // same parameter and return types as the closure type's function call
1580*67e74705SXin Li // operator.
1581*67e74705SXin Li // FIXME: Fix generic lambda to block conversions.
1582*67e74705SXin Li if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1583*67e74705SXin Li !Class->isGenericLambda())
1584*67e74705SXin Li addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1585*67e74705SXin Li
1586*67e74705SXin Li // Finalize the lambda class.
1587*67e74705SXin Li SmallVector<Decl*, 4> Fields(Class->fields());
1588*67e74705SXin Li ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1589*67e74705SXin Li SourceLocation(), nullptr);
1590*67e74705SXin Li CheckCompletedCXXClass(Class);
1591*67e74705SXin Li }
1592*67e74705SXin Li
1593*67e74705SXin Li Cleanup.mergeFrom(LambdaCleanup);
1594*67e74705SXin Li
1595*67e74705SXin Li LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1596*67e74705SXin Li CaptureDefault, CaptureDefaultLoc,
1597*67e74705SXin Li Captures,
1598*67e74705SXin Li ExplicitParams, ExplicitResultType,
1599*67e74705SXin Li CaptureInits, ArrayIndexVars,
1600*67e74705SXin Li ArrayIndexStarts, EndLoc,
1601*67e74705SXin Li ContainsUnexpandedParameterPack);
1602*67e74705SXin Li // If the lambda expression's call operator is not explicitly marked constexpr
1603*67e74705SXin Li // and we are not in a dependent context, analyze the call operator to infer
1604*67e74705SXin Li // its constexpr-ness, supressing diagnostics while doing so.
1605*67e74705SXin Li if (getLangOpts().CPlusPlus1z && !CallOperator->isInvalidDecl() &&
1606*67e74705SXin Li !CallOperator->isConstexpr() &&
1607*67e74705SXin Li !Class->getDeclContext()->isDependentContext()) {
1608*67e74705SXin Li TentativeAnalysisScope DiagnosticScopeGuard(*this);
1609*67e74705SXin Li CallOperator->setConstexpr(
1610*67e74705SXin Li CheckConstexprFunctionDecl(CallOperator) &&
1611*67e74705SXin Li CheckConstexprFunctionBody(CallOperator, CallOperator->getBody()));
1612*67e74705SXin Li }
1613*67e74705SXin Li
1614*67e74705SXin Li if (!CurContext->isDependentContext()) {
1615*67e74705SXin Li switch (ExprEvalContexts.back().Context) {
1616*67e74705SXin Li // C++11 [expr.prim.lambda]p2:
1617*67e74705SXin Li // A lambda-expression shall not appear in an unevaluated operand
1618*67e74705SXin Li // (Clause 5).
1619*67e74705SXin Li case Unevaluated:
1620*67e74705SXin Li case UnevaluatedAbstract:
1621*67e74705SXin Li // C++1y [expr.const]p2:
1622*67e74705SXin Li // A conditional-expression e is a core constant expression unless the
1623*67e74705SXin Li // evaluation of e, following the rules of the abstract machine, would
1624*67e74705SXin Li // evaluate [...] a lambda-expression.
1625*67e74705SXin Li //
1626*67e74705SXin Li // This is technically incorrect, there are some constant evaluated contexts
1627*67e74705SXin Li // where this should be allowed. We should probably fix this when DR1607 is
1628*67e74705SXin Li // ratified, it lays out the exact set of conditions where we shouldn't
1629*67e74705SXin Li // allow a lambda-expression.
1630*67e74705SXin Li case ConstantEvaluated:
1631*67e74705SXin Li // We don't actually diagnose this case immediately, because we
1632*67e74705SXin Li // could be within a context where we might find out later that
1633*67e74705SXin Li // the expression is potentially evaluated (e.g., for typeid).
1634*67e74705SXin Li ExprEvalContexts.back().Lambdas.push_back(Lambda);
1635*67e74705SXin Li break;
1636*67e74705SXin Li
1637*67e74705SXin Li case DiscardedStatement:
1638*67e74705SXin Li case PotentiallyEvaluated:
1639*67e74705SXin Li case PotentiallyEvaluatedIfUsed:
1640*67e74705SXin Li break;
1641*67e74705SXin Li }
1642*67e74705SXin Li }
1643*67e74705SXin Li
1644*67e74705SXin Li return MaybeBindToTemporary(Lambda);
1645*67e74705SXin Li }
1646*67e74705SXin Li
BuildBlockForLambdaConversion(SourceLocation CurrentLocation,SourceLocation ConvLocation,CXXConversionDecl * Conv,Expr * Src)1647*67e74705SXin Li ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1648*67e74705SXin Li SourceLocation ConvLocation,
1649*67e74705SXin Li CXXConversionDecl *Conv,
1650*67e74705SXin Li Expr *Src) {
1651*67e74705SXin Li // Make sure that the lambda call operator is marked used.
1652*67e74705SXin Li CXXRecordDecl *Lambda = Conv->getParent();
1653*67e74705SXin Li CXXMethodDecl *CallOperator
1654*67e74705SXin Li = cast<CXXMethodDecl>(
1655*67e74705SXin Li Lambda->lookup(
1656*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1657*67e74705SXin Li CallOperator->setReferenced();
1658*67e74705SXin Li CallOperator->markUsed(Context);
1659*67e74705SXin Li
1660*67e74705SXin Li ExprResult Init = PerformCopyInitialization(
1661*67e74705SXin Li InitializedEntity::InitializeBlock(ConvLocation,
1662*67e74705SXin Li Src->getType(),
1663*67e74705SXin Li /*NRVO=*/false),
1664*67e74705SXin Li CurrentLocation, Src);
1665*67e74705SXin Li if (!Init.isInvalid())
1666*67e74705SXin Li Init = ActOnFinishFullExpr(Init.get());
1667*67e74705SXin Li
1668*67e74705SXin Li if (Init.isInvalid())
1669*67e74705SXin Li return ExprError();
1670*67e74705SXin Li
1671*67e74705SXin Li // Create the new block to be returned.
1672*67e74705SXin Li BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1673*67e74705SXin Li
1674*67e74705SXin Li // Set the type information.
1675*67e74705SXin Li Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1676*67e74705SXin Li Block->setIsVariadic(CallOperator->isVariadic());
1677*67e74705SXin Li Block->setBlockMissingReturnType(false);
1678*67e74705SXin Li
1679*67e74705SXin Li // Add parameters.
1680*67e74705SXin Li SmallVector<ParmVarDecl *, 4> BlockParams;
1681*67e74705SXin Li for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1682*67e74705SXin Li ParmVarDecl *From = CallOperator->getParamDecl(I);
1683*67e74705SXin Li BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1684*67e74705SXin Li From->getLocStart(),
1685*67e74705SXin Li From->getLocation(),
1686*67e74705SXin Li From->getIdentifier(),
1687*67e74705SXin Li From->getType(),
1688*67e74705SXin Li From->getTypeSourceInfo(),
1689*67e74705SXin Li From->getStorageClass(),
1690*67e74705SXin Li /*DefaultArg=*/nullptr));
1691*67e74705SXin Li }
1692*67e74705SXin Li Block->setParams(BlockParams);
1693*67e74705SXin Li
1694*67e74705SXin Li Block->setIsConversionFromLambda(true);
1695*67e74705SXin Li
1696*67e74705SXin Li // Add capture. The capture uses a fake variable, which doesn't correspond
1697*67e74705SXin Li // to any actual memory location. However, the initializer copy-initializes
1698*67e74705SXin Li // the lambda object.
1699*67e74705SXin Li TypeSourceInfo *CapVarTSI =
1700*67e74705SXin Li Context.getTrivialTypeSourceInfo(Src->getType());
1701*67e74705SXin Li VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1702*67e74705SXin Li ConvLocation, nullptr,
1703*67e74705SXin Li Src->getType(), CapVarTSI,
1704*67e74705SXin Li SC_None);
1705*67e74705SXin Li BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1706*67e74705SXin Li /*Nested=*/false, /*Copy=*/Init.get());
1707*67e74705SXin Li Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
1708*67e74705SXin Li
1709*67e74705SXin Li // Add a fake function body to the block. IR generation is responsible
1710*67e74705SXin Li // for filling in the actual body, which cannot be expressed as an AST.
1711*67e74705SXin Li Block->setBody(new (Context) CompoundStmt(ConvLocation));
1712*67e74705SXin Li
1713*67e74705SXin Li // Create the block literal expression.
1714*67e74705SXin Li Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1715*67e74705SXin Li ExprCleanupObjects.push_back(Block);
1716*67e74705SXin Li Cleanup.setExprNeedsCleanups(true);
1717*67e74705SXin Li
1718*67e74705SXin Li return BuildBlock;
1719*67e74705SXin Li }
1720