blob: 489c895c99680bd14d097a6a0520d3fe279634f9 [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"
14#include "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000016#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000017#include "clang/Sema/ScopeInfo.h"
18#include "clang/Sema/SemaInternal.h"
Douglas Gregor3ac109c2012-02-10 17:46:20 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/AST/ExprCXX.h"
21using namespace clang;
22using namespace sema;
23
Douglas Gregorf4b7de12012-02-21 19:11:17 +000024CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000025 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000026 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000027 DeclContext *DC = CurContext;
28 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
29 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000030
Douglas Gregore2a7ad02012-02-08 21:18:48 +000031 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000032 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000033 IntroducerRange.getBegin(),
34 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000035 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000036
37 return Class;
38}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000039
Douglas Gregorf54486a2012-04-04 17:40:10 +000040/// \brief Determine whether the given context is or is enclosed in an inline
41/// function.
42static bool isInInlineFunction(const DeclContext *DC) {
43 while (!DC->isFileContext()) {
44 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
45 if (FD->isInlined())
46 return true;
47
48 DC = DC->getLexicalParent();
49 }
50
51 return false;
52}
53
Douglas Gregordfca6f52012-02-13 22:00:16 +000054CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +000055 SourceRange IntroducerRange,
56 TypeSourceInfo *MethodType,
57 SourceLocation EndLoc,
Richard Smithadb1d4c2012-07-22 23:45:10 +000058 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000059 // C++11 [expr.prim.lambda]p5:
60 // The closure type for a lambda-expression has a public inline function
61 // call operator (13.5.4) whose parameters and return type are described by
62 // the lambda-expression's parameter-declaration-clause and
63 // trailing-return-type respectively.
64 DeclarationName MethodName
65 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
66 DeclarationNameLoc MethodNameLoc;
67 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
68 = IntroducerRange.getBegin().getRawEncoding();
69 MethodNameLoc.CXXOperatorName.EndOpNameLoc
70 = IntroducerRange.getEnd().getRawEncoding();
71 CXXMethodDecl *Method
72 = CXXMethodDecl::Create(Context, Class, EndLoc,
73 DeclarationNameInfo(MethodName,
74 IntroducerRange.getBegin(),
75 MethodNameLoc),
76 MethodType->getType(), MethodType,
77 /*isStatic=*/false,
78 SC_None,
79 /*isInline=*/true,
80 /*isConstExpr=*/false,
81 EndLoc);
82 Method->setAccess(AS_public);
83
84 // Temporarily set the lexical declaration context to the current
85 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000086 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000087
Douglas Gregorc6889e72012-02-14 22:28:59 +000088 // Add parameters.
89 if (!Params.empty()) {
90 Method->setParams(Params);
91 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
92 const_cast<ParmVarDecl **>(Params.end()),
93 /*CheckParameterNames=*/false);
94
95 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
96 PEnd = Method->param_end();
97 P != PEnd; ++P)
98 (*P)->setOwningFunction(Method);
99 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000100
101 // Allocate a mangling number for this lambda expression, if the ABI
102 // requires one.
103 Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
104
105 enum ContextKind {
106 Normal,
107 DefaultArgument,
108 DataMember,
109 StaticDataMember
110 } Kind = Normal;
111
112 // Default arguments of member function parameters that appear in a class
113 // definition, as well as the initializers of data members, receive special
114 // treatment. Identify them.
115 if (ContextDecl) {
116 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
117 if (const DeclContext *LexicalDC
118 = Param->getDeclContext()->getLexicalParent())
119 if (LexicalDC->isRecord())
120 Kind = DefaultArgument;
121 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
122 if (Var->getDeclContext()->isRecord())
123 Kind = StaticDataMember;
124 } else if (isa<FieldDecl>(ContextDecl)) {
125 Kind = DataMember;
Douglas Gregorf54486a2012-04-04 17:40:10 +0000126 }
127 }
128
Richard Smithadb1d4c2012-07-22 23:45:10 +0000129 // Itanium ABI [5.1.7]:
130 // In the following contexts [...] the one-definition rule requires closure
131 // types in different translation units to "correspond":
132 bool IsInNonspecializedTemplate =
133 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
134 unsigned ManglingNumber;
135 switch (Kind) {
136 case Normal:
137 // -- the bodies of non-exported nonspecialized template functions
138 // -- the bodies of inline functions
139 if ((IsInNonspecializedTemplate &&
140 !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
141 isInInlineFunction(CurContext))
142 ManglingNumber = Context.getLambdaManglingNumber(Method);
143 else
144 ManglingNumber = 0;
145
146 // There is no special context for this lambda.
147 ContextDecl = 0;
148 break;
149
150 case StaticDataMember:
151 // -- the initializers of nonspecialized static members of template classes
152 if (!IsInNonspecializedTemplate) {
153 ManglingNumber = 0;
154 ContextDecl = 0;
155 break;
156 }
157 // Fall through to assign a mangling number.
158
159 case DataMember:
160 // -- the in-class initializers of class members
161 case DefaultArgument:
162 // -- default arguments appearing in class definitions
163 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
164 .getManglingNumber(Method);
165 break;
166 }
167
168 Class->setLambdaMangling(ManglingNumber, ContextDecl);
169
Douglas Gregordfca6f52012-02-13 22:00:16 +0000170 return Method;
171}
172
173LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
174 SourceRange IntroducerRange,
175 LambdaCaptureDefault CaptureDefault,
176 bool ExplicitParams,
177 bool ExplicitResultType,
178 bool Mutable) {
179 PushLambdaScope(CallOperator->getParent(), CallOperator);
180 LambdaScopeInfo *LSI = getCurLambda();
181 if (CaptureDefault == LCD_ByCopy)
182 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
183 else if (CaptureDefault == LCD_ByRef)
184 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
185 LSI->IntroducerRange = IntroducerRange;
186 LSI->ExplicitParams = ExplicitParams;
187 LSI->Mutable = Mutable;
188
189 if (ExplicitResultType) {
190 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000191
192 if (!LSI->ReturnType->isDependentType() &&
193 !LSI->ReturnType->isVoidType()) {
194 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
195 diag::err_lambda_incomplete_result)) {
196 // Do nothing.
197 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
198 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
199 << LSI->ReturnType;
200 }
201 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000202 } else {
203 LSI->HasImplicitReturnType = true;
204 }
205
206 return LSI;
207}
208
209void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
210 LSI->finishedExplicitCaptures();
211}
212
Douglas Gregorc6889e72012-02-14 22:28:59 +0000213void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000214 // Introduce our parameters into the function scope
215 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
216 p < NumParams; ++p) {
217 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000218
219 // If this has an identifier, add it to the scope stack.
220 if (CurScope && Param->getIdentifier()) {
221 CheckShadow(CurScope, Param);
222
223 PushOnScopeChains(Param, CurScope);
224 }
225 }
226}
227
Jordan Rose7dd900e2012-07-02 21:19:23 +0000228static bool checkReturnValueType(const ASTContext &Ctx, const Expr *E,
229 QualType &DeducedType,
230 QualType &AlternateType) {
231 // Handle ReturnStmts with no expressions.
232 if (!E) {
233 if (AlternateType.isNull())
234 AlternateType = Ctx.VoidTy;
235
236 return Ctx.hasSameType(DeducedType, Ctx.VoidTy);
237 }
238
239 QualType StrictType = E->getType();
240 QualType LooseType = StrictType;
241
242 // In C, enum constants have the type of their underlying integer type,
243 // not the enum. When inferring block return types, we should allow
244 // the enum type if an enum constant is used, unless the enum is
245 // anonymous (in which case there can be no variables of its type).
246 if (!Ctx.getLangOpts().CPlusPlus) {
247 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
248 if (DRE) {
249 const Decl *D = DRE->getDecl();
250 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
251 const EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
252 if (Enum->getDeclName() || Enum->getTypedefNameForAnonDecl())
253 LooseType = Ctx.getTypeDeclType(Enum);
254 }
255 }
256 }
257
258 // Special case for the first return statement we find.
259 // The return type has already been tentatively set, but we might still
260 // have an alternate type we should prefer.
261 if (AlternateType.isNull())
262 AlternateType = LooseType;
263
264 if (Ctx.hasSameType(DeducedType, StrictType)) {
265 // FIXME: The loose type is different when there are constants from two
266 // different enums. We could consider warning here.
267 if (AlternateType != Ctx.DependentTy)
268 if (!Ctx.hasSameType(AlternateType, LooseType))
269 AlternateType = Ctx.VoidTy;
270 return true;
271 }
272
273 if (Ctx.hasSameType(DeducedType, LooseType)) {
274 // Use DependentTy to signal that we're using an alternate type and may
275 // need to add casts somewhere.
276 AlternateType = Ctx.DependentTy;
277 return true;
278 }
279
280 if (Ctx.hasSameType(AlternateType, StrictType) ||
281 Ctx.hasSameType(AlternateType, LooseType)) {
282 DeducedType = AlternateType;
283 // Use DependentTy to signal that we're using an alternate type and may
284 // need to add casts somewhere.
285 AlternateType = Ctx.DependentTy;
286 return true;
287 }
288
289 return false;
290}
291
292void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
293 assert(CSI.HasImplicitReturnType);
294
295 // First case: no return statements, implicit void return type.
296 ASTContext &Ctx = getASTContext();
297 if (CSI.Returns.empty()) {
298 // It's possible there were simply no /valid/ return statements.
299 // In this case, the first one we found may have at least given us a type.
300 if (CSI.ReturnType.isNull())
301 CSI.ReturnType = Ctx.VoidTy;
302 return;
303 }
304
305 // Second case: at least one return statement has dependent type.
306 // Delay type checking until instantiation.
307 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
308 if (CSI.ReturnType->isDependentType())
309 return;
310
311 // Third case: only one return statement. Don't bother doing extra work!
312 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
313 E = CSI.Returns.end();
314 if (I+1 == E)
315 return;
316
317 // General case: many return statements.
318 // Check that they all have compatible return types.
319 // For now, that means "identical", with an exception for enum constants.
320 // (In C, enum constants have the type of their underlying integer type,
321 // not the type of the enum. C++ uses the type of the enum.)
322 QualType AlternateType;
323
324 // We require the return types to strictly match here.
325 for (; I != E; ++I) {
326 const ReturnStmt *RS = *I;
327 const Expr *RetE = RS->getRetValue();
328 if (!checkReturnValueType(Ctx, RetE, CSI.ReturnType, AlternateType)) {
329 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
330 Diag(RS->getLocStart(),
331 diag::err_typecheck_missing_return_type_incompatible)
332 << (RetE ? RetE->getType() : Ctx.VoidTy) << CSI.ReturnType
333 << isa<LambdaScopeInfo>(CSI);
334 // Don't bother fixing up the return statements in the block if some of
335 // them are unfixable anyway.
336 AlternateType = Ctx.VoidTy;
337 // Continue iterating so that we keep emitting diagnostics.
338 }
339 }
340
341 // If our return statements turned out to be compatible, but we needed to
342 // pick a different return type, go through and fix the ones that need it.
343 if (AlternateType == Ctx.DependentTy) {
344 for (SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
345 E = CSI.Returns.end();
346 I != E; ++I) {
347 ReturnStmt *RS = *I;
348 Expr *RetE = RS->getRetValue();
349 if (RetE->getType() == CSI.ReturnType)
350 continue;
351
352 // Right now we only support integral fixup casts.
353 assert(CSI.ReturnType->isIntegralOrUnscopedEnumerationType());
354 assert(RetE->getType()->isIntegralOrUnscopedEnumerationType());
355 ExprResult Casted = ImpCastExprToType(RetE, CSI.ReturnType,
356 CK_IntegralCast);
357 assert(Casted.isUsable());
358 RS->setRetValue(Casted.take());
359 }
360 }
361}
362
Douglas Gregordfca6f52012-02-13 22:00:16 +0000363void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
364 Declarator &ParamInfo,
365 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000366 // Determine if we're within a context where we know that the lambda will
367 // be dependent, because there are template parameters in scope.
368 bool KnownDependent = false;
369 if (Scope *TmplScope = CurScope->getTemplateParamParent())
370 if (!TmplScope->decl_empty())
371 KnownDependent = true;
372
Douglas Gregordfca6f52012-02-13 22:00:16 +0000373 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000374 TypeSourceInfo *MethodTyInfo;
375 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000376 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000377 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000378 SourceLocation EndLoc;
Richard Smith3bc22262012-08-30 13:13:20 +0000379 llvm::SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000380 if (ParamInfo.getNumTypeObjects() == 0) {
381 // C++11 [expr.prim.lambda]p4:
382 // If a lambda-expression does not include a lambda-declarator, it is as
383 // if the lambda-declarator were ().
384 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000385 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000386 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000387 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
388 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000389 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
390 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000391 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000392 EndLoc = Intro.Range.getEnd();
393 } else {
394 assert(ParamInfo.isFunctionDeclarator() &&
395 "lambda-declarator is a function");
396 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
397
398 // C++11 [expr.prim.lambda]p5:
399 // This function call operator is declared const (9.3.1) if and only if
400 // the lambda-expression's parameter-declaration-clause is not followed
401 // by mutable. It is neither virtual nor declared volatile. [...]
402 if (!FTI.hasMutableQualifier())
403 FTI.TypeQuals |= DeclSpec::TQ_const;
404
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000405 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000406 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000407 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000408
409 ExplicitResultType
410 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
411 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000412
413 Params.reserve(FTI.NumArgs);
414 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
415 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000416
417 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000418 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
419 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000420 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000421
422 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
423 KnownDependent);
424
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000425 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000426 MethodTyInfo, EndLoc, Params);
427
428 if (ExplicitParams)
429 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000430
Douglas Gregor503384f2012-02-09 00:47:04 +0000431 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000432 ProcessDeclAttributes(CurScope, Method, ParamInfo);
433
Douglas Gregor503384f2012-02-09 00:47:04 +0000434 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000435 PushDeclContext(CurScope, Method);
436
437 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000438 LambdaScopeInfo *LSI
439 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
440 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000441 !Method->isConst());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000442
443 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000444 SourceLocation PrevCaptureLoc
445 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000446 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
447 C = Intro.Captures.begin(),
448 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000449 C != E;
450 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000451 if (C->Kind == LCK_This) {
452 // C++11 [expr.prim.lambda]p8:
453 // An identifier or this shall not appear more than once in a
454 // lambda-capture.
455 if (LSI->isCXXThisCaptured()) {
456 Diag(C->Loc, diag::err_capture_more_than_once)
457 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000458 << SourceRange(LSI->getCXXThisCapture().getLocation())
459 << FixItHint::CreateRemoval(
460 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000461 continue;
462 }
463
464 // C++11 [expr.prim.lambda]p8:
465 // If a lambda-capture includes a capture-default that is =, the
466 // lambda-capture shall not contain this [...].
467 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000468 Diag(C->Loc, diag::err_this_capture_with_copy_default)
469 << FixItHint::CreateRemoval(
470 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000471 continue;
472 }
473
474 // C++11 [expr.prim.lambda]p12:
475 // If this is captured by a local lambda expression, its nearest
476 // enclosing function shall be a non-static member function.
477 QualType ThisCaptureType = getCurrentThisType();
478 if (ThisCaptureType.isNull()) {
479 Diag(C->Loc, diag::err_this_capture) << true;
480 continue;
481 }
482
483 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
484 continue;
485 }
486
487 assert(C->Id && "missing identifier for capture");
488
489 // C++11 [expr.prim.lambda]p8:
490 // If a lambda-capture includes a capture-default that is &, the
491 // identifiers in the lambda-capture shall not be preceded by &.
492 // If a lambda-capture includes a capture-default that is =, [...]
493 // each identifier it contains shall be preceded by &.
494 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000495 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
496 << FixItHint::CreateRemoval(
497 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000498 continue;
499 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000500 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
501 << FixItHint::CreateRemoval(
502 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000503 continue;
504 }
505
506 DeclarationNameInfo Name(C->Id, C->Loc);
507 LookupResult R(*this, Name, LookupOrdinaryName);
508 LookupName(R, CurScope);
509 if (R.isAmbiguous())
510 continue;
511 if (R.empty()) {
512 // FIXME: Disable corrections that would add qualification?
513 CXXScopeSpec ScopeSpec;
514 DeclFilterCCC<VarDecl> Validator;
515 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
516 continue;
517 }
518
519 // C++11 [expr.prim.lambda]p10:
520 // The identifiers in a capture-list are looked up using the usual rules
521 // for unqualified name lookup (3.4.1); each such lookup shall find a
522 // variable with automatic storage duration declared in the reaching
523 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000524 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000525 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000526 VarDecl *Var = R.getAsSingle<VarDecl>();
527 if (!Var) {
528 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
529 continue;
530 }
531
Eli Friedman9cd5b242012-09-18 21:11:30 +0000532 // Ignore invalid decls; they'll just confuse the code later.
533 if (Var->isInvalidDecl())
534 continue;
535
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000536 if (!Var->hasLocalStorage()) {
537 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
538 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
539 continue;
540 }
541
542 // C++11 [expr.prim.lambda]p8:
543 // An identifier or this shall not appear more than once in a
544 // lambda-capture.
545 if (LSI->isCaptured(Var)) {
546 Diag(C->Loc, diag::err_capture_more_than_once)
547 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000548 << SourceRange(LSI->getCapture(Var).getLocation())
549 << FixItHint::CreateRemoval(
550 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000551 continue;
552 }
553
Douglas Gregora7365242012-02-14 19:27:52 +0000554 // C++11 [expr.prim.lambda]p23:
555 // A capture followed by an ellipsis is a pack expansion (14.5.3).
556 SourceLocation EllipsisLoc;
557 if (C->EllipsisLoc.isValid()) {
558 if (Var->isParameterPack()) {
559 EllipsisLoc = C->EllipsisLoc;
560 } else {
561 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
562 << SourceRange(C->Loc);
563
564 // Just ignore the ellipsis.
565 }
566 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000567 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000568 }
569
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000570 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
571 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000572 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000573 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000574 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000575
Richard Smith612409e2012-07-25 03:56:55 +0000576 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
577
Douglas Gregorc6889e72012-02-14 22:28:59 +0000578 // Add lambda parameters into scope.
579 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580
Douglas Gregordfca6f52012-02-13 22:00:16 +0000581 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000582 // cleanups from the enclosing full-expression.
583 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000584}
585
Douglas Gregordfca6f52012-02-13 22:00:16 +0000586void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
587 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000588 // Leave the expression-evaluation context.
589 DiscardCleanupsInEvaluationContext();
590 PopExpressionEvaluationContext();
591
592 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000593 if (!IsInstantiation)
594 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000595
596 // Finalize the lambda.
597 LambdaScopeInfo *LSI = getCurLambda();
598 CXXRecordDecl *Class = LSI->Lambda;
599 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000600 SmallVector<Decl*, 4> Fields;
601 for (RecordDecl::field_iterator i = Class->field_begin(),
602 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000603 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000604 ActOnFields(0, Class->getLocation(), Class, Fields,
605 SourceLocation(), SourceLocation(), 0);
606 CheckCompletedCXXClass(Class);
607
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000608 PopFunctionScopeInfo();
609}
610
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000611/// \brief Add a lambda's conversion to function pointer, as described in
612/// C++11 [expr.prim.lambda]p6.
613static void addFunctionPointerConversion(Sema &S,
614 SourceRange IntroducerRange,
615 CXXRecordDecl *Class,
616 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000617 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000618 const FunctionProtoType *Proto
619 = CallOperator->getType()->getAs<FunctionProtoType>();
620 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000621 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000622 {
623 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
624 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000625 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
626 Proto->arg_type_begin(),
627 Proto->getNumArgs(),
628 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000629 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
630 }
631
632 FunctionProtoType::ExtProtoInfo ExtInfo;
633 ExtInfo.TypeQuals = Qualifiers::Const;
634 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
635
636 SourceLocation Loc = IntroducerRange.getBegin();
637 DeclarationName Name
638 = S.Context.DeclarationNames.getCXXConversionFunctionName(
639 S.Context.getCanonicalType(FunctionPtrTy));
640 DeclarationNameLoc NameLoc;
641 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
642 Loc);
643 CXXConversionDecl *Conversion
644 = CXXConversionDecl::Create(S.Context, Class, Loc,
645 DeclarationNameInfo(Name, Loc, NameLoc),
646 ConvTy,
647 S.Context.getTrivialTypeSourceInfo(ConvTy,
648 Loc),
649 /*isInline=*/false, /*isExplicit=*/false,
650 /*isConstexpr=*/false,
651 CallOperator->getBody()->getLocEnd());
652 Conversion->setAccess(AS_public);
653 Conversion->setImplicit(true);
654 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000655
656 // Add a non-static member function "__invoke" that will be the result of
657 // the conversion.
658 Name = &S.Context.Idents.get("__invoke");
659 CXXMethodDecl *Invoke
660 = CXXMethodDecl::Create(S.Context, Class, Loc,
661 DeclarationNameInfo(Name, Loc), FunctionTy,
662 CallOperator->getTypeSourceInfo(),
663 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
664 /*IsConstexpr=*/false,
665 CallOperator->getBody()->getLocEnd());
666 SmallVector<ParmVarDecl *, 4> InvokeParams;
667 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
668 ParmVarDecl *From = CallOperator->getParamDecl(I);
669 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
670 From->getLocStart(),
671 From->getLocation(),
672 From->getIdentifier(),
673 From->getType(),
674 From->getTypeSourceInfo(),
675 From->getStorageClass(),
676 From->getStorageClassAsWritten(),
677 /*DefaultArg=*/0));
678 }
679 Invoke->setParams(InvokeParams);
680 Invoke->setAccess(AS_private);
681 Invoke->setImplicit(true);
682 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000683}
684
Douglas Gregorc2956e52012-02-15 22:08:38 +0000685/// \brief Add a lambda's conversion to block pointer.
686static void addBlockPointerConversion(Sema &S,
687 SourceRange IntroducerRange,
688 CXXRecordDecl *Class,
689 CXXMethodDecl *CallOperator) {
690 const FunctionProtoType *Proto
691 = CallOperator->getType()->getAs<FunctionProtoType>();
692 QualType BlockPtrTy;
693 {
694 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
695 ExtInfo.TypeQuals = 0;
696 QualType FunctionTy
697 = S.Context.getFunctionType(Proto->getResultType(),
698 Proto->arg_type_begin(),
699 Proto->getNumArgs(),
700 ExtInfo);
701 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
702 }
703
704 FunctionProtoType::ExtProtoInfo ExtInfo;
705 ExtInfo.TypeQuals = Qualifiers::Const;
706 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
707
708 SourceLocation Loc = IntroducerRange.getBegin();
709 DeclarationName Name
710 = S.Context.DeclarationNames.getCXXConversionFunctionName(
711 S.Context.getCanonicalType(BlockPtrTy));
712 DeclarationNameLoc NameLoc;
713 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
714 CXXConversionDecl *Conversion
715 = CXXConversionDecl::Create(S.Context, Class, Loc,
716 DeclarationNameInfo(Name, Loc, NameLoc),
717 ConvTy,
718 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
719 /*isInline=*/false, /*isExplicit=*/false,
720 /*isConstexpr=*/false,
721 CallOperator->getBody()->getLocEnd());
722 Conversion->setAccess(AS_public);
723 Conversion->setImplicit(true);
724 Class->addDecl(Conversion);
725}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000726
Douglas Gregordfca6f52012-02-13 22:00:16 +0000727ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000728 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000729 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000730 // Collect information from the lambda scope.
731 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
732 llvm::SmallVector<Expr *, 4> CaptureInits;
733 LambdaCaptureDefault CaptureDefault;
734 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000735 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000736 SourceRange IntroducerRange;
737 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000738 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000739 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000740 bool ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000741 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
742 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000743 {
744 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000745 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000746 Class = LSI->Lambda;
747 IntroducerRange = LSI->IntroducerRange;
748 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000749 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000750 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000751 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000752 ArrayIndexVars.swap(LSI->ArrayIndexVars);
753 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
754
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000755 // Translate captures.
756 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
757 LambdaScopeInfo::Capture From = LSI->Captures[I];
758 assert(!From.isBlockCapture() && "Cannot capture __block variables");
759 bool IsImplicit = I >= LSI->NumExplicitCaptures;
760
761 // Handle 'this' capture.
762 if (From.isThisCapture()) {
763 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
764 IsImplicit,
765 LCK_This));
766 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
767 getCurrentThisType(),
768 /*isImplicit=*/true));
769 continue;
770 }
771
772 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000773 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
774 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000775 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000776 CaptureInits.push_back(From.getCopyExpr());
777 }
778
779 switch (LSI->ImpCaptureStyle) {
780 case CapturingScopeInfo::ImpCap_None:
781 CaptureDefault = LCD_None;
782 break;
783
784 case CapturingScopeInfo::ImpCap_LambdaByval:
785 CaptureDefault = LCD_ByCopy;
786 break;
787
788 case CapturingScopeInfo::ImpCap_LambdaByref:
789 CaptureDefault = LCD_ByRef;
790 break;
791
792 case CapturingScopeInfo::ImpCap_Block:
793 llvm_unreachable("block capture in lambda");
794 break;
795 }
796
Douglas Gregor54042f12012-02-09 10:18:50 +0000797 // C++11 [expr.prim.lambda]p4:
798 // If a lambda-expression does not include a
799 // trailing-return-type, it is as if the trailing-return-type
800 // denotes the following type:
801 // FIXME: Assumes current resolution to core issue 975.
802 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000803 deduceClosureReturnType(*LSI);
804
Douglas Gregor54042f12012-02-09 10:18:50 +0000805 // - if there are no return statements in the
806 // compound-statement, or all return statements return
807 // either an expression of type void or no expression or
808 // braced-init-list, the type void;
809 if (LSI->ReturnType.isNull()) {
810 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000811 }
812
813 // Create a function type with the inferred return type.
814 const FunctionProtoType *Proto
815 = CallOperator->getType()->getAs<FunctionProtoType>();
816 QualType FunctionTy
817 = Context.getFunctionType(LSI->ReturnType,
818 Proto->arg_type_begin(),
819 Proto->getNumArgs(),
820 Proto->getExtProtoInfo());
821 CallOperator->setType(FunctionTy);
822 }
823
Douglas Gregor215e4e12012-02-12 17:34:23 +0000824 // C++ [expr.prim.lambda]p7:
825 // The lambda-expression's compound-statement yields the
826 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000827 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000828 CallOperator->setLexicalDeclContext(Class);
829 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000830 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000831
Douglas Gregorb5559712012-02-10 16:13:20 +0000832 // C++11 [expr.prim.lambda]p6:
833 // The closure type for a lambda-expression with no lambda-capture
834 // has a public non-virtual non-explicit const conversion function
835 // to pointer to function having the same parameter and return
836 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000837 if (Captures.empty() && CaptureDefault == LCD_None)
838 addFunctionPointerConversion(*this, IntroducerRange, Class,
839 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000840
Douglas Gregorc2956e52012-02-15 22:08:38 +0000841 // Objective-C++:
842 // The closure type for a lambda-expression has a public non-virtual
843 // non-explicit const conversion function to a block pointer having the
844 // same parameter and return types as the closure type's function call
845 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000846 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000847 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
848
Douglas Gregorb5559712012-02-10 16:13:20 +0000849 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000850 SmallVector<Decl*, 4> Fields;
851 for (RecordDecl::field_iterator i = Class->field_begin(),
852 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000853 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000854 ActOnFields(0, Class->getLocation(), Class, Fields,
855 SourceLocation(), SourceLocation(), 0);
856 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000857 }
858
Douglas Gregor503384f2012-02-09 00:47:04 +0000859 if (LambdaExprNeedsCleanups)
860 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000861
Douglas Gregore2c59132012-02-09 08:14:43 +0000862 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
863 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000864 ExplicitParams, ExplicitResultType,
865 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +0000866 ArrayIndexStarts, Body->getLocEnd(),
867 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +0000868
869 // C++11 [expr.prim.lambda]p2:
870 // A lambda-expression shall not appear in an unevaluated operand
871 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000872 if (!CurContext->isDependentContext()) {
873 switch (ExprEvalContexts.back().Context) {
874 case Unevaluated:
875 // We don't actually diagnose this case immediately, because we
876 // could be within a context where we might find out later that
877 // the expression is potentially evaluated (e.g., for typeid).
878 ExprEvalContexts.back().Lambdas.push_back(Lambda);
879 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000880
Douglas Gregord5387e82012-02-14 00:00:48 +0000881 case ConstantEvaluated:
882 case PotentiallyEvaluated:
883 case PotentiallyEvaluatedIfUsed:
884 break;
885 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000886 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000887
Douglas Gregor503384f2012-02-09 00:47:04 +0000888 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000889}
Eli Friedman23f02672012-03-01 04:01:32 +0000890
891ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
892 SourceLocation ConvLocation,
893 CXXConversionDecl *Conv,
894 Expr *Src) {
895 // Make sure that the lambda call operator is marked used.
896 CXXRecordDecl *Lambda = Conv->getParent();
897 CXXMethodDecl *CallOperator
898 = cast<CXXMethodDecl>(
899 *Lambda->lookup(
900 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
901 CallOperator->setReferenced();
902 CallOperator->setUsed();
903
904 ExprResult Init = PerformCopyInitialization(
905 InitializedEntity::InitializeBlock(ConvLocation,
906 Src->getType(),
907 /*NRVO=*/false),
908 CurrentLocation, Src);
909 if (!Init.isInvalid())
910 Init = ActOnFinishFullExpr(Init.take());
911
912 if (Init.isInvalid())
913 return ExprError();
914
915 // Create the new block to be returned.
916 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
917
918 // Set the type information.
919 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
920 Block->setIsVariadic(CallOperator->isVariadic());
921 Block->setBlockMissingReturnType(false);
922
923 // Add parameters.
924 SmallVector<ParmVarDecl *, 4> BlockParams;
925 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
926 ParmVarDecl *From = CallOperator->getParamDecl(I);
927 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
928 From->getLocStart(),
929 From->getLocation(),
930 From->getIdentifier(),
931 From->getType(),
932 From->getTypeSourceInfo(),
933 From->getStorageClass(),
934 From->getStorageClassAsWritten(),
935 /*DefaultArg=*/0));
936 }
937 Block->setParams(BlockParams);
938
939 Block->setIsConversionFromLambda(true);
940
941 // Add capture. The capture uses a fake variable, which doesn't correspond
942 // to any actual memory location. However, the initializer copy-initializes
943 // the lambda object.
944 TypeSourceInfo *CapVarTSI =
945 Context.getTrivialTypeSourceInfo(Src->getType());
946 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
947 ConvLocation, 0,
948 Src->getType(), CapVarTSI,
949 SC_None, SC_None);
950 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
951 /*Nested=*/false, /*Copy=*/Init.take());
952 Block->setCaptures(Context, &Capture, &Capture + 1,
953 /*CapturesCXXThis=*/false);
954
955 // Add a fake function body to the block. IR generation is responsible
956 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +0000957 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +0000958
959 // Create the block literal expression.
960 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
961 ExprCleanupObjects.push_back(Block);
962 ExprNeedsCleanups = true;
963
964 return BuildBlock;
965}