blob: bed71a676f8a4eca15275528c480c278e462648b [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);
Manuel Klimek28cc16a2013-08-22 12:12:05 +0000146 QualType AutoTy = PVD->getType();
Faisal Valiecb58192013-08-22 01:49:11 +0000147 // Now replace the 'auto' in the function parameter with this invented
148 // template type parameter.
149 QualType TemplParamType = QualType(TemplateParam->getTypeForDecl(), 0);
150
151 TypeSourceInfo *AutoTSI = PVD->getTypeSourceInfo();
152 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfo(AutoTSI, TemplParamType);
153 PVD->setType(NewTSI->getType());
154 PVD->setTypeSourceInfo(NewTSI);
155 return PVD;
156}
157
158
159static inline TemplateParameterList *
160 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI,
161 Sema &SemaRef) {
162 if (LSI->GLTemplateParameterList)
163 return LSI->GLTemplateParameterList;
164 else if (LSI->AutoTemplateParams.size()) {
165 SourceRange IntroRange = LSI->IntroducerRange;
166 SourceLocation LAngleLoc = IntroRange.getBegin();
167 SourceLocation RAngleLoc = IntroRange.getEnd();
168 LSI->GLTemplateParameterList =
169 TemplateParameterList::Create(SemaRef.Context,
170 /* Template kw loc */ SourceLocation(),
171 LAngleLoc,
172 (NamedDecl**)LSI->AutoTemplateParams.data(),
173 LSI->AutoTemplateParams.size(), RAngleLoc);
174 }
175 return LSI->GLTemplateParameterList;
176}
177
178
179
Douglas Gregordfca6f52012-02-13 22:00:16 +0000180CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000181 SourceRange IntroducerRange,
182 TypeSourceInfo *MethodType,
183 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000184 ArrayRef<ParmVarDecl *> Params) {
Faisal Valiecb58192013-08-22 01:49:11 +0000185 TemplateParameterList *TemplateParams =
186 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000187 // C++11 [expr.prim.lambda]p5:
188 // The closure type for a lambda-expression has a public inline function
189 // call operator (13.5.4) whose parameters and return type are described by
190 // the lambda-expression's parameter-declaration-clause and
191 // trailing-return-type respectively.
192 DeclarationName MethodName
193 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
194 DeclarationNameLoc MethodNameLoc;
195 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
196 = IntroducerRange.getBegin().getRawEncoding();
197 MethodNameLoc.CXXOperatorName.EndOpNameLoc
198 = IntroducerRange.getEnd().getRawEncoding();
199 CXXMethodDecl *Method
200 = CXXMethodDecl::Create(Context, Class, EndLoc,
201 DeclarationNameInfo(MethodName,
202 IntroducerRange.getBegin(),
203 MethodNameLoc),
204 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000205 SC_None,
206 /*isInline=*/true,
207 /*isConstExpr=*/false,
208 EndLoc);
209 Method->setAccess(AS_public);
210
211 // Temporarily set the lexical declaration context to the current
212 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000213 Method->setLexicalDeclContext(CurContext);
Faisal Valiecb58192013-08-22 01:49:11 +0000214 // Create a function template if we have a template parameter list
215 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
216 FunctionTemplateDecl::Create(Context, Class,
217 Method->getLocation(), MethodName,
218 TemplateParams,
219 Method) : 0;
220 if (TemplateMethod) {
221 TemplateMethod->setLexicalDeclContext(CurContext);
222 TemplateMethod->setAccess(AS_public);
223 Method->setDescribedFunctionTemplate(TemplateMethod);
224 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000225
Douglas Gregorc6889e72012-02-14 22:28:59 +0000226 // Add parameters.
227 if (!Params.empty()) {
228 Method->setParams(Params);
229 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
230 const_cast<ParmVarDecl **>(Params.end()),
231 /*CheckParameterNames=*/false);
232
233 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
234 PEnd = Method->param_end();
235 P != PEnd; ++P)
236 (*P)->setOwningFunction(Method);
237 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000238
Eli Friedman07369dd2013-07-01 20:22:57 +0000239 Decl *ManglingContextDecl;
240 if (MangleNumberingContext *MCtx =
241 getCurrentMangleNumberContext(Class->getDeclContext(),
242 ManglingContextDecl)) {
243 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
244 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000245 }
246
Douglas Gregordfca6f52012-02-13 22:00:16 +0000247 return Method;
248}
249
Faisal Valiecb58192013-08-22 01:49:11 +0000250void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
251 CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000252 SourceRange IntroducerRange,
253 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000254 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000255 bool ExplicitParams,
256 bool ExplicitResultType,
257 bool Mutable) {
Faisal Valiecb58192013-08-22 01:49:11 +0000258 LSI->CallOperator = CallOperator;
259 LSI->Lambda = CallOperator->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000260 if (CaptureDefault == LCD_ByCopy)
261 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
262 else if (CaptureDefault == LCD_ByRef)
263 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000264 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000265 LSI->IntroducerRange = IntroducerRange;
266 LSI->ExplicitParams = ExplicitParams;
267 LSI->Mutable = Mutable;
268
269 if (ExplicitResultType) {
270 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000271
272 if (!LSI->ReturnType->isDependentType() &&
273 !LSI->ReturnType->isVoidType()) {
274 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
275 diag::err_lambda_incomplete_result)) {
276 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000277 }
278 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000279 } else {
280 LSI->HasImplicitReturnType = true;
281 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000282}
283
284void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
285 LSI->finishedExplicitCaptures();
286}
287
Douglas Gregorc6889e72012-02-14 22:28:59 +0000288void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000289 // Introduce our parameters into the function scope
290 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
291 p < NumParams; ++p) {
292 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000293
294 // If this has an identifier, add it to the scope stack.
295 if (CurScope && Param->getIdentifier()) {
296 CheckShadow(CurScope, Param);
297
298 PushOnScopeChains(Param, CurScope);
299 }
300 }
301}
302
John McCall41d01642013-03-09 00:54:31 +0000303/// If this expression is an enumerator-like expression of some type
304/// T, return the type T; otherwise, return null.
305///
306/// Pointer comparisons on the result here should always work because
307/// it's derived from either the parent of an EnumConstantDecl
308/// (i.e. the definition) or the declaration returned by
309/// EnumType::getDecl() (i.e. the definition).
310static EnumDecl *findEnumForBlockReturn(Expr *E) {
311 // An expression is an enumerator-like expression of type T if,
312 // ignoring parens and parens-like expressions:
313 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000314
John McCall41d01642013-03-09 00:54:31 +0000315 // - it is an enumerator whose enum type is T or
316 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
317 if (EnumConstantDecl *D
318 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
319 return cast<EnumDecl>(D->getDeclContext());
320 }
321 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000322 }
323
John McCall41d01642013-03-09 00:54:31 +0000324 // - it is a comma expression whose RHS is an enumerator-like
325 // expression of type T or
326 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
327 if (BO->getOpcode() == BO_Comma)
328 return findEnumForBlockReturn(BO->getRHS());
329 return 0;
330 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000331
John McCall41d01642013-03-09 00:54:31 +0000332 // - it is a statement-expression whose value expression is an
333 // enumerator-like expression of type T or
334 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
335 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
336 return findEnumForBlockReturn(last);
337 return 0;
338 }
339
340 // - it is a ternary conditional operator (not the GNU ?:
341 // extension) whose second and third operands are
342 // enumerator-like expressions of type T or
343 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
344 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
345 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
346 return ED;
347 return 0;
348 }
349
350 // (implicitly:)
351 // - it is an implicit integral conversion applied to an
352 // enumerator-like expression of type T or
353 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000354 // We can sometimes see integral conversions in valid
355 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000356 if (ICE->getCastKind() == CK_IntegralCast)
357 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000358
359 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000360 }
361
362 // - it is an expression of that formal enum type.
363 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
364 return ET->getDecl();
365 }
366
367 // Otherwise, nope.
368 return 0;
369}
370
371/// Attempt to find a type T for which the returned expression of the
372/// given statement is an enumerator-like expression of that type.
373static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
374 if (Expr *retValue = ret->getRetValue())
375 return findEnumForBlockReturn(retValue);
376 return 0;
377}
378
379/// Attempt to find a common type T for which all of the returned
380/// expressions in a block are enumerator-like expressions of that
381/// type.
382static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
383 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
384
385 // Try to find one for the first return.
386 EnumDecl *ED = findEnumForBlockReturn(*i);
387 if (!ED) return 0;
388
389 // Check that the rest of the returns have the same enum.
390 for (++i; i != e; ++i) {
391 if (findEnumForBlockReturn(*i) != ED)
392 return 0;
393 }
394
395 // Never infer an anonymous enum type.
396 if (!ED->hasNameForLinkage()) return 0;
397
398 return ED;
399}
400
401/// Adjust the given return statements so that they formally return
402/// the given type. It should require, at most, an IntegralCast.
403static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
404 QualType returnType) {
405 for (ArrayRef<ReturnStmt*>::iterator
406 i = returns.begin(), e = returns.end(); i != e; ++i) {
407 ReturnStmt *ret = *i;
408 Expr *retValue = ret->getRetValue();
409 if (S.Context.hasSameType(retValue->getType(), returnType))
410 continue;
411
412 // Right now we only support integral fixup casts.
413 assert(returnType->isIntegralOrUnscopedEnumerationType());
414 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
415
416 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
417
418 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
419 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
420 E, /*base path*/ 0, VK_RValue);
421 if (cleanups) {
422 cleanups->setSubExpr(E);
423 } else {
424 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000425 }
426 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000427}
428
429void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Faisal Valiecb58192013-08-22 01:49:11 +0000430 assert(CSI.HasImplicitReturnType || CSI.ReturnType->isUndeducedType());
Jordan Rose7dd900e2012-07-02 21:19:23 +0000431
John McCall41d01642013-03-09 00:54:31 +0000432 // C++ Core Issue #975, proposed resolution:
433 // If a lambda-expression does not include a trailing-return-type,
434 // it is as if the trailing-return-type denotes the following type:
435 // - if there are no return statements in the compound-statement,
436 // or all return statements return either an expression of type
437 // void or no expression or braced-init-list, the type void;
438 // - otherwise, if all return statements return an expression
439 // and the types of the returned expressions after
440 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
441 // array-to-pointer conversion (4.2 [conv.array]), and
442 // function-to-pointer conversion (4.3 [conv.func]) are the
443 // same, that common type;
444 // - otherwise, the program is ill-formed.
445 //
446 // In addition, in blocks in non-C++ modes, if all of the return
447 // statements are enumerator-like expressions of some type T, where
448 // T has a name for linkage, then we infer the return type of the
449 // block to be that type.
450
Jordan Rose7dd900e2012-07-02 21:19:23 +0000451 // First case: no return statements, implicit void return type.
452 ASTContext &Ctx = getASTContext();
453 if (CSI.Returns.empty()) {
454 // It's possible there were simply no /valid/ return statements.
455 // In this case, the first one we found may have at least given us a type.
456 if (CSI.ReturnType.isNull())
457 CSI.ReturnType = Ctx.VoidTy;
458 return;
459 }
460
461 // Second case: at least one return statement has dependent type.
462 // Delay type checking until instantiation.
463 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Faisal Valiecb58192013-08-22 01:49:11 +0000464 if (CSI.ReturnType->isDependentType() || CSI.ReturnType->isUndeducedType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000465 return;
466
John McCall41d01642013-03-09 00:54:31 +0000467 // Try to apply the enum-fuzz rule.
468 if (!getLangOpts().CPlusPlus) {
469 assert(isa<BlockScopeInfo>(CSI));
470 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
471 if (ED) {
472 CSI.ReturnType = Context.getTypeDeclType(ED);
473 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
474 return;
475 }
476 }
477
Jordan Rose7dd900e2012-07-02 21:19:23 +0000478 // Third case: only one return statement. Don't bother doing extra work!
479 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
480 E = CSI.Returns.end();
481 if (I+1 == E)
482 return;
483
484 // General case: many return statements.
485 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000486
487 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000488 // Note that we've already done the required promotions as part of
489 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000490 for (; I != E; ++I) {
491 const ReturnStmt *RS = *I;
492 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000493
John McCall41d01642013-03-09 00:54:31 +0000494 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
495 if (Context.hasSameType(ReturnType, CSI.ReturnType))
496 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000497
John McCall41d01642013-03-09 00:54:31 +0000498 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
499 // TODO: It's possible that the *first* return is the divergent one.
500 Diag(RS->getLocStart(),
501 diag::err_typecheck_missing_return_type_incompatible)
502 << ReturnType << CSI.ReturnType
503 << isa<LambdaScopeInfo>(CSI);
504 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000505 }
506}
507
Richard Smith0d8e9642013-05-16 06:20:58 +0000508FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
509 IdentifierInfo *Id, Expr *InitExpr) {
510 LambdaScopeInfo *LSI = getCurLambda();
511
512 // C++1y [expr.prim.lambda]p11:
513 // The type of [the] member corresponds to the type of a hypothetical
514 // variable declaration of the form "auto init-capture;"
515 QualType DeductType = Context.getAutoDeductType();
516 TypeLocBuilder TLB;
517 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
518 if (ByRef) {
519 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
520 assert(!DeductType.isNull() && "can't build reference to auto");
521 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
522 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000523 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000524
525 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
526 Expr *Init = InitExpr;
527 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
528 if (Parens->getNumExprs() == 1) {
529 Init = Parens->getExpr(0);
530 InitKind = InitializationKind::CreateDirect(
531 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
532 } else {
533 // C++1y [dcl.spec.auto]p3:
534 // In an initializer of the form ( expression-list ), the
535 // expression-list shall be a single assignment-expression.
536 if (Parens->getNumExprs() == 0)
537 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
538 << Id;
539 else if (Parens->getNumExprs() > 1)
540 Diag(Parens->getExpr(1)->getLocStart(),
541 diag::err_init_capture_multiple_expressions)
542 << Id;
543 return 0;
544 }
545 } else if (isa<InitListExpr>(Init))
546 // We do not need to distinguish between direct-list-initialization
547 // and copy-list-initialization here, because we will always deduce
548 // std::initializer_list<T>, and direct- and copy-list-initialization
549 // always behave the same for such a type.
550 // FIXME: We should model whether an '=' was present.
551 InitKind = InitializationKind::CreateDirectList(Loc);
552 else
553 InitKind = InitializationKind::CreateCopy(Loc, Loc);
554 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000555 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000556 if (isa<InitListExpr>(Init))
557 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
558 << Id << Init->getSourceRange();
559 else
560 Diag(Loc, diag::err_init_capture_deduction_failure)
561 << Id << Init->getType() << Init->getSourceRange();
562 }
563 if (DeducedType.isNull())
564 return 0;
565
566 // [...] a non-static data member named by the identifier is declared in
567 // the closure type. This member is not a bit-field and not mutable.
568 // Core issue: the member is (probably...) public.
569 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000570 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000571 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
572 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
573 LSI->Lambda->addDecl(NewFD);
574
575 if (CurContext->isDependentContext()) {
576 LSI->addInitCapture(NewFD, InitExpr);
577 } else {
578 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
579 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
580 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
581 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
582 if (!InitResult.isInvalid())
583 LSI->addInitCapture(NewFD, InitResult.take());
584 }
585 }
586
587 return NewFD;
588}
589
Douglas Gregordfca6f52012-02-13 22:00:16 +0000590void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valiecb58192013-08-22 01:49:11 +0000591 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000592 // Determine if we're within a context where we know that the lambda will
593 // be dependent, because there are template parameters in scope.
594 bool KnownDependent = false;
Faisal Valiecb58192013-08-22 01:49:11 +0000595 LambdaScopeInfo *const LSI = getCurLambda();
596 assert(LSI && "LambdaScopeInfo should be on stack!");
597 TemplateParameterList *TemplateParams =
598 getGenericLambdaTemplateParameterList(LSI, *this);
599
600 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
601 // Since we have our own TemplateParams, so check if an outer scope
602 // has template params, only then are we in a dependent scope.
603 if (TemplateParams) {
604 TmplScope = TmplScope->getParent();
605 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
606 }
607 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000608 KnownDependent = true;
Faisal Valiecb58192013-08-22 01:49:11 +0000609 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000610 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000611 TypeSourceInfo *MethodTyInfo;
612 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000613 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000614 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000615 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000616 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000617 if (ParamInfo.getNumTypeObjects() == 0) {
618 // C++11 [expr.prim.lambda]p4:
619 // If a lambda-expression does not include a lambda-declarator, it is as
620 // if the lambda-declarator were ().
621 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000622 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000623 EPI.TypeQuals |= DeclSpec::TQ_const;
Faisal Valiecb58192013-08-22 01:49:11 +0000624 // For C++1y, use the new return type deduction machinery, by imaginging
625 // 'auto' if no trailing return type.
626 QualType DefaultTypeForNoTrailingReturn = getLangOpts().CPlusPlus1y ?
627 Context.getAutoDeductType() : Context.DependentTy;
628 QualType MethodTy = Context.getFunctionType(DefaultTypeForNoTrailingReturn, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000629 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000630 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
631 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000632 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000633 EndLoc = Intro.Range.getEnd();
634 } else {
635 assert(ParamInfo.isFunctionDeclarator() &&
636 "lambda-declarator is a function");
637 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
638
639 // C++11 [expr.prim.lambda]p5:
640 // This function call operator is declared const (9.3.1) if and only if
641 // the lambda-expression's parameter-declaration-clause is not followed
642 // by mutable. It is neither virtual nor declared volatile. [...]
643 if (!FTI.hasMutableQualifier())
644 FTI.TypeQuals |= DeclSpec::TQ_const;
645
Faisal Valiecb58192013-08-22 01:49:11 +0000646 ExplicitResultType = FTI.hasTrailingReturnType();
647 // In C++11 if there is no explicit return type, the return type is
648 // artificially set to DependentTy, whereas in C++1y it is set to AutoTy
649 // (through ConvertDeclSpecToType) which allows us to support both
650 // C++11 and C++1y return type deduction semantics.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000651 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000652 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000653 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000654
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000655 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
656 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
657 // Empty arg list, don't push any params.
658 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
659 } else {
660 Params.reserve(FTI.NumArgs);
661 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
662 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
663 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000664
665 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000666 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
667 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000668 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000669
670 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
671 KnownDependent);
672
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000673 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000674 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000675 if (ExplicitParams)
676 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000677
Bill Wendlingad017fa2012-12-20 19:22:21 +0000678 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000679 ProcessDeclAttributes(CurScope, Method, ParamInfo);
680
Douglas Gregor503384f2012-02-09 00:47:04 +0000681 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000682 PushDeclContext(CurScope, Method);
683
Faisal Valiecb58192013-08-22 01:49:11 +0000684 // Build the lambda scope.
685 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000686 Intro.Range,
687 Intro.Default, Intro.DefaultLoc,
688 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000689 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000690 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000691
692 // Distinct capture names, for diagnostics.
693 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
694
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000695 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000696 SourceLocation PrevCaptureLoc
697 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000698 for (SmallVectorImpl<LambdaCapture>::const_iterator
699 C = Intro.Captures.begin(),
700 E = Intro.Captures.end();
701 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000702 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000703 if (C->Kind == LCK_This) {
704 // C++11 [expr.prim.lambda]p8:
705 // An identifier or this shall not appear more than once in a
706 // lambda-capture.
707 if (LSI->isCXXThisCaptured()) {
708 Diag(C->Loc, diag::err_capture_more_than_once)
709 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000710 << SourceRange(LSI->getCXXThisCapture().getLocation())
711 << FixItHint::CreateRemoval(
712 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000713 continue;
714 }
715
716 // C++11 [expr.prim.lambda]p8:
717 // If a lambda-capture includes a capture-default that is =, the
718 // lambda-capture shall not contain this [...].
719 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000720 Diag(C->Loc, diag::err_this_capture_with_copy_default)
721 << FixItHint::CreateRemoval(
722 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000723 continue;
724 }
725
726 // C++11 [expr.prim.lambda]p12:
727 // If this is captured by a local lambda expression, its nearest
728 // enclosing function shall be a non-static member function.
729 QualType ThisCaptureType = getCurrentThisType();
730 if (ThisCaptureType.isNull()) {
731 Diag(C->Loc, diag::err_this_capture) << true;
732 continue;
733 }
734
735 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
736 continue;
737 }
738
Richard Smith0d8e9642013-05-16 06:20:58 +0000739 assert(C->Id && "missing identifier for capture");
740
Richard Smith0a664b82013-05-09 21:36:41 +0000741 if (C->Init.isInvalid())
742 continue;
743 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000744 // C++11 [expr.prim.lambda]p8:
745 // An identifier or this shall not appear more than once in a
746 // lambda-capture.
747 if (!CaptureNames.insert(C->Id))
748 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
749
750 if (C->Init.get()->containsUnexpandedParameterPack())
751 ContainsUnexpandedParameterPack = true;
752
753 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
754 C->Id, C->Init.take());
755 // C++1y [expr.prim.lambda]p11:
756 // Within the lambda-expression's lambda-declarator and
757 // compound-statement, the identifier in the init-capture
758 // hides any declaration of the same name in scopes enclosing
759 // the lambda-expression.
760 if (NewFD)
761 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000762 continue;
763 }
764
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000765 // C++11 [expr.prim.lambda]p8:
766 // If a lambda-capture includes a capture-default that is &, the
767 // identifiers in the lambda-capture shall not be preceded by &.
768 // If a lambda-capture includes a capture-default that is =, [...]
769 // each identifier it contains shall be preceded by &.
770 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000771 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
772 << FixItHint::CreateRemoval(
773 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000774 continue;
775 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000776 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
777 << FixItHint::CreateRemoval(
778 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000779 continue;
780 }
781
Richard Smith0d8e9642013-05-16 06:20:58 +0000782 // C++11 [expr.prim.lambda]p10:
783 // The identifiers in a capture-list are looked up using the usual
784 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000785 DeclarationNameInfo Name(C->Id, C->Loc);
786 LookupResult R(*this, Name, LookupOrdinaryName);
787 LookupName(R, CurScope);
788 if (R.isAmbiguous())
789 continue;
790 if (R.empty()) {
791 // FIXME: Disable corrections that would add qualification?
792 CXXScopeSpec ScopeSpec;
793 DeclFilterCCC<VarDecl> Validator;
794 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
795 continue;
796 }
797
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000798 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000799
800 // C++11 [expr.prim.lambda]p8:
801 // An identifier or this shall not appear more than once in a
802 // lambda-capture.
803 if (!CaptureNames.insert(C->Id)) {
804 if (Var && LSI->isCaptured(Var)) {
805 Diag(C->Loc, diag::err_capture_more_than_once)
806 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
807 << FixItHint::CreateRemoval(
808 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
809 } else
810 // Previous capture was an init-capture: no fixit.
811 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
812 continue;
813 }
814
815 // C++11 [expr.prim.lambda]p10:
816 // [...] each such lookup shall find a variable with automatic storage
817 // duration declared in the reaching scope of the local lambda expression.
818 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000819 if (!Var) {
820 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
821 continue;
822 }
823
Eli Friedman9cd5b242012-09-18 21:11:30 +0000824 // Ignore invalid decls; they'll just confuse the code later.
825 if (Var->isInvalidDecl())
826 continue;
827
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000828 if (!Var->hasLocalStorage()) {
829 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
830 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
831 continue;
832 }
833
Douglas Gregora7365242012-02-14 19:27:52 +0000834 // C++11 [expr.prim.lambda]p23:
835 // A capture followed by an ellipsis is a pack expansion (14.5.3).
836 SourceLocation EllipsisLoc;
837 if (C->EllipsisLoc.isValid()) {
838 if (Var->isParameterPack()) {
839 EllipsisLoc = C->EllipsisLoc;
840 } else {
841 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
842 << SourceRange(C->Loc);
843
844 // Just ignore the ellipsis.
845 }
846 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000847 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000848 }
849
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000850 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
851 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000852 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000853 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000854 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000855
Richard Smith612409e2012-07-25 03:56:55 +0000856 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
857
Douglas Gregorc6889e72012-02-14 22:28:59 +0000858 // Add lambda parameters into scope.
859 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000860
Douglas Gregordfca6f52012-02-13 22:00:16 +0000861 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000862 // cleanups from the enclosing full-expression.
863 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000864}
865
Douglas Gregordfca6f52012-02-13 22:00:16 +0000866void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
867 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000868 // Leave the expression-evaluation context.
869 DiscardCleanupsInEvaluationContext();
870 PopExpressionEvaluationContext();
871
872 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000873 if (!IsInstantiation)
874 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000875
876 // Finalize the lambda.
877 LambdaScopeInfo *LSI = getCurLambda();
878 CXXRecordDecl *Class = LSI->Lambda;
879 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000880 SmallVector<Decl*, 4> Fields;
881 for (RecordDecl::field_iterator i = Class->field_begin(),
882 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000883 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000884 ActOnFields(0, Class->getLocation(), Class, Fields,
885 SourceLocation(), SourceLocation(), 0);
886 CheckCompletedCXXClass(Class);
887
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000888 PopFunctionScopeInfo();
889}
890
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000891/// \brief Add a lambda's conversion to function pointer, as described in
892/// C++11 [expr.prim.lambda]p6.
893static void addFunctionPointerConversion(Sema &S,
894 SourceRange IntroducerRange,
895 CXXRecordDecl *Class,
896 CXXMethodDecl *CallOperator) {
Faisal Valiecb58192013-08-22 01:49:11 +0000897 // FIXME: The conversion operator needs to be fixed for generic lambdas.
898 if (Class->isGenericLambda()) return;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000899 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000900 const FunctionProtoType *Proto
901 = CallOperator->getType()->getAs<FunctionProtoType>();
902 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000903 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000904 {
905 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
906 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000907 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
908 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000909 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
910 }
911
912 FunctionProtoType::ExtProtoInfo ExtInfo;
913 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000914 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000915 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000916
917 SourceLocation Loc = IntroducerRange.getBegin();
918 DeclarationName Name
919 = S.Context.DeclarationNames.getCXXConversionFunctionName(
920 S.Context.getCanonicalType(FunctionPtrTy));
921 DeclarationNameLoc NameLoc;
922 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
923 Loc);
924 CXXConversionDecl *Conversion
925 = CXXConversionDecl::Create(S.Context, Class, Loc,
926 DeclarationNameInfo(Name, Loc, NameLoc),
927 ConvTy,
928 S.Context.getTrivialTypeSourceInfo(ConvTy,
929 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000930 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000931 /*isConstexpr=*/false,
932 CallOperator->getBody()->getLocEnd());
933 Conversion->setAccess(AS_public);
934 Conversion->setImplicit(true);
935 Class->addDecl(Conversion);
Faisal Valiecb58192013-08-22 01:49:11 +0000936 // Add a non-static member function that will be the result of
937 // the conversion with a certain unique ID.
938 Name = &S.Context.Idents.get(getLambdaStaticInvokerName());
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000939 CXXMethodDecl *Invoke
940 = CXXMethodDecl::Create(S.Context, Class, Loc,
941 DeclarationNameInfo(Name, Loc), FunctionTy,
942 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000943 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000944 /*IsConstexpr=*/false,
945 CallOperator->getBody()->getLocEnd());
946 SmallVector<ParmVarDecl *, 4> InvokeParams;
947 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
948 ParmVarDecl *From = CallOperator->getParamDecl(I);
949 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
950 From->getLocStart(),
951 From->getLocation(),
952 From->getIdentifier(),
953 From->getType(),
954 From->getTypeSourceInfo(),
955 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000956 /*DefaultArg=*/0));
957 }
958 Invoke->setParams(InvokeParams);
959 Invoke->setAccess(AS_private);
960 Invoke->setImplicit(true);
961 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000962}
963
Douglas Gregorc2956e52012-02-15 22:08:38 +0000964/// \brief Add a lambda's conversion to block pointer.
965static void addBlockPointerConversion(Sema &S,
966 SourceRange IntroducerRange,
967 CXXRecordDecl *Class,
968 CXXMethodDecl *CallOperator) {
969 const FunctionProtoType *Proto
970 = CallOperator->getType()->getAs<FunctionProtoType>();
971 QualType BlockPtrTy;
972 {
973 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
974 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000975 QualType FunctionTy = S.Context.getFunctionType(
976 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000977 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
978 }
979
980 FunctionProtoType::ExtProtoInfo ExtInfo;
981 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000982 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000983
984 SourceLocation Loc = IntroducerRange.getBegin();
985 DeclarationName Name
986 = S.Context.DeclarationNames.getCXXConversionFunctionName(
987 S.Context.getCanonicalType(BlockPtrTy));
988 DeclarationNameLoc NameLoc;
989 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
990 CXXConversionDecl *Conversion
991 = CXXConversionDecl::Create(S.Context, Class, Loc,
992 DeclarationNameInfo(Name, Loc, NameLoc),
993 ConvTy,
994 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000995 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000996 /*isConstexpr=*/false,
997 CallOperator->getBody()->getLocEnd());
998 Conversion->setAccess(AS_public);
999 Conversion->setImplicit(true);
1000 Class->addDecl(Conversion);
1001}
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001002
Douglas Gregordfca6f52012-02-13 22:00:16 +00001003ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001004 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001005 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001006 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001007 SmallVector<LambdaExpr::Capture, 4> Captures;
1008 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001009 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001010 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001011 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001012 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001013 SourceRange IntroducerRange;
1014 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001015 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001016 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001017 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001018 SmallVector<VarDecl *, 4> ArrayIndexVars;
1019 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001020 {
1021 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001022 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001023 Class = LSI->Lambda;
1024 IntroducerRange = LSI->IntroducerRange;
1025 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001026 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001027 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001028 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001029 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1030 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1031
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001032 // Translate captures.
1033 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1034 LambdaScopeInfo::Capture From = LSI->Captures[I];
1035 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1036 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1037
1038 // Handle 'this' capture.
1039 if (From.isThisCapture()) {
1040 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1041 IsImplicit,
1042 LCK_This));
1043 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1044 getCurrentThisType(),
1045 /*isImplicit=*/true));
1046 continue;
1047 }
1048
Richard Smith0d8e9642013-05-16 06:20:58 +00001049 if (From.isInitCapture()) {
1050 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
1051 CaptureInits.push_back(From.getInitExpr());
1052 continue;
1053 }
1054
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001055 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001056 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1057 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001058 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001059 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001060 }
1061
1062 switch (LSI->ImpCaptureStyle) {
1063 case CapturingScopeInfo::ImpCap_None:
1064 CaptureDefault = LCD_None;
1065 break;
1066
1067 case CapturingScopeInfo::ImpCap_LambdaByval:
1068 CaptureDefault = LCD_ByCopy;
1069 break;
1070
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001071 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001072 case CapturingScopeInfo::ImpCap_LambdaByref:
1073 CaptureDefault = LCD_ByRef;
1074 break;
1075
1076 case CapturingScopeInfo::ImpCap_Block:
1077 llvm_unreachable("block capture in lambda");
1078 break;
1079 }
James Dennettf68af642013-08-09 23:08:25 +00001080 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001081
Douglas Gregor54042f12012-02-09 10:18:50 +00001082 // C++11 [expr.prim.lambda]p4:
1083 // If a lambda-expression does not include a
1084 // trailing-return-type, it is as if the trailing-return-type
1085 // denotes the following type:
Faisal Valiecb58192013-08-22 01:49:11 +00001086 // Skip for C++1y return type deduction semantics which uses
1087 // different machinery currently.
1088 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001089 // FIXME: Assumes current resolution to core issue 975.
Faisal Valiecb58192013-08-22 01:49:11 +00001090 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001091 deduceClosureReturnType(*LSI);
1092
Douglas Gregor54042f12012-02-09 10:18:50 +00001093 // - if there are no return statements in the
1094 // compound-statement, or all return statements return
1095 // either an expression of type void or no expression or
1096 // braced-init-list, the type void;
1097 if (LSI->ReturnType.isNull()) {
1098 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001099 }
1100
1101 // Create a function type with the inferred return type.
1102 const FunctionProtoType *Proto
1103 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001104 QualType FunctionTy = Context.getFunctionType(
1105 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001106 CallOperator->setType(FunctionTy);
1107 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001108 // C++ [expr.prim.lambda]p7:
1109 // The lambda-expression's compound-statement yields the
1110 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001111 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001112 CallOperator->setLexicalDeclContext(Class);
Faisal Valiecb58192013-08-22 01:49:11 +00001113 Decl *TemplateOrNonTemplateCallOperatorDecl =
1114 !CallOperator->getDescribedFunctionTemplate() ? cast<Decl>(CallOperator)
1115 : CallOperator->getDescribedFunctionTemplate();
1116
1117 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1118 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1119
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001120 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001121
Douglas Gregorb5559712012-02-10 16:13:20 +00001122 // C++11 [expr.prim.lambda]p6:
1123 // The closure type for a lambda-expression with no lambda-capture
1124 // has a public non-virtual non-explicit const conversion function
1125 // to pointer to function having the same parameter and return
1126 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001127 if (Captures.empty() && CaptureDefault == LCD_None)
1128 addFunctionPointerConversion(*this, IntroducerRange, Class,
1129 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001130
Douglas Gregorc2956e52012-02-15 22:08:38 +00001131 // Objective-C++:
1132 // The closure type for a lambda-expression has a public non-virtual
1133 // non-explicit const conversion function to a block pointer having the
1134 // same parameter and return types as the closure type's function call
1135 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001136 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001137 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1138
Douglas Gregorb5559712012-02-10 16:13:20 +00001139 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001140 SmallVector<Decl*, 4> Fields;
1141 for (RecordDecl::field_iterator i = Class->field_begin(),
1142 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001143 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001144 ActOnFields(0, Class->getLocation(), Class, Fields,
1145 SourceLocation(), SourceLocation(), 0);
1146 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001147 }
1148
Douglas Gregor503384f2012-02-09 00:47:04 +00001149 if (LambdaExprNeedsCleanups)
1150 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001151
Douglas Gregore2c59132012-02-09 08:14:43 +00001152 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001153 CaptureDefault, CaptureDefaultLoc,
1154 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001155 ExplicitParams, ExplicitResultType,
1156 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001157 ArrayIndexStarts, Body->getLocEnd(),
1158 ContainsUnexpandedParameterPack);
Faisal Valiecb58192013-08-22 01:49:11 +00001159 Class->setLambdaExpr(Lambda);
Douglas Gregore2c59132012-02-09 08:14:43 +00001160 // C++11 [expr.prim.lambda]p2:
1161 // A lambda-expression shall not appear in an unevaluated operand
1162 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001163 if (!CurContext->isDependentContext()) {
1164 switch (ExprEvalContexts.back().Context) {
1165 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001166 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001167 // We don't actually diagnose this case immediately, because we
1168 // could be within a context where we might find out later that
1169 // the expression is potentially evaluated (e.g., for typeid).
1170 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1171 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001172
Douglas Gregord5387e82012-02-14 00:00:48 +00001173 case ConstantEvaluated:
1174 case PotentiallyEvaluated:
1175 case PotentiallyEvaluatedIfUsed:
1176 break;
1177 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001178 }
Faisal Valiecb58192013-08-22 01:49:11 +00001179 // TODO: Implement capturing.
1180 if (Lambda->isGenericLambda()) {
1181 if (Lambda->getCaptureDefault() != LCD_None) {
1182 Diag(Lambda->getIntroducerRange().getBegin(),
1183 diag::err_glambda_not_fully_implemented)
1184 << " capturing not implemented yet";
1185 return ExprError();
1186 }
1187 }
Douglas Gregor503384f2012-02-09 00:47:04 +00001188 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001189}
Eli Friedman23f02672012-03-01 04:01:32 +00001190
1191ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1192 SourceLocation ConvLocation,
1193 CXXConversionDecl *Conv,
1194 Expr *Src) {
1195 // Make sure that the lambda call operator is marked used.
1196 CXXRecordDecl *Lambda = Conv->getParent();
1197 CXXMethodDecl *CallOperator
1198 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001199 Lambda->lookup(
1200 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001201 CallOperator->setReferenced();
1202 CallOperator->setUsed();
1203
1204 ExprResult Init = PerformCopyInitialization(
1205 InitializedEntity::InitializeBlock(ConvLocation,
1206 Src->getType(),
1207 /*NRVO=*/false),
1208 CurrentLocation, Src);
1209 if (!Init.isInvalid())
1210 Init = ActOnFinishFullExpr(Init.take());
1211
1212 if (Init.isInvalid())
1213 return ExprError();
1214
1215 // Create the new block to be returned.
1216 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1217
1218 // Set the type information.
1219 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1220 Block->setIsVariadic(CallOperator->isVariadic());
1221 Block->setBlockMissingReturnType(false);
1222
1223 // Add parameters.
1224 SmallVector<ParmVarDecl *, 4> BlockParams;
1225 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1226 ParmVarDecl *From = CallOperator->getParamDecl(I);
1227 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1228 From->getLocStart(),
1229 From->getLocation(),
1230 From->getIdentifier(),
1231 From->getType(),
1232 From->getTypeSourceInfo(),
1233 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001234 /*DefaultArg=*/0));
1235 }
1236 Block->setParams(BlockParams);
1237
1238 Block->setIsConversionFromLambda(true);
1239
1240 // Add capture. The capture uses a fake variable, which doesn't correspond
1241 // to any actual memory location. However, the initializer copy-initializes
1242 // the lambda object.
1243 TypeSourceInfo *CapVarTSI =
1244 Context.getTrivialTypeSourceInfo(Src->getType());
1245 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1246 ConvLocation, 0,
1247 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001248 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001249 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1250 /*Nested=*/false, /*Copy=*/Init.take());
1251 Block->setCaptures(Context, &Capture, &Capture + 1,
1252 /*CapturesCXXThis=*/false);
1253
1254 // Add a fake function body to the block. IR generation is responsible
1255 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001256 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001257
1258 // Create the block literal expression.
1259 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1260 ExprCleanupObjects.push_back(Block);
1261 ExprNeedsCleanups = true;
1262
1263 return BuildBlock;
1264}