blob: 21202c176f32eaadf4d60f660ef63b5cba96b864 [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"
17#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000018#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000019#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/SemaInternal.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000021using 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,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000058 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;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000379 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,
Jordan Rosebea522f2013-03-08 21:51:21 +0000388 ArrayRef<QualType>(),
389 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000390 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
391 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000392 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000393 EndLoc = Intro.Range.getEnd();
394 } else {
395 assert(ParamInfo.isFunctionDeclarator() &&
396 "lambda-declarator is a function");
397 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
398
399 // C++11 [expr.prim.lambda]p5:
400 // This function call operator is declared const (9.3.1) if and only if
401 // the lambda-expression's parameter-declaration-clause is not followed
402 // by mutable. It is neither virtual nor declared volatile. [...]
403 if (!FTI.hasMutableQualifier())
404 FTI.TypeQuals |= DeclSpec::TQ_const;
405
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000406 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000407 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000408 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000409
410 ExplicitResultType
411 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
412 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000413
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000414 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
415 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
416 // Empty arg list, don't push any params.
417 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
418 } else {
419 Params.reserve(FTI.NumArgs);
420 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
421 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
422 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000423
424 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000425 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
426 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000427 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000428
429 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
430 KnownDependent);
431
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000432 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000433 MethodTyInfo, EndLoc, Params);
434
435 if (ExplicitParams)
436 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000437
Bill Wendlingad017fa2012-12-20 19:22:21 +0000438 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000439 ProcessDeclAttributes(CurScope, Method, ParamInfo);
440
Douglas Gregor503384f2012-02-09 00:47:04 +0000441 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000442 PushDeclContext(CurScope, Method);
443
444 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000445 LambdaScopeInfo *LSI
446 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
447 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000448 !Method->isConst());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000449
450 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000451 SourceLocation PrevCaptureLoc
452 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000453 for (SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000454 C = Intro.Captures.begin(),
455 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000456 C != E;
457 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000458 if (C->Kind == LCK_This) {
459 // C++11 [expr.prim.lambda]p8:
460 // An identifier or this shall not appear more than once in a
461 // lambda-capture.
462 if (LSI->isCXXThisCaptured()) {
463 Diag(C->Loc, diag::err_capture_more_than_once)
464 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000465 << SourceRange(LSI->getCXXThisCapture().getLocation())
466 << FixItHint::CreateRemoval(
467 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000468 continue;
469 }
470
471 // C++11 [expr.prim.lambda]p8:
472 // If a lambda-capture includes a capture-default that is =, the
473 // lambda-capture shall not contain this [...].
474 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000475 Diag(C->Loc, diag::err_this_capture_with_copy_default)
476 << FixItHint::CreateRemoval(
477 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000478 continue;
479 }
480
481 // C++11 [expr.prim.lambda]p12:
482 // If this is captured by a local lambda expression, its nearest
483 // enclosing function shall be a non-static member function.
484 QualType ThisCaptureType = getCurrentThisType();
485 if (ThisCaptureType.isNull()) {
486 Diag(C->Loc, diag::err_this_capture) << true;
487 continue;
488 }
489
490 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
491 continue;
492 }
493
494 assert(C->Id && "missing identifier for capture");
495
496 // C++11 [expr.prim.lambda]p8:
497 // If a lambda-capture includes a capture-default that is &, the
498 // identifiers in the lambda-capture shall not be preceded by &.
499 // If a lambda-capture includes a capture-default that is =, [...]
500 // each identifier it contains shall be preceded by &.
501 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000502 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
503 << FixItHint::CreateRemoval(
504 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000505 continue;
506 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000507 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
508 << FixItHint::CreateRemoval(
509 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000510 continue;
511 }
512
513 DeclarationNameInfo Name(C->Id, C->Loc);
514 LookupResult R(*this, Name, LookupOrdinaryName);
515 LookupName(R, CurScope);
516 if (R.isAmbiguous())
517 continue;
518 if (R.empty()) {
519 // FIXME: Disable corrections that would add qualification?
520 CXXScopeSpec ScopeSpec;
521 DeclFilterCCC<VarDecl> Validator;
522 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
523 continue;
524 }
525
526 // C++11 [expr.prim.lambda]p10:
527 // The identifiers in a capture-list are looked up using the usual rules
528 // for unqualified name lookup (3.4.1); each such lookup shall find a
529 // variable with automatic storage duration declared in the reaching
530 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000531 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000532 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000533 VarDecl *Var = R.getAsSingle<VarDecl>();
534 if (!Var) {
535 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
536 continue;
537 }
538
Eli Friedman9cd5b242012-09-18 21:11:30 +0000539 // Ignore invalid decls; they'll just confuse the code later.
540 if (Var->isInvalidDecl())
541 continue;
542
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000543 if (!Var->hasLocalStorage()) {
544 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
545 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
546 continue;
547 }
548
549 // C++11 [expr.prim.lambda]p8:
550 // An identifier or this shall not appear more than once in a
551 // lambda-capture.
552 if (LSI->isCaptured(Var)) {
553 Diag(C->Loc, diag::err_capture_more_than_once)
554 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000555 << SourceRange(LSI->getCapture(Var).getLocation())
556 << FixItHint::CreateRemoval(
557 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000558 continue;
559 }
560
Douglas Gregora7365242012-02-14 19:27:52 +0000561 // C++11 [expr.prim.lambda]p23:
562 // A capture followed by an ellipsis is a pack expansion (14.5.3).
563 SourceLocation EllipsisLoc;
564 if (C->EllipsisLoc.isValid()) {
565 if (Var->isParameterPack()) {
566 EllipsisLoc = C->EllipsisLoc;
567 } else {
568 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
569 << SourceRange(C->Loc);
570
571 // Just ignore the ellipsis.
572 }
573 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000574 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000575 }
576
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000577 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
578 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000579 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000581 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000582
Richard Smith612409e2012-07-25 03:56:55 +0000583 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
584
Douglas Gregorc6889e72012-02-14 22:28:59 +0000585 // Add lambda parameters into scope.
586 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000587
Douglas Gregordfca6f52012-02-13 22:00:16 +0000588 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000589 // cleanups from the enclosing full-expression.
590 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000591}
592
Douglas Gregordfca6f52012-02-13 22:00:16 +0000593void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
594 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000595 // Leave the expression-evaluation context.
596 DiscardCleanupsInEvaluationContext();
597 PopExpressionEvaluationContext();
598
599 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000600 if (!IsInstantiation)
601 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000602
603 // Finalize the lambda.
604 LambdaScopeInfo *LSI = getCurLambda();
605 CXXRecordDecl *Class = LSI->Lambda;
606 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000607 SmallVector<Decl*, 4> Fields;
608 for (RecordDecl::field_iterator i = Class->field_begin(),
609 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000610 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000611 ActOnFields(0, Class->getLocation(), Class, Fields,
612 SourceLocation(), SourceLocation(), 0);
613 CheckCompletedCXXClass(Class);
614
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000615 PopFunctionScopeInfo();
616}
617
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000618/// \brief Add a lambda's conversion to function pointer, as described in
619/// C++11 [expr.prim.lambda]p6.
620static void addFunctionPointerConversion(Sema &S,
621 SourceRange IntroducerRange,
622 CXXRecordDecl *Class,
623 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000624 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000625 const FunctionProtoType *Proto
626 = CallOperator->getType()->getAs<FunctionProtoType>();
627 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000628 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000629 {
630 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
631 ExtInfo.TypeQuals = 0;
Jordan Rosebea522f2013-03-08 21:51:21 +0000632 FunctionTy =
633 S.Context.getFunctionType(Proto->getResultType(),
634 ArrayRef<QualType>(Proto->arg_type_begin(),
635 Proto->getNumArgs()),
636 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000637 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
638 }
639
640 FunctionProtoType::ExtProtoInfo ExtInfo;
641 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000642 QualType ConvTy =
643 S.Context.getFunctionType(FunctionPtrTy, ArrayRef<QualType>(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000644
645 SourceLocation Loc = IntroducerRange.getBegin();
646 DeclarationName Name
647 = S.Context.DeclarationNames.getCXXConversionFunctionName(
648 S.Context.getCanonicalType(FunctionPtrTy));
649 DeclarationNameLoc NameLoc;
650 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
651 Loc);
652 CXXConversionDecl *Conversion
653 = CXXConversionDecl::Create(S.Context, Class, Loc,
654 DeclarationNameInfo(Name, Loc, NameLoc),
655 ConvTy,
656 S.Context.getTrivialTypeSourceInfo(ConvTy,
657 Loc),
658 /*isInline=*/false, /*isExplicit=*/false,
659 /*isConstexpr=*/false,
660 CallOperator->getBody()->getLocEnd());
661 Conversion->setAccess(AS_public);
662 Conversion->setImplicit(true);
663 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000664
665 // Add a non-static member function "__invoke" that will be the result of
666 // the conversion.
667 Name = &S.Context.Idents.get("__invoke");
668 CXXMethodDecl *Invoke
669 = CXXMethodDecl::Create(S.Context, Class, Loc,
670 DeclarationNameInfo(Name, Loc), FunctionTy,
671 CallOperator->getTypeSourceInfo(),
672 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
673 /*IsConstexpr=*/false,
674 CallOperator->getBody()->getLocEnd());
675 SmallVector<ParmVarDecl *, 4> InvokeParams;
676 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
677 ParmVarDecl *From = CallOperator->getParamDecl(I);
678 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
679 From->getLocStart(),
680 From->getLocation(),
681 From->getIdentifier(),
682 From->getType(),
683 From->getTypeSourceInfo(),
684 From->getStorageClass(),
685 From->getStorageClassAsWritten(),
686 /*DefaultArg=*/0));
687 }
688 Invoke->setParams(InvokeParams);
689 Invoke->setAccess(AS_private);
690 Invoke->setImplicit(true);
691 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000692}
693
Douglas Gregorc2956e52012-02-15 22:08:38 +0000694/// \brief Add a lambda's conversion to block pointer.
695static void addBlockPointerConversion(Sema &S,
696 SourceRange IntroducerRange,
697 CXXRecordDecl *Class,
698 CXXMethodDecl *CallOperator) {
699 const FunctionProtoType *Proto
700 = CallOperator->getType()->getAs<FunctionProtoType>();
701 QualType BlockPtrTy;
702 {
703 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
704 ExtInfo.TypeQuals = 0;
705 QualType FunctionTy
706 = S.Context.getFunctionType(Proto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +0000707 ArrayRef<QualType>(Proto->arg_type_begin(),
708 Proto->getNumArgs()),
Douglas Gregorc2956e52012-02-15 22:08:38 +0000709 ExtInfo);
710 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
711 }
712
713 FunctionProtoType::ExtProtoInfo ExtInfo;
714 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000715 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, ArrayRef<QualType>(),
716 ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000717
718 SourceLocation Loc = IntroducerRange.getBegin();
719 DeclarationName Name
720 = S.Context.DeclarationNames.getCXXConversionFunctionName(
721 S.Context.getCanonicalType(BlockPtrTy));
722 DeclarationNameLoc NameLoc;
723 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
724 CXXConversionDecl *Conversion
725 = CXXConversionDecl::Create(S.Context, Class, Loc,
726 DeclarationNameInfo(Name, Loc, NameLoc),
727 ConvTy,
728 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
729 /*isInline=*/false, /*isExplicit=*/false,
730 /*isConstexpr=*/false,
731 CallOperator->getBody()->getLocEnd());
732 Conversion->setAccess(AS_public);
733 Conversion->setImplicit(true);
734 Class->addDecl(Conversion);
735}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000736
Douglas Gregordfca6f52012-02-13 22:00:16 +0000737ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000738 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000739 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000740 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000741 SmallVector<LambdaExpr::Capture, 4> Captures;
742 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000743 LambdaCaptureDefault CaptureDefault;
744 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000745 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000746 SourceRange IntroducerRange;
747 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000748 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000749 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000750 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000751 SmallVector<VarDecl *, 4> ArrayIndexVars;
752 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000753 {
754 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000755 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000756 Class = LSI->Lambda;
757 IntroducerRange = LSI->IntroducerRange;
758 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000759 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000760 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000761 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000762 ArrayIndexVars.swap(LSI->ArrayIndexVars);
763 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
764
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000765 // Translate captures.
766 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
767 LambdaScopeInfo::Capture From = LSI->Captures[I];
768 assert(!From.isBlockCapture() && "Cannot capture __block variables");
769 bool IsImplicit = I >= LSI->NumExplicitCaptures;
770
771 // Handle 'this' capture.
772 if (From.isThisCapture()) {
773 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
774 IsImplicit,
775 LCK_This));
776 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
777 getCurrentThisType(),
778 /*isImplicit=*/true));
779 continue;
780 }
781
782 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000783 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
784 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000785 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000786 CaptureInits.push_back(From.getCopyExpr());
787 }
788
789 switch (LSI->ImpCaptureStyle) {
790 case CapturingScopeInfo::ImpCap_None:
791 CaptureDefault = LCD_None;
792 break;
793
794 case CapturingScopeInfo::ImpCap_LambdaByval:
795 CaptureDefault = LCD_ByCopy;
796 break;
797
798 case CapturingScopeInfo::ImpCap_LambdaByref:
799 CaptureDefault = LCD_ByRef;
800 break;
801
802 case CapturingScopeInfo::ImpCap_Block:
803 llvm_unreachable("block capture in lambda");
804 break;
805 }
806
Douglas Gregor54042f12012-02-09 10:18:50 +0000807 // C++11 [expr.prim.lambda]p4:
808 // If a lambda-expression does not include a
809 // trailing-return-type, it is as if the trailing-return-type
810 // denotes the following type:
811 // FIXME: Assumes current resolution to core issue 975.
812 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000813 deduceClosureReturnType(*LSI);
814
Douglas Gregor54042f12012-02-09 10:18:50 +0000815 // - if there are no return statements in the
816 // compound-statement, or all return statements return
817 // either an expression of type void or no expression or
818 // braced-init-list, the type void;
819 if (LSI->ReturnType.isNull()) {
820 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000821 }
822
823 // Create a function type with the inferred return type.
824 const FunctionProtoType *Proto
825 = CallOperator->getType()->getAs<FunctionProtoType>();
826 QualType FunctionTy
827 = Context.getFunctionType(LSI->ReturnType,
Jordan Rosebea522f2013-03-08 21:51:21 +0000828 ArrayRef<QualType>(Proto->arg_type_begin(),
829 Proto->getNumArgs()),
Douglas Gregor54042f12012-02-09 10:18:50 +0000830 Proto->getExtProtoInfo());
831 CallOperator->setType(FunctionTy);
832 }
833
Douglas Gregor215e4e12012-02-12 17:34:23 +0000834 // C++ [expr.prim.lambda]p7:
835 // The lambda-expression's compound-statement yields the
836 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000837 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000838 CallOperator->setLexicalDeclContext(Class);
839 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000840 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000841
Douglas Gregorb5559712012-02-10 16:13:20 +0000842 // C++11 [expr.prim.lambda]p6:
843 // The closure type for a lambda-expression with no lambda-capture
844 // has a public non-virtual non-explicit const conversion function
845 // to pointer to function having the same parameter and return
846 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000847 if (Captures.empty() && CaptureDefault == LCD_None)
848 addFunctionPointerConversion(*this, IntroducerRange, Class,
849 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000850
Douglas Gregorc2956e52012-02-15 22:08:38 +0000851 // Objective-C++:
852 // The closure type for a lambda-expression has a public non-virtual
853 // non-explicit const conversion function to a block pointer having the
854 // same parameter and return types as the closure type's function call
855 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000856 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000857 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
858
Douglas Gregorb5559712012-02-10 16:13:20 +0000859 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000860 SmallVector<Decl*, 4> Fields;
861 for (RecordDecl::field_iterator i = Class->field_begin(),
862 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000863 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000864 ActOnFields(0, Class->getLocation(), Class, Fields,
865 SourceLocation(), SourceLocation(), 0);
866 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000867 }
868
Douglas Gregor503384f2012-02-09 00:47:04 +0000869 if (LambdaExprNeedsCleanups)
870 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000871
Douglas Gregore2c59132012-02-09 08:14:43 +0000872 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
873 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000874 ExplicitParams, ExplicitResultType,
875 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +0000876 ArrayIndexStarts, Body->getLocEnd(),
877 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +0000878
879 // C++11 [expr.prim.lambda]p2:
880 // A lambda-expression shall not appear in an unevaluated operand
881 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000882 if (!CurContext->isDependentContext()) {
883 switch (ExprEvalContexts.back().Context) {
884 case Unevaluated:
885 // We don't actually diagnose this case immediately, because we
886 // could be within a context where we might find out later that
887 // the expression is potentially evaluated (e.g., for typeid).
888 ExprEvalContexts.back().Lambdas.push_back(Lambda);
889 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000890
Douglas Gregord5387e82012-02-14 00:00:48 +0000891 case ConstantEvaluated:
892 case PotentiallyEvaluated:
893 case PotentiallyEvaluatedIfUsed:
894 break;
895 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000896 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000897
Douglas Gregor503384f2012-02-09 00:47:04 +0000898 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000899}
Eli Friedman23f02672012-03-01 04:01:32 +0000900
901ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
902 SourceLocation ConvLocation,
903 CXXConversionDecl *Conv,
904 Expr *Src) {
905 // Make sure that the lambda call operator is marked used.
906 CXXRecordDecl *Lambda = Conv->getParent();
907 CXXMethodDecl *CallOperator
908 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +0000909 Lambda->lookup(
910 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +0000911 CallOperator->setReferenced();
912 CallOperator->setUsed();
913
914 ExprResult Init = PerformCopyInitialization(
915 InitializedEntity::InitializeBlock(ConvLocation,
916 Src->getType(),
917 /*NRVO=*/false),
918 CurrentLocation, Src);
919 if (!Init.isInvalid())
920 Init = ActOnFinishFullExpr(Init.take());
921
922 if (Init.isInvalid())
923 return ExprError();
924
925 // Create the new block to be returned.
926 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
927
928 // Set the type information.
929 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
930 Block->setIsVariadic(CallOperator->isVariadic());
931 Block->setBlockMissingReturnType(false);
932
933 // Add parameters.
934 SmallVector<ParmVarDecl *, 4> BlockParams;
935 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
936 ParmVarDecl *From = CallOperator->getParamDecl(I);
937 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
938 From->getLocStart(),
939 From->getLocation(),
940 From->getIdentifier(),
941 From->getType(),
942 From->getTypeSourceInfo(),
943 From->getStorageClass(),
944 From->getStorageClassAsWritten(),
945 /*DefaultArg=*/0));
946 }
947 Block->setParams(BlockParams);
948
949 Block->setIsConversionFromLambda(true);
950
951 // Add capture. The capture uses a fake variable, which doesn't correspond
952 // to any actual memory location. However, the initializer copy-initializes
953 // the lambda object.
954 TypeSourceInfo *CapVarTSI =
955 Context.getTrivialTypeSourceInfo(Src->getType());
956 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
957 ConvLocation, 0,
958 Src->getType(), CapVarTSI,
959 SC_None, SC_None);
960 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
961 /*Nested=*/false, /*Copy=*/Init.take());
962 Block->setCaptures(Context, &Capture, &Capture + 1,
963 /*CapturesCXXThis=*/false);
964
965 // Add a fake function body to the block. IR generation is responsible
966 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +0000967 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +0000968
969 // Create the block literal expression.
970 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
971 ExprCleanupObjects.push_back(Block);
972 ExprNeedsCleanups = true;
973
974 return BuildBlock;
975}