blob: 32cc176119d4cd45abea094b9f4e32dc45e53b67 [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"
Richard Smith0d8e9642013-05-16 06:20:58 +000021#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000022using namespace clang;
23using namespace sema;
24
Douglas Gregorf4b7de12012-02-21 19:11:17 +000025CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000026 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000027 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000028 DeclContext *DC = CurContext;
29 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
30 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000031
Douglas Gregore2a7ad02012-02-08 21:18:48 +000032 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000033 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000034 IntroducerRange.getBegin(),
35 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000036 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000037
38 return Class;
39}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000040
Douglas Gregorf54486a2012-04-04 17:40:10 +000041/// \brief Determine whether the given context is or is enclosed in an inline
42/// function.
43static bool isInInlineFunction(const DeclContext *DC) {
44 while (!DC->isFileContext()) {
45 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
46 if (FD->isInlined())
47 return true;
48
49 DC = DC->getLexicalParent();
50 }
51
52 return false;
53}
54
Douglas Gregordfca6f52012-02-13 22:00:16 +000055CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +000056 SourceRange IntroducerRange,
57 TypeSourceInfo *MethodType,
58 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000059 ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000060 // C++11 [expr.prim.lambda]p5:
61 // The closure type for a lambda-expression has a public inline function
62 // call operator (13.5.4) whose parameters and return type are described by
63 // the lambda-expression's parameter-declaration-clause and
64 // trailing-return-type respectively.
65 DeclarationName MethodName
66 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67 DeclarationNameLoc MethodNameLoc;
68 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69 = IntroducerRange.getBegin().getRawEncoding();
70 MethodNameLoc.CXXOperatorName.EndOpNameLoc
71 = IntroducerRange.getEnd().getRawEncoding();
72 CXXMethodDecl *Method
73 = CXXMethodDecl::Create(Context, Class, EndLoc,
74 DeclarationNameInfo(MethodName,
75 IntroducerRange.getBegin(),
76 MethodNameLoc),
77 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +000078 SC_None,
79 /*isInline=*/true,
80 /*isConstExpr=*/false,
81 EndLoc);
82 Method->setAccess(AS_public);
83
84 // Temporarily set the lexical declaration context to the current
85 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000086 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000087
Douglas Gregorc6889e72012-02-14 22:28:59 +000088 // Add parameters.
89 if (!Params.empty()) {
90 Method->setParams(Params);
91 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
92 const_cast<ParmVarDecl **>(Params.end()),
93 /*CheckParameterNames=*/false);
94
95 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
96 PEnd = Method->param_end();
97 P != PEnd; ++P)
98 (*P)->setOwningFunction(Method);
99 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000100
101 // Allocate a mangling number for this lambda expression, if the ABI
102 // requires one.
103 Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
104
105 enum ContextKind {
106 Normal,
107 DefaultArgument,
108 DataMember,
109 StaticDataMember
110 } Kind = Normal;
111
112 // Default arguments of member function parameters that appear in a class
113 // definition, as well as the initializers of data members, receive special
114 // treatment. Identify them.
115 if (ContextDecl) {
116 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
117 if (const DeclContext *LexicalDC
118 = Param->getDeclContext()->getLexicalParent())
119 if (LexicalDC->isRecord())
120 Kind = DefaultArgument;
121 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
122 if (Var->getDeclContext()->isRecord())
123 Kind = StaticDataMember;
124 } else if (isa<FieldDecl>(ContextDecl)) {
125 Kind = DataMember;
Douglas Gregorf54486a2012-04-04 17:40:10 +0000126 }
127 }
128
Richard Smithadb1d4c2012-07-22 23:45:10 +0000129 // Itanium ABI [5.1.7]:
130 // In the following contexts [...] the one-definition rule requires closure
131 // types in different translation units to "correspond":
132 bool IsInNonspecializedTemplate =
133 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
134 unsigned ManglingNumber;
135 switch (Kind) {
136 case Normal:
137 // -- the bodies of non-exported nonspecialized template functions
138 // -- the bodies of inline functions
139 if ((IsInNonspecializedTemplate &&
140 !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
141 isInInlineFunction(CurContext))
142 ManglingNumber = Context.getLambdaManglingNumber(Method);
143 else
144 ManglingNumber = 0;
145
146 // There is no special context for this lambda.
147 ContextDecl = 0;
148 break;
149
150 case StaticDataMember:
151 // -- the initializers of nonspecialized static members of template classes
152 if (!IsInNonspecializedTemplate) {
153 ManglingNumber = 0;
154 ContextDecl = 0;
155 break;
156 }
157 // Fall through to assign a mangling number.
158
159 case DataMember:
160 // -- the in-class initializers of class members
161 case DefaultArgument:
162 // -- default arguments appearing in class definitions
163 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
164 .getManglingNumber(Method);
165 break;
166 }
167
168 Class->setLambdaMangling(ManglingNumber, ContextDecl);
169
Douglas Gregordfca6f52012-02-13 22:00:16 +0000170 return Method;
171}
172
173LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
174 SourceRange IntroducerRange,
175 LambdaCaptureDefault CaptureDefault,
176 bool ExplicitParams,
177 bool ExplicitResultType,
178 bool Mutable) {
179 PushLambdaScope(CallOperator->getParent(), CallOperator);
180 LambdaScopeInfo *LSI = getCurLambda();
181 if (CaptureDefault == LCD_ByCopy)
182 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
183 else if (CaptureDefault == LCD_ByRef)
184 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
185 LSI->IntroducerRange = IntroducerRange;
186 LSI->ExplicitParams = ExplicitParams;
187 LSI->Mutable = Mutable;
188
189 if (ExplicitResultType) {
190 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000191
192 if (!LSI->ReturnType->isDependentType() &&
193 !LSI->ReturnType->isVoidType()) {
194 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
195 diag::err_lambda_incomplete_result)) {
196 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000197 }
198 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000199 } else {
200 LSI->HasImplicitReturnType = true;
201 }
202
203 return LSI;
204}
205
206void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
207 LSI->finishedExplicitCaptures();
208}
209
Douglas Gregorc6889e72012-02-14 22:28:59 +0000210void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000211 // Introduce our parameters into the function scope
212 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
213 p < NumParams; ++p) {
214 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000215
216 // If this has an identifier, add it to the scope stack.
217 if (CurScope && Param->getIdentifier()) {
218 CheckShadow(CurScope, Param);
219
220 PushOnScopeChains(Param, CurScope);
221 }
222 }
223}
224
John McCall41d01642013-03-09 00:54:31 +0000225/// If this expression is an enumerator-like expression of some type
226/// T, return the type T; otherwise, return null.
227///
228/// Pointer comparisons on the result here should always work because
229/// it's derived from either the parent of an EnumConstantDecl
230/// (i.e. the definition) or the declaration returned by
231/// EnumType::getDecl() (i.e. the definition).
232static EnumDecl *findEnumForBlockReturn(Expr *E) {
233 // An expression is an enumerator-like expression of type T if,
234 // ignoring parens and parens-like expressions:
235 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000236
John McCall41d01642013-03-09 00:54:31 +0000237 // - it is an enumerator whose enum type is T or
238 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
239 if (EnumConstantDecl *D
240 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
241 return cast<EnumDecl>(D->getDeclContext());
242 }
243 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000244 }
245
John McCall41d01642013-03-09 00:54:31 +0000246 // - it is a comma expression whose RHS is an enumerator-like
247 // expression of type T or
248 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
249 if (BO->getOpcode() == BO_Comma)
250 return findEnumForBlockReturn(BO->getRHS());
251 return 0;
252 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000253
John McCall41d01642013-03-09 00:54:31 +0000254 // - it is a statement-expression whose value expression is an
255 // enumerator-like expression of type T or
256 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
257 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
258 return findEnumForBlockReturn(last);
259 return 0;
260 }
261
262 // - it is a ternary conditional operator (not the GNU ?:
263 // extension) whose second and third operands are
264 // enumerator-like expressions of type T or
265 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
266 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
267 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
268 return ED;
269 return 0;
270 }
271
272 // (implicitly:)
273 // - it is an implicit integral conversion applied to an
274 // enumerator-like expression of type T or
275 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000276 // We can sometimes see integral conversions in valid
277 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000278 if (ICE->getCastKind() == CK_IntegralCast)
279 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000280
281 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000282 }
283
284 // - it is an expression of that formal enum type.
285 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
286 return ET->getDecl();
287 }
288
289 // Otherwise, nope.
290 return 0;
291}
292
293/// Attempt to find a type T for which the returned expression of the
294/// given statement is an enumerator-like expression of that type.
295static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
296 if (Expr *retValue = ret->getRetValue())
297 return findEnumForBlockReturn(retValue);
298 return 0;
299}
300
301/// Attempt to find a common type T for which all of the returned
302/// expressions in a block are enumerator-like expressions of that
303/// type.
304static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
305 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
306
307 // Try to find one for the first return.
308 EnumDecl *ED = findEnumForBlockReturn(*i);
309 if (!ED) return 0;
310
311 // Check that the rest of the returns have the same enum.
312 for (++i; i != e; ++i) {
313 if (findEnumForBlockReturn(*i) != ED)
314 return 0;
315 }
316
317 // Never infer an anonymous enum type.
318 if (!ED->hasNameForLinkage()) return 0;
319
320 return ED;
321}
322
323/// Adjust the given return statements so that they formally return
324/// the given type. It should require, at most, an IntegralCast.
325static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
326 QualType returnType) {
327 for (ArrayRef<ReturnStmt*>::iterator
328 i = returns.begin(), e = returns.end(); i != e; ++i) {
329 ReturnStmt *ret = *i;
330 Expr *retValue = ret->getRetValue();
331 if (S.Context.hasSameType(retValue->getType(), returnType))
332 continue;
333
334 // Right now we only support integral fixup casts.
335 assert(returnType->isIntegralOrUnscopedEnumerationType());
336 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
337
338 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
339
340 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
341 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
342 E, /*base path*/ 0, VK_RValue);
343 if (cleanups) {
344 cleanups->setSubExpr(E);
345 } else {
346 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000347 }
348 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000349}
350
351void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
352 assert(CSI.HasImplicitReturnType);
353
John McCall41d01642013-03-09 00:54:31 +0000354 // C++ Core Issue #975, proposed resolution:
355 // If a lambda-expression does not include a trailing-return-type,
356 // it is as if the trailing-return-type denotes the following type:
357 // - if there are no return statements in the compound-statement,
358 // or all return statements return either an expression of type
359 // void or no expression or braced-init-list, the type void;
360 // - otherwise, if all return statements return an expression
361 // and the types of the returned expressions after
362 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
363 // array-to-pointer conversion (4.2 [conv.array]), and
364 // function-to-pointer conversion (4.3 [conv.func]) are the
365 // same, that common type;
366 // - otherwise, the program is ill-formed.
367 //
368 // In addition, in blocks in non-C++ modes, if all of the return
369 // statements are enumerator-like expressions of some type T, where
370 // T has a name for linkage, then we infer the return type of the
371 // block to be that type.
372
Jordan Rose7dd900e2012-07-02 21:19:23 +0000373 // First case: no return statements, implicit void return type.
374 ASTContext &Ctx = getASTContext();
375 if (CSI.Returns.empty()) {
376 // It's possible there were simply no /valid/ return statements.
377 // In this case, the first one we found may have at least given us a type.
378 if (CSI.ReturnType.isNull())
379 CSI.ReturnType = Ctx.VoidTy;
380 return;
381 }
382
383 // Second case: at least one return statement has dependent type.
384 // Delay type checking until instantiation.
385 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
386 if (CSI.ReturnType->isDependentType())
387 return;
388
John McCall41d01642013-03-09 00:54:31 +0000389 // Try to apply the enum-fuzz rule.
390 if (!getLangOpts().CPlusPlus) {
391 assert(isa<BlockScopeInfo>(CSI));
392 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
393 if (ED) {
394 CSI.ReturnType = Context.getTypeDeclType(ED);
395 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
396 return;
397 }
398 }
399
Jordan Rose7dd900e2012-07-02 21:19:23 +0000400 // Third case: only one return statement. Don't bother doing extra work!
401 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
402 E = CSI.Returns.end();
403 if (I+1 == E)
404 return;
405
406 // General case: many return statements.
407 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000408
409 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000410 // Note that we've already done the required promotions as part of
411 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000412 for (; I != E; ++I) {
413 const ReturnStmt *RS = *I;
414 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000415
John McCall41d01642013-03-09 00:54:31 +0000416 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
417 if (Context.hasSameType(ReturnType, CSI.ReturnType))
418 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000419
John McCall41d01642013-03-09 00:54:31 +0000420 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
421 // TODO: It's possible that the *first* return is the divergent one.
422 Diag(RS->getLocStart(),
423 diag::err_typecheck_missing_return_type_incompatible)
424 << ReturnType << CSI.ReturnType
425 << isa<LambdaScopeInfo>(CSI);
426 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000427 }
428}
429
Richard Smith0d8e9642013-05-16 06:20:58 +0000430FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
431 IdentifierInfo *Id, Expr *InitExpr) {
432 LambdaScopeInfo *LSI = getCurLambda();
433
434 // C++1y [expr.prim.lambda]p11:
435 // The type of [the] member corresponds to the type of a hypothetical
436 // variable declaration of the form "auto init-capture;"
437 QualType DeductType = Context.getAutoDeductType();
438 TypeLocBuilder TLB;
439 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
440 if (ByRef) {
441 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
442 assert(!DeductType.isNull() && "can't build reference to auto");
443 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
444 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000445 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000446
447 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
448 Expr *Init = InitExpr;
449 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
450 if (Parens->getNumExprs() == 1) {
451 Init = Parens->getExpr(0);
452 InitKind = InitializationKind::CreateDirect(
453 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
454 } else {
455 // C++1y [dcl.spec.auto]p3:
456 // In an initializer of the form ( expression-list ), the
457 // expression-list shall be a single assignment-expression.
458 if (Parens->getNumExprs() == 0)
459 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
460 << Id;
461 else if (Parens->getNumExprs() > 1)
462 Diag(Parens->getExpr(1)->getLocStart(),
463 diag::err_init_capture_multiple_expressions)
464 << Id;
465 return 0;
466 }
467 } else if (isa<InitListExpr>(Init))
468 // We do not need to distinguish between direct-list-initialization
469 // and copy-list-initialization here, because we will always deduce
470 // std::initializer_list<T>, and direct- and copy-list-initialization
471 // always behave the same for such a type.
472 // FIXME: We should model whether an '=' was present.
473 InitKind = InitializationKind::CreateDirectList(Loc);
474 else
475 InitKind = InitializationKind::CreateCopy(Loc, Loc);
476 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000477 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000478 if (isa<InitListExpr>(Init))
479 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
480 << Id << Init->getSourceRange();
481 else
482 Diag(Loc, diag::err_init_capture_deduction_failure)
483 << Id << Init->getType() << Init->getSourceRange();
484 }
485 if (DeducedType.isNull())
486 return 0;
487
488 // [...] a non-static data member named by the identifier is declared in
489 // the closure type. This member is not a bit-field and not mutable.
490 // Core issue: the member is (probably...) public.
491 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000492 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000493 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
494 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
495 LSI->Lambda->addDecl(NewFD);
496
497 if (CurContext->isDependentContext()) {
498 LSI->addInitCapture(NewFD, InitExpr);
499 } else {
500 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
501 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
502 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
503 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
504 if (!InitResult.isInvalid())
505 LSI->addInitCapture(NewFD, InitResult.take());
506 }
507 }
508
509 return NewFD;
510}
511
Douglas Gregordfca6f52012-02-13 22:00:16 +0000512void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
513 Declarator &ParamInfo,
514 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000515 // Determine if we're within a context where we know that the lambda will
516 // be dependent, because there are template parameters in scope.
517 bool KnownDependent = false;
518 if (Scope *TmplScope = CurScope->getTemplateParamParent())
519 if (!TmplScope->decl_empty())
520 KnownDependent = true;
521
Douglas Gregordfca6f52012-02-13 22:00:16 +0000522 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000523 TypeSourceInfo *MethodTyInfo;
524 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000525 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000526 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000527 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000528 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000529 if (ParamInfo.getNumTypeObjects() == 0) {
530 // C++11 [expr.prim.lambda]p4:
531 // If a lambda-expression does not include a lambda-declarator, it is as
532 // if the lambda-declarator were ().
533 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000534 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000535 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000536 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000537 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000538 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
539 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000540 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000541 EndLoc = Intro.Range.getEnd();
542 } else {
543 assert(ParamInfo.isFunctionDeclarator() &&
544 "lambda-declarator is a function");
545 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
546
547 // C++11 [expr.prim.lambda]p5:
548 // This function call operator is declared const (9.3.1) if and only if
549 // the lambda-expression's parameter-declaration-clause is not followed
550 // by mutable. It is neither virtual nor declared volatile. [...]
551 if (!FTI.hasMutableQualifier())
552 FTI.TypeQuals |= DeclSpec::TQ_const;
553
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000554 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000555 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000556 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000557
558 ExplicitResultType
559 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
560 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000561
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000562 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
563 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
564 // Empty arg list, don't push any params.
565 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
566 } else {
567 Params.reserve(FTI.NumArgs);
568 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
569 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
570 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000571
572 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000573 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
574 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000575 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000576
577 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
578 KnownDependent);
579
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000580 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000581 MethodTyInfo, EndLoc, Params);
582
583 if (ExplicitParams)
584 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000585
Bill Wendlingad017fa2012-12-20 19:22:21 +0000586 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000587 ProcessDeclAttributes(CurScope, Method, ParamInfo);
588
Douglas Gregor503384f2012-02-09 00:47:04 +0000589 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000590 PushDeclContext(CurScope, Method);
591
592 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000593 LambdaScopeInfo *LSI
594 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
595 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000596 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000597
598 // Distinct capture names, for diagnostics.
599 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
600
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000601 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000602 SourceLocation PrevCaptureLoc
603 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000604 for (SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000605 C = Intro.Captures.begin(),
606 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000607 C != E;
608 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000609 if (C->Kind == LCK_This) {
610 // C++11 [expr.prim.lambda]p8:
611 // An identifier or this shall not appear more than once in a
612 // lambda-capture.
613 if (LSI->isCXXThisCaptured()) {
614 Diag(C->Loc, diag::err_capture_more_than_once)
615 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000616 << SourceRange(LSI->getCXXThisCapture().getLocation())
617 << FixItHint::CreateRemoval(
618 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000619 continue;
620 }
621
622 // C++11 [expr.prim.lambda]p8:
623 // If a lambda-capture includes a capture-default that is =, the
624 // lambda-capture shall not contain this [...].
625 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000626 Diag(C->Loc, diag::err_this_capture_with_copy_default)
627 << FixItHint::CreateRemoval(
628 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000629 continue;
630 }
631
632 // C++11 [expr.prim.lambda]p12:
633 // If this is captured by a local lambda expression, its nearest
634 // enclosing function shall be a non-static member function.
635 QualType ThisCaptureType = getCurrentThisType();
636 if (ThisCaptureType.isNull()) {
637 Diag(C->Loc, diag::err_this_capture) << true;
638 continue;
639 }
640
641 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
642 continue;
643 }
644
Richard Smith0d8e9642013-05-16 06:20:58 +0000645 assert(C->Id && "missing identifier for capture");
646
Richard Smith0a664b82013-05-09 21:36:41 +0000647 if (C->Init.isInvalid())
648 continue;
649 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000650 // C++11 [expr.prim.lambda]p8:
651 // An identifier or this shall not appear more than once in a
652 // lambda-capture.
653 if (!CaptureNames.insert(C->Id))
654 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
655
656 if (C->Init.get()->containsUnexpandedParameterPack())
657 ContainsUnexpandedParameterPack = true;
658
659 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
660 C->Id, C->Init.take());
661 // C++1y [expr.prim.lambda]p11:
662 // Within the lambda-expression's lambda-declarator and
663 // compound-statement, the identifier in the init-capture
664 // hides any declaration of the same name in scopes enclosing
665 // the lambda-expression.
666 if (NewFD)
667 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000668 continue;
669 }
670
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000671 // C++11 [expr.prim.lambda]p8:
672 // If a lambda-capture includes a capture-default that is &, the
673 // identifiers in the lambda-capture shall not be preceded by &.
674 // If a lambda-capture includes a capture-default that is =, [...]
675 // each identifier it contains shall be preceded by &.
676 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000677 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
678 << FixItHint::CreateRemoval(
679 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000680 continue;
681 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000682 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
683 << FixItHint::CreateRemoval(
684 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000685 continue;
686 }
687
Richard Smith0d8e9642013-05-16 06:20:58 +0000688 // C++11 [expr.prim.lambda]p10:
689 // The identifiers in a capture-list are looked up using the usual
690 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000691 DeclarationNameInfo Name(C->Id, C->Loc);
692 LookupResult R(*this, Name, LookupOrdinaryName);
693 LookupName(R, CurScope);
694 if (R.isAmbiguous())
695 continue;
696 if (R.empty()) {
697 // FIXME: Disable corrections that would add qualification?
698 CXXScopeSpec ScopeSpec;
699 DeclFilterCCC<VarDecl> Validator;
700 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
701 continue;
702 }
703
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000704 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000705
706 // C++11 [expr.prim.lambda]p8:
707 // An identifier or this shall not appear more than once in a
708 // lambda-capture.
709 if (!CaptureNames.insert(C->Id)) {
710 if (Var && LSI->isCaptured(Var)) {
711 Diag(C->Loc, diag::err_capture_more_than_once)
712 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
713 << FixItHint::CreateRemoval(
714 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
715 } else
716 // Previous capture was an init-capture: no fixit.
717 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
718 continue;
719 }
720
721 // C++11 [expr.prim.lambda]p10:
722 // [...] each such lookup shall find a variable with automatic storage
723 // duration declared in the reaching scope of the local lambda expression.
724 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000725 if (!Var) {
726 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
727 continue;
728 }
729
Eli Friedman9cd5b242012-09-18 21:11:30 +0000730 // Ignore invalid decls; they'll just confuse the code later.
731 if (Var->isInvalidDecl())
732 continue;
733
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000734 if (!Var->hasLocalStorage()) {
735 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
736 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
737 continue;
738 }
739
Douglas Gregora7365242012-02-14 19:27:52 +0000740 // C++11 [expr.prim.lambda]p23:
741 // A capture followed by an ellipsis is a pack expansion (14.5.3).
742 SourceLocation EllipsisLoc;
743 if (C->EllipsisLoc.isValid()) {
744 if (Var->isParameterPack()) {
745 EllipsisLoc = C->EllipsisLoc;
746 } else {
747 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
748 << SourceRange(C->Loc);
749
750 // Just ignore the ellipsis.
751 }
752 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000753 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000754 }
755
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000756 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
757 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000758 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000759 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000760 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000761
Richard Smith612409e2012-07-25 03:56:55 +0000762 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
763
Douglas Gregorc6889e72012-02-14 22:28:59 +0000764 // Add lambda parameters into scope.
765 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000766
Douglas Gregordfca6f52012-02-13 22:00:16 +0000767 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000768 // cleanups from the enclosing full-expression.
769 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000770}
771
Douglas Gregordfca6f52012-02-13 22:00:16 +0000772void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
773 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000774 // Leave the expression-evaluation context.
775 DiscardCleanupsInEvaluationContext();
776 PopExpressionEvaluationContext();
777
778 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000779 if (!IsInstantiation)
780 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000781
782 // Finalize the lambda.
783 LambdaScopeInfo *LSI = getCurLambda();
784 CXXRecordDecl *Class = LSI->Lambda;
785 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000786 SmallVector<Decl*, 4> Fields;
787 for (RecordDecl::field_iterator i = Class->field_begin(),
788 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000789 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000790 ActOnFields(0, Class->getLocation(), Class, Fields,
791 SourceLocation(), SourceLocation(), 0);
792 CheckCompletedCXXClass(Class);
793
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000794 PopFunctionScopeInfo();
795}
796
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000797/// \brief Add a lambda's conversion to function pointer, as described in
798/// C++11 [expr.prim.lambda]p6.
799static void addFunctionPointerConversion(Sema &S,
800 SourceRange IntroducerRange,
801 CXXRecordDecl *Class,
802 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000803 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000804 const FunctionProtoType *Proto
805 = CallOperator->getType()->getAs<FunctionProtoType>();
806 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000807 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000808 {
809 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
810 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000811 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
812 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000813 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
814 }
815
816 FunctionProtoType::ExtProtoInfo ExtInfo;
817 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000818 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000819 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000820
821 SourceLocation Loc = IntroducerRange.getBegin();
822 DeclarationName Name
823 = S.Context.DeclarationNames.getCXXConversionFunctionName(
824 S.Context.getCanonicalType(FunctionPtrTy));
825 DeclarationNameLoc NameLoc;
826 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
827 Loc);
828 CXXConversionDecl *Conversion
829 = CXXConversionDecl::Create(S.Context, Class, Loc,
830 DeclarationNameInfo(Name, Loc, NameLoc),
831 ConvTy,
832 S.Context.getTrivialTypeSourceInfo(ConvTy,
833 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000834 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000835 /*isConstexpr=*/false,
836 CallOperator->getBody()->getLocEnd());
837 Conversion->setAccess(AS_public);
838 Conversion->setImplicit(true);
839 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000840
841 // Add a non-static member function "__invoke" that will be the result of
842 // the conversion.
843 Name = &S.Context.Idents.get("__invoke");
844 CXXMethodDecl *Invoke
845 = CXXMethodDecl::Create(S.Context, Class, Loc,
846 DeclarationNameInfo(Name, Loc), FunctionTy,
847 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000848 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000849 /*IsConstexpr=*/false,
850 CallOperator->getBody()->getLocEnd());
851 SmallVector<ParmVarDecl *, 4> InvokeParams;
852 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
853 ParmVarDecl *From = CallOperator->getParamDecl(I);
854 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
855 From->getLocStart(),
856 From->getLocation(),
857 From->getIdentifier(),
858 From->getType(),
859 From->getTypeSourceInfo(),
860 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000861 /*DefaultArg=*/0));
862 }
863 Invoke->setParams(InvokeParams);
864 Invoke->setAccess(AS_private);
865 Invoke->setImplicit(true);
866 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000867}
868
Douglas Gregorc2956e52012-02-15 22:08:38 +0000869/// \brief Add a lambda's conversion to block pointer.
870static void addBlockPointerConversion(Sema &S,
871 SourceRange IntroducerRange,
872 CXXRecordDecl *Class,
873 CXXMethodDecl *CallOperator) {
874 const FunctionProtoType *Proto
875 = CallOperator->getType()->getAs<FunctionProtoType>();
876 QualType BlockPtrTy;
877 {
878 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
879 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000880 QualType FunctionTy = S.Context.getFunctionType(
881 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000882 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
883 }
884
885 FunctionProtoType::ExtProtoInfo ExtInfo;
886 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000887 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000888
889 SourceLocation Loc = IntroducerRange.getBegin();
890 DeclarationName Name
891 = S.Context.DeclarationNames.getCXXConversionFunctionName(
892 S.Context.getCanonicalType(BlockPtrTy));
893 DeclarationNameLoc NameLoc;
894 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
895 CXXConversionDecl *Conversion
896 = CXXConversionDecl::Create(S.Context, Class, Loc,
897 DeclarationNameInfo(Name, Loc, NameLoc),
898 ConvTy,
899 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000900 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000901 /*isConstexpr=*/false,
902 CallOperator->getBody()->getLocEnd());
903 Conversion->setAccess(AS_public);
904 Conversion->setImplicit(true);
905 Class->addDecl(Conversion);
906}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000907
Douglas Gregordfca6f52012-02-13 22:00:16 +0000908ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000909 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000910 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000911 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000912 SmallVector<LambdaExpr::Capture, 4> Captures;
913 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000914 LambdaCaptureDefault CaptureDefault;
915 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000916 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000917 SourceRange IntroducerRange;
918 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000919 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000920 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000921 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000922 SmallVector<VarDecl *, 4> ArrayIndexVars;
923 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000924 {
925 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000926 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000927 Class = LSI->Lambda;
928 IntroducerRange = LSI->IntroducerRange;
929 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000930 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000931 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000932 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000933 ArrayIndexVars.swap(LSI->ArrayIndexVars);
934 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
935
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000936 // Translate captures.
937 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
938 LambdaScopeInfo::Capture From = LSI->Captures[I];
939 assert(!From.isBlockCapture() && "Cannot capture __block variables");
940 bool IsImplicit = I >= LSI->NumExplicitCaptures;
941
942 // Handle 'this' capture.
943 if (From.isThisCapture()) {
944 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
945 IsImplicit,
946 LCK_This));
947 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
948 getCurrentThisType(),
949 /*isImplicit=*/true));
950 continue;
951 }
952
Richard Smith0d8e9642013-05-16 06:20:58 +0000953 if (From.isInitCapture()) {
954 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
955 CaptureInits.push_back(From.getInitExpr());
956 continue;
957 }
958
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000959 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000960 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
961 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000962 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000963 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000964 }
965
966 switch (LSI->ImpCaptureStyle) {
967 case CapturingScopeInfo::ImpCap_None:
968 CaptureDefault = LCD_None;
969 break;
970
971 case CapturingScopeInfo::ImpCap_LambdaByval:
972 CaptureDefault = LCD_ByCopy;
973 break;
974
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000975 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000976 case CapturingScopeInfo::ImpCap_LambdaByref:
977 CaptureDefault = LCD_ByRef;
978 break;
979
980 case CapturingScopeInfo::ImpCap_Block:
981 llvm_unreachable("block capture in lambda");
982 break;
983 }
984
Douglas Gregor54042f12012-02-09 10:18:50 +0000985 // C++11 [expr.prim.lambda]p4:
986 // If a lambda-expression does not include a
987 // trailing-return-type, it is as if the trailing-return-type
988 // denotes the following type:
989 // FIXME: Assumes current resolution to core issue 975.
990 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000991 deduceClosureReturnType(*LSI);
992
Douglas Gregor54042f12012-02-09 10:18:50 +0000993 // - if there are no return statements in the
994 // compound-statement, or all return statements return
995 // either an expression of type void or no expression or
996 // braced-init-list, the type void;
997 if (LSI->ReturnType.isNull()) {
998 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000999 }
1000
1001 // Create a function type with the inferred return type.
1002 const FunctionProtoType *Proto
1003 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001004 QualType FunctionTy = Context.getFunctionType(
1005 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001006 CallOperator->setType(FunctionTy);
1007 }
1008
Douglas Gregor215e4e12012-02-12 17:34:23 +00001009 // C++ [expr.prim.lambda]p7:
1010 // The lambda-expression's compound-statement yields the
1011 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001012 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001013 CallOperator->setLexicalDeclContext(Class);
1014 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001015 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001016
Douglas Gregorb5559712012-02-10 16:13:20 +00001017 // C++11 [expr.prim.lambda]p6:
1018 // The closure type for a lambda-expression with no lambda-capture
1019 // has a public non-virtual non-explicit const conversion function
1020 // to pointer to function having the same parameter and return
1021 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001022 if (Captures.empty() && CaptureDefault == LCD_None)
1023 addFunctionPointerConversion(*this, IntroducerRange, Class,
1024 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001025
Douglas Gregorc2956e52012-02-15 22:08:38 +00001026 // Objective-C++:
1027 // The closure type for a lambda-expression has a public non-virtual
1028 // non-explicit const conversion function to a block pointer having the
1029 // same parameter and return types as the closure type's function call
1030 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001031 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001032 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1033
Douglas Gregorb5559712012-02-10 16:13:20 +00001034 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001035 SmallVector<Decl*, 4> Fields;
1036 for (RecordDecl::field_iterator i = Class->field_begin(),
1037 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001038 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001039 ActOnFields(0, Class->getLocation(), Class, Fields,
1040 SourceLocation(), SourceLocation(), 0);
1041 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001042 }
1043
Douglas Gregor503384f2012-02-09 00:47:04 +00001044 if (LambdaExprNeedsCleanups)
1045 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001046
Douglas Gregore2c59132012-02-09 08:14:43 +00001047 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1048 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001049 ExplicitParams, ExplicitResultType,
1050 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001051 ArrayIndexStarts, Body->getLocEnd(),
1052 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +00001053
1054 // C++11 [expr.prim.lambda]p2:
1055 // A lambda-expression shall not appear in an unevaluated operand
1056 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001057 if (!CurContext->isDependentContext()) {
1058 switch (ExprEvalContexts.back().Context) {
1059 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001060 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001061 // We don't actually diagnose this case immediately, because we
1062 // could be within a context where we might find out later that
1063 // the expression is potentially evaluated (e.g., for typeid).
1064 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1065 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001066
Douglas Gregord5387e82012-02-14 00:00:48 +00001067 case ConstantEvaluated:
1068 case PotentiallyEvaluated:
1069 case PotentiallyEvaluatedIfUsed:
1070 break;
1071 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001072 }
Douglas Gregord5387e82012-02-14 00:00:48 +00001073
Douglas Gregor503384f2012-02-09 00:47:04 +00001074 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001075}
Eli Friedman23f02672012-03-01 04:01:32 +00001076
1077ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1078 SourceLocation ConvLocation,
1079 CXXConversionDecl *Conv,
1080 Expr *Src) {
1081 // Make sure that the lambda call operator is marked used.
1082 CXXRecordDecl *Lambda = Conv->getParent();
1083 CXXMethodDecl *CallOperator
1084 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001085 Lambda->lookup(
1086 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001087 CallOperator->setReferenced();
1088 CallOperator->setUsed();
1089
1090 ExprResult Init = PerformCopyInitialization(
1091 InitializedEntity::InitializeBlock(ConvLocation,
1092 Src->getType(),
1093 /*NRVO=*/false),
1094 CurrentLocation, Src);
1095 if (!Init.isInvalid())
1096 Init = ActOnFinishFullExpr(Init.take());
1097
1098 if (Init.isInvalid())
1099 return ExprError();
1100
1101 // Create the new block to be returned.
1102 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1103
1104 // Set the type information.
1105 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1106 Block->setIsVariadic(CallOperator->isVariadic());
1107 Block->setBlockMissingReturnType(false);
1108
1109 // Add parameters.
1110 SmallVector<ParmVarDecl *, 4> BlockParams;
1111 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1112 ParmVarDecl *From = CallOperator->getParamDecl(I);
1113 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1114 From->getLocStart(),
1115 From->getLocation(),
1116 From->getIdentifier(),
1117 From->getType(),
1118 From->getTypeSourceInfo(),
1119 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001120 /*DefaultArg=*/0));
1121 }
1122 Block->setParams(BlockParams);
1123
1124 Block->setIsConversionFromLambda(true);
1125
1126 // Add capture. The capture uses a fake variable, which doesn't correspond
1127 // to any actual memory location. However, the initializer copy-initializes
1128 // the lambda object.
1129 TypeSourceInfo *CapVarTSI =
1130 Context.getTrivialTypeSourceInfo(Src->getType());
1131 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1132 ConvLocation, 0,
1133 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001134 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001135 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1136 /*Nested=*/false, /*Copy=*/Init.take());
1137 Block->setCaptures(Context, &Capture, &Capture + 1,
1138 /*CapturesCXXThis=*/false);
1139
1140 // Add a fake function body to the block. IR generation is responsible
1141 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001142 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001143
1144 // Create the block literal expression.
1145 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1146 ExprCleanupObjects.push_back(Block);
1147 ExprNeedsCleanups = true;
1148
1149 return BuildBlock;
1150}