blob: 77e6bfd086652d282133843a072fed48b55eec4a [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,
Douglas Gregordfca6f52012-02-13 22:00:16 +000077 SC_None,
78 /*isInline=*/true,
79 /*isConstExpr=*/false,
80 EndLoc);
81 Method->setAccess(AS_public);
82
83 // Temporarily set the lexical declaration context to the current
84 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000085 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000086
Douglas Gregorc6889e72012-02-14 22:28:59 +000087 // Add parameters.
88 if (!Params.empty()) {
89 Method->setParams(Params);
90 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
91 const_cast<ParmVarDecl **>(Params.end()),
92 /*CheckParameterNames=*/false);
93
94 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
95 PEnd = Method->param_end();
96 P != PEnd; ++P)
97 (*P)->setOwningFunction(Method);
98 }
Richard Smithadb1d4c2012-07-22 23:45:10 +000099
100 // Allocate a mangling number for this lambda expression, if the ABI
101 // requires one.
102 Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
103
104 enum ContextKind {
105 Normal,
106 DefaultArgument,
107 DataMember,
108 StaticDataMember
109 } Kind = Normal;
110
111 // Default arguments of member function parameters that appear in a class
112 // definition, as well as the initializers of data members, receive special
113 // treatment. Identify them.
114 if (ContextDecl) {
115 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
116 if (const DeclContext *LexicalDC
117 = Param->getDeclContext()->getLexicalParent())
118 if (LexicalDC->isRecord())
119 Kind = DefaultArgument;
120 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
121 if (Var->getDeclContext()->isRecord())
122 Kind = StaticDataMember;
123 } else if (isa<FieldDecl>(ContextDecl)) {
124 Kind = DataMember;
Douglas Gregorf54486a2012-04-04 17:40:10 +0000125 }
126 }
127
Richard Smithadb1d4c2012-07-22 23:45:10 +0000128 // Itanium ABI [5.1.7]:
129 // In the following contexts [...] the one-definition rule requires closure
130 // types in different translation units to "correspond":
131 bool IsInNonspecializedTemplate =
132 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
133 unsigned ManglingNumber;
134 switch (Kind) {
135 case Normal:
136 // -- the bodies of non-exported nonspecialized template functions
137 // -- the bodies of inline functions
138 if ((IsInNonspecializedTemplate &&
139 !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
140 isInInlineFunction(CurContext))
141 ManglingNumber = Context.getLambdaManglingNumber(Method);
142 else
143 ManglingNumber = 0;
144
145 // There is no special context for this lambda.
146 ContextDecl = 0;
147 break;
148
149 case StaticDataMember:
150 // -- the initializers of nonspecialized static members of template classes
151 if (!IsInNonspecializedTemplate) {
152 ManglingNumber = 0;
153 ContextDecl = 0;
154 break;
155 }
156 // Fall through to assign a mangling number.
157
158 case DataMember:
159 // -- the in-class initializers of class members
160 case DefaultArgument:
161 // -- default arguments appearing in class definitions
162 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
163 .getManglingNumber(Method);
164 break;
165 }
166
167 Class->setLambdaMangling(ManglingNumber, ContextDecl);
168
Douglas Gregordfca6f52012-02-13 22:00:16 +0000169 return Method;
170}
171
172LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
173 SourceRange IntroducerRange,
174 LambdaCaptureDefault CaptureDefault,
175 bool ExplicitParams,
176 bool ExplicitResultType,
177 bool Mutable) {
178 PushLambdaScope(CallOperator->getParent(), CallOperator);
179 LambdaScopeInfo *LSI = getCurLambda();
180 if (CaptureDefault == LCD_ByCopy)
181 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
182 else if (CaptureDefault == LCD_ByRef)
183 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
184 LSI->IntroducerRange = IntroducerRange;
185 LSI->ExplicitParams = ExplicitParams;
186 LSI->Mutable = Mutable;
187
188 if (ExplicitResultType) {
189 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000190
191 if (!LSI->ReturnType->isDependentType() &&
192 !LSI->ReturnType->isVoidType()) {
193 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
194 diag::err_lambda_incomplete_result)) {
195 // Do nothing.
196 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
197 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
198 << LSI->ReturnType;
199 }
200 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000201 } else {
202 LSI->HasImplicitReturnType = true;
203 }
204
205 return LSI;
206}
207
208void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
209 LSI->finishedExplicitCaptures();
210}
211
Douglas Gregorc6889e72012-02-14 22:28:59 +0000212void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000213 // Introduce our parameters into the function scope
214 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
215 p < NumParams; ++p) {
216 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000217
218 // If this has an identifier, add it to the scope stack.
219 if (CurScope && Param->getIdentifier()) {
220 CheckShadow(CurScope, Param);
221
222 PushOnScopeChains(Param, CurScope);
223 }
224 }
225}
226
John McCall41d01642013-03-09 00:54:31 +0000227/// If this expression is an enumerator-like expression of some type
228/// T, return the type T; otherwise, return null.
229///
230/// Pointer comparisons on the result here should always work because
231/// it's derived from either the parent of an EnumConstantDecl
232/// (i.e. the definition) or the declaration returned by
233/// EnumType::getDecl() (i.e. the definition).
234static EnumDecl *findEnumForBlockReturn(Expr *E) {
235 // An expression is an enumerator-like expression of type T if,
236 // ignoring parens and parens-like expressions:
237 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000238
John McCall41d01642013-03-09 00:54:31 +0000239 // - it is an enumerator whose enum type is T or
240 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
241 if (EnumConstantDecl *D
242 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
243 return cast<EnumDecl>(D->getDeclContext());
244 }
245 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000246 }
247
John McCall41d01642013-03-09 00:54:31 +0000248 // - it is a comma expression whose RHS is an enumerator-like
249 // expression of type T or
250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
251 if (BO->getOpcode() == BO_Comma)
252 return findEnumForBlockReturn(BO->getRHS());
253 return 0;
254 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000255
John McCall41d01642013-03-09 00:54:31 +0000256 // - it is a statement-expression whose value expression is an
257 // enumerator-like expression of type T or
258 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
259 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
260 return findEnumForBlockReturn(last);
261 return 0;
262 }
263
264 // - it is a ternary conditional operator (not the GNU ?:
265 // extension) whose second and third operands are
266 // enumerator-like expressions of type T or
267 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
268 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
269 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
270 return ED;
271 return 0;
272 }
273
274 // (implicitly:)
275 // - it is an implicit integral conversion applied to an
276 // enumerator-like expression of type T or
277 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
278 // We can only see integral conversions in valid enumerator-like
279 // expressions.
280 if (ICE->getCastKind() == CK_IntegralCast)
281 return findEnumForBlockReturn(ICE->getSubExpr());
282 return 0;
283 }
284
285 // - it is an expression of that formal enum type.
286 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
287 return ET->getDecl();
288 }
289
290 // Otherwise, nope.
291 return 0;
292}
293
294/// Attempt to find a type T for which the returned expression of the
295/// given statement is an enumerator-like expression of that type.
296static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
297 if (Expr *retValue = ret->getRetValue())
298 return findEnumForBlockReturn(retValue);
299 return 0;
300}
301
302/// Attempt to find a common type T for which all of the returned
303/// expressions in a block are enumerator-like expressions of that
304/// type.
305static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
306 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
307
308 // Try to find one for the first return.
309 EnumDecl *ED = findEnumForBlockReturn(*i);
310 if (!ED) return 0;
311
312 // Check that the rest of the returns have the same enum.
313 for (++i; i != e; ++i) {
314 if (findEnumForBlockReturn(*i) != ED)
315 return 0;
316 }
317
318 // Never infer an anonymous enum type.
319 if (!ED->hasNameForLinkage()) return 0;
320
321 return ED;
322}
323
324/// Adjust the given return statements so that they formally return
325/// the given type. It should require, at most, an IntegralCast.
326static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
327 QualType returnType) {
328 for (ArrayRef<ReturnStmt*>::iterator
329 i = returns.begin(), e = returns.end(); i != e; ++i) {
330 ReturnStmt *ret = *i;
331 Expr *retValue = ret->getRetValue();
332 if (S.Context.hasSameType(retValue->getType(), returnType))
333 continue;
334
335 // Right now we only support integral fixup casts.
336 assert(returnType->isIntegralOrUnscopedEnumerationType());
337 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
338
339 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
340
341 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
342 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
343 E, /*base path*/ 0, VK_RValue);
344 if (cleanups) {
345 cleanups->setSubExpr(E);
346 } else {
347 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000348 }
349 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000350}
351
352void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
353 assert(CSI.HasImplicitReturnType);
354
John McCall41d01642013-03-09 00:54:31 +0000355 // C++ Core Issue #975, proposed resolution:
356 // If a lambda-expression does not include a trailing-return-type,
357 // it is as if the trailing-return-type denotes the following type:
358 // - if there are no return statements in the compound-statement,
359 // or all return statements return either an expression of type
360 // void or no expression or braced-init-list, the type void;
361 // - otherwise, if all return statements return an expression
362 // and the types of the returned expressions after
363 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
364 // array-to-pointer conversion (4.2 [conv.array]), and
365 // function-to-pointer conversion (4.3 [conv.func]) are the
366 // same, that common type;
367 // - otherwise, the program is ill-formed.
368 //
369 // In addition, in blocks in non-C++ modes, if all of the return
370 // statements are enumerator-like expressions of some type T, where
371 // T has a name for linkage, then we infer the return type of the
372 // block to be that type.
373
Jordan Rose7dd900e2012-07-02 21:19:23 +0000374 // First case: no return statements, implicit void return type.
375 ASTContext &Ctx = getASTContext();
376 if (CSI.Returns.empty()) {
377 // It's possible there were simply no /valid/ return statements.
378 // In this case, the first one we found may have at least given us a type.
379 if (CSI.ReturnType.isNull())
380 CSI.ReturnType = Ctx.VoidTy;
381 return;
382 }
383
384 // Second case: at least one return statement has dependent type.
385 // Delay type checking until instantiation.
386 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
387 if (CSI.ReturnType->isDependentType())
388 return;
389
John McCall41d01642013-03-09 00:54:31 +0000390 // Try to apply the enum-fuzz rule.
391 if (!getLangOpts().CPlusPlus) {
392 assert(isa<BlockScopeInfo>(CSI));
393 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
394 if (ED) {
395 CSI.ReturnType = Context.getTypeDeclType(ED);
396 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
397 return;
398 }
399 }
400
Jordan Rose7dd900e2012-07-02 21:19:23 +0000401 // Third case: only one return statement. Don't bother doing extra work!
402 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
403 E = CSI.Returns.end();
404 if (I+1 == E)
405 return;
406
407 // General case: many return statements.
408 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000409
410 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000411 // Note that we've already done the required promotions as part of
412 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000413 for (; I != E; ++I) {
414 const ReturnStmt *RS = *I;
415 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000416
John McCall41d01642013-03-09 00:54:31 +0000417 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
418 if (Context.hasSameType(ReturnType, CSI.ReturnType))
419 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000420
John McCall41d01642013-03-09 00:54:31 +0000421 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
422 // TODO: It's possible that the *first* return is the divergent one.
423 Diag(RS->getLocStart(),
424 diag::err_typecheck_missing_return_type_incompatible)
425 << ReturnType << CSI.ReturnType
426 << isa<LambdaScopeInfo>(CSI);
427 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000428 }
429}
430
Douglas Gregordfca6f52012-02-13 22:00:16 +0000431void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
432 Declarator &ParamInfo,
433 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000434 // Determine if we're within a context where we know that the lambda will
435 // be dependent, because there are template parameters in scope.
436 bool KnownDependent = false;
437 if (Scope *TmplScope = CurScope->getTemplateParamParent())
438 if (!TmplScope->decl_empty())
439 KnownDependent = true;
440
Douglas Gregordfca6f52012-02-13 22:00:16 +0000441 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000442 TypeSourceInfo *MethodTyInfo;
443 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000444 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000445 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000446 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000447 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000448 if (ParamInfo.getNumTypeObjects() == 0) {
449 // C++11 [expr.prim.lambda]p4:
450 // If a lambda-expression does not include a lambda-declarator, it is as
451 // if the lambda-declarator were ().
452 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000453 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000454 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000455 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
Jordan Rosebea522f2013-03-08 21:51:21 +0000456 ArrayRef<QualType>(),
457 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000458 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
459 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000460 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000461 EndLoc = Intro.Range.getEnd();
462 } else {
463 assert(ParamInfo.isFunctionDeclarator() &&
464 "lambda-declarator is a function");
465 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
466
467 // C++11 [expr.prim.lambda]p5:
468 // This function call operator is declared const (9.3.1) if and only if
469 // the lambda-expression's parameter-declaration-clause is not followed
470 // by mutable. It is neither virtual nor declared volatile. [...]
471 if (!FTI.hasMutableQualifier())
472 FTI.TypeQuals |= DeclSpec::TQ_const;
473
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000474 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000475 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000476 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000477
478 ExplicitResultType
479 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
480 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000481
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000482 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
483 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
484 // Empty arg list, don't push any params.
485 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
486 } else {
487 Params.reserve(FTI.NumArgs);
488 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
489 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
490 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000491
492 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000493 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
494 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000495 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000496
497 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
498 KnownDependent);
499
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000500 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000501 MethodTyInfo, EndLoc, Params);
502
503 if (ExplicitParams)
504 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000505
Bill Wendlingad017fa2012-12-20 19:22:21 +0000506 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000507 ProcessDeclAttributes(CurScope, Method, ParamInfo);
508
Douglas Gregor503384f2012-02-09 00:47:04 +0000509 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000510 PushDeclContext(CurScope, Method);
511
512 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000513 LambdaScopeInfo *LSI
514 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
515 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000516 !Method->isConst());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000517
518 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000519 SourceLocation PrevCaptureLoc
520 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000521 for (SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000522 C = Intro.Captures.begin(),
523 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000524 C != E;
525 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000526 if (C->Kind == LCK_This) {
527 // C++11 [expr.prim.lambda]p8:
528 // An identifier or this shall not appear more than once in a
529 // lambda-capture.
530 if (LSI->isCXXThisCaptured()) {
531 Diag(C->Loc, diag::err_capture_more_than_once)
532 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000533 << SourceRange(LSI->getCXXThisCapture().getLocation())
534 << FixItHint::CreateRemoval(
535 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000536 continue;
537 }
538
539 // C++11 [expr.prim.lambda]p8:
540 // If a lambda-capture includes a capture-default that is =, the
541 // lambda-capture shall not contain this [...].
542 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000543 Diag(C->Loc, diag::err_this_capture_with_copy_default)
544 << FixItHint::CreateRemoval(
545 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000546 continue;
547 }
548
549 // C++11 [expr.prim.lambda]p12:
550 // If this is captured by a local lambda expression, its nearest
551 // enclosing function shall be a non-static member function.
552 QualType ThisCaptureType = getCurrentThisType();
553 if (ThisCaptureType.isNull()) {
554 Diag(C->Loc, diag::err_this_capture) << true;
555 continue;
556 }
557
558 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
559 continue;
560 }
561
562 assert(C->Id && "missing identifier for capture");
563
564 // C++11 [expr.prim.lambda]p8:
565 // If a lambda-capture includes a capture-default that is &, the
566 // identifiers in the lambda-capture shall not be preceded by &.
567 // If a lambda-capture includes a capture-default that is =, [...]
568 // each identifier it contains shall be preceded by &.
569 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000570 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
571 << FixItHint::CreateRemoval(
572 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000573 continue;
574 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000575 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
576 << FixItHint::CreateRemoval(
577 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000578 continue;
579 }
580
581 DeclarationNameInfo Name(C->Id, C->Loc);
582 LookupResult R(*this, Name, LookupOrdinaryName);
583 LookupName(R, CurScope);
584 if (R.isAmbiguous())
585 continue;
586 if (R.empty()) {
587 // FIXME: Disable corrections that would add qualification?
588 CXXScopeSpec ScopeSpec;
589 DeclFilterCCC<VarDecl> Validator;
590 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
591 continue;
592 }
593
594 // C++11 [expr.prim.lambda]p10:
595 // The identifiers in a capture-list are looked up using the usual rules
596 // for unqualified name lookup (3.4.1); each such lookup shall find a
597 // variable with automatic storage duration declared in the reaching
598 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000599 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000600 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000601 VarDecl *Var = R.getAsSingle<VarDecl>();
602 if (!Var) {
603 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
604 continue;
605 }
606
Eli Friedman9cd5b242012-09-18 21:11:30 +0000607 // Ignore invalid decls; they'll just confuse the code later.
608 if (Var->isInvalidDecl())
609 continue;
610
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000611 if (!Var->hasLocalStorage()) {
612 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
613 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
614 continue;
615 }
616
617 // C++11 [expr.prim.lambda]p8:
618 // An identifier or this shall not appear more than once in a
619 // lambda-capture.
620 if (LSI->isCaptured(Var)) {
621 Diag(C->Loc, diag::err_capture_more_than_once)
622 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000623 << SourceRange(LSI->getCapture(Var).getLocation())
624 << FixItHint::CreateRemoval(
625 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000626 continue;
627 }
628
Douglas Gregora7365242012-02-14 19:27:52 +0000629 // C++11 [expr.prim.lambda]p23:
630 // A capture followed by an ellipsis is a pack expansion (14.5.3).
631 SourceLocation EllipsisLoc;
632 if (C->EllipsisLoc.isValid()) {
633 if (Var->isParameterPack()) {
634 EllipsisLoc = C->EllipsisLoc;
635 } else {
636 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
637 << SourceRange(C->Loc);
638
639 // Just ignore the ellipsis.
640 }
641 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000642 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000643 }
644
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000645 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
646 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000647 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000648 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000649 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000650
Richard Smith612409e2012-07-25 03:56:55 +0000651 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
652
Douglas Gregorc6889e72012-02-14 22:28:59 +0000653 // Add lambda parameters into scope.
654 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000655
Douglas Gregordfca6f52012-02-13 22:00:16 +0000656 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000657 // cleanups from the enclosing full-expression.
658 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000659}
660
Douglas Gregordfca6f52012-02-13 22:00:16 +0000661void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
662 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000663 // Leave the expression-evaluation context.
664 DiscardCleanupsInEvaluationContext();
665 PopExpressionEvaluationContext();
666
667 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000668 if (!IsInstantiation)
669 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000670
671 // Finalize the lambda.
672 LambdaScopeInfo *LSI = getCurLambda();
673 CXXRecordDecl *Class = LSI->Lambda;
674 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000675 SmallVector<Decl*, 4> Fields;
676 for (RecordDecl::field_iterator i = Class->field_begin(),
677 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000678 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000679 ActOnFields(0, Class->getLocation(), Class, Fields,
680 SourceLocation(), SourceLocation(), 0);
681 CheckCompletedCXXClass(Class);
682
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000683 PopFunctionScopeInfo();
684}
685
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000686/// \brief Add a lambda's conversion to function pointer, as described in
687/// C++11 [expr.prim.lambda]p6.
688static void addFunctionPointerConversion(Sema &S,
689 SourceRange IntroducerRange,
690 CXXRecordDecl *Class,
691 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000692 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000693 const FunctionProtoType *Proto
694 = CallOperator->getType()->getAs<FunctionProtoType>();
695 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000696 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000697 {
698 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
699 ExtInfo.TypeQuals = 0;
Jordan Rosebea522f2013-03-08 21:51:21 +0000700 FunctionTy =
701 S.Context.getFunctionType(Proto->getResultType(),
702 ArrayRef<QualType>(Proto->arg_type_begin(),
703 Proto->getNumArgs()),
704 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000705 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
706 }
707
708 FunctionProtoType::ExtProtoInfo ExtInfo;
709 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000710 QualType ConvTy =
711 S.Context.getFunctionType(FunctionPtrTy, ArrayRef<QualType>(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000712
713 SourceLocation Loc = IntroducerRange.getBegin();
714 DeclarationName Name
715 = S.Context.DeclarationNames.getCXXConversionFunctionName(
716 S.Context.getCanonicalType(FunctionPtrTy));
717 DeclarationNameLoc NameLoc;
718 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
719 Loc);
720 CXXConversionDecl *Conversion
721 = CXXConversionDecl::Create(S.Context, Class, Loc,
722 DeclarationNameInfo(Name, Loc, NameLoc),
723 ConvTy,
724 S.Context.getTrivialTypeSourceInfo(ConvTy,
725 Loc),
726 /*isInline=*/false, /*isExplicit=*/false,
727 /*isConstexpr=*/false,
728 CallOperator->getBody()->getLocEnd());
729 Conversion->setAccess(AS_public);
730 Conversion->setImplicit(true);
731 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000732
733 // Add a non-static member function "__invoke" that will be the result of
734 // the conversion.
735 Name = &S.Context.Idents.get("__invoke");
736 CXXMethodDecl *Invoke
737 = CXXMethodDecl::Create(S.Context, Class, Loc,
738 DeclarationNameInfo(Name, Loc), FunctionTy,
739 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000740 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000741 /*IsConstexpr=*/false,
742 CallOperator->getBody()->getLocEnd());
743 SmallVector<ParmVarDecl *, 4> InvokeParams;
744 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
745 ParmVarDecl *From = CallOperator->getParamDecl(I);
746 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
747 From->getLocStart(),
748 From->getLocation(),
749 From->getIdentifier(),
750 From->getType(),
751 From->getTypeSourceInfo(),
752 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000753 /*DefaultArg=*/0));
754 }
755 Invoke->setParams(InvokeParams);
756 Invoke->setAccess(AS_private);
757 Invoke->setImplicit(true);
758 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000759}
760
Douglas Gregorc2956e52012-02-15 22:08:38 +0000761/// \brief Add a lambda's conversion to block pointer.
762static void addBlockPointerConversion(Sema &S,
763 SourceRange IntroducerRange,
764 CXXRecordDecl *Class,
765 CXXMethodDecl *CallOperator) {
766 const FunctionProtoType *Proto
767 = CallOperator->getType()->getAs<FunctionProtoType>();
768 QualType BlockPtrTy;
769 {
770 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
771 ExtInfo.TypeQuals = 0;
772 QualType FunctionTy
773 = S.Context.getFunctionType(Proto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +0000774 ArrayRef<QualType>(Proto->arg_type_begin(),
775 Proto->getNumArgs()),
Douglas Gregorc2956e52012-02-15 22:08:38 +0000776 ExtInfo);
777 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
778 }
779
780 FunctionProtoType::ExtProtoInfo ExtInfo;
781 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000782 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, ArrayRef<QualType>(),
783 ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000784
785 SourceLocation Loc = IntroducerRange.getBegin();
786 DeclarationName Name
787 = S.Context.DeclarationNames.getCXXConversionFunctionName(
788 S.Context.getCanonicalType(BlockPtrTy));
789 DeclarationNameLoc NameLoc;
790 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
791 CXXConversionDecl *Conversion
792 = CXXConversionDecl::Create(S.Context, Class, Loc,
793 DeclarationNameInfo(Name, Loc, NameLoc),
794 ConvTy,
795 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
796 /*isInline=*/false, /*isExplicit=*/false,
797 /*isConstexpr=*/false,
798 CallOperator->getBody()->getLocEnd());
799 Conversion->setAccess(AS_public);
800 Conversion->setImplicit(true);
801 Class->addDecl(Conversion);
802}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000803
Douglas Gregordfca6f52012-02-13 22:00:16 +0000804ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000805 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000806 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000807 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000808 SmallVector<LambdaExpr::Capture, 4> Captures;
809 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000810 LambdaCaptureDefault CaptureDefault;
811 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000812 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000813 SourceRange IntroducerRange;
814 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000815 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000816 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000817 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000818 SmallVector<VarDecl *, 4> ArrayIndexVars;
819 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000820 {
821 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000822 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000823 Class = LSI->Lambda;
824 IntroducerRange = LSI->IntroducerRange;
825 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000826 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000827 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000828 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000829 ArrayIndexVars.swap(LSI->ArrayIndexVars);
830 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
831
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000832 // Translate captures.
833 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
834 LambdaScopeInfo::Capture From = LSI->Captures[I];
835 assert(!From.isBlockCapture() && "Cannot capture __block variables");
836 bool IsImplicit = I >= LSI->NumExplicitCaptures;
837
838 // Handle 'this' capture.
839 if (From.isThisCapture()) {
840 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
841 IsImplicit,
842 LCK_This));
843 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
844 getCurrentThisType(),
845 /*isImplicit=*/true));
846 continue;
847 }
848
849 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000850 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
851 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000852 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000853 CaptureInits.push_back(From.getCopyExpr());
854 }
855
856 switch (LSI->ImpCaptureStyle) {
857 case CapturingScopeInfo::ImpCap_None:
858 CaptureDefault = LCD_None;
859 break;
860
861 case CapturingScopeInfo::ImpCap_LambdaByval:
862 CaptureDefault = LCD_ByCopy;
863 break;
864
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000865 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000866 case CapturingScopeInfo::ImpCap_LambdaByref:
867 CaptureDefault = LCD_ByRef;
868 break;
869
870 case CapturingScopeInfo::ImpCap_Block:
871 llvm_unreachable("block capture in lambda");
872 break;
873 }
874
Douglas Gregor54042f12012-02-09 10:18:50 +0000875 // C++11 [expr.prim.lambda]p4:
876 // If a lambda-expression does not include a
877 // trailing-return-type, it is as if the trailing-return-type
878 // denotes the following type:
879 // FIXME: Assumes current resolution to core issue 975.
880 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000881 deduceClosureReturnType(*LSI);
882
Douglas Gregor54042f12012-02-09 10:18:50 +0000883 // - if there are no return statements in the
884 // compound-statement, or all return statements return
885 // either an expression of type void or no expression or
886 // braced-init-list, the type void;
887 if (LSI->ReturnType.isNull()) {
888 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000889 }
890
891 // Create a function type with the inferred return type.
892 const FunctionProtoType *Proto
893 = CallOperator->getType()->getAs<FunctionProtoType>();
894 QualType FunctionTy
895 = Context.getFunctionType(LSI->ReturnType,
Jordan Rosebea522f2013-03-08 21:51:21 +0000896 ArrayRef<QualType>(Proto->arg_type_begin(),
897 Proto->getNumArgs()),
Douglas Gregor54042f12012-02-09 10:18:50 +0000898 Proto->getExtProtoInfo());
899 CallOperator->setType(FunctionTy);
900 }
901
Douglas Gregor215e4e12012-02-12 17:34:23 +0000902 // C++ [expr.prim.lambda]p7:
903 // The lambda-expression's compound-statement yields the
904 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000905 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000906 CallOperator->setLexicalDeclContext(Class);
907 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000908 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000909
Douglas Gregorb5559712012-02-10 16:13:20 +0000910 // C++11 [expr.prim.lambda]p6:
911 // The closure type for a lambda-expression with no lambda-capture
912 // has a public non-virtual non-explicit const conversion function
913 // to pointer to function having the same parameter and return
914 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000915 if (Captures.empty() && CaptureDefault == LCD_None)
916 addFunctionPointerConversion(*this, IntroducerRange, Class,
917 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000918
Douglas Gregorc2956e52012-02-15 22:08:38 +0000919 // Objective-C++:
920 // The closure type for a lambda-expression has a public non-virtual
921 // non-explicit const conversion function to a block pointer having the
922 // same parameter and return types as the closure type's function call
923 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000924 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000925 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
926
Douglas Gregorb5559712012-02-10 16:13:20 +0000927 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000928 SmallVector<Decl*, 4> Fields;
929 for (RecordDecl::field_iterator i = Class->field_begin(),
930 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000931 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000932 ActOnFields(0, Class->getLocation(), Class, Fields,
933 SourceLocation(), SourceLocation(), 0);
934 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000935 }
936
Douglas Gregor503384f2012-02-09 00:47:04 +0000937 if (LambdaExprNeedsCleanups)
938 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000939
Douglas Gregore2c59132012-02-09 08:14:43 +0000940 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
941 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000942 ExplicitParams, ExplicitResultType,
943 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +0000944 ArrayIndexStarts, Body->getLocEnd(),
945 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +0000946
947 // C++11 [expr.prim.lambda]p2:
948 // A lambda-expression shall not appear in an unevaluated operand
949 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000950 if (!CurContext->isDependentContext()) {
951 switch (ExprEvalContexts.back().Context) {
952 case Unevaluated:
953 // We don't actually diagnose this case immediately, because we
954 // could be within a context where we might find out later that
955 // the expression is potentially evaluated (e.g., for typeid).
956 ExprEvalContexts.back().Lambdas.push_back(Lambda);
957 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000958
Douglas Gregord5387e82012-02-14 00:00:48 +0000959 case ConstantEvaluated:
960 case PotentiallyEvaluated:
961 case PotentiallyEvaluatedIfUsed:
962 break;
963 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000964 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000965
Douglas Gregor503384f2012-02-09 00:47:04 +0000966 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000967}
Eli Friedman23f02672012-03-01 04:01:32 +0000968
969ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
970 SourceLocation ConvLocation,
971 CXXConversionDecl *Conv,
972 Expr *Src) {
973 // Make sure that the lambda call operator is marked used.
974 CXXRecordDecl *Lambda = Conv->getParent();
975 CXXMethodDecl *CallOperator
976 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +0000977 Lambda->lookup(
978 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +0000979 CallOperator->setReferenced();
980 CallOperator->setUsed();
981
982 ExprResult Init = PerformCopyInitialization(
983 InitializedEntity::InitializeBlock(ConvLocation,
984 Src->getType(),
985 /*NRVO=*/false),
986 CurrentLocation, Src);
987 if (!Init.isInvalid())
988 Init = ActOnFinishFullExpr(Init.take());
989
990 if (Init.isInvalid())
991 return ExprError();
992
993 // Create the new block to be returned.
994 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
995
996 // Set the type information.
997 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
998 Block->setIsVariadic(CallOperator->isVariadic());
999 Block->setBlockMissingReturnType(false);
1000
1001 // Add parameters.
1002 SmallVector<ParmVarDecl *, 4> BlockParams;
1003 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1004 ParmVarDecl *From = CallOperator->getParamDecl(I);
1005 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1006 From->getLocStart(),
1007 From->getLocation(),
1008 From->getIdentifier(),
1009 From->getType(),
1010 From->getTypeSourceInfo(),
1011 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001012 /*DefaultArg=*/0));
1013 }
1014 Block->setParams(BlockParams);
1015
1016 Block->setIsConversionFromLambda(true);
1017
1018 // Add capture. The capture uses a fake variable, which doesn't correspond
1019 // to any actual memory location. However, the initializer copy-initializes
1020 // the lambda object.
1021 TypeSourceInfo *CapVarTSI =
1022 Context.getTrivialTypeSourceInfo(Src->getType());
1023 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1024 ConvLocation, 0,
1025 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001026 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001027 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1028 /*Nested=*/false, /*Copy=*/Init.take());
1029 Block->setCaptures(Context, &Capture, &Capture + 1,
1030 /*CapturesCXXThis=*/false);
1031
1032 // Add a fake function body to the block. IR generation is responsible
1033 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001034 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001035
1036 // Create the block literal expression.
1037 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1038 ExprCleanupObjects.push_back(Block);
1039 ExprNeedsCleanups = true;
1040
1041 return BuildBlock;
1042}