blob: 2023c1f61e3b9883db3d7a0a00ca89afa0b3d64e [file] [log] [blame]
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ lambda expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/DeclSpec.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "TypeLocBuilder.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000015#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ExprCXX.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000017#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
Douglas Gregor6f88e5e2012-02-21 04:17:39 +000021#include "clang/Sema/Scope.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000022#include "clang/Sema/ScopeInfo.h"
23#include "clang/Sema/SemaInternal.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000024#include "clang/Sema/SemaLambda.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000025using namespace clang;
26using namespace sema;
27
Faisal Valiab3d6462013-12-07 20:22:44 +000028/// \brief Examines the FunctionScopeInfo stack to determine the nearest
29/// enclosing lambda (to the current lambda) that is 'capture-ready' for
30/// the variable referenced in the current lambda (i.e. \p VarToCapture).
31/// If successful, returns the index into Sema's FunctionScopeInfo stack
32/// of the capture-ready lambda's LambdaScopeInfo.
33///
34/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
35/// lambda - is on top) to determine the index of the nearest enclosing/outer
36/// lambda that is ready to capture the \p VarToCapture being referenced in
37/// the current lambda.
38/// As we climb down the stack, we want the index of the first such lambda -
39/// that is the lambda with the highest index that is 'capture-ready'.
40///
41/// A lambda 'L' is capture-ready for 'V' (var or this) if:
42/// - its enclosing context is non-dependent
43/// - and if the chain of lambdas between L and the lambda in which
44/// V is potentially used (i.e. the lambda at the top of the scope info
45/// stack), can all capture or have already captured V.
46/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
47///
48/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
49/// for whether it is 'capture-capable' (see
50/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
51/// capture.
52///
53/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
54/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
55/// is at the top of the stack and has the highest index.
56/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
57///
58/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
59/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
60/// which is capture-ready. If the return value evaluates to 'false' then
61/// no lambda is capture-ready for \p VarToCapture.
62
63static inline Optional<unsigned>
64getStackIndexOfNearestEnclosingCaptureReadyLambda(
65 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
66 VarDecl *VarToCapture) {
67 // Label failure to capture.
68 const Optional<unsigned> NoLambdaIsCaptureReady;
69
70 assert(
71 isa<clang::sema::LambdaScopeInfo>(
72 FunctionScopes[FunctionScopes.size() - 1]) &&
73 "The function on the top of sema's function-info stack must be a lambda");
Faisal Valia17d19f2013-11-07 05:17:06 +000074
Faisal Valiab3d6462013-12-07 20:22:44 +000075 // If VarToCapture is null, we are attempting to capture 'this'.
76 const bool IsCapturingThis = !VarToCapture;
Faisal Valia17d19f2013-11-07 05:17:06 +000077 const bool IsCapturingVariable = !IsCapturingThis;
Faisal Valiab3d6462013-12-07 20:22:44 +000078
79 // Start with the current lambda at the top of the stack (highest index).
Faisal Valia17d19f2013-11-07 05:17:06 +000080 unsigned CurScopeIndex = FunctionScopes.size() - 1;
Faisal Valiab3d6462013-12-07 20:22:44 +000081 DeclContext *EnclosingDC =
82 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
83
84 do {
85 const clang::sema::LambdaScopeInfo *LSI =
86 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
87 // IF we have climbed down to an intervening enclosing lambda that contains
88 // the variable declaration - it obviously can/must not capture the
Faisal Valia17d19f2013-11-07 05:17:06 +000089 // variable.
Faisal Valiab3d6462013-12-07 20:22:44 +000090 // Since its enclosing DC is dependent, all the lambdas between it and the
91 // innermost nested lambda are dependent (otherwise we wouldn't have
92 // arrived here) - so we don't yet have a lambda that can capture the
93 // variable.
94 if (IsCapturingVariable &&
95 VarToCapture->getDeclContext()->Equals(EnclosingDC))
96 return NoLambdaIsCaptureReady;
97
98 // For an enclosing lambda to be capture ready for an entity, all
99 // intervening lambda's have to be able to capture that entity. If even
100 // one of the intervening lambda's is not capable of capturing the entity
101 // then no enclosing lambda can ever capture that entity.
102 // For e.g.
103 // const int x = 10;
104 // [=](auto a) { #1
105 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
106 // [=](auto c) { #3
107 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
108 // }; }; };
Faisal Valia17d19f2013-11-07 05:17:06 +0000109 // If they do not have a default implicit capture, check to see
110 // if the entity has already been explicitly captured.
Faisal Valiab3d6462013-12-07 20:22:44 +0000111 // If even a single dependent enclosing lambda lacks the capability
112 // to ever capture this variable, there is no further enclosing
Faisal Valia17d19f2013-11-07 05:17:06 +0000113 // non-dependent lambda that can capture this variable.
114 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
Faisal Valiab3d6462013-12-07 20:22:44 +0000115 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
116 return NoLambdaIsCaptureReady;
Faisal Valia17d19f2013-11-07 05:17:06 +0000117 if (IsCapturingThis && !LSI->isCXXThisCaptured())
Faisal Valiab3d6462013-12-07 20:22:44 +0000118 return NoLambdaIsCaptureReady;
Faisal Valia17d19f2013-11-07 05:17:06 +0000119 }
120 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
Faisal Valiab3d6462013-12-07 20:22:44 +0000121
122 assert(CurScopeIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +0000123 --CurScopeIndex;
Faisal Valiab3d6462013-12-07 20:22:44 +0000124 } while (!EnclosingDC->isTranslationUnit() &&
125 EnclosingDC->isDependentContext() &&
126 isLambdaCallOperator(EnclosingDC));
Faisal Valia17d19f2013-11-07 05:17:06 +0000127
Faisal Valiab3d6462013-12-07 20:22:44 +0000128 assert(CurScopeIndex < (FunctionScopes.size() - 1));
129 // If the enclosingDC is not dependent, then the immediately nested lambda
130 // (one index above) is capture-ready.
131 if (!EnclosingDC->isDependentContext())
132 return CurScopeIndex + 1;
133 return NoLambdaIsCaptureReady;
134}
135
136/// \brief Examines the FunctionScopeInfo stack to determine the nearest
137/// enclosing lambda (to the current lambda) that is 'capture-capable' for
138/// the variable referenced in the current lambda (i.e. \p VarToCapture).
139/// If successful, returns the index into Sema's FunctionScopeInfo stack
140/// of the capture-capable lambda's LambdaScopeInfo.
141///
142/// Given the current stack of lambdas being processed by Sema and
143/// the variable of interest, to identify the nearest enclosing lambda (to the
144/// current lambda at the top of the stack) that can truly capture
145/// a variable, it has to have the following two properties:
146/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
147/// - climb down the stack (i.e. starting from the innermost and examining
148/// each outer lambda step by step) checking if each enclosing
149/// lambda can either implicitly or explicitly capture the variable.
150/// Record the first such lambda that is enclosed in a non-dependent
151/// context. If no such lambda currently exists return failure.
152/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
153/// capture the variable by checking all its enclosing lambdas:
154/// - check if all outer lambdas enclosing the 'capture-ready' lambda
155/// identified above in 'a' can also capture the variable (this is done
156/// via tryCaptureVariable for variables and CheckCXXThisCapture for
157/// 'this' by passing in the index of the Lambda identified in step 'a')
158///
159/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
160/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
161/// is at the top of the stack.
162///
163/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
164///
165///
166/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
167/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
168/// which is capture-capable. If the return value evaluates to 'false' then
169/// no lambda is capture-capable for \p VarToCapture.
170
171Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
172 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
173 VarDecl *VarToCapture, Sema &S) {
174
Faisal Vali5035a8c2013-12-09 00:15:23 +0000175 const Optional<unsigned> NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000176
177 const Optional<unsigned> OptionalStackIndex =
178 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
179 VarToCapture);
180 if (!OptionalStackIndex)
Faisal Vali5035a8c2013-12-09 00:15:23 +0000181 return NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000182
183 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
Faisal Vali5ab61b02013-12-08 15:00:29 +0000184 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
185 S.getCurGenericLambda()) &&
186 "The capture ready lambda for a potential capture can only be the "
Faisal Vali40e84582013-12-08 15:04:03 +0000187 "current lambda if it is a generic lambda");
Faisal Valiab3d6462013-12-07 20:22:44 +0000188
189 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
190 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
191
192 // If VarToCapture is null, we are attempting to capture 'this'
193 const bool IsCapturingThis = !VarToCapture;
Faisal Valia17d19f2013-11-07 05:17:06 +0000194 const bool IsCapturingVariable = !IsCapturingThis;
195
196 if (IsCapturingVariable) {
Faisal Valiab3d6462013-12-07 20:22:44 +0000197 // Check if the capture-ready lambda can truly capture the variable, by
198 // checking whether all enclosing lambdas of the capture-ready lambda allow
199 // the capture - i.e. make sure it is capture-capable.
Faisal Valia17d19f2013-11-07 05:17:06 +0000200 QualType CaptureType, DeclRefType;
Faisal Valiab3d6462013-12-07 20:22:44 +0000201 const bool CanCaptureVariable =
202 !S.tryCaptureVariable(VarToCapture,
203 /*ExprVarIsUsedInLoc*/ SourceLocation(),
204 clang::Sema::TryCapture_Implicit,
205 /*EllipsisLoc*/ SourceLocation(),
206 /*BuildAndDiagnose*/ false, CaptureType,
207 DeclRefType, &IndexOfCaptureReadyLambda);
208 if (!CanCaptureVariable)
Faisal Vali5035a8c2013-12-09 00:15:23 +0000209 return NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000210 } else {
211 // Check if the capture-ready lambda can truly capture 'this' by checking
212 // whether all enclosing lambdas of the capture-ready lambda can capture
213 // 'this'.
214 const bool CanCaptureThis =
215 !S.CheckCXXThisCapture(
216 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
217 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
218 &IndexOfCaptureReadyLambda);
219 if (!CanCaptureThis)
Faisal Vali5035a8c2013-12-09 00:15:23 +0000220 return NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000221 }
222 return IndexOfCaptureReadyLambda;
Faisal Valia17d19f2013-11-07 05:17:06 +0000223}
Faisal Valic1a6dc42013-10-23 16:10:50 +0000224
225static inline TemplateParameterList *
226getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
227 if (LSI->GLTemplateParameterList)
228 return LSI->GLTemplateParameterList;
229
230 if (LSI->AutoTemplateParams.size()) {
231 SourceRange IntroRange = LSI->IntroducerRange;
232 SourceLocation LAngleLoc = IntroRange.getBegin();
233 SourceLocation RAngleLoc = IntroRange.getEnd();
234 LSI->GLTemplateParameterList = TemplateParameterList::Create(
Faisal Valiab3d6462013-12-07 20:22:44 +0000235 SemaRef.Context,
236 /*Template kw loc*/ SourceLocation(), LAngleLoc,
237 (NamedDecl **)LSI->AutoTemplateParams.data(),
238 LSI->AutoTemplateParams.size(), RAngleLoc);
Faisal Valic1a6dc42013-10-23 16:10:50 +0000239 }
240 return LSI->GLTemplateParameterList;
241}
242
Douglas Gregor680e9e02012-02-21 19:11:17 +0000243CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedmand564afb2012-09-19 01:18:11 +0000244 TypeSourceInfo *Info,
Faisal Valic1a6dc42013-10-23 16:10:50 +0000245 bool KnownDependent,
246 LambdaCaptureDefault CaptureDefault) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000247 DeclContext *DC = CurContext;
248 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
249 DC = DC->getParent();
Faisal Valic1a6dc42013-10-23 16:10:50 +0000250 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
251 *this);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000252 // Start constructing the lambda class.
Eli Friedmand564afb2012-09-19 01:18:11 +0000253 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregor680e9e02012-02-21 19:11:17 +0000254 IntroducerRange.getBegin(),
Faisal Valic1a6dc42013-10-23 16:10:50 +0000255 KnownDependent,
256 IsGenericLambda,
257 CaptureDefault);
Douglas Gregor43c3f282012-02-20 20:47:06 +0000258 DC->addDecl(Class);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000259
260 return Class;
261}
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000262
Douglas Gregorb61e8092012-04-04 17:40:10 +0000263/// \brief Determine whether the given context is or is enclosed in an inline
264/// function.
265static bool isInInlineFunction(const DeclContext *DC) {
266 while (!DC->isFileContext()) {
267 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
268 if (FD->isInlined())
269 return true;
270
271 DC = DC->getLexicalParent();
272 }
273
274 return false;
275}
276
Eli Friedman7e346a82013-07-01 20:22:57 +0000277MangleNumberingContext *
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000278Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman7e346a82013-07-01 20:22:57 +0000279 Decl *&ManglingContextDecl) {
280 // Compute the context for allocating mangling numbers in the current
281 // expression, if the ABI requires them.
282 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
283
284 enum ContextKind {
285 Normal,
286 DefaultArgument,
287 DataMember,
288 StaticDataMember
289 } Kind = Normal;
290
291 // Default arguments of member function parameters that appear in a class
292 // definition, as well as the initializers of data members, receive special
293 // treatment. Identify them.
294 if (ManglingContextDecl) {
295 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
296 if (const DeclContext *LexicalDC
297 = Param->getDeclContext()->getLexicalParent())
298 if (LexicalDC->isRecord())
299 Kind = DefaultArgument;
300 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
301 if (Var->getDeclContext()->isRecord())
302 Kind = StaticDataMember;
303 } else if (isa<FieldDecl>(ManglingContextDecl)) {
304 Kind = DataMember;
305 }
306 }
307
308 // Itanium ABI [5.1.7]:
309 // In the following contexts [...] the one-definition rule requires closure
310 // types in different translation units to "correspond":
311 bool IsInNonspecializedTemplate =
312 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
313 switch (Kind) {
314 case Normal:
315 // -- the bodies of non-exported nonspecialized template functions
316 // -- the bodies of inline functions
317 if ((IsInNonspecializedTemplate &&
318 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
319 isInInlineFunction(CurContext)) {
320 ManglingContextDecl = 0;
321 return &Context.getManglingNumberContext(DC);
322 }
323
324 ManglingContextDecl = 0;
325 return 0;
326
327 case StaticDataMember:
328 // -- the initializers of nonspecialized static members of template classes
329 if (!IsInNonspecializedTemplate) {
330 ManglingContextDecl = 0;
331 return 0;
332 }
333 // Fall through to get the current context.
334
335 case DataMember:
336 // -- the in-class initializers of class members
337 case DefaultArgument:
338 // -- default arguments appearing in class definitions
Reid Klecknerd8110b62013-09-10 20:14:30 +0000339 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman7e346a82013-07-01 20:22:57 +0000340 }
Andy Gibbs456198d2013-07-02 16:01:56 +0000341
342 llvm_unreachable("unexpected context");
Eli Friedman7e346a82013-07-01 20:22:57 +0000343}
344
Reid Klecknerd8110b62013-09-10 20:14:30 +0000345MangleNumberingContext &
346Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
347 ASTContext &Ctx) {
348 assert(ManglingContextDecl && "Need to have a context declaration");
349 if (!MangleNumbering)
350 MangleNumbering = Ctx.createMangleNumberingContext();
351 return *MangleNumbering;
352}
353
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000354CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith4db51c22013-09-25 05:02:54 +0000355 SourceRange IntroducerRange,
356 TypeSourceInfo *MethodTypeInfo,
357 SourceLocation EndLoc,
358 ArrayRef<ParmVarDecl *> Params) {
359 QualType MethodType = MethodTypeInfo->getType();
Faisal Vali2b391ab2013-09-26 19:54:12 +0000360 TemplateParameterList *TemplateParams =
361 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
362 // If a lambda appears in a dependent context or is a generic lambda (has
363 // template parameters) and has an 'auto' return type, deduce it to a
364 // dependent type.
365 if (Class->isDependentContext() || TemplateParams) {
Richard Smith4db51c22013-09-25 05:02:54 +0000366 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
367 QualType Result = FPT->getResultType();
368 if (Result->isUndeducedType()) {
369 Result = SubstAutoType(Result, Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +0000370 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smith4db51c22013-09-25 05:02:54 +0000371 FPT->getExtProtoInfo());
372 }
373 }
374
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000375 // C++11 [expr.prim.lambda]p5:
376 // The closure type for a lambda-expression has a public inline function
377 // call operator (13.5.4) whose parameters and return type are described by
378 // the lambda-expression's parameter-declaration-clause and
379 // trailing-return-type respectively.
380 DeclarationName MethodName
381 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
382 DeclarationNameLoc MethodNameLoc;
383 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
384 = IntroducerRange.getBegin().getRawEncoding();
385 MethodNameLoc.CXXOperatorName.EndOpNameLoc
386 = IntroducerRange.getEnd().getRawEncoding();
387 CXXMethodDecl *Method
388 = CXXMethodDecl::Create(Context, Class, EndLoc,
389 DeclarationNameInfo(MethodName,
390 IntroducerRange.getBegin(),
391 MethodNameLoc),
Richard Smith4db51c22013-09-25 05:02:54 +0000392 MethodType, MethodTypeInfo,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000393 SC_None,
394 /*isInline=*/true,
395 /*isConstExpr=*/false,
396 EndLoc);
397 Method->setAccess(AS_public);
398
399 // Temporarily set the lexical declaration context to the current
400 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregor43c3f282012-02-20 20:47:06 +0000401 Method->setLexicalDeclContext(CurContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000402 // Create a function template if we have a template parameter list
403 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
404 FunctionTemplateDecl::Create(Context, Class,
405 Method->getLocation(), MethodName,
406 TemplateParams,
407 Method) : 0;
408 if (TemplateMethod) {
409 TemplateMethod->setLexicalDeclContext(CurContext);
410 TemplateMethod->setAccess(AS_public);
411 Method->setDescribedFunctionTemplate(TemplateMethod);
412 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000413
Douglas Gregoradb376e2012-02-14 22:28:59 +0000414 // Add parameters.
415 if (!Params.empty()) {
416 Method->setParams(Params);
417 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
418 const_cast<ParmVarDecl **>(Params.end()),
419 /*CheckParameterNames=*/false);
420
421 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
422 PEnd = Method->param_end();
423 P != PEnd; ++P)
424 (*P)->setOwningFunction(Method);
425 }
Richard Smith505df232012-07-22 23:45:10 +0000426
Eli Friedman7e346a82013-07-01 20:22:57 +0000427 Decl *ManglingContextDecl;
428 if (MangleNumberingContext *MCtx =
429 getCurrentMangleNumberContext(Class->getDeclContext(),
430 ManglingContextDecl)) {
431 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
432 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorb61e8092012-04-04 17:40:10 +0000433 }
434
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000435 return Method;
436}
437
Faisal Vali2b391ab2013-09-26 19:54:12 +0000438void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
439 CXXMethodDecl *CallOperator,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000440 SourceRange IntroducerRange,
441 LambdaCaptureDefault CaptureDefault,
James Dennettddd36ff2013-08-09 23:08:25 +0000442 SourceLocation CaptureDefaultLoc,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000443 bool ExplicitParams,
444 bool ExplicitResultType,
445 bool Mutable) {
Faisal Vali2b391ab2013-09-26 19:54:12 +0000446 LSI->CallOperator = CallOperator;
Faisal Valic1a6dc42013-10-23 16:10:50 +0000447 CXXRecordDecl *LambdaClass = CallOperator->getParent();
448 LSI->Lambda = LambdaClass;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000449 if (CaptureDefault == LCD_ByCopy)
450 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
451 else if (CaptureDefault == LCD_ByRef)
452 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettddd36ff2013-08-09 23:08:25 +0000453 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000454 LSI->IntroducerRange = IntroducerRange;
455 LSI->ExplicitParams = ExplicitParams;
456 LSI->Mutable = Mutable;
457
458 if (ExplicitResultType) {
459 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor621003e2012-02-14 21:20:44 +0000460
461 if (!LSI->ReturnType->isDependentType() &&
462 !LSI->ReturnType->isVoidType()) {
463 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
464 diag::err_lambda_incomplete_result)) {
465 // Do nothing.
Douglas Gregor621003e2012-02-14 21:20:44 +0000466 }
467 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000468 } else {
469 LSI->HasImplicitReturnType = true;
470 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000471}
472
473void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
474 LSI->finishedExplicitCaptures();
475}
476
Douglas Gregoradb376e2012-02-14 22:28:59 +0000477void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000478 // Introduce our parameters into the function scope
479 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
480 p < NumParams; ++p) {
481 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000482
483 // If this has an identifier, add it to the scope stack.
484 if (CurScope && Param->getIdentifier()) {
485 CheckShadow(CurScope, Param);
486
487 PushOnScopeChains(Param, CurScope);
488 }
489 }
490}
491
John McCalle4c11cc2013-03-09 00:54:31 +0000492/// If this expression is an enumerator-like expression of some type
493/// T, return the type T; otherwise, return null.
494///
495/// Pointer comparisons on the result here should always work because
496/// it's derived from either the parent of an EnumConstantDecl
497/// (i.e. the definition) or the declaration returned by
498/// EnumType::getDecl() (i.e. the definition).
499static EnumDecl *findEnumForBlockReturn(Expr *E) {
500 // An expression is an enumerator-like expression of type T if,
501 // ignoring parens and parens-like expressions:
502 E = E->IgnoreParens();
Jordan Rosed39e5f12012-07-02 21:19:23 +0000503
John McCalle4c11cc2013-03-09 00:54:31 +0000504 // - it is an enumerator whose enum type is T or
505 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
506 if (EnumConstantDecl *D
507 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
508 return cast<EnumDecl>(D->getDeclContext());
509 }
510 return 0;
Jordan Rosed39e5f12012-07-02 21:19:23 +0000511 }
512
John McCalle4c11cc2013-03-09 00:54:31 +0000513 // - it is a comma expression whose RHS is an enumerator-like
514 // expression of type T or
515 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
516 if (BO->getOpcode() == BO_Comma)
517 return findEnumForBlockReturn(BO->getRHS());
518 return 0;
519 }
Jordan Rosed39e5f12012-07-02 21:19:23 +0000520
John McCalle4c11cc2013-03-09 00:54:31 +0000521 // - it is a statement-expression whose value expression is an
522 // enumerator-like expression of type T or
523 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
524 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
525 return findEnumForBlockReturn(last);
526 return 0;
527 }
528
529 // - it is a ternary conditional operator (not the GNU ?:
530 // extension) whose second and third operands are
531 // enumerator-like expressions of type T or
532 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
533 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
534 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
535 return ED;
536 return 0;
537 }
538
539 // (implicitly:)
540 // - it is an implicit integral conversion applied to an
541 // enumerator-like expression of type T or
542 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall1b4259b2013-05-08 03:34:22 +0000543 // We can sometimes see integral conversions in valid
544 // enumerator-like expressions.
John McCalle4c11cc2013-03-09 00:54:31 +0000545 if (ICE->getCastKind() == CK_IntegralCast)
546 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall1b4259b2013-05-08 03:34:22 +0000547
548 // Otherwise, just rely on the type.
John McCalle4c11cc2013-03-09 00:54:31 +0000549 }
550
551 // - it is an expression of that formal enum type.
552 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
553 return ET->getDecl();
554 }
555
556 // Otherwise, nope.
557 return 0;
558}
559
560/// Attempt to find a type T for which the returned expression of the
561/// given statement is an enumerator-like expression of that type.
562static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
563 if (Expr *retValue = ret->getRetValue())
564 return findEnumForBlockReturn(retValue);
565 return 0;
566}
567
568/// Attempt to find a common type T for which all of the returned
569/// expressions in a block are enumerator-like expressions of that
570/// type.
571static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
572 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
573
574 // Try to find one for the first return.
575 EnumDecl *ED = findEnumForBlockReturn(*i);
576 if (!ED) return 0;
577
578 // Check that the rest of the returns have the same enum.
579 for (++i; i != e; ++i) {
580 if (findEnumForBlockReturn(*i) != ED)
581 return 0;
582 }
583
584 // Never infer an anonymous enum type.
585 if (!ED->hasNameForLinkage()) return 0;
586
587 return ED;
588}
589
590/// Adjust the given return statements so that they formally return
591/// the given type. It should require, at most, an IntegralCast.
592static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
593 QualType returnType) {
594 for (ArrayRef<ReturnStmt*>::iterator
595 i = returns.begin(), e = returns.end(); i != e; ++i) {
596 ReturnStmt *ret = *i;
597 Expr *retValue = ret->getRetValue();
598 if (S.Context.hasSameType(retValue->getType(), returnType))
599 continue;
600
601 // Right now we only support integral fixup casts.
602 assert(returnType->isIntegralOrUnscopedEnumerationType());
603 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
604
605 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
606
607 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
608 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
609 E, /*base path*/ 0, VK_RValue);
610 if (cleanups) {
611 cleanups->setSubExpr(E);
612 } else {
613 ret->setRetValue(E);
Jordan Rosed39e5f12012-07-02 21:19:23 +0000614 }
615 }
Jordan Rosed39e5f12012-07-02 21:19:23 +0000616}
617
618void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000619 assert(CSI.HasImplicitReturnType);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000620 // If it was ever a placeholder, it had to been deduced to DependentTy.
621 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rosed39e5f12012-07-02 21:19:23 +0000622
John McCalle4c11cc2013-03-09 00:54:31 +0000623 // C++ Core Issue #975, proposed resolution:
624 // If a lambda-expression does not include a trailing-return-type,
625 // it is as if the trailing-return-type denotes the following type:
626 // - if there are no return statements in the compound-statement,
627 // or all return statements return either an expression of type
628 // void or no expression or braced-init-list, the type void;
629 // - otherwise, if all return statements return an expression
630 // and the types of the returned expressions after
631 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
632 // array-to-pointer conversion (4.2 [conv.array]), and
633 // function-to-pointer conversion (4.3 [conv.func]) are the
634 // same, that common type;
635 // - otherwise, the program is ill-formed.
636 //
637 // In addition, in blocks in non-C++ modes, if all of the return
638 // statements are enumerator-like expressions of some type T, where
639 // T has a name for linkage, then we infer the return type of the
640 // block to be that type.
641
Jordan Rosed39e5f12012-07-02 21:19:23 +0000642 // First case: no return statements, implicit void return type.
643 ASTContext &Ctx = getASTContext();
644 if (CSI.Returns.empty()) {
645 // It's possible there were simply no /valid/ return statements.
646 // In this case, the first one we found may have at least given us a type.
647 if (CSI.ReturnType.isNull())
648 CSI.ReturnType = Ctx.VoidTy;
649 return;
650 }
651
652 // Second case: at least one return statement has dependent type.
653 // Delay type checking until instantiation.
654 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000655 if (CSI.ReturnType->isDependentType())
Jordan Rosed39e5f12012-07-02 21:19:23 +0000656 return;
657
John McCalle4c11cc2013-03-09 00:54:31 +0000658 // Try to apply the enum-fuzz rule.
659 if (!getLangOpts().CPlusPlus) {
660 assert(isa<BlockScopeInfo>(CSI));
661 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
662 if (ED) {
663 CSI.ReturnType = Context.getTypeDeclType(ED);
664 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
665 return;
666 }
667 }
668
Jordan Rosed39e5f12012-07-02 21:19:23 +0000669 // Third case: only one return statement. Don't bother doing extra work!
670 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
671 E = CSI.Returns.end();
672 if (I+1 == E)
673 return;
674
675 // General case: many return statements.
676 // Check that they all have compatible return types.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000677
678 // We require the return types to strictly match here.
John McCalle4c11cc2013-03-09 00:54:31 +0000679 // Note that we've already done the required promotions as part of
680 // processing the return statement.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000681 for (; I != E; ++I) {
682 const ReturnStmt *RS = *I;
683 const Expr *RetE = RS->getRetValue();
Jordan Rosed39e5f12012-07-02 21:19:23 +0000684
John McCalle4c11cc2013-03-09 00:54:31 +0000685 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
686 if (Context.hasSameType(ReturnType, CSI.ReturnType))
687 continue;
Jordan Rosed39e5f12012-07-02 21:19:23 +0000688
John McCalle4c11cc2013-03-09 00:54:31 +0000689 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
690 // TODO: It's possible that the *first* return is the divergent one.
691 Diag(RS->getLocStart(),
692 diag::err_typecheck_missing_return_type_incompatible)
693 << ReturnType << CSI.ReturnType
694 << isa<LambdaScopeInfo>(CSI);
695 // Continue iterating so that we keep emitting diagnostics.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000696 }
697}
698
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000699QualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc,
700 bool ByRef,
701 IdentifierInfo *Id,
702 Expr *&Init) {
703
704 // We do not need to distinguish between direct-list-initialization
705 // and copy-list-initialization here, because we will always deduce
706 // std::initializer_list<T>, and direct- and copy-list-initialization
707 // always behave the same for such a type.
708 // FIXME: We should model whether an '=' was present.
709 const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
710
711 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
712 // deduce against.
Richard Smithba71c082013-05-16 06:20:58 +0000713 QualType DeductType = Context.getAutoDeductType();
714 TypeLocBuilder TLB;
715 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
716 if (ByRef) {
717 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
718 assert(!DeductType.isNull() && "can't build reference to auto");
719 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
720 }
Eli Friedman7152fbe2013-06-07 20:31:48 +0000721 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smithba71c082013-05-16 06:20:58 +0000722
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000723 // Are we a non-list direct initialization?
724 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
725
726 Expr *DeduceInit = Init;
727 // Initializer could be a C++ direct-initializer. Deduction only works if it
728 // contains exactly one expression.
729 if (CXXDirectInit) {
730 if (CXXDirectInit->getNumExprs() == 0) {
731 Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression)
732 << DeclarationName(Id) << TSI->getType() << Loc;
733 return QualType();
734 } else if (CXXDirectInit->getNumExprs() > 1) {
735 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
736 diag::err_init_capture_multiple_expressions)
737 << DeclarationName(Id) << TSI->getType() << Loc;
738 return QualType();
739 } else {
740 DeduceInit = CXXDirectInit->getExpr(0);
741 }
742 }
743
744 // Now deduce against the initialization expression and store the deduced
745 // type below.
746 QualType DeducedType;
747 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
748 if (isa<InitListExpr>(Init))
749 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
750 << DeclarationName(Id)
751 << (DeduceInit->getType().isNull() ? TSI->getType()
752 : DeduceInit->getType())
753 << DeduceInit->getSourceRange();
754 else
755 Diag(Loc, diag::err_init_capture_deduction_failure)
756 << DeclarationName(Id) << TSI->getType()
757 << (DeduceInit->getType().isNull() ? TSI->getType()
758 : DeduceInit->getType())
759 << DeduceInit->getSourceRange();
760 }
761 if (DeducedType.isNull())
762 return QualType();
763
764 // Perform initialization analysis and ensure any implicit conversions
765 // (such as lvalue-to-rvalue) are enforced.
766 InitializedEntity Entity =
767 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
768 InitializationKind Kind =
769 IsDirectInit
770 ? (CXXDirectInit ? InitializationKind::CreateDirect(
771 Loc, Init->getLocStart(), Init->getLocEnd())
772 : InitializationKind::CreateDirectList(Loc))
773 : InitializationKind::CreateCopy(Loc, Init->getLocStart());
774
775 MultiExprArg Args = Init;
776 if (CXXDirectInit)
777 Args =
778 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
779 QualType DclT;
780 InitializationSequence InitSeq(*this, Entity, Kind, Args);
781 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
782
783 if (Result.isInvalid())
784 return QualType();
785 Init = Result.takeAs<Expr>();
786
787 // The init-capture initialization is a full-expression that must be
788 // processed as one before we enter the declcontext of the lambda's
789 // call-operator.
790 Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
791 /*IsConstexpr*/ false,
792 /*IsLambdaInitCaptureInitalizer*/ true);
793 if (Result.isInvalid())
794 return QualType();
795
796 Init = Result.takeAs<Expr>();
797 return DeducedType;
798}
799
800VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
801 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) {
802
803 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
804 Loc);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000805 // Create a dummy variable representing the init-capture. This is not actually
806 // used as a variable, and only exists as a way to name and refer to the
807 // init-capture.
808 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith75e3f692013-09-28 04:31:26 +0000809 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000810 Loc, Id, InitCaptureType, TSI, SC_Auto);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000811 NewVD->setInitCapture(true);
812 NewVD->setReferenced(true);
813 NewVD->markUsed(Context);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000814 NewVD->setInit(Init);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000815 return NewVD;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000816
Richard Smithbb13c9a2013-09-28 04:02:39 +0000817}
Richard Smithba71c082013-05-16 06:20:58 +0000818
Richard Smithbb13c9a2013-09-28 04:02:39 +0000819FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
820 FieldDecl *Field = FieldDecl::Create(
821 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
822 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
823 Field->setImplicit(true);
824 Field->setAccess(AS_private);
825 LSI->Lambda->addDecl(Field);
Richard Smithba71c082013-05-16 06:20:58 +0000826
Richard Smithbb13c9a2013-09-28 04:02:39 +0000827 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
828 /*isNested*/false, Var->getLocation(), SourceLocation(),
829 Var->getType(), Var->getInit());
830 return Field;
Richard Smithba71c082013-05-16 06:20:58 +0000831}
832
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000833void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Vali2b391ab2013-09-26 19:54:12 +0000834 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregor680e9e02012-02-21 19:11:17 +0000835 // Determine if we're within a context where we know that the lambda will
836 // be dependent, because there are template parameters in scope.
837 bool KnownDependent = false;
Faisal Vali2b391ab2013-09-26 19:54:12 +0000838 LambdaScopeInfo *const LSI = getCurLambda();
839 assert(LSI && "LambdaScopeInfo should be on stack!");
840 TemplateParameterList *TemplateParams =
841 getGenericLambdaTemplateParameterList(LSI, *this);
842
843 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
844 // Since we have our own TemplateParams, so check if an outer scope
845 // has template params, only then are we in a dependent scope.
846 if (TemplateParams) {
847 TmplScope = TmplScope->getParent();
848 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
849 }
850 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregor680e9e02012-02-21 19:11:17 +0000851 KnownDependent = true;
Faisal Vali2b391ab2013-09-26 19:54:12 +0000852 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000853 // Determine the signature of the call operator.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000854 TypeSourceInfo *MethodTyInfo;
855 bool ExplicitParams = true;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000856 bool ExplicitResultType = true;
Richard Smith2589b9802012-07-25 03:56:55 +0000857 bool ContainsUnexpandedParameterPack = false;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000858 SourceLocation EndLoc;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000859 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000860 if (ParamInfo.getNumTypeObjects() == 0) {
861 // C++11 [expr.prim.lambda]p4:
862 // If a lambda-expression does not include a lambda-declarator, it is as
863 // if the lambda-declarator were ().
Reid Kleckner78af0702013-08-27 23:08:25 +0000864 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
865 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smith5e580292012-02-10 09:58:53 +0000866 EPI.HasTrailingReturn = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000867 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith4db51c22013-09-25 05:02:54 +0000868 // C++1y [expr.prim.lambda]:
869 // The lambda return type is 'auto', which is replaced by the
870 // trailing-return type if provided and/or deduced from 'return'
871 // statements
872 // We don't do this before C++1y, because we don't support deduced return
873 // types there.
874 QualType DefaultTypeForNoTrailingReturn =
875 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
876 : Context.DependentTy;
877 QualType MethodTy =
878 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000879 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
880 ExplicitParams = false;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000881 ExplicitResultType = false;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000882 EndLoc = Intro.Range.getEnd();
883 } else {
884 assert(ParamInfo.isFunctionDeclarator() &&
885 "lambda-declarator is a function");
886 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith4db51c22013-09-25 05:02:54 +0000887
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000888 // C++11 [expr.prim.lambda]p5:
889 // This function call operator is declared const (9.3.1) if and only if
890 // the lambda-expression's parameter-declaration-clause is not followed
891 // by mutable. It is neither virtual nor declared volatile. [...]
892 if (!FTI.hasMutableQualifier())
893 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith4db51c22013-09-25 05:02:54 +0000894
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000895 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000896 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000897 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith4db51c22013-09-25 05:02:54 +0000898
899 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000900
Eli Friedman8f5e9832012-09-20 01:40:23 +0000901 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
902 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
903 // Empty arg list, don't push any params.
904 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
905 } else {
906 Params.reserve(FTI.NumArgs);
907 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
908 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
909 }
Douglas Gregor7efd007c2012-06-15 16:59:29 +0000910
911 // Check for unexpanded parameter packs in the method type.
Richard Smith2589b9802012-07-25 03:56:55 +0000912 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
913 ContainsUnexpandedParameterPack = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000914 }
Eli Friedmand564afb2012-09-19 01:18:11 +0000915
916 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
Faisal Valic1a6dc42013-10-23 16:10:50 +0000917 KnownDependent, Intro.Default);
Eli Friedmand564afb2012-09-19 01:18:11 +0000918
Douglas Gregor7efd007c2012-06-15 16:59:29 +0000919 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregoradb376e2012-02-14 22:28:59 +0000920 MethodTyInfo, EndLoc, Params);
Douglas Gregoradb376e2012-02-14 22:28:59 +0000921 if (ExplicitParams)
922 CheckCXXDefaultArguments(Method);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000923
Bill Wendling44426052012-12-20 19:22:21 +0000924 // Attributes on the lambda apply to the method.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000925 ProcessDeclAttributes(CurScope, Method, ParamInfo);
926
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000927 // Introduce the function call operator as the current declaration context.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000928 PushDeclContext(CurScope, Method);
929
Faisal Vali2b391ab2013-09-26 19:54:12 +0000930 // Build the lambda scope.
931 buildLambdaScope(LSI, Method,
James Dennettddd36ff2013-08-09 23:08:25 +0000932 Intro.Range,
933 Intro.Default, Intro.DefaultLoc,
934 ExplicitParams,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000935 ExplicitResultType,
David Blaikief5697e52012-08-10 00:55:35 +0000936 !Method->isConst());
Richard Smithba71c082013-05-16 06:20:58 +0000937
938 // Distinct capture names, for diagnostics.
939 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
940
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000941 // Handle explicit captures.
Douglas Gregora1bffa22012-02-10 17:46:20 +0000942 SourceLocation PrevCaptureLoc
943 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper2341c0d2013-07-04 03:08:24 +0000944 for (SmallVectorImpl<LambdaCapture>::const_iterator
945 C = Intro.Captures.begin(),
946 E = Intro.Captures.end();
947 C != E;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000948 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000949 if (C->Kind == LCK_This) {
950 // C++11 [expr.prim.lambda]p8:
951 // An identifier or this shall not appear more than once in a
952 // lambda-capture.
953 if (LSI->isCXXThisCaptured()) {
954 Diag(C->Loc, diag::err_capture_more_than_once)
955 << "'this'"
Douglas Gregora1bffa22012-02-10 17:46:20 +0000956 << SourceRange(LSI->getCXXThisCapture().getLocation())
957 << FixItHint::CreateRemoval(
958 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000959 continue;
960 }
961
962 // C++11 [expr.prim.lambda]p8:
963 // If a lambda-capture includes a capture-default that is =, the
964 // lambda-capture shall not contain this [...].
965 if (Intro.Default == LCD_ByCopy) {
Douglas Gregora1bffa22012-02-10 17:46:20 +0000966 Diag(C->Loc, diag::err_this_capture_with_copy_default)
967 << FixItHint::CreateRemoval(
968 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000969 continue;
970 }
971
972 // C++11 [expr.prim.lambda]p12:
973 // If this is captured by a local lambda expression, its nearest
974 // enclosing function shall be a non-static member function.
975 QualType ThisCaptureType = getCurrentThisType();
976 if (ThisCaptureType.isNull()) {
977 Diag(C->Loc, diag::err_this_capture) << true;
978 continue;
979 }
980
981 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
982 continue;
983 }
984
Richard Smithba71c082013-05-16 06:20:58 +0000985 assert(C->Id && "missing identifier for capture");
986
Richard Smith21b3ab42013-05-09 21:36:41 +0000987 if (C->Init.isInvalid())
988 continue;
Richard Smithba71c082013-05-16 06:20:58 +0000989
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000990 VarDecl *Var = 0;
Richard Smithbb13c9a2013-09-28 04:02:39 +0000991 if (C->Init.isUsable()) {
Richard Smith5b013f52013-09-28 05:38:27 +0000992 Diag(C->Loc, getLangOpts().CPlusPlus1y
993 ? diag::warn_cxx11_compat_init_capture
994 : diag::ext_init_capture);
995
Richard Smithba71c082013-05-16 06:20:58 +0000996 if (C->Init.get()->containsUnexpandedParameterPack())
997 ContainsUnexpandedParameterPack = true;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000998 // If the initializer expression is usable, but the InitCaptureType
999 // is not, then an error has occurred - so ignore the capture for now.
1000 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1001 // FIXME: we should create the init capture variable and mark it invalid
1002 // in this case.
1003 if (C->InitCaptureType.get().isNull())
1004 continue;
1005 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1006 C->Id, C->Init.take());
Richard Smithba71c082013-05-16 06:20:58 +00001007 // C++1y [expr.prim.lambda]p11:
Richard Smithbb13c9a2013-09-28 04:02:39 +00001008 // An init-capture behaves as if it declares and explicitly
1009 // captures a variable [...] whose declarative region is the
1010 // lambda-expression's compound-statement
1011 if (Var)
1012 PushOnScopeChains(Var, CurScope, false);
1013 } else {
1014 // C++11 [expr.prim.lambda]p8:
1015 // If a lambda-capture includes a capture-default that is &, the
1016 // identifiers in the lambda-capture shall not be preceded by &.
1017 // If a lambda-capture includes a capture-default that is =, [...]
1018 // each identifier it contains shall be preceded by &.
1019 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1020 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1021 << FixItHint::CreateRemoval(
1022 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001023 continue;
Richard Smithbb13c9a2013-09-28 04:02:39 +00001024 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1025 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1026 << FixItHint::CreateRemoval(
1027 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1028 continue;
1029 }
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001030
Richard Smithbb13c9a2013-09-28 04:02:39 +00001031 // C++11 [expr.prim.lambda]p10:
1032 // The identifiers in a capture-list are looked up using the usual
1033 // rules for unqualified name lookup (3.4.1)
1034 DeclarationNameInfo Name(C->Id, C->Loc);
1035 LookupResult R(*this, Name, LookupOrdinaryName);
1036 LookupName(R, CurScope);
1037 if (R.isAmbiguous())
1038 continue;
1039 if (R.empty()) {
1040 // FIXME: Disable corrections that would add qualification?
1041 CXXScopeSpec ScopeSpec;
1042 DeclFilterCCC<VarDecl> Validator;
1043 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1044 continue;
1045 }
1046
1047 Var = R.getAsSingle<VarDecl>();
1048 }
Richard Smithba71c082013-05-16 06:20:58 +00001049
1050 // C++11 [expr.prim.lambda]p8:
1051 // An identifier or this shall not appear more than once in a
1052 // lambda-capture.
1053 if (!CaptureNames.insert(C->Id)) {
1054 if (Var && LSI->isCaptured(Var)) {
1055 Diag(C->Loc, diag::err_capture_more_than_once)
1056 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1057 << FixItHint::CreateRemoval(
1058 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1059 } else
Richard Smithbb13c9a2013-09-28 04:02:39 +00001060 // Previous capture captured something different (one or both was
1061 // an init-cpature): no fixit.
Richard Smithba71c082013-05-16 06:20:58 +00001062 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1063 continue;
1064 }
1065
1066 // C++11 [expr.prim.lambda]p10:
1067 // [...] each such lookup shall find a variable with automatic storage
1068 // duration declared in the reaching scope of the local lambda expression.
1069 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001070 if (!Var) {
1071 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1072 continue;
1073 }
1074
Eli Friedmane979db12012-09-18 21:11:30 +00001075 // Ignore invalid decls; they'll just confuse the code later.
1076 if (Var->isInvalidDecl())
1077 continue;
1078
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001079 if (!Var->hasLocalStorage()) {
1080 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1081 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1082 continue;
1083 }
1084
Douglas Gregor3e308b12012-02-14 19:27:52 +00001085 // C++11 [expr.prim.lambda]p23:
1086 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1087 SourceLocation EllipsisLoc;
1088 if (C->EllipsisLoc.isValid()) {
1089 if (Var->isParameterPack()) {
1090 EllipsisLoc = C->EllipsisLoc;
1091 } else {
1092 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1093 << SourceRange(C->Loc);
1094
1095 // Just ignore the ellipsis.
1096 }
1097 } else if (Var->isParameterPack()) {
Richard Smith2589b9802012-07-25 03:56:55 +00001098 ContainsUnexpandedParameterPack = true;
Douglas Gregor3e308b12012-02-14 19:27:52 +00001099 }
Richard Smithbb13c9a2013-09-28 04:02:39 +00001100
1101 if (C->Init.isUsable()) {
1102 buildInitCaptureField(LSI, Var);
1103 } else {
1104 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1105 TryCapture_ExplicitByVal;
1106 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1107 }
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001108 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001109 finishLambdaExplicitCaptures(LSI);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001110
Richard Smith2589b9802012-07-25 03:56:55 +00001111 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1112
Douglas Gregoradb376e2012-02-14 22:28:59 +00001113 // Add lambda parameters into scope.
1114 addLambdaParameters(Method, CurScope);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001115
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001116 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001117 // cleanups from the enclosing full-expression.
1118 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001119}
1120
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001121void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1122 bool IsInstantiation) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001123 // Leave the expression-evaluation context.
1124 DiscardCleanupsInEvaluationContext();
1125 PopExpressionEvaluationContext();
1126
1127 // Leave the context of the lambda.
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001128 if (!IsInstantiation)
1129 PopDeclContext();
Douglas Gregorab23d9a2012-02-09 01:28:42 +00001130
1131 // Finalize the lambda.
1132 LambdaScopeInfo *LSI = getCurLambda();
1133 CXXRecordDecl *Class = LSI->Lambda;
1134 Class->setInvalidDecl();
David Blaikie2d7c57e2012-04-30 02:36:29 +00001135 SmallVector<Decl*, 4> Fields;
1136 for (RecordDecl::field_iterator i = Class->field_begin(),
1137 e = Class->field_end(); i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +00001138 Fields.push_back(*i);
Douglas Gregorab23d9a2012-02-09 01:28:42 +00001139 ActOnFields(0, Class->getLocation(), Class, Fields,
1140 SourceLocation(), SourceLocation(), 0);
1141 CheckCompletedCXXClass(Class);
1142
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001143 PopFunctionScopeInfo();
1144}
1145
Douglas Gregor13f09b42012-02-15 22:00:51 +00001146/// \brief Add a lambda's conversion to function pointer, as described in
1147/// C++11 [expr.prim.lambda]p6.
1148static void addFunctionPointerConversion(Sema &S,
1149 SourceRange IntroducerRange,
1150 CXXRecordDecl *Class,
1151 CXXMethodDecl *CallOperator) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00001152 // Add the conversion to function pointer.
Faisal Vali66605d42013-10-24 01:05:22 +00001153 const FunctionProtoType *CallOpProto =
1154 CallOperator->getType()->getAs<FunctionProtoType>();
1155 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1156 CallOpProto->getExtProtoInfo();
1157 QualType PtrToFunctionTy;
1158 QualType InvokerFunctionTy;
Douglas Gregor13f09b42012-02-15 22:00:51 +00001159 {
Faisal Vali66605d42013-10-24 01:05:22 +00001160 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
Reid Kleckner78af0702013-08-27 23:08:25 +00001161 CallingConv CC = S.Context.getDefaultCallingConvention(
Faisal Vali66605d42013-10-24 01:05:22 +00001162 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1163 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1164 InvokerExtInfo.TypeQuals = 0;
1165 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1166 "Lambda's call operator should not have a reference qualifier");
Alp Toker9cacbab2014-01-20 20:26:09 +00001167 InvokerFunctionTy =
1168 S.Context.getFunctionType(CallOpProto->getResultType(),
1169 CallOpProto->getParamTypes(), InvokerExtInfo);
Faisal Vali66605d42013-10-24 01:05:22 +00001170 PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
Douglas Gregor13f09b42012-02-15 22:00:51 +00001171 }
Reid Kleckner78af0702013-08-27 23:08:25 +00001172
Faisal Vali66605d42013-10-24 01:05:22 +00001173 // Create the type of the conversion function.
1174 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1175 S.Context.getDefaultCallingConvention(
Reid Kleckner78af0702013-08-27 23:08:25 +00001176 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Faisal Vali66605d42013-10-24 01:05:22 +00001177 // The conversion function is always const.
1178 ConvExtInfo.TypeQuals = Qualifiers::Const;
1179 QualType ConvTy =
1180 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
Reid Kleckner78af0702013-08-27 23:08:25 +00001181
Douglas Gregor13f09b42012-02-15 22:00:51 +00001182 SourceLocation Loc = IntroducerRange.getBegin();
Faisal Vali66605d42013-10-24 01:05:22 +00001183 DeclarationName ConversionName
Douglas Gregor13f09b42012-02-15 22:00:51 +00001184 = S.Context.DeclarationNames.getCXXConversionFunctionName(
Faisal Vali66605d42013-10-24 01:05:22 +00001185 S.Context.getCanonicalType(PtrToFunctionTy));
1186 DeclarationNameLoc ConvNameLoc;
1187 // Construct a TypeSourceInfo for the conversion function, and wire
1188 // all the parameters appropriately for the FunctionProtoTypeLoc
1189 // so that everything works during transformation/instantiation of
1190 // generic lambdas.
1191 // The main reason for wiring up the parameters of the conversion
1192 // function with that of the call operator is so that constructs
1193 // like the following work:
1194 // auto L = [](auto b) { <-- 1
1195 // return [](auto a) -> decltype(a) { <-- 2
1196 // return a;
1197 // };
1198 // };
1199 // int (*fp)(int) = L(5);
1200 // Because the trailing return type can contain DeclRefExprs that refer
1201 // to the original call operator's variables, we hijack the call
1202 // operators ParmVarDecls below.
1203 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1204 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1205 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1206
1207 // The conversion function is a conversion to a pointer-to-function.
1208 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1209 FunctionProtoTypeLoc ConvTL =
1210 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1211 // Get the result of the conversion function which is a pointer-to-function.
1212 PointerTypeLoc PtrToFunctionTL =
1213 ConvTL.getResultLoc().getAs<PointerTypeLoc>();
1214 // Do the same for the TypeSourceInfo that is used to name the conversion
1215 // operator.
1216 PointerTypeLoc ConvNamePtrToFunctionTL =
1217 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1218
1219 // Get the underlying function types that the conversion function will
1220 // be converting to (should match the type of the call operator).
1221 FunctionProtoTypeLoc CallOpConvTL =
1222 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1223 FunctionProtoTypeLoc CallOpConvNameTL =
1224 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1225
1226 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1227 // These parameter's are essentially used to transform the name and
1228 // the type of the conversion operator. By using the same parameters
1229 // as the call operator's we don't have to fix any back references that
1230 // the trailing return type of the call operator's uses (such as
1231 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1232 // - we can simply use the return type of the call operator, and
1233 // everything should work.
1234 SmallVector<ParmVarDecl *, 4> InvokerParams;
1235 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1236 ParmVarDecl *From = CallOperator->getParamDecl(I);
1237
1238 InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1239 // Temporarily add to the TU. This is set to the invoker below.
1240 S.Context.getTranslationUnitDecl(),
1241 From->getLocStart(),
1242 From->getLocation(),
1243 From->getIdentifier(),
1244 From->getType(),
1245 From->getTypeSourceInfo(),
1246 From->getStorageClass(),
1247 /*DefaultArg=*/0));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001248 CallOpConvTL.setParam(I, From);
1249 CallOpConvNameTL.setParam(I, From);
Faisal Vali66605d42013-10-24 01:05:22 +00001250 }
1251
Douglas Gregor13f09b42012-02-15 22:00:51 +00001252 CXXConversionDecl *Conversion
1253 = CXXConversionDecl::Create(S.Context, Class, Loc,
Faisal Vali66605d42013-10-24 01:05:22 +00001254 DeclarationNameInfo(ConversionName,
1255 Loc, ConvNameLoc),
Douglas Gregor13f09b42012-02-15 22:00:51 +00001256 ConvTy,
Faisal Vali66605d42013-10-24 01:05:22 +00001257 ConvTSI,
Eli Friedman8f54e132013-06-13 19:39:48 +00001258 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregor13f09b42012-02-15 22:00:51 +00001259 /*isConstexpr=*/false,
1260 CallOperator->getBody()->getLocEnd());
1261 Conversion->setAccess(AS_public);
1262 Conversion->setImplicit(true);
Faisal Vali571df122013-09-29 08:45:24 +00001263
1264 if (Class->isGenericLambda()) {
1265 // Create a template version of the conversion operator, using the template
1266 // parameter list of the function call operator.
1267 FunctionTemplateDecl *TemplateCallOperator =
1268 CallOperator->getDescribedFunctionTemplate();
1269 FunctionTemplateDecl *ConversionTemplate =
1270 FunctionTemplateDecl::Create(S.Context, Class,
Faisal Vali66605d42013-10-24 01:05:22 +00001271 Loc, ConversionName,
Faisal Vali571df122013-09-29 08:45:24 +00001272 TemplateCallOperator->getTemplateParameters(),
1273 Conversion);
1274 ConversionTemplate->setAccess(AS_public);
1275 ConversionTemplate->setImplicit(true);
1276 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1277 Class->addDecl(ConversionTemplate);
1278 } else
1279 Class->addDecl(Conversion);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001280 // Add a non-static member function that will be the result of
1281 // the conversion with a certain unique ID.
Faisal Vali66605d42013-10-24 01:05:22 +00001282 DeclarationName InvokerName = &S.Context.Idents.get(
1283 getLambdaStaticInvokerName());
Faisal Vali571df122013-09-29 08:45:24 +00001284 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1285 // we should get a prebuilt TrivialTypeSourceInfo from Context
1286 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1287 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1288 // loop below and then use its Params to set Invoke->setParams(...) below.
1289 // This would avoid the 'const' qualifier of the calloperator from
1290 // contaminating the type of the invoker, which is currently adjusted
Faisal Vali66605d42013-10-24 01:05:22 +00001291 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1292 // trailing return type of the invoker would require a visitor to rebuild
1293 // the trailing return type and adjusting all back DeclRefExpr's to refer
1294 // to the new static invoker parameters - not the call operator's.
Douglas Gregor355efbb2012-02-17 03:02:34 +00001295 CXXMethodDecl *Invoke
1296 = CXXMethodDecl::Create(S.Context, Class, Loc,
Faisal Vali66605d42013-10-24 01:05:22 +00001297 DeclarationNameInfo(InvokerName, Loc),
1298 InvokerFunctionTy,
1299 CallOperator->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001300 SC_Static, /*IsInline=*/true,
Douglas Gregor355efbb2012-02-17 03:02:34 +00001301 /*IsConstexpr=*/false,
1302 CallOperator->getBody()->getLocEnd());
Faisal Vali66605d42013-10-24 01:05:22 +00001303 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1304 InvokerParams[I]->setOwningFunction(Invoke);
1305 Invoke->setParams(InvokerParams);
Douglas Gregor355efbb2012-02-17 03:02:34 +00001306 Invoke->setAccess(AS_private);
1307 Invoke->setImplicit(true);
Faisal Vali571df122013-09-29 08:45:24 +00001308 if (Class->isGenericLambda()) {
1309 FunctionTemplateDecl *TemplateCallOperator =
1310 CallOperator->getDescribedFunctionTemplate();
1311 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
Faisal Vali66605d42013-10-24 01:05:22 +00001312 S.Context, Class, Loc, InvokerName,
Faisal Vali571df122013-09-29 08:45:24 +00001313 TemplateCallOperator->getTemplateParameters(),
1314 Invoke);
1315 StaticInvokerTemplate->setAccess(AS_private);
1316 StaticInvokerTemplate->setImplicit(true);
1317 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1318 Class->addDecl(StaticInvokerTemplate);
1319 } else
1320 Class->addDecl(Invoke);
Douglas Gregor13f09b42012-02-15 22:00:51 +00001321}
1322
Douglas Gregor33e863c2012-02-15 22:08:38 +00001323/// \brief Add a lambda's conversion to block pointer.
1324static void addBlockPointerConversion(Sema &S,
1325 SourceRange IntroducerRange,
1326 CXXRecordDecl *Class,
1327 CXXMethodDecl *CallOperator) {
1328 const FunctionProtoType *Proto
1329 = CallOperator->getType()->getAs<FunctionProtoType>();
1330 QualType BlockPtrTy;
1331 {
1332 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1333 ExtInfo.TypeQuals = 0;
Reid Kleckner896b32f2013-06-10 20:51:09 +00001334 QualType FunctionTy = S.Context.getFunctionType(
Alp Toker9cacbab2014-01-20 20:26:09 +00001335 Proto->getResultType(), Proto->getParamTypes(), ExtInfo);
Douglas Gregor33e863c2012-02-15 22:08:38 +00001336 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1337 }
Reid Kleckner78af0702013-08-27 23:08:25 +00001338
1339 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1340 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregor33e863c2012-02-15 22:08:38 +00001341 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001342 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregor33e863c2012-02-15 22:08:38 +00001343
1344 SourceLocation Loc = IntroducerRange.getBegin();
1345 DeclarationName Name
1346 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1347 S.Context.getCanonicalType(BlockPtrTy));
1348 DeclarationNameLoc NameLoc;
1349 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1350 CXXConversionDecl *Conversion
1351 = CXXConversionDecl::Create(S.Context, Class, Loc,
1352 DeclarationNameInfo(Name, Loc, NameLoc),
1353 ConvTy,
1354 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedmanef102822013-06-13 20:56:27 +00001355 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregor33e863c2012-02-15 22:08:38 +00001356 /*isConstexpr=*/false,
1357 CallOperator->getBody()->getLocEnd());
1358 Conversion->setAccess(AS_public);
1359 Conversion->setImplicit(true);
1360 Class->addDecl(Conversion);
1361}
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001362
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001363ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor63798542012-02-20 19:44:39 +00001364 Scope *CurScope,
Douglas Gregor63798542012-02-20 19:44:39 +00001365 bool IsInstantiation) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001366 // Collect information from the lambda scope.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001367 SmallVector<LambdaExpr::Capture, 4> Captures;
1368 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001369 LambdaCaptureDefault CaptureDefault;
James Dennettddd36ff2013-08-09 23:08:25 +00001370 SourceLocation CaptureDefaultLoc;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001371 CXXRecordDecl *Class;
Douglas Gregor12695102012-02-10 08:36:38 +00001372 CXXMethodDecl *CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001373 SourceRange IntroducerRange;
1374 bool ExplicitParams;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001375 bool ExplicitResultType;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001376 bool LambdaExprNeedsCleanups;
Richard Smith2589b9802012-07-25 03:56:55 +00001377 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001378 SmallVector<VarDecl *, 4> ArrayIndexVars;
1379 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001380 {
1381 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregor12695102012-02-10 08:36:38 +00001382 CallOperator = LSI->CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001383 Class = LSI->Lambda;
1384 IntroducerRange = LSI->IntroducerRange;
1385 ExplicitParams = LSI->ExplicitParams;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001386 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001387 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith2589b9802012-07-25 03:56:55 +00001388 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor54fcea62012-02-13 16:35:30 +00001389 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1390 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1391
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001392 // Translate captures.
1393 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1394 LambdaScopeInfo::Capture From = LSI->Captures[I];
1395 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1396 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1397
1398 // Handle 'this' capture.
1399 if (From.isThisCapture()) {
1400 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1401 IsImplicit,
1402 LCK_This));
1403 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1404 getCurrentThisType(),
1405 /*isImplicit=*/true));
1406 continue;
1407 }
1408
1409 VarDecl *Var = From.getVariable();
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001410 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1411 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregor3e308b12012-02-14 19:27:52 +00001412 Kind, Var, From.getEllipsisLoc()));
Richard Smithba71c082013-05-16 06:20:58 +00001413 CaptureInits.push_back(From.getInitExpr());
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001414 }
1415
1416 switch (LSI->ImpCaptureStyle) {
1417 case CapturingScopeInfo::ImpCap_None:
1418 CaptureDefault = LCD_None;
1419 break;
1420
1421 case CapturingScopeInfo::ImpCap_LambdaByval:
1422 CaptureDefault = LCD_ByCopy;
1423 break;
1424
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001425 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001426 case CapturingScopeInfo::ImpCap_LambdaByref:
1427 CaptureDefault = LCD_ByRef;
1428 break;
1429
1430 case CapturingScopeInfo::ImpCap_Block:
1431 llvm_unreachable("block capture in lambda");
1432 break;
1433 }
James Dennettddd36ff2013-08-09 23:08:25 +00001434 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001435
Douglas Gregor73456262012-02-09 10:18:50 +00001436 // C++11 [expr.prim.lambda]p4:
1437 // If a lambda-expression does not include a
1438 // trailing-return-type, it is as if the trailing-return-type
1439 // denotes the following type:
Richard Smith4db51c22013-09-25 05:02:54 +00001440 //
1441 // Skip for C++1y return type deduction semantics which uses
1442 // different machinery.
1443 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor73456262012-02-09 10:18:50 +00001444 // FIXME: Assumes current resolution to core issue 975.
Richard Smith4db51c22013-09-25 05:02:54 +00001445 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rosed39e5f12012-07-02 21:19:23 +00001446 deduceClosureReturnType(*LSI);
1447
Douglas Gregor73456262012-02-09 10:18:50 +00001448 // - if there are no return statements in the
1449 // compound-statement, or all return statements return
1450 // either an expression of type void or no expression or
1451 // braced-init-list, the type void;
1452 if (LSI->ReturnType.isNull()) {
1453 LSI->ReturnType = Context.VoidTy;
Douglas Gregor73456262012-02-09 10:18:50 +00001454 }
1455
1456 // Create a function type with the inferred return type.
1457 const FunctionProtoType *Proto
1458 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner896b32f2013-06-10 20:51:09 +00001459 QualType FunctionTy = Context.getFunctionType(
Alp Toker9cacbab2014-01-20 20:26:09 +00001460 LSI->ReturnType, Proto->getParamTypes(), Proto->getExtProtoInfo());
Douglas Gregor73456262012-02-09 10:18:50 +00001461 CallOperator->setType(FunctionTy);
1462 }
Douglas Gregor1a22d282012-02-12 17:34:23 +00001463 // C++ [expr.prim.lambda]p7:
1464 // The lambda-expression's compound-statement yields the
1465 // function-body (8.4) of the function call operator [...].
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001466 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor1a22d282012-02-12 17:34:23 +00001467 CallOperator->setLexicalDeclContext(Class);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001468 Decl *TemplateOrNonTemplateCallOperatorDecl =
1469 CallOperator->getDescribedFunctionTemplate()
1470 ? CallOperator->getDescribedFunctionTemplate()
1471 : cast<Decl>(CallOperator);
1472
1473 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1474 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1475
Douglas Gregor5dbc14f2012-02-21 20:05:31 +00001476 PopExpressionEvaluationContext();
Douglas Gregor1a22d282012-02-12 17:34:23 +00001477
Douglas Gregor04bbab52012-02-10 16:13:20 +00001478 // C++11 [expr.prim.lambda]p6:
1479 // The closure type for a lambda-expression with no lambda-capture
1480 // has a public non-virtual non-explicit const conversion function
1481 // to pointer to function having the same parameter and return
1482 // types as the closure type's function call operator.
Douglas Gregor13f09b42012-02-15 22:00:51 +00001483 if (Captures.empty() && CaptureDefault == LCD_None)
1484 addFunctionPointerConversion(*this, IntroducerRange, Class,
1485 CallOperator);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001486
Douglas Gregor33e863c2012-02-15 22:08:38 +00001487 // Objective-C++:
1488 // The closure type for a lambda-expression has a public non-virtual
1489 // non-explicit const conversion function to a block pointer having the
1490 // same parameter and return types as the closure type's function call
1491 // operator.
Faisal Vali571df122013-09-29 08:45:24 +00001492 // FIXME: Fix generic lambda to block conversions.
1493 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1494 !Class->isGenericLambda())
Douglas Gregor33e863c2012-02-15 22:08:38 +00001495 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1496
Douglas Gregor04bbab52012-02-10 16:13:20 +00001497 // Finalize the lambda class.
David Blaikie2d7c57e2012-04-30 02:36:29 +00001498 SmallVector<Decl*, 4> Fields;
1499 for (RecordDecl::field_iterator i = Class->field_begin(),
1500 e = Class->field_end(); i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +00001501 Fields.push_back(*i);
Douglas Gregor04bbab52012-02-10 16:13:20 +00001502 ActOnFields(0, Class->getLocation(), Class, Fields,
1503 SourceLocation(), SourceLocation(), 0);
1504 CheckCompletedCXXClass(Class);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001505 }
1506
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001507 if (LambdaExprNeedsCleanups)
1508 ExprNeedsCleanups = true;
Douglas Gregor63798542012-02-20 19:44:39 +00001509
Douglas Gregor89625492012-02-09 08:14:43 +00001510 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettddd36ff2013-08-09 23:08:25 +00001511 CaptureDefault, CaptureDefaultLoc,
1512 Captures,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001513 ExplicitParams, ExplicitResultType,
1514 CaptureInits, ArrayIndexVars,
Richard Smith2589b9802012-07-25 03:56:55 +00001515 ArrayIndexStarts, Body->getLocEnd(),
1516 ContainsUnexpandedParameterPack);
David Majnemer9adc3612013-10-25 09:12:52 +00001517
Douglas Gregorb4328232012-02-14 00:00:48 +00001518 if (!CurContext->isDependentContext()) {
1519 switch (ExprEvalContexts.back().Context) {
David Majnemer9adc3612013-10-25 09:12:52 +00001520 // C++11 [expr.prim.lambda]p2:
1521 // A lambda-expression shall not appear in an unevaluated operand
1522 // (Clause 5).
Douglas Gregorb4328232012-02-14 00:00:48 +00001523 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +00001524 case UnevaluatedAbstract:
David Majnemer9adc3612013-10-25 09:12:52 +00001525 // C++1y [expr.const]p2:
1526 // A conditional-expression e is a core constant expression unless the
1527 // evaluation of e, following the rules of the abstract machine, would
1528 // evaluate [...] a lambda-expression.
David Majnemer2748da92013-11-05 08:01:18 +00001529 //
1530 // This is technically incorrect, there are some constant evaluated contexts
1531 // where this should be allowed. We should probably fix this when DR1607 is
1532 // ratified, it lays out the exact set of conditions where we shouldn't
1533 // allow a lambda-expression.
David Majnemer9adc3612013-10-25 09:12:52 +00001534 case ConstantEvaluated:
Douglas Gregorb4328232012-02-14 00:00:48 +00001535 // We don't actually diagnose this case immediately, because we
1536 // could be within a context where we might find out later that
1537 // the expression is potentially evaluated (e.g., for typeid).
1538 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1539 break;
Douglas Gregor89625492012-02-09 08:14:43 +00001540
Douglas Gregorb4328232012-02-14 00:00:48 +00001541 case PotentiallyEvaluated:
1542 case PotentiallyEvaluatedIfUsed:
1543 break;
1544 }
Douglas Gregor89625492012-02-09 08:14:43 +00001545 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001546
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001547 return MaybeBindToTemporary(Lambda);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001548}
Eli Friedman98b01ed2012-03-01 04:01:32 +00001549
1550ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1551 SourceLocation ConvLocation,
1552 CXXConversionDecl *Conv,
1553 Expr *Src) {
1554 // Make sure that the lambda call operator is marked used.
1555 CXXRecordDecl *Lambda = Conv->getParent();
1556 CXXMethodDecl *CallOperator
1557 = cast<CXXMethodDecl>(
David Blaikieff7d47a2012-12-19 00:45:41 +00001558 Lambda->lookup(
1559 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman98b01ed2012-03-01 04:01:32 +00001560 CallOperator->setReferenced();
Eli Friedman276dd182013-09-05 00:02:25 +00001561 CallOperator->markUsed(Context);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001562
1563 ExprResult Init = PerformCopyInitialization(
1564 InitializedEntity::InitializeBlock(ConvLocation,
1565 Src->getType(),
1566 /*NRVO=*/false),
1567 CurrentLocation, Src);
1568 if (!Init.isInvalid())
1569 Init = ActOnFinishFullExpr(Init.take());
1570
1571 if (Init.isInvalid())
1572 return ExprError();
1573
1574 // Create the new block to be returned.
1575 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1576
1577 // Set the type information.
1578 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1579 Block->setIsVariadic(CallOperator->isVariadic());
1580 Block->setBlockMissingReturnType(false);
1581
1582 // Add parameters.
1583 SmallVector<ParmVarDecl *, 4> BlockParams;
1584 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1585 ParmVarDecl *From = CallOperator->getParamDecl(I);
1586 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1587 From->getLocStart(),
1588 From->getLocation(),
1589 From->getIdentifier(),
1590 From->getType(),
1591 From->getTypeSourceInfo(),
1592 From->getStorageClass(),
Eli Friedman98b01ed2012-03-01 04:01:32 +00001593 /*DefaultArg=*/0));
1594 }
1595 Block->setParams(BlockParams);
1596
1597 Block->setIsConversionFromLambda(true);
1598
1599 // Add capture. The capture uses a fake variable, which doesn't correspond
1600 // to any actual memory location. However, the initializer copy-initializes
1601 // the lambda object.
1602 TypeSourceInfo *CapVarTSI =
1603 Context.getTrivialTypeSourceInfo(Src->getType());
1604 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1605 ConvLocation, 0,
1606 Src->getType(), CapVarTSI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001607 SC_None);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001608 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1609 /*Nested=*/false, /*Copy=*/Init.take());
1610 Block->setCaptures(Context, &Capture, &Capture + 1,
1611 /*CapturesCXXThis=*/false);
1612
1613 // Add a fake function body to the block. IR generation is responsible
1614 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramere2a929d2012-07-04 17:03:41 +00001615 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman98b01ed2012-03-01 04:01:32 +00001616
1617 // Create the block literal expression.
1618 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1619 ExprCleanupObjects.push_back(Block);
1620 ExprNeedsCleanups = true;
1621
1622 return BuildBlock;
1623}