blob: 1d6a4d6909897d16097e3384f20400aa8e861d00 [file] [log] [blame]
Douglas Gregore2a7ad02012-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 Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/AST/ExprCXX.h"
15#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000016#include "clang/Sema/Initialization.h"
Faisal Valiecb58192013-08-22 01:49:11 +000017#include "clang/Sema/SemaLambda.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000018#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000019#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/Sema/ScopeInfo.h"
21#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000022#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000023using namespace clang;
24using namespace sema;
25
Douglas Gregorf4b7de12012-02-21 19:11:17 +000026CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000027 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000028 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000029 DeclContext *DC = CurContext;
30 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
31 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000032
Douglas Gregore2a7ad02012-02-08 21:18:48 +000033 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000034 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000035 IntroducerRange.getBegin(),
36 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000037 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000038
39 return Class;
40}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000041
Douglas Gregorf54486a2012-04-04 17:40:10 +000042/// \brief Determine whether the given context is or is enclosed in an inline
43/// function.
44static bool isInInlineFunction(const DeclContext *DC) {
45 while (!DC->isFileContext()) {
46 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
47 if (FD->isInlined())
48 return true;
49
50 DC = DC->getLexicalParent();
51 }
52
53 return false;
54}
55
Eli Friedman07369dd2013-07-01 20:22:57 +000056MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000057Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000058 Decl *&ManglingContextDecl) {
59 // Compute the context for allocating mangling numbers in the current
60 // expression, if the ABI requires them.
61 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
62
63 enum ContextKind {
64 Normal,
65 DefaultArgument,
66 DataMember,
67 StaticDataMember
68 } Kind = Normal;
69
70 // Default arguments of member function parameters that appear in a class
71 // definition, as well as the initializers of data members, receive special
72 // treatment. Identify them.
73 if (ManglingContextDecl) {
74 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
75 if (const DeclContext *LexicalDC
76 = Param->getDeclContext()->getLexicalParent())
77 if (LexicalDC->isRecord())
78 Kind = DefaultArgument;
79 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
80 if (Var->getDeclContext()->isRecord())
81 Kind = StaticDataMember;
82 } else if (isa<FieldDecl>(ManglingContextDecl)) {
83 Kind = DataMember;
84 }
85 }
86
87 // Itanium ABI [5.1.7]:
88 // In the following contexts [...] the one-definition rule requires closure
89 // types in different translation units to "correspond":
90 bool IsInNonspecializedTemplate =
91 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
92 switch (Kind) {
93 case Normal:
94 // -- the bodies of non-exported nonspecialized template functions
95 // -- the bodies of inline functions
96 if ((IsInNonspecializedTemplate &&
97 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
98 isInInlineFunction(CurContext)) {
99 ManglingContextDecl = 0;
100 return &Context.getManglingNumberContext(DC);
101 }
102
103 ManglingContextDecl = 0;
104 return 0;
105
106 case StaticDataMember:
107 // -- the initializers of nonspecialized static members of template classes
108 if (!IsInNonspecializedTemplate) {
109 ManglingContextDecl = 0;
110 return 0;
111 }
112 // Fall through to get the current context.
113
114 case DataMember:
115 // -- the in-class initializers of class members
116 case DefaultArgument:
117 // -- default arguments appearing in class definitions
118 return &ExprEvalContexts.back().getMangleNumberingContext();
119 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000120
121 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000122}
123
Faisal Valiecb58192013-08-22 01:49:11 +0000124
125ParmVarDecl *Sema::ActOnLambdaAutoParameter(ParmVarDecl *PVD) {
126 LambdaScopeInfo *LSI = getCurLambda();
127 assert(LSI && "No LambdaScopeInfo on the stack!");
128 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
129 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
130 // Invent a template type parameter corresponding to the auto
131 // containing parameter.
132 TemplateTypeParmDecl *TemplateParam =
133 TemplateTypeParmDecl::Create(Context,
134 // Temporarily add to the TranslationUnit DeclContext. When the
135 // associated TemplateParameterList is attached to a template
136 // declaration (such as FunctionTemplateDecl), the DeclContext
137 // for each template parameter gets updated appropriately via
138 // a call to AdoptTemplateParameterList.
139 Context.getTranslationUnitDecl(),
140 SourceLocation(),
141 PVD->getLocation(),
142 TemplateParameterDepth,
143 AutoParameterPosition, // our template param index
144 /* Identifier*/ 0, false, PVD->isParameterPack());
145 LSI->AutoTemplateParams.push_back(TemplateParam);
Faisal Valiecb58192013-08-22 01:49:11 +0000146 // Now replace the 'auto' in the function parameter with this invented
147 // template type parameter.
148 QualType TemplParamType = QualType(TemplateParam->getTypeForDecl(), 0);
149
150 TypeSourceInfo *AutoTSI = PVD->getTypeSourceInfo();
151 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfo(AutoTSI, TemplParamType);
152 PVD->setType(NewTSI->getType());
153 PVD->setTypeSourceInfo(NewTSI);
154 return PVD;
155}
156
157
158static inline TemplateParameterList *
159 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI,
160 Sema &SemaRef) {
161 if (LSI->GLTemplateParameterList)
162 return LSI->GLTemplateParameterList;
163 else if (LSI->AutoTemplateParams.size()) {
164 SourceRange IntroRange = LSI->IntroducerRange;
165 SourceLocation LAngleLoc = IntroRange.getBegin();
166 SourceLocation RAngleLoc = IntroRange.getEnd();
167 LSI->GLTemplateParameterList =
168 TemplateParameterList::Create(SemaRef.Context,
169 /* Template kw loc */ SourceLocation(),
170 LAngleLoc,
171 (NamedDecl**)LSI->AutoTemplateParams.data(),
172 LSI->AutoTemplateParams.size(), RAngleLoc);
173 }
174 return LSI->GLTemplateParameterList;
175}
176
177
178
Douglas Gregordfca6f52012-02-13 22:00:16 +0000179CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000180 SourceRange IntroducerRange,
181 TypeSourceInfo *MethodType,
182 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000183 ArrayRef<ParmVarDecl *> Params) {
Faisal Valiecb58192013-08-22 01:49:11 +0000184 TemplateParameterList *TemplateParams =
185 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000186 // C++11 [expr.prim.lambda]p5:
187 // The closure type for a lambda-expression has a public inline function
188 // call operator (13.5.4) whose parameters and return type are described by
189 // the lambda-expression's parameter-declaration-clause and
190 // trailing-return-type respectively.
191 DeclarationName MethodName
192 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
193 DeclarationNameLoc MethodNameLoc;
194 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
195 = IntroducerRange.getBegin().getRawEncoding();
196 MethodNameLoc.CXXOperatorName.EndOpNameLoc
197 = IntroducerRange.getEnd().getRawEncoding();
198 CXXMethodDecl *Method
199 = CXXMethodDecl::Create(Context, Class, EndLoc,
200 DeclarationNameInfo(MethodName,
201 IntroducerRange.getBegin(),
202 MethodNameLoc),
203 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000204 SC_None,
205 /*isInline=*/true,
206 /*isConstExpr=*/false,
207 EndLoc);
208 Method->setAccess(AS_public);
209
210 // Temporarily set the lexical declaration context to the current
211 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000212 Method->setLexicalDeclContext(CurContext);
Faisal Valiecb58192013-08-22 01:49:11 +0000213 // Create a function template if we have a template parameter list
214 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
215 FunctionTemplateDecl::Create(Context, Class,
216 Method->getLocation(), MethodName,
217 TemplateParams,
218 Method) : 0;
219 if (TemplateMethod) {
220 TemplateMethod->setLexicalDeclContext(CurContext);
221 TemplateMethod->setAccess(AS_public);
222 Method->setDescribedFunctionTemplate(TemplateMethod);
223 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000224
Douglas Gregorc6889e72012-02-14 22:28:59 +0000225 // Add parameters.
226 if (!Params.empty()) {
227 Method->setParams(Params);
228 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
229 const_cast<ParmVarDecl **>(Params.end()),
230 /*CheckParameterNames=*/false);
231
232 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
233 PEnd = Method->param_end();
234 P != PEnd; ++P)
235 (*P)->setOwningFunction(Method);
236 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000237
Eli Friedman07369dd2013-07-01 20:22:57 +0000238 Decl *ManglingContextDecl;
239 if (MangleNumberingContext *MCtx =
240 getCurrentMangleNumberContext(Class->getDeclContext(),
241 ManglingContextDecl)) {
242 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
243 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000244 }
245
Douglas Gregordfca6f52012-02-13 22:00:16 +0000246 return Method;
247}
248
Faisal Valiecb58192013-08-22 01:49:11 +0000249void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
250 CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000251 SourceRange IntroducerRange,
252 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000253 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000254 bool ExplicitParams,
255 bool ExplicitResultType,
256 bool Mutable) {
Faisal Valiecb58192013-08-22 01:49:11 +0000257 LSI->CallOperator = CallOperator;
258 LSI->Lambda = CallOperator->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000259 if (CaptureDefault == LCD_ByCopy)
260 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
261 else if (CaptureDefault == LCD_ByRef)
262 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000263 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000264 LSI->IntroducerRange = IntroducerRange;
265 LSI->ExplicitParams = ExplicitParams;
266 LSI->Mutable = Mutable;
267
268 if (ExplicitResultType) {
269 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000270
271 if (!LSI->ReturnType->isDependentType() &&
272 !LSI->ReturnType->isVoidType()) {
273 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
274 diag::err_lambda_incomplete_result)) {
275 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000276 }
277 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000278 } else {
279 LSI->HasImplicitReturnType = true;
280 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000281}
282
283void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
284 LSI->finishedExplicitCaptures();
285}
286
Douglas Gregorc6889e72012-02-14 22:28:59 +0000287void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000288 // Introduce our parameters into the function scope
289 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
290 p < NumParams; ++p) {
291 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000292
293 // If this has an identifier, add it to the scope stack.
294 if (CurScope && Param->getIdentifier()) {
295 CheckShadow(CurScope, Param);
296
297 PushOnScopeChains(Param, CurScope);
298 }
299 }
300}
301
John McCall41d01642013-03-09 00:54:31 +0000302/// If this expression is an enumerator-like expression of some type
303/// T, return the type T; otherwise, return null.
304///
305/// Pointer comparisons on the result here should always work because
306/// it's derived from either the parent of an EnumConstantDecl
307/// (i.e. the definition) or the declaration returned by
308/// EnumType::getDecl() (i.e. the definition).
309static EnumDecl *findEnumForBlockReturn(Expr *E) {
310 // An expression is an enumerator-like expression of type T if,
311 // ignoring parens and parens-like expressions:
312 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000313
John McCall41d01642013-03-09 00:54:31 +0000314 // - it is an enumerator whose enum type is T or
315 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
316 if (EnumConstantDecl *D
317 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
318 return cast<EnumDecl>(D->getDeclContext());
319 }
320 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000321 }
322
John McCall41d01642013-03-09 00:54:31 +0000323 // - it is a comma expression whose RHS is an enumerator-like
324 // expression of type T or
325 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
326 if (BO->getOpcode() == BO_Comma)
327 return findEnumForBlockReturn(BO->getRHS());
328 return 0;
329 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000330
John McCall41d01642013-03-09 00:54:31 +0000331 // - it is a statement-expression whose value expression is an
332 // enumerator-like expression of type T or
333 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
334 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
335 return findEnumForBlockReturn(last);
336 return 0;
337 }
338
339 // - it is a ternary conditional operator (not the GNU ?:
340 // extension) whose second and third operands are
341 // enumerator-like expressions of type T or
342 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
343 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
344 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
345 return ED;
346 return 0;
347 }
348
349 // (implicitly:)
350 // - it is an implicit integral conversion applied to an
351 // enumerator-like expression of type T or
352 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000353 // We can sometimes see integral conversions in valid
354 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000355 if (ICE->getCastKind() == CK_IntegralCast)
356 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000357
358 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000359 }
360
361 // - it is an expression of that formal enum type.
362 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
363 return ET->getDecl();
364 }
365
366 // Otherwise, nope.
367 return 0;
368}
369
370/// Attempt to find a type T for which the returned expression of the
371/// given statement is an enumerator-like expression of that type.
372static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
373 if (Expr *retValue = ret->getRetValue())
374 return findEnumForBlockReturn(retValue);
375 return 0;
376}
377
378/// Attempt to find a common type T for which all of the returned
379/// expressions in a block are enumerator-like expressions of that
380/// type.
381static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
382 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
383
384 // Try to find one for the first return.
385 EnumDecl *ED = findEnumForBlockReturn(*i);
386 if (!ED) return 0;
387
388 // Check that the rest of the returns have the same enum.
389 for (++i; i != e; ++i) {
390 if (findEnumForBlockReturn(*i) != ED)
391 return 0;
392 }
393
394 // Never infer an anonymous enum type.
395 if (!ED->hasNameForLinkage()) return 0;
396
397 return ED;
398}
399
400/// Adjust the given return statements so that they formally return
401/// the given type. It should require, at most, an IntegralCast.
402static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
403 QualType returnType) {
404 for (ArrayRef<ReturnStmt*>::iterator
405 i = returns.begin(), e = returns.end(); i != e; ++i) {
406 ReturnStmt *ret = *i;
407 Expr *retValue = ret->getRetValue();
408 if (S.Context.hasSameType(retValue->getType(), returnType))
409 continue;
410
411 // Right now we only support integral fixup casts.
412 assert(returnType->isIntegralOrUnscopedEnumerationType());
413 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
414
415 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
416
417 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
418 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
419 E, /*base path*/ 0, VK_RValue);
420 if (cleanups) {
421 cleanups->setSubExpr(E);
422 } else {
423 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000424 }
425 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000426}
427
428void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Faisal Valiecb58192013-08-22 01:49:11 +0000429 assert(CSI.HasImplicitReturnType || CSI.ReturnType->isUndeducedType());
Jordan Rose7dd900e2012-07-02 21:19:23 +0000430
John McCall41d01642013-03-09 00:54:31 +0000431 // C++ Core Issue #975, proposed resolution:
432 // If a lambda-expression does not include a trailing-return-type,
433 // it is as if the trailing-return-type denotes the following type:
434 // - if there are no return statements in the compound-statement,
435 // or all return statements return either an expression of type
436 // void or no expression or braced-init-list, the type void;
437 // - otherwise, if all return statements return an expression
438 // and the types of the returned expressions after
439 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
440 // array-to-pointer conversion (4.2 [conv.array]), and
441 // function-to-pointer conversion (4.3 [conv.func]) are the
442 // same, that common type;
443 // - otherwise, the program is ill-formed.
444 //
445 // In addition, in blocks in non-C++ modes, if all of the return
446 // statements are enumerator-like expressions of some type T, where
447 // T has a name for linkage, then we infer the return type of the
448 // block to be that type.
449
Jordan Rose7dd900e2012-07-02 21:19:23 +0000450 // First case: no return statements, implicit void return type.
451 ASTContext &Ctx = getASTContext();
452 if (CSI.Returns.empty()) {
453 // It's possible there were simply no /valid/ return statements.
454 // In this case, the first one we found may have at least given us a type.
455 if (CSI.ReturnType.isNull())
456 CSI.ReturnType = Ctx.VoidTy;
457 return;
458 }
459
460 // Second case: at least one return statement has dependent type.
461 // Delay type checking until instantiation.
462 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Faisal Valiecb58192013-08-22 01:49:11 +0000463 if (CSI.ReturnType->isDependentType() || CSI.ReturnType->isUndeducedType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000464 return;
465
John McCall41d01642013-03-09 00:54:31 +0000466 // Try to apply the enum-fuzz rule.
467 if (!getLangOpts().CPlusPlus) {
468 assert(isa<BlockScopeInfo>(CSI));
469 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
470 if (ED) {
471 CSI.ReturnType = Context.getTypeDeclType(ED);
472 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
473 return;
474 }
475 }
476
Jordan Rose7dd900e2012-07-02 21:19:23 +0000477 // Third case: only one return statement. Don't bother doing extra work!
478 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
479 E = CSI.Returns.end();
480 if (I+1 == E)
481 return;
482
483 // General case: many return statements.
484 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000485
486 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000487 // Note that we've already done the required promotions as part of
488 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000489 for (; I != E; ++I) {
490 const ReturnStmt *RS = *I;
491 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000492
John McCall41d01642013-03-09 00:54:31 +0000493 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
494 if (Context.hasSameType(ReturnType, CSI.ReturnType))
495 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000496
John McCall41d01642013-03-09 00:54:31 +0000497 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
498 // TODO: It's possible that the *first* return is the divergent one.
499 Diag(RS->getLocStart(),
500 diag::err_typecheck_missing_return_type_incompatible)
501 << ReturnType << CSI.ReturnType
502 << isa<LambdaScopeInfo>(CSI);
503 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000504 }
505}
506
Richard Smith0d8e9642013-05-16 06:20:58 +0000507FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
508 IdentifierInfo *Id, Expr *InitExpr) {
509 LambdaScopeInfo *LSI = getCurLambda();
510
511 // C++1y [expr.prim.lambda]p11:
512 // The type of [the] member corresponds to the type of a hypothetical
513 // variable declaration of the form "auto init-capture;"
514 QualType DeductType = Context.getAutoDeductType();
515 TypeLocBuilder TLB;
516 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
517 if (ByRef) {
518 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
519 assert(!DeductType.isNull() && "can't build reference to auto");
520 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
521 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000522 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000523
524 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
525 Expr *Init = InitExpr;
526 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
527 if (Parens->getNumExprs() == 1) {
528 Init = Parens->getExpr(0);
529 InitKind = InitializationKind::CreateDirect(
530 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
531 } else {
532 // C++1y [dcl.spec.auto]p3:
533 // In an initializer of the form ( expression-list ), the
534 // expression-list shall be a single assignment-expression.
535 if (Parens->getNumExprs() == 0)
536 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
537 << Id;
538 else if (Parens->getNumExprs() > 1)
539 Diag(Parens->getExpr(1)->getLocStart(),
540 diag::err_init_capture_multiple_expressions)
541 << Id;
542 return 0;
543 }
544 } else if (isa<InitListExpr>(Init))
545 // We do not need to distinguish between direct-list-initialization
546 // and copy-list-initialization here, because we will always deduce
547 // std::initializer_list<T>, and direct- and copy-list-initialization
548 // always behave the same for such a type.
549 // FIXME: We should model whether an '=' was present.
550 InitKind = InitializationKind::CreateDirectList(Loc);
551 else
552 InitKind = InitializationKind::CreateCopy(Loc, Loc);
553 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000554 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000555 if (isa<InitListExpr>(Init))
556 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
557 << Id << Init->getSourceRange();
558 else
559 Diag(Loc, diag::err_init_capture_deduction_failure)
560 << Id << Init->getType() << Init->getSourceRange();
561 }
562 if (DeducedType.isNull())
563 return 0;
564
565 // [...] a non-static data member named by the identifier is declared in
566 // the closure type. This member is not a bit-field and not mutable.
567 // Core issue: the member is (probably...) public.
568 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000569 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000570 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
571 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
572 LSI->Lambda->addDecl(NewFD);
573
574 if (CurContext->isDependentContext()) {
575 LSI->addInitCapture(NewFD, InitExpr);
576 } else {
577 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
578 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
579 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
580 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
581 if (!InitResult.isInvalid())
582 LSI->addInitCapture(NewFD, InitResult.take());
583 }
584 }
585
586 return NewFD;
587}
588
Douglas Gregordfca6f52012-02-13 22:00:16 +0000589void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valiecb58192013-08-22 01:49:11 +0000590 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000591 // Determine if we're within a context where we know that the lambda will
592 // be dependent, because there are template parameters in scope.
593 bool KnownDependent = false;
Faisal Valiecb58192013-08-22 01:49:11 +0000594 LambdaScopeInfo *const LSI = getCurLambda();
595 assert(LSI && "LambdaScopeInfo should be on stack!");
596 TemplateParameterList *TemplateParams =
597 getGenericLambdaTemplateParameterList(LSI, *this);
598
599 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
600 // Since we have our own TemplateParams, so check if an outer scope
601 // has template params, only then are we in a dependent scope.
602 if (TemplateParams) {
603 TmplScope = TmplScope->getParent();
604 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
605 }
606 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000607 KnownDependent = true;
Faisal Valiecb58192013-08-22 01:49:11 +0000608 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000609 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 TypeSourceInfo *MethodTyInfo;
611 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000612 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000613 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000614 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000615 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000616 if (ParamInfo.getNumTypeObjects() == 0) {
617 // C++11 [expr.prim.lambda]p4:
618 // If a lambda-expression does not include a lambda-declarator, it is as
619 // if the lambda-declarator were ().
620 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000621 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000622 EPI.TypeQuals |= DeclSpec::TQ_const;
Faisal Valiecb58192013-08-22 01:49:11 +0000623 // For C++1y, use the new return type deduction machinery, by imaginging
624 // 'auto' if no trailing return type.
625 QualType DefaultTypeForNoTrailingReturn = getLangOpts().CPlusPlus1y ?
626 Context.getAutoDeductType() : Context.DependentTy;
627 QualType MethodTy = Context.getFunctionType(DefaultTypeForNoTrailingReturn, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000628 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000629 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
630 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000631 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000632 EndLoc = Intro.Range.getEnd();
633 } else {
634 assert(ParamInfo.isFunctionDeclarator() &&
635 "lambda-declarator is a function");
636 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
637
638 // C++11 [expr.prim.lambda]p5:
639 // This function call operator is declared const (9.3.1) if and only if
640 // the lambda-expression's parameter-declaration-clause is not followed
641 // by mutable. It is neither virtual nor declared volatile. [...]
642 if (!FTI.hasMutableQualifier())
643 FTI.TypeQuals |= DeclSpec::TQ_const;
644
Faisal Valiecb58192013-08-22 01:49:11 +0000645 ExplicitResultType = FTI.hasTrailingReturnType();
646 // In C++11 if there is no explicit return type, the return type is
647 // artificially set to DependentTy, whereas in C++1y it is set to AutoTy
648 // (through ConvertDeclSpecToType) which allows us to support both
649 // C++11 and C++1y return type deduction semantics.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000650 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000651 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000652 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000653
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000654 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
655 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
656 // Empty arg list, don't push any params.
657 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
658 } else {
659 Params.reserve(FTI.NumArgs);
660 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
661 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
662 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000663
664 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000665 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
666 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000667 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000668
669 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
670 KnownDependent);
671
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000672 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000673 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000674 if (ExplicitParams)
675 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000676
Bill Wendlingad017fa2012-12-20 19:22:21 +0000677 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000678 ProcessDeclAttributes(CurScope, Method, ParamInfo);
679
Douglas Gregor503384f2012-02-09 00:47:04 +0000680 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000681 PushDeclContext(CurScope, Method);
682
Faisal Valiecb58192013-08-22 01:49:11 +0000683 // Build the lambda scope.
684 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000685 Intro.Range,
686 Intro.Default, Intro.DefaultLoc,
687 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000688 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000689 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000690
691 // Distinct capture names, for diagnostics.
692 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
693
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000694 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000695 SourceLocation PrevCaptureLoc
696 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000697 for (SmallVectorImpl<LambdaCapture>::const_iterator
698 C = Intro.Captures.begin(),
699 E = Intro.Captures.end();
700 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000701 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000702 if (C->Kind == LCK_This) {
703 // C++11 [expr.prim.lambda]p8:
704 // An identifier or this shall not appear more than once in a
705 // lambda-capture.
706 if (LSI->isCXXThisCaptured()) {
707 Diag(C->Loc, diag::err_capture_more_than_once)
708 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000709 << SourceRange(LSI->getCXXThisCapture().getLocation())
710 << FixItHint::CreateRemoval(
711 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000712 continue;
713 }
714
715 // C++11 [expr.prim.lambda]p8:
716 // If a lambda-capture includes a capture-default that is =, the
717 // lambda-capture shall not contain this [...].
718 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000719 Diag(C->Loc, diag::err_this_capture_with_copy_default)
720 << FixItHint::CreateRemoval(
721 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000722 continue;
723 }
724
725 // C++11 [expr.prim.lambda]p12:
726 // If this is captured by a local lambda expression, its nearest
727 // enclosing function shall be a non-static member function.
728 QualType ThisCaptureType = getCurrentThisType();
729 if (ThisCaptureType.isNull()) {
730 Diag(C->Loc, diag::err_this_capture) << true;
731 continue;
732 }
733
734 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
735 continue;
736 }
737
Richard Smith0d8e9642013-05-16 06:20:58 +0000738 assert(C->Id && "missing identifier for capture");
739
Richard Smith0a664b82013-05-09 21:36:41 +0000740 if (C->Init.isInvalid())
741 continue;
742 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000743 // C++11 [expr.prim.lambda]p8:
744 // An identifier or this shall not appear more than once in a
745 // lambda-capture.
746 if (!CaptureNames.insert(C->Id))
747 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
748
749 if (C->Init.get()->containsUnexpandedParameterPack())
750 ContainsUnexpandedParameterPack = true;
751
752 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
753 C->Id, C->Init.take());
754 // C++1y [expr.prim.lambda]p11:
755 // Within the lambda-expression's lambda-declarator and
756 // compound-statement, the identifier in the init-capture
757 // hides any declaration of the same name in scopes enclosing
758 // the lambda-expression.
759 if (NewFD)
760 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000761 continue;
762 }
763
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000764 // C++11 [expr.prim.lambda]p8:
765 // If a lambda-capture includes a capture-default that is &, the
766 // identifiers in the lambda-capture shall not be preceded by &.
767 // If a lambda-capture includes a capture-default that is =, [...]
768 // each identifier it contains shall be preceded by &.
769 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000770 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
771 << FixItHint::CreateRemoval(
772 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000773 continue;
774 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000775 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
776 << FixItHint::CreateRemoval(
777 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000778 continue;
779 }
780
Richard Smith0d8e9642013-05-16 06:20:58 +0000781 // C++11 [expr.prim.lambda]p10:
782 // The identifiers in a capture-list are looked up using the usual
783 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000784 DeclarationNameInfo Name(C->Id, C->Loc);
785 LookupResult R(*this, Name, LookupOrdinaryName);
786 LookupName(R, CurScope);
787 if (R.isAmbiguous())
788 continue;
789 if (R.empty()) {
790 // FIXME: Disable corrections that would add qualification?
791 CXXScopeSpec ScopeSpec;
792 DeclFilterCCC<VarDecl> Validator;
793 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
794 continue;
795 }
796
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000797 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000798
799 // C++11 [expr.prim.lambda]p8:
800 // An identifier or this shall not appear more than once in a
801 // lambda-capture.
802 if (!CaptureNames.insert(C->Id)) {
803 if (Var && LSI->isCaptured(Var)) {
804 Diag(C->Loc, diag::err_capture_more_than_once)
805 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
806 << FixItHint::CreateRemoval(
807 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
808 } else
809 // Previous capture was an init-capture: no fixit.
810 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
811 continue;
812 }
813
814 // C++11 [expr.prim.lambda]p10:
815 // [...] each such lookup shall find a variable with automatic storage
816 // duration declared in the reaching scope of the local lambda expression.
817 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000818 if (!Var) {
819 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
820 continue;
821 }
822
Eli Friedman9cd5b242012-09-18 21:11:30 +0000823 // Ignore invalid decls; they'll just confuse the code later.
824 if (Var->isInvalidDecl())
825 continue;
826
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000827 if (!Var->hasLocalStorage()) {
828 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
829 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
830 continue;
831 }
832
Douglas Gregora7365242012-02-14 19:27:52 +0000833 // C++11 [expr.prim.lambda]p23:
834 // A capture followed by an ellipsis is a pack expansion (14.5.3).
835 SourceLocation EllipsisLoc;
836 if (C->EllipsisLoc.isValid()) {
837 if (Var->isParameterPack()) {
838 EllipsisLoc = C->EllipsisLoc;
839 } else {
840 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
841 << SourceRange(C->Loc);
842
843 // Just ignore the ellipsis.
844 }
845 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000846 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000847 }
848
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000849 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
850 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000851 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000852 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000853 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000854
Richard Smith612409e2012-07-25 03:56:55 +0000855 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
856
Douglas Gregorc6889e72012-02-14 22:28:59 +0000857 // Add lambda parameters into scope.
858 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000859
Douglas Gregordfca6f52012-02-13 22:00:16 +0000860 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000861 // cleanups from the enclosing full-expression.
862 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000863}
864
Douglas Gregordfca6f52012-02-13 22:00:16 +0000865void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
866 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000867 // Leave the expression-evaluation context.
868 DiscardCleanupsInEvaluationContext();
869 PopExpressionEvaluationContext();
870
871 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000872 if (!IsInstantiation)
873 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000874
875 // Finalize the lambda.
876 LambdaScopeInfo *LSI = getCurLambda();
877 CXXRecordDecl *Class = LSI->Lambda;
878 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000879 SmallVector<Decl*, 4> Fields;
880 for (RecordDecl::field_iterator i = Class->field_begin(),
881 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000882 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000883 ActOnFields(0, Class->getLocation(), Class, Fields,
884 SourceLocation(), SourceLocation(), 0);
885 CheckCompletedCXXClass(Class);
886
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000887 PopFunctionScopeInfo();
888}
889
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000890/// \brief Add a lambda's conversion to function pointer, as described in
891/// C++11 [expr.prim.lambda]p6.
892static void addFunctionPointerConversion(Sema &S,
893 SourceRange IntroducerRange,
894 CXXRecordDecl *Class,
895 CXXMethodDecl *CallOperator) {
Faisal Valiecb58192013-08-22 01:49:11 +0000896 // FIXME: The conversion operator needs to be fixed for generic lambdas.
897 if (Class->isGenericLambda()) return;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000898 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000899 const FunctionProtoType *Proto
900 = CallOperator->getType()->getAs<FunctionProtoType>();
901 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000902 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000903 {
904 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
905 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000906 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
907 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000908 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
909 }
910
911 FunctionProtoType::ExtProtoInfo ExtInfo;
912 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000913 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000914 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000915
916 SourceLocation Loc = IntroducerRange.getBegin();
917 DeclarationName Name
918 = S.Context.DeclarationNames.getCXXConversionFunctionName(
919 S.Context.getCanonicalType(FunctionPtrTy));
920 DeclarationNameLoc NameLoc;
921 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
922 Loc);
923 CXXConversionDecl *Conversion
924 = CXXConversionDecl::Create(S.Context, Class, Loc,
925 DeclarationNameInfo(Name, Loc, NameLoc),
926 ConvTy,
927 S.Context.getTrivialTypeSourceInfo(ConvTy,
928 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000929 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000930 /*isConstexpr=*/false,
931 CallOperator->getBody()->getLocEnd());
932 Conversion->setAccess(AS_public);
933 Conversion->setImplicit(true);
934 Class->addDecl(Conversion);
Faisal Valiecb58192013-08-22 01:49:11 +0000935 // Add a non-static member function that will be the result of
936 // the conversion with a certain unique ID.
937 Name = &S.Context.Idents.get(getLambdaStaticInvokerName());
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000938 CXXMethodDecl *Invoke
939 = CXXMethodDecl::Create(S.Context, Class, Loc,
940 DeclarationNameInfo(Name, Loc), FunctionTy,
941 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000942 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000943 /*IsConstexpr=*/false,
944 CallOperator->getBody()->getLocEnd());
945 SmallVector<ParmVarDecl *, 4> InvokeParams;
946 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
947 ParmVarDecl *From = CallOperator->getParamDecl(I);
948 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
949 From->getLocStart(),
950 From->getLocation(),
951 From->getIdentifier(),
952 From->getType(),
953 From->getTypeSourceInfo(),
954 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000955 /*DefaultArg=*/0));
956 }
957 Invoke->setParams(InvokeParams);
958 Invoke->setAccess(AS_private);
959 Invoke->setImplicit(true);
960 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000961}
962
Douglas Gregorc2956e52012-02-15 22:08:38 +0000963/// \brief Add a lambda's conversion to block pointer.
964static void addBlockPointerConversion(Sema &S,
965 SourceRange IntroducerRange,
966 CXXRecordDecl *Class,
967 CXXMethodDecl *CallOperator) {
968 const FunctionProtoType *Proto
969 = CallOperator->getType()->getAs<FunctionProtoType>();
970 QualType BlockPtrTy;
971 {
972 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
973 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000974 QualType FunctionTy = S.Context.getFunctionType(
975 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000976 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
977 }
978
979 FunctionProtoType::ExtProtoInfo ExtInfo;
980 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000981 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000982
983 SourceLocation Loc = IntroducerRange.getBegin();
984 DeclarationName Name
985 = S.Context.DeclarationNames.getCXXConversionFunctionName(
986 S.Context.getCanonicalType(BlockPtrTy));
987 DeclarationNameLoc NameLoc;
988 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
989 CXXConversionDecl *Conversion
990 = CXXConversionDecl::Create(S.Context, Class, Loc,
991 DeclarationNameInfo(Name, Loc, NameLoc),
992 ConvTy,
993 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000994 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000995 /*isConstexpr=*/false,
996 CallOperator->getBody()->getLocEnd());
997 Conversion->setAccess(AS_public);
998 Conversion->setImplicit(true);
999 Class->addDecl(Conversion);
1000}
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001001
Douglas Gregordfca6f52012-02-13 22:00:16 +00001002ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001003 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001004 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001005 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001006 SmallVector<LambdaExpr::Capture, 4> Captures;
1007 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001008 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001009 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001010 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001011 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001012 SourceRange IntroducerRange;
1013 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001014 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001015 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001016 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001017 SmallVector<VarDecl *, 4> ArrayIndexVars;
1018 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001019 {
1020 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001021 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001022 Class = LSI->Lambda;
1023 IntroducerRange = LSI->IntroducerRange;
1024 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001025 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001026 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001027 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001028 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1029 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1030
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001031 // Translate captures.
1032 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1033 LambdaScopeInfo::Capture From = LSI->Captures[I];
1034 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1035 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1036
1037 // Handle 'this' capture.
1038 if (From.isThisCapture()) {
1039 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1040 IsImplicit,
1041 LCK_This));
1042 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1043 getCurrentThisType(),
1044 /*isImplicit=*/true));
1045 continue;
1046 }
1047
Richard Smith0d8e9642013-05-16 06:20:58 +00001048 if (From.isInitCapture()) {
1049 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
1050 CaptureInits.push_back(From.getInitExpr());
1051 continue;
1052 }
1053
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001054 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001055 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1056 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001057 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001058 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001059 }
1060
1061 switch (LSI->ImpCaptureStyle) {
1062 case CapturingScopeInfo::ImpCap_None:
1063 CaptureDefault = LCD_None;
1064 break;
1065
1066 case CapturingScopeInfo::ImpCap_LambdaByval:
1067 CaptureDefault = LCD_ByCopy;
1068 break;
1069
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001070 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001071 case CapturingScopeInfo::ImpCap_LambdaByref:
1072 CaptureDefault = LCD_ByRef;
1073 break;
1074
1075 case CapturingScopeInfo::ImpCap_Block:
1076 llvm_unreachable("block capture in lambda");
1077 break;
1078 }
James Dennettf68af642013-08-09 23:08:25 +00001079 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001080
Douglas Gregor54042f12012-02-09 10:18:50 +00001081 // C++11 [expr.prim.lambda]p4:
1082 // If a lambda-expression does not include a
1083 // trailing-return-type, it is as if the trailing-return-type
1084 // denotes the following type:
Faisal Valiecb58192013-08-22 01:49:11 +00001085 // Skip for C++1y return type deduction semantics which uses
1086 // different machinery currently.
1087 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001088 // FIXME: Assumes current resolution to core issue 975.
Faisal Valiecb58192013-08-22 01:49:11 +00001089 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001090 deduceClosureReturnType(*LSI);
1091
Douglas Gregor54042f12012-02-09 10:18:50 +00001092 // - if there are no return statements in the
1093 // compound-statement, or all return statements return
1094 // either an expression of type void or no expression or
1095 // braced-init-list, the type void;
1096 if (LSI->ReturnType.isNull()) {
1097 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001098 }
1099
1100 // Create a function type with the inferred return type.
1101 const FunctionProtoType *Proto
1102 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001103 QualType FunctionTy = Context.getFunctionType(
1104 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001105 CallOperator->setType(FunctionTy);
1106 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001107 // C++ [expr.prim.lambda]p7:
1108 // The lambda-expression's compound-statement yields the
1109 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001110 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001111 CallOperator->setLexicalDeclContext(Class);
Faisal Valiecb58192013-08-22 01:49:11 +00001112 Decl *TemplateOrNonTemplateCallOperatorDecl =
1113 !CallOperator->getDescribedFunctionTemplate() ? cast<Decl>(CallOperator)
1114 : CallOperator->getDescribedFunctionTemplate();
1115
1116 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1117 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1118
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001119 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001120
Douglas Gregorb5559712012-02-10 16:13:20 +00001121 // C++11 [expr.prim.lambda]p6:
1122 // The closure type for a lambda-expression with no lambda-capture
1123 // has a public non-virtual non-explicit const conversion function
1124 // to pointer to function having the same parameter and return
1125 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001126 if (Captures.empty() && CaptureDefault == LCD_None)
1127 addFunctionPointerConversion(*this, IntroducerRange, Class,
1128 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001129
Douglas Gregorc2956e52012-02-15 22:08:38 +00001130 // Objective-C++:
1131 // The closure type for a lambda-expression has a public non-virtual
1132 // non-explicit const conversion function to a block pointer having the
1133 // same parameter and return types as the closure type's function call
1134 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001135 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001136 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1137
Douglas Gregorb5559712012-02-10 16:13:20 +00001138 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001139 SmallVector<Decl*, 4> Fields;
1140 for (RecordDecl::field_iterator i = Class->field_begin(),
1141 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001142 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001143 ActOnFields(0, Class->getLocation(), Class, Fields,
1144 SourceLocation(), SourceLocation(), 0);
1145 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001146 }
1147
Douglas Gregor503384f2012-02-09 00:47:04 +00001148 if (LambdaExprNeedsCleanups)
1149 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001150
Douglas Gregore2c59132012-02-09 08:14:43 +00001151 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001152 CaptureDefault, CaptureDefaultLoc,
1153 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001154 ExplicitParams, ExplicitResultType,
1155 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001156 ArrayIndexStarts, Body->getLocEnd(),
1157 ContainsUnexpandedParameterPack);
Faisal Valiecb58192013-08-22 01:49:11 +00001158 Class->setLambdaExpr(Lambda);
Douglas Gregore2c59132012-02-09 08:14:43 +00001159 // C++11 [expr.prim.lambda]p2:
1160 // A lambda-expression shall not appear in an unevaluated operand
1161 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001162 if (!CurContext->isDependentContext()) {
1163 switch (ExprEvalContexts.back().Context) {
1164 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001165 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001166 // We don't actually diagnose this case immediately, because we
1167 // could be within a context where we might find out later that
1168 // the expression is potentially evaluated (e.g., for typeid).
1169 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1170 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001171
Douglas Gregord5387e82012-02-14 00:00:48 +00001172 case ConstantEvaluated:
1173 case PotentiallyEvaluated:
1174 case PotentiallyEvaluatedIfUsed:
1175 break;
1176 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001177 }
Faisal Valiecb58192013-08-22 01:49:11 +00001178 // TODO: Implement capturing.
1179 if (Lambda->isGenericLambda()) {
1180 if (Lambda->getCaptureDefault() != LCD_None) {
1181 Diag(Lambda->getIntroducerRange().getBegin(),
1182 diag::err_glambda_not_fully_implemented)
1183 << " capturing not implemented yet";
1184 return ExprError();
1185 }
1186 }
Douglas Gregor503384f2012-02-09 00:47:04 +00001187 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001188}
Eli Friedman23f02672012-03-01 04:01:32 +00001189
1190ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1191 SourceLocation ConvLocation,
1192 CXXConversionDecl *Conv,
1193 Expr *Src) {
1194 // Make sure that the lambda call operator is marked used.
1195 CXXRecordDecl *Lambda = Conv->getParent();
1196 CXXMethodDecl *CallOperator
1197 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001198 Lambda->lookup(
1199 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001200 CallOperator->setReferenced();
1201 CallOperator->setUsed();
1202
1203 ExprResult Init = PerformCopyInitialization(
1204 InitializedEntity::InitializeBlock(ConvLocation,
1205 Src->getType(),
1206 /*NRVO=*/false),
1207 CurrentLocation, Src);
1208 if (!Init.isInvalid())
1209 Init = ActOnFinishFullExpr(Init.take());
1210
1211 if (Init.isInvalid())
1212 return ExprError();
1213
1214 // Create the new block to be returned.
1215 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1216
1217 // Set the type information.
1218 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1219 Block->setIsVariadic(CallOperator->isVariadic());
1220 Block->setBlockMissingReturnType(false);
1221
1222 // Add parameters.
1223 SmallVector<ParmVarDecl *, 4> BlockParams;
1224 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1225 ParmVarDecl *From = CallOperator->getParamDecl(I);
1226 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1227 From->getLocStart(),
1228 From->getLocation(),
1229 From->getIdentifier(),
1230 From->getType(),
1231 From->getTypeSourceInfo(),
1232 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001233 /*DefaultArg=*/0));
1234 }
1235 Block->setParams(BlockParams);
1236
1237 Block->setIsConversionFromLambda(true);
1238
1239 // Add capture. The capture uses a fake variable, which doesn't correspond
1240 // to any actual memory location. However, the initializer copy-initializes
1241 // the lambda object.
1242 TypeSourceInfo *CapVarTSI =
1243 Context.getTrivialTypeSourceInfo(Src->getType());
1244 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1245 ConvLocation, 0,
1246 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001247 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001248 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1249 /*Nested=*/false, /*Copy=*/Init.take());
1250 Block->setCaptures(Context, &Capture, &Capture + 1,
1251 /*CapturesCXXThis=*/false);
1252
1253 // Add a fake function body to the block. IR generation is responsible
1254 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001255 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001256
1257 // Create the block literal expression.
1258 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1259 ExprCleanupObjects.push_back(Block);
1260 ExprNeedsCleanups = true;
1261
1262 return BuildBlock;
1263}