blob: c7ba3cc822f3d83b5c79aa9a38f2badf9e6c770a [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;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000455 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000456 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000457 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
458 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000459 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000460 EndLoc = Intro.Range.getEnd();
461 } else {
462 assert(ParamInfo.isFunctionDeclarator() &&
463 "lambda-declarator is a function");
464 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
465
466 // C++11 [expr.prim.lambda]p5:
467 // This function call operator is declared const (9.3.1) if and only if
468 // the lambda-expression's parameter-declaration-clause is not followed
469 // by mutable. It is neither virtual nor declared volatile. [...]
470 if (!FTI.hasMutableQualifier())
471 FTI.TypeQuals |= DeclSpec::TQ_const;
472
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000473 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000474 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000475 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000476
477 ExplicitResultType
478 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
479 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000480
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000481 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
482 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
483 // Empty arg list, don't push any params.
484 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
485 } else {
486 Params.reserve(FTI.NumArgs);
487 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
488 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
489 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000490
491 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000492 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
493 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000494 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000495
496 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
497 KnownDependent);
498
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000499 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000500 MethodTyInfo, EndLoc, Params);
501
502 if (ExplicitParams)
503 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000504
Bill Wendlingad017fa2012-12-20 19:22:21 +0000505 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000506 ProcessDeclAttributes(CurScope, Method, ParamInfo);
507
Douglas Gregor503384f2012-02-09 00:47:04 +0000508 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000509 PushDeclContext(CurScope, Method);
510
511 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000512 LambdaScopeInfo *LSI
513 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
514 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000515 !Method->isConst());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000516
517 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000518 SourceLocation PrevCaptureLoc
519 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000520 for (SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000521 C = Intro.Captures.begin(),
522 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000523 C != E;
524 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000525 if (C->Kind == LCK_This) {
526 // C++11 [expr.prim.lambda]p8:
527 // An identifier or this shall not appear more than once in a
528 // lambda-capture.
529 if (LSI->isCXXThisCaptured()) {
530 Diag(C->Loc, diag::err_capture_more_than_once)
531 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000532 << SourceRange(LSI->getCXXThisCapture().getLocation())
533 << FixItHint::CreateRemoval(
534 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000535 continue;
536 }
537
538 // C++11 [expr.prim.lambda]p8:
539 // If a lambda-capture includes a capture-default that is =, the
540 // lambda-capture shall not contain this [...].
541 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000542 Diag(C->Loc, diag::err_this_capture_with_copy_default)
543 << FixItHint::CreateRemoval(
544 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000545 continue;
546 }
547
548 // C++11 [expr.prim.lambda]p12:
549 // If this is captured by a local lambda expression, its nearest
550 // enclosing function shall be a non-static member function.
551 QualType ThisCaptureType = getCurrentThisType();
552 if (ThisCaptureType.isNull()) {
553 Diag(C->Loc, diag::err_this_capture) << true;
554 continue;
555 }
556
557 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
558 continue;
559 }
560
561 assert(C->Id && "missing identifier for capture");
562
563 // C++11 [expr.prim.lambda]p8:
564 // If a lambda-capture includes a capture-default that is &, the
565 // identifiers in the lambda-capture shall not be preceded by &.
566 // If a lambda-capture includes a capture-default that is =, [...]
567 // each identifier it contains shall be preceded by &.
568 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000569 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
570 << FixItHint::CreateRemoval(
571 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000572 continue;
573 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000574 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
575 << FixItHint::CreateRemoval(
576 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000577 continue;
578 }
579
580 DeclarationNameInfo Name(C->Id, C->Loc);
581 LookupResult R(*this, Name, LookupOrdinaryName);
582 LookupName(R, CurScope);
583 if (R.isAmbiguous())
584 continue;
585 if (R.empty()) {
586 // FIXME: Disable corrections that would add qualification?
587 CXXScopeSpec ScopeSpec;
588 DeclFilterCCC<VarDecl> Validator;
589 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
590 continue;
591 }
592
593 // C++11 [expr.prim.lambda]p10:
594 // The identifiers in a capture-list are looked up using the usual rules
595 // for unqualified name lookup (3.4.1); each such lookup shall find a
596 // variable with automatic storage duration declared in the reaching
597 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000598 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000599 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000600 VarDecl *Var = R.getAsSingle<VarDecl>();
601 if (!Var) {
602 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
603 continue;
604 }
605
Eli Friedman9cd5b242012-09-18 21:11:30 +0000606 // Ignore invalid decls; they'll just confuse the code later.
607 if (Var->isInvalidDecl())
608 continue;
609
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 if (!Var->hasLocalStorage()) {
611 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
612 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
613 continue;
614 }
615
616 // C++11 [expr.prim.lambda]p8:
617 // An identifier or this shall not appear more than once in a
618 // lambda-capture.
619 if (LSI->isCaptured(Var)) {
620 Diag(C->Loc, diag::err_capture_more_than_once)
621 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000622 << SourceRange(LSI->getCapture(Var).getLocation())
623 << FixItHint::CreateRemoval(
624 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000625 continue;
626 }
627
Douglas Gregora7365242012-02-14 19:27:52 +0000628 // C++11 [expr.prim.lambda]p23:
629 // A capture followed by an ellipsis is a pack expansion (14.5.3).
630 SourceLocation EllipsisLoc;
631 if (C->EllipsisLoc.isValid()) {
632 if (Var->isParameterPack()) {
633 EllipsisLoc = C->EllipsisLoc;
634 } else {
635 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636 << SourceRange(C->Loc);
637
638 // Just ignore the ellipsis.
639 }
640 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000641 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000642 }
643
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000644 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
645 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000646 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000647 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000648 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000649
Richard Smith612409e2012-07-25 03:56:55 +0000650 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
651
Douglas Gregorc6889e72012-02-14 22:28:59 +0000652 // Add lambda parameters into scope.
653 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000654
Douglas Gregordfca6f52012-02-13 22:00:16 +0000655 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000656 // cleanups from the enclosing full-expression.
657 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000658}
659
Douglas Gregordfca6f52012-02-13 22:00:16 +0000660void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
661 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000662 // Leave the expression-evaluation context.
663 DiscardCleanupsInEvaluationContext();
664 PopExpressionEvaluationContext();
665
666 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000667 if (!IsInstantiation)
668 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000669
670 // Finalize the lambda.
671 LambdaScopeInfo *LSI = getCurLambda();
672 CXXRecordDecl *Class = LSI->Lambda;
673 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000674 SmallVector<Decl*, 4> Fields;
675 for (RecordDecl::field_iterator i = Class->field_begin(),
676 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000677 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000678 ActOnFields(0, Class->getLocation(), Class, Fields,
679 SourceLocation(), SourceLocation(), 0);
680 CheckCompletedCXXClass(Class);
681
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000682 PopFunctionScopeInfo();
683}
684
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000685/// \brief Add a lambda's conversion to function pointer, as described in
686/// C++11 [expr.prim.lambda]p6.
687static void addFunctionPointerConversion(Sema &S,
688 SourceRange IntroducerRange,
689 CXXRecordDecl *Class,
690 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000691 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000692 const FunctionProtoType *Proto
693 = CallOperator->getType()->getAs<FunctionProtoType>();
694 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000695 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000696 {
697 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
698 ExtInfo.TypeQuals = 0;
Jordan Rosebea522f2013-03-08 21:51:21 +0000699 FunctionTy =
700 S.Context.getFunctionType(Proto->getResultType(),
701 ArrayRef<QualType>(Proto->arg_type_begin(),
702 Proto->getNumArgs()),
703 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000704 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
705 }
706
707 FunctionProtoType::ExtProtoInfo ExtInfo;
708 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000709 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000710 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000711
712 SourceLocation Loc = IntroducerRange.getBegin();
713 DeclarationName Name
714 = S.Context.DeclarationNames.getCXXConversionFunctionName(
715 S.Context.getCanonicalType(FunctionPtrTy));
716 DeclarationNameLoc NameLoc;
717 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
718 Loc);
719 CXXConversionDecl *Conversion
720 = CXXConversionDecl::Create(S.Context, Class, Loc,
721 DeclarationNameInfo(Name, Loc, NameLoc),
722 ConvTy,
723 S.Context.getTrivialTypeSourceInfo(ConvTy,
724 Loc),
725 /*isInline=*/false, /*isExplicit=*/false,
726 /*isConstexpr=*/false,
727 CallOperator->getBody()->getLocEnd());
728 Conversion->setAccess(AS_public);
729 Conversion->setImplicit(true);
730 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000731
732 // Add a non-static member function "__invoke" that will be the result of
733 // the conversion.
734 Name = &S.Context.Idents.get("__invoke");
735 CXXMethodDecl *Invoke
736 = CXXMethodDecl::Create(S.Context, Class, Loc,
737 DeclarationNameInfo(Name, Loc), FunctionTy,
738 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000739 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000740 /*IsConstexpr=*/false,
741 CallOperator->getBody()->getLocEnd());
742 SmallVector<ParmVarDecl *, 4> InvokeParams;
743 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
744 ParmVarDecl *From = CallOperator->getParamDecl(I);
745 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
746 From->getLocStart(),
747 From->getLocation(),
748 From->getIdentifier(),
749 From->getType(),
750 From->getTypeSourceInfo(),
751 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000752 /*DefaultArg=*/0));
753 }
754 Invoke->setParams(InvokeParams);
755 Invoke->setAccess(AS_private);
756 Invoke->setImplicit(true);
757 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000758}
759
Douglas Gregorc2956e52012-02-15 22:08:38 +0000760/// \brief Add a lambda's conversion to block pointer.
761static void addBlockPointerConversion(Sema &S,
762 SourceRange IntroducerRange,
763 CXXRecordDecl *Class,
764 CXXMethodDecl *CallOperator) {
765 const FunctionProtoType *Proto
766 = CallOperator->getType()->getAs<FunctionProtoType>();
767 QualType BlockPtrTy;
768 {
769 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
770 ExtInfo.TypeQuals = 0;
771 QualType FunctionTy
772 = S.Context.getFunctionType(Proto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +0000773 ArrayRef<QualType>(Proto->arg_type_begin(),
774 Proto->getNumArgs()),
Douglas Gregorc2956e52012-02-15 22:08:38 +0000775 ExtInfo);
776 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
777 }
778
779 FunctionProtoType::ExtProtoInfo ExtInfo;
780 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000781 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000782
783 SourceLocation Loc = IntroducerRange.getBegin();
784 DeclarationName Name
785 = S.Context.DeclarationNames.getCXXConversionFunctionName(
786 S.Context.getCanonicalType(BlockPtrTy));
787 DeclarationNameLoc NameLoc;
788 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
789 CXXConversionDecl *Conversion
790 = CXXConversionDecl::Create(S.Context, Class, Loc,
791 DeclarationNameInfo(Name, Loc, NameLoc),
792 ConvTy,
793 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
794 /*isInline=*/false, /*isExplicit=*/false,
795 /*isConstexpr=*/false,
796 CallOperator->getBody()->getLocEnd());
797 Conversion->setAccess(AS_public);
798 Conversion->setImplicit(true);
799 Class->addDecl(Conversion);
800}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000801
Douglas Gregordfca6f52012-02-13 22:00:16 +0000802ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000803 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000804 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000805 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000806 SmallVector<LambdaExpr::Capture, 4> Captures;
807 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000808 LambdaCaptureDefault CaptureDefault;
809 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000810 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000811 SourceRange IntroducerRange;
812 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000813 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000814 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000815 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000816 SmallVector<VarDecl *, 4> ArrayIndexVars;
817 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000818 {
819 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000820 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000821 Class = LSI->Lambda;
822 IntroducerRange = LSI->IntroducerRange;
823 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000824 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000825 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000826 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000827 ArrayIndexVars.swap(LSI->ArrayIndexVars);
828 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
829
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000830 // Translate captures.
831 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
832 LambdaScopeInfo::Capture From = LSI->Captures[I];
833 assert(!From.isBlockCapture() && "Cannot capture __block variables");
834 bool IsImplicit = I >= LSI->NumExplicitCaptures;
835
836 // Handle 'this' capture.
837 if (From.isThisCapture()) {
838 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
839 IsImplicit,
840 LCK_This));
841 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
842 getCurrentThisType(),
843 /*isImplicit=*/true));
844 continue;
845 }
846
847 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000848 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
849 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000850 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000851 CaptureInits.push_back(From.getCopyExpr());
852 }
853
854 switch (LSI->ImpCaptureStyle) {
855 case CapturingScopeInfo::ImpCap_None:
856 CaptureDefault = LCD_None;
857 break;
858
859 case CapturingScopeInfo::ImpCap_LambdaByval:
860 CaptureDefault = LCD_ByCopy;
861 break;
862
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000863 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000864 case CapturingScopeInfo::ImpCap_LambdaByref:
865 CaptureDefault = LCD_ByRef;
866 break;
867
868 case CapturingScopeInfo::ImpCap_Block:
869 llvm_unreachable("block capture in lambda");
870 break;
871 }
872
Douglas Gregor54042f12012-02-09 10:18:50 +0000873 // C++11 [expr.prim.lambda]p4:
874 // If a lambda-expression does not include a
875 // trailing-return-type, it is as if the trailing-return-type
876 // denotes the following type:
877 // FIXME: Assumes current resolution to core issue 975.
878 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000879 deduceClosureReturnType(*LSI);
880
Douglas Gregor54042f12012-02-09 10:18:50 +0000881 // - if there are no return statements in the
882 // compound-statement, or all return statements return
883 // either an expression of type void or no expression or
884 // braced-init-list, the type void;
885 if (LSI->ReturnType.isNull()) {
886 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000887 }
888
889 // Create a function type with the inferred return type.
890 const FunctionProtoType *Proto
891 = CallOperator->getType()->getAs<FunctionProtoType>();
892 QualType FunctionTy
893 = Context.getFunctionType(LSI->ReturnType,
Jordan Rosebea522f2013-03-08 21:51:21 +0000894 ArrayRef<QualType>(Proto->arg_type_begin(),
895 Proto->getNumArgs()),
Douglas Gregor54042f12012-02-09 10:18:50 +0000896 Proto->getExtProtoInfo());
897 CallOperator->setType(FunctionTy);
898 }
899
Douglas Gregor215e4e12012-02-12 17:34:23 +0000900 // C++ [expr.prim.lambda]p7:
901 // The lambda-expression's compound-statement yields the
902 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000903 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000904 CallOperator->setLexicalDeclContext(Class);
905 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000906 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000907
Douglas Gregorb5559712012-02-10 16:13:20 +0000908 // C++11 [expr.prim.lambda]p6:
909 // The closure type for a lambda-expression with no lambda-capture
910 // has a public non-virtual non-explicit const conversion function
911 // to pointer to function having the same parameter and return
912 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000913 if (Captures.empty() && CaptureDefault == LCD_None)
914 addFunctionPointerConversion(*this, IntroducerRange, Class,
915 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000916
Douglas Gregorc2956e52012-02-15 22:08:38 +0000917 // Objective-C++:
918 // The closure type for a lambda-expression has a public non-virtual
919 // non-explicit const conversion function to a block pointer having the
920 // same parameter and return types as the closure type's function call
921 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000922 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000923 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
924
Douglas Gregorb5559712012-02-10 16:13:20 +0000925 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000926 SmallVector<Decl*, 4> Fields;
927 for (RecordDecl::field_iterator i = Class->field_begin(),
928 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000929 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000930 ActOnFields(0, Class->getLocation(), Class, Fields,
931 SourceLocation(), SourceLocation(), 0);
932 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000933 }
934
Douglas Gregor503384f2012-02-09 00:47:04 +0000935 if (LambdaExprNeedsCleanups)
936 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000937
Douglas Gregore2c59132012-02-09 08:14:43 +0000938 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
939 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000940 ExplicitParams, ExplicitResultType,
941 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +0000942 ArrayIndexStarts, Body->getLocEnd(),
943 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +0000944
945 // C++11 [expr.prim.lambda]p2:
946 // A lambda-expression shall not appear in an unevaluated operand
947 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000948 if (!CurContext->isDependentContext()) {
949 switch (ExprEvalContexts.back().Context) {
950 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +0000951 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +0000952 // We don't actually diagnose this case immediately, because we
953 // could be within a context where we might find out later that
954 // the expression is potentially evaluated (e.g., for typeid).
955 ExprEvalContexts.back().Lambdas.push_back(Lambda);
956 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000957
Douglas Gregord5387e82012-02-14 00:00:48 +0000958 case ConstantEvaluated:
959 case PotentiallyEvaluated:
960 case PotentiallyEvaluatedIfUsed:
961 break;
962 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000963 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000964
Douglas Gregor503384f2012-02-09 00:47:04 +0000965 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000966}
Eli Friedman23f02672012-03-01 04:01:32 +0000967
968ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
969 SourceLocation ConvLocation,
970 CXXConversionDecl *Conv,
971 Expr *Src) {
972 // Make sure that the lambda call operator is marked used.
973 CXXRecordDecl *Lambda = Conv->getParent();
974 CXXMethodDecl *CallOperator
975 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +0000976 Lambda->lookup(
977 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +0000978 CallOperator->setReferenced();
979 CallOperator->setUsed();
980
981 ExprResult Init = PerformCopyInitialization(
982 InitializedEntity::InitializeBlock(ConvLocation,
983 Src->getType(),
984 /*NRVO=*/false),
985 CurrentLocation, Src);
986 if (!Init.isInvalid())
987 Init = ActOnFinishFullExpr(Init.take());
988
989 if (Init.isInvalid())
990 return ExprError();
991
992 // Create the new block to be returned.
993 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
994
995 // Set the type information.
996 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
997 Block->setIsVariadic(CallOperator->isVariadic());
998 Block->setBlockMissingReturnType(false);
999
1000 // Add parameters.
1001 SmallVector<ParmVarDecl *, 4> BlockParams;
1002 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1003 ParmVarDecl *From = CallOperator->getParamDecl(I);
1004 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1005 From->getLocStart(),
1006 From->getLocation(),
1007 From->getIdentifier(),
1008 From->getType(),
1009 From->getTypeSourceInfo(),
1010 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001011 /*DefaultArg=*/0));
1012 }
1013 Block->setParams(BlockParams);
1014
1015 Block->setIsConversionFromLambda(true);
1016
1017 // Add capture. The capture uses a fake variable, which doesn't correspond
1018 // to any actual memory location. However, the initializer copy-initializes
1019 // the lambda object.
1020 TypeSourceInfo *CapVarTSI =
1021 Context.getTrivialTypeSourceInfo(Src->getType());
1022 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1023 ConvLocation, 0,
1024 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001025 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001026 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1027 /*Nested=*/false, /*Copy=*/Init.take());
1028 Block->setCaptures(Context, &Capture, &Capture + 1,
1029 /*CapturesCXXThis=*/false);
1030
1031 // Add a fake function body to the block. IR generation is responsible
1032 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001033 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001034
1035 // Create the block literal expression.
1036 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1037 ExprCleanupObjects.push_back(Block);
1038 ExprNeedsCleanups = true;
1039
1040 return BuildBlock;
1041}