blob: 761feffc2650fcb753b4b72333302af0603d6cc1 [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"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000015#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000019#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/Sema/ScopeInfo.h"
21#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000022#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000023using namespace clang;
24using namespace sema;
25
Douglas Gregorf4b7de12012-02-21 19:11:17 +000026CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000027 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000028 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000029 DeclContext *DC = CurContext;
30 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
31 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000032
Douglas Gregore2a7ad02012-02-08 21:18:48 +000033 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000034 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000035 IntroducerRange.getBegin(),
36 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000037 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000038
39 return Class;
40}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000041
Douglas Gregorf54486a2012-04-04 17:40:10 +000042/// \brief Determine whether the given context is or is enclosed in an inline
43/// function.
44static bool isInInlineFunction(const DeclContext *DC) {
45 while (!DC->isFileContext()) {
46 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
47 if (FD->isInlined())
48 return true;
49
50 DC = DC->getLexicalParent();
51 }
52
53 return false;
54}
55
Eli Friedman07369dd2013-07-01 20:22:57 +000056MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000057Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000058 Decl *&ManglingContextDecl) {
59 // Compute the context for allocating mangling numbers in the current
60 // expression, if the ABI requires them.
61 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
62
63 enum ContextKind {
64 Normal,
65 DefaultArgument,
66 DataMember,
67 StaticDataMember
68 } Kind = Normal;
69
70 // Default arguments of member function parameters that appear in a class
71 // definition, as well as the initializers of data members, receive special
72 // treatment. Identify them.
73 if (ManglingContextDecl) {
74 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
75 if (const DeclContext *LexicalDC
76 = Param->getDeclContext()->getLexicalParent())
77 if (LexicalDC->isRecord())
78 Kind = DefaultArgument;
79 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
80 if (Var->getDeclContext()->isRecord())
81 Kind = StaticDataMember;
82 } else if (isa<FieldDecl>(ManglingContextDecl)) {
83 Kind = DataMember;
84 }
85 }
86
87 // Itanium ABI [5.1.7]:
88 // In the following contexts [...] the one-definition rule requires closure
89 // types in different translation units to "correspond":
90 bool IsInNonspecializedTemplate =
91 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
92 switch (Kind) {
93 case Normal:
94 // -- the bodies of non-exported nonspecialized template functions
95 // -- the bodies of inline functions
96 if ((IsInNonspecializedTemplate &&
97 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
98 isInInlineFunction(CurContext)) {
99 ManglingContextDecl = 0;
100 return &Context.getManglingNumberContext(DC);
101 }
102
103 ManglingContextDecl = 0;
104 return 0;
105
106 case StaticDataMember:
107 // -- the initializers of nonspecialized static members of template classes
108 if (!IsInNonspecializedTemplate) {
109 ManglingContextDecl = 0;
110 return 0;
111 }
112 // Fall through to get the current context.
113
114 case DataMember:
115 // -- the in-class initializers of class members
116 case DefaultArgument:
117 // -- default arguments appearing in class definitions
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000118 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman07369dd2013-07-01 20:22:57 +0000119 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000120
121 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000122}
123
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000124MangleNumberingContext &
125Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
126 ASTContext &Ctx) {
127 assert(ManglingContextDecl && "Need to have a context declaration");
128 if (!MangleNumbering)
129 MangleNumbering = Ctx.createMangleNumberingContext();
130 return *MangleNumbering;
131}
132
Douglas Gregordfca6f52012-02-13 22:00:16 +0000133CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000134 SourceRange IntroducerRange,
135 TypeSourceInfo *MethodType,
136 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000137 ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000138 // C++11 [expr.prim.lambda]p5:
139 // The closure type for a lambda-expression has a public inline function
140 // call operator (13.5.4) whose parameters and return type are described by
141 // the lambda-expression's parameter-declaration-clause and
142 // trailing-return-type respectively.
143 DeclarationName MethodName
144 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
145 DeclarationNameLoc MethodNameLoc;
146 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
147 = IntroducerRange.getBegin().getRawEncoding();
148 MethodNameLoc.CXXOperatorName.EndOpNameLoc
149 = IntroducerRange.getEnd().getRawEncoding();
150 CXXMethodDecl *Method
151 = CXXMethodDecl::Create(Context, Class, EndLoc,
152 DeclarationNameInfo(MethodName,
153 IntroducerRange.getBegin(),
154 MethodNameLoc),
155 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000156 SC_None,
157 /*isInline=*/true,
158 /*isConstExpr=*/false,
159 EndLoc);
160 Method->setAccess(AS_public);
161
162 // Temporarily set the lexical declaration context to the current
163 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000164 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000165
Douglas Gregorc6889e72012-02-14 22:28:59 +0000166 // Add parameters.
167 if (!Params.empty()) {
168 Method->setParams(Params);
169 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
170 const_cast<ParmVarDecl **>(Params.end()),
171 /*CheckParameterNames=*/false);
172
173 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
174 PEnd = Method->param_end();
175 P != PEnd; ++P)
176 (*P)->setOwningFunction(Method);
177 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000178
Eli Friedman07369dd2013-07-01 20:22:57 +0000179 Decl *ManglingContextDecl;
180 if (MangleNumberingContext *MCtx =
181 getCurrentMangleNumberContext(Class->getDeclContext(),
182 ManglingContextDecl)) {
183 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
184 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000185 }
186
Douglas Gregordfca6f52012-02-13 22:00:16 +0000187 return Method;
188}
189
Manuel Klimek152b4e42013-08-22 12:12:24 +0000190LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000191 SourceRange IntroducerRange,
192 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000193 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000194 bool ExplicitParams,
195 bool ExplicitResultType,
196 bool Mutable) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000197 PushLambdaScope(CallOperator->getParent(), CallOperator);
198 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000199 if (CaptureDefault == LCD_ByCopy)
200 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
201 else if (CaptureDefault == LCD_ByRef)
202 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000203 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000204 LSI->IntroducerRange = IntroducerRange;
205 LSI->ExplicitParams = ExplicitParams;
206 LSI->Mutable = Mutable;
207
208 if (ExplicitResultType) {
209 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000210
211 if (!LSI->ReturnType->isDependentType() &&
212 !LSI->ReturnType->isVoidType()) {
213 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
214 diag::err_lambda_incomplete_result)) {
215 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000216 }
217 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000218 } else {
219 LSI->HasImplicitReturnType = true;
220 }
Manuel Klimek152b4e42013-08-22 12:12:24 +0000221
222 return LSI;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000223}
224
225void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
226 LSI->finishedExplicitCaptures();
227}
228
Douglas Gregorc6889e72012-02-14 22:28:59 +0000229void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000230 // Introduce our parameters into the function scope
231 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
232 p < NumParams; ++p) {
233 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000234
235 // If this has an identifier, add it to the scope stack.
236 if (CurScope && Param->getIdentifier()) {
237 CheckShadow(CurScope, Param);
238
239 PushOnScopeChains(Param, CurScope);
240 }
241 }
242}
243
John McCall41d01642013-03-09 00:54:31 +0000244/// If this expression is an enumerator-like expression of some type
245/// T, return the type T; otherwise, return null.
246///
247/// Pointer comparisons on the result here should always work because
248/// it's derived from either the parent of an EnumConstantDecl
249/// (i.e. the definition) or the declaration returned by
250/// EnumType::getDecl() (i.e. the definition).
251static EnumDecl *findEnumForBlockReturn(Expr *E) {
252 // An expression is an enumerator-like expression of type T if,
253 // ignoring parens and parens-like expressions:
254 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000255
John McCall41d01642013-03-09 00:54:31 +0000256 // - it is an enumerator whose enum type is T or
257 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
258 if (EnumConstantDecl *D
259 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
260 return cast<EnumDecl>(D->getDeclContext());
261 }
262 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000263 }
264
John McCall41d01642013-03-09 00:54:31 +0000265 // - it is a comma expression whose RHS is an enumerator-like
266 // expression of type T or
267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
268 if (BO->getOpcode() == BO_Comma)
269 return findEnumForBlockReturn(BO->getRHS());
270 return 0;
271 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000272
John McCall41d01642013-03-09 00:54:31 +0000273 // - it is a statement-expression whose value expression is an
274 // enumerator-like expression of type T or
275 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
276 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
277 return findEnumForBlockReturn(last);
278 return 0;
279 }
280
281 // - it is a ternary conditional operator (not the GNU ?:
282 // extension) whose second and third operands are
283 // enumerator-like expressions of type T or
284 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
285 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
286 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
287 return ED;
288 return 0;
289 }
290
291 // (implicitly:)
292 // - it is an implicit integral conversion applied to an
293 // enumerator-like expression of type T or
294 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000295 // We can sometimes see integral conversions in valid
296 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000297 if (ICE->getCastKind() == CK_IntegralCast)
298 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000299
300 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000301 }
302
303 // - it is an expression of that formal enum type.
304 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
305 return ET->getDecl();
306 }
307
308 // Otherwise, nope.
309 return 0;
310}
311
312/// Attempt to find a type T for which the returned expression of the
313/// given statement is an enumerator-like expression of that type.
314static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
315 if (Expr *retValue = ret->getRetValue())
316 return findEnumForBlockReturn(retValue);
317 return 0;
318}
319
320/// Attempt to find a common type T for which all of the returned
321/// expressions in a block are enumerator-like expressions of that
322/// type.
323static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
324 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
325
326 // Try to find one for the first return.
327 EnumDecl *ED = findEnumForBlockReturn(*i);
328 if (!ED) return 0;
329
330 // Check that the rest of the returns have the same enum.
331 for (++i; i != e; ++i) {
332 if (findEnumForBlockReturn(*i) != ED)
333 return 0;
334 }
335
336 // Never infer an anonymous enum type.
337 if (!ED->hasNameForLinkage()) return 0;
338
339 return ED;
340}
341
342/// Adjust the given return statements so that they formally return
343/// the given type. It should require, at most, an IntegralCast.
344static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
345 QualType returnType) {
346 for (ArrayRef<ReturnStmt*>::iterator
347 i = returns.begin(), e = returns.end(); i != e; ++i) {
348 ReturnStmt *ret = *i;
349 Expr *retValue = ret->getRetValue();
350 if (S.Context.hasSameType(retValue->getType(), returnType))
351 continue;
352
353 // Right now we only support integral fixup casts.
354 assert(returnType->isIntegralOrUnscopedEnumerationType());
355 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
356
357 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
358
359 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
360 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
361 E, /*base path*/ 0, VK_RValue);
362 if (cleanups) {
363 cleanups->setSubExpr(E);
364 } else {
365 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000366 }
367 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000368}
369
370void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000371 assert(CSI.HasImplicitReturnType);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000372
John McCall41d01642013-03-09 00:54:31 +0000373 // C++ Core Issue #975, proposed resolution:
374 // If a lambda-expression does not include a trailing-return-type,
375 // it is as if the trailing-return-type denotes the following type:
376 // - if there are no return statements in the compound-statement,
377 // or all return statements return either an expression of type
378 // void or no expression or braced-init-list, the type void;
379 // - otherwise, if all return statements return an expression
380 // and the types of the returned expressions after
381 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
382 // array-to-pointer conversion (4.2 [conv.array]), and
383 // function-to-pointer conversion (4.3 [conv.func]) are the
384 // same, that common type;
385 // - otherwise, the program is ill-formed.
386 //
387 // In addition, in blocks in non-C++ modes, if all of the return
388 // statements are enumerator-like expressions of some type T, where
389 // T has a name for linkage, then we infer the return type of the
390 // block to be that type.
391
Jordan Rose7dd900e2012-07-02 21:19:23 +0000392 // First case: no return statements, implicit void return type.
393 ASTContext &Ctx = getASTContext();
394 if (CSI.Returns.empty()) {
395 // It's possible there were simply no /valid/ return statements.
396 // In this case, the first one we found may have at least given us a type.
397 if (CSI.ReturnType.isNull())
398 CSI.ReturnType = Ctx.VoidTy;
399 return;
400 }
401
402 // Second case: at least one return statement has dependent type.
403 // Delay type checking until instantiation.
404 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000405 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000406 return;
407
John McCall41d01642013-03-09 00:54:31 +0000408 // Try to apply the enum-fuzz rule.
409 if (!getLangOpts().CPlusPlus) {
410 assert(isa<BlockScopeInfo>(CSI));
411 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
412 if (ED) {
413 CSI.ReturnType = Context.getTypeDeclType(ED);
414 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
415 return;
416 }
417 }
418
Jordan Rose7dd900e2012-07-02 21:19:23 +0000419 // Third case: only one return statement. Don't bother doing extra work!
420 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
421 E = CSI.Returns.end();
422 if (I+1 == E)
423 return;
424
425 // General case: many return statements.
426 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000427
428 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000429 // Note that we've already done the required promotions as part of
430 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000431 for (; I != E; ++I) {
432 const ReturnStmt *RS = *I;
433 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000434
John McCall41d01642013-03-09 00:54:31 +0000435 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
436 if (Context.hasSameType(ReturnType, CSI.ReturnType))
437 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000438
John McCall41d01642013-03-09 00:54:31 +0000439 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
440 // TODO: It's possible that the *first* return is the divergent one.
441 Diag(RS->getLocStart(),
442 diag::err_typecheck_missing_return_type_incompatible)
443 << ReturnType << CSI.ReturnType
444 << isa<LambdaScopeInfo>(CSI);
445 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000446 }
447}
448
Richard Smith0d8e9642013-05-16 06:20:58 +0000449FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
450 IdentifierInfo *Id, Expr *InitExpr) {
451 LambdaScopeInfo *LSI = getCurLambda();
452
453 // C++1y [expr.prim.lambda]p11:
454 // The type of [the] member corresponds to the type of a hypothetical
455 // variable declaration of the form "auto init-capture;"
456 QualType DeductType = Context.getAutoDeductType();
457 TypeLocBuilder TLB;
458 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
459 if (ByRef) {
460 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
461 assert(!DeductType.isNull() && "can't build reference to auto");
462 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
463 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000464 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000465
466 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
467 Expr *Init = InitExpr;
468 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
469 if (Parens->getNumExprs() == 1) {
470 Init = Parens->getExpr(0);
471 InitKind = InitializationKind::CreateDirect(
472 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
473 } else {
474 // C++1y [dcl.spec.auto]p3:
475 // In an initializer of the form ( expression-list ), the
476 // expression-list shall be a single assignment-expression.
477 if (Parens->getNumExprs() == 0)
478 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
479 << Id;
480 else if (Parens->getNumExprs() > 1)
481 Diag(Parens->getExpr(1)->getLocStart(),
482 diag::err_init_capture_multiple_expressions)
483 << Id;
484 return 0;
485 }
486 } else if (isa<InitListExpr>(Init))
487 // We do not need to distinguish between direct-list-initialization
488 // and copy-list-initialization here, because we will always deduce
489 // std::initializer_list<T>, and direct- and copy-list-initialization
490 // always behave the same for such a type.
491 // FIXME: We should model whether an '=' was present.
492 InitKind = InitializationKind::CreateDirectList(Loc);
493 else
494 InitKind = InitializationKind::CreateCopy(Loc, Loc);
495 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000496 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000497 if (isa<InitListExpr>(Init))
498 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
499 << Id << Init->getSourceRange();
500 else
501 Diag(Loc, diag::err_init_capture_deduction_failure)
502 << Id << Init->getType() << Init->getSourceRange();
503 }
504 if (DeducedType.isNull())
505 return 0;
506
507 // [...] a non-static data member named by the identifier is declared in
508 // the closure type. This member is not a bit-field and not mutable.
509 // Core issue: the member is (probably...) public.
510 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000511 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000512 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
513 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
514 LSI->Lambda->addDecl(NewFD);
515
516 if (CurContext->isDependentContext()) {
517 LSI->addInitCapture(NewFD, InitExpr);
518 } else {
519 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
520 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
521 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
522 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
523 if (!InitResult.isInvalid())
524 LSI->addInitCapture(NewFD, InitResult.take());
525 }
526 }
527
528 return NewFD;
529}
530
Douglas Gregordfca6f52012-02-13 22:00:16 +0000531void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Manuel Klimek152b4e42013-08-22 12:12:24 +0000532 Declarator &ParamInfo,
533 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000534 // Determine if we're within a context where we know that the lambda will
535 // be dependent, because there are template parameters in scope.
536 bool KnownDependent = false;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000537 if (Scope *TmplScope = CurScope->getTemplateParamParent())
538 if (!TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000539 KnownDependent = true;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000540
Douglas Gregordfca6f52012-02-13 22:00:16 +0000541 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000542 TypeSourceInfo *MethodTyInfo;
543 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000544 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000545 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000546 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000547 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000548 if (ParamInfo.getNumTypeObjects() == 0) {
549 // C++11 [expr.prim.lambda]p4:
550 // If a lambda-expression does not include a lambda-declarator, it is as
551 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000552 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
553 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000554 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000555 EPI.TypeQuals |= DeclSpec::TQ_const;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000556 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000557 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000558 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
559 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000560 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000561 EndLoc = Intro.Range.getEnd();
562 } else {
563 assert(ParamInfo.isFunctionDeclarator() &&
564 "lambda-declarator is a function");
565 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
566
567 // C++11 [expr.prim.lambda]p5:
568 // This function call operator is declared const (9.3.1) if and only if
569 // the lambda-expression's parameter-declaration-clause is not followed
570 // by mutable. It is neither virtual nor declared volatile. [...]
571 if (!FTI.hasMutableQualifier())
572 FTI.TypeQuals |= DeclSpec::TQ_const;
573
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000574 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000575 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000576 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000577
Manuel Klimek152b4e42013-08-22 12:12:24 +0000578 ExplicitResultType
579 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
580 != Context.DependentTy;
581
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000582 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
583 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
584 // Empty arg list, don't push any params.
585 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
586 } else {
587 Params.reserve(FTI.NumArgs);
588 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
589 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
590 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000591
592 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000593 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
594 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000595 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000596
597 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
598 KnownDependent);
599
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000600 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000601 MethodTyInfo, EndLoc, Params);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000602
Douglas Gregorc6889e72012-02-14 22:28:59 +0000603 if (ExplicitParams)
604 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000605
Bill Wendlingad017fa2012-12-20 19:22:21 +0000606 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000607 ProcessDeclAttributes(CurScope, Method, ParamInfo);
608
Douglas Gregor503384f2012-02-09 00:47:04 +0000609 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 PushDeclContext(CurScope, Method);
611
Manuel Klimek152b4e42013-08-22 12:12:24 +0000612 // Introduce the lambda scope.
613 LambdaScopeInfo *LSI
614 = enterLambdaScope(Method,
James Dennettf68af642013-08-09 23:08:25 +0000615 Intro.Range,
616 Intro.Default, Intro.DefaultLoc,
617 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000618 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000619 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000620
621 // Distinct capture names, for diagnostics.
622 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
623
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000624 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000625 SourceLocation PrevCaptureLoc
626 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000627 for (SmallVectorImpl<LambdaCapture>::const_iterator
628 C = Intro.Captures.begin(),
629 E = Intro.Captures.end();
630 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000631 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000632 if (C->Kind == LCK_This) {
633 // C++11 [expr.prim.lambda]p8:
634 // An identifier or this shall not appear more than once in a
635 // lambda-capture.
636 if (LSI->isCXXThisCaptured()) {
637 Diag(C->Loc, diag::err_capture_more_than_once)
638 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000639 << SourceRange(LSI->getCXXThisCapture().getLocation())
640 << FixItHint::CreateRemoval(
641 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000642 continue;
643 }
644
645 // C++11 [expr.prim.lambda]p8:
646 // If a lambda-capture includes a capture-default that is =, the
647 // lambda-capture shall not contain this [...].
648 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000649 Diag(C->Loc, diag::err_this_capture_with_copy_default)
650 << FixItHint::CreateRemoval(
651 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000652 continue;
653 }
654
655 // C++11 [expr.prim.lambda]p12:
656 // If this is captured by a local lambda expression, its nearest
657 // enclosing function shall be a non-static member function.
658 QualType ThisCaptureType = getCurrentThisType();
659 if (ThisCaptureType.isNull()) {
660 Diag(C->Loc, diag::err_this_capture) << true;
661 continue;
662 }
663
664 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
665 continue;
666 }
667
Richard Smith0d8e9642013-05-16 06:20:58 +0000668 assert(C->Id && "missing identifier for capture");
669
Richard Smith0a664b82013-05-09 21:36:41 +0000670 if (C->Init.isInvalid())
671 continue;
672 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000673 // C++11 [expr.prim.lambda]p8:
674 // An identifier or this shall not appear more than once in a
675 // lambda-capture.
676 if (!CaptureNames.insert(C->Id))
677 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
678
679 if (C->Init.get()->containsUnexpandedParameterPack())
680 ContainsUnexpandedParameterPack = true;
681
682 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
683 C->Id, C->Init.take());
684 // C++1y [expr.prim.lambda]p11:
685 // Within the lambda-expression's lambda-declarator and
686 // compound-statement, the identifier in the init-capture
687 // hides any declaration of the same name in scopes enclosing
688 // the lambda-expression.
689 if (NewFD)
690 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000691 continue;
692 }
693
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000694 // C++11 [expr.prim.lambda]p8:
695 // If a lambda-capture includes a capture-default that is &, the
696 // identifiers in the lambda-capture shall not be preceded by &.
697 // If a lambda-capture includes a capture-default that is =, [...]
698 // each identifier it contains shall be preceded by &.
699 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000700 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
701 << FixItHint::CreateRemoval(
702 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000703 continue;
704 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000705 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
706 << FixItHint::CreateRemoval(
707 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000708 continue;
709 }
710
Richard Smith0d8e9642013-05-16 06:20:58 +0000711 // C++11 [expr.prim.lambda]p10:
712 // The identifiers in a capture-list are looked up using the usual
713 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000714 DeclarationNameInfo Name(C->Id, C->Loc);
715 LookupResult R(*this, Name, LookupOrdinaryName);
716 LookupName(R, CurScope);
717 if (R.isAmbiguous())
718 continue;
719 if (R.empty()) {
720 // FIXME: Disable corrections that would add qualification?
721 CXXScopeSpec ScopeSpec;
722 DeclFilterCCC<VarDecl> Validator;
723 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
724 continue;
725 }
726
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000727 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000728
729 // C++11 [expr.prim.lambda]p8:
730 // An identifier or this shall not appear more than once in a
731 // lambda-capture.
732 if (!CaptureNames.insert(C->Id)) {
733 if (Var && LSI->isCaptured(Var)) {
734 Diag(C->Loc, diag::err_capture_more_than_once)
735 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
736 << FixItHint::CreateRemoval(
737 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
738 } else
739 // Previous capture was an init-capture: no fixit.
740 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
741 continue;
742 }
743
744 // C++11 [expr.prim.lambda]p10:
745 // [...] each such lookup shall find a variable with automatic storage
746 // duration declared in the reaching scope of the local lambda expression.
747 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000748 if (!Var) {
749 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
750 continue;
751 }
752
Eli Friedman9cd5b242012-09-18 21:11:30 +0000753 // Ignore invalid decls; they'll just confuse the code later.
754 if (Var->isInvalidDecl())
755 continue;
756
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000757 if (!Var->hasLocalStorage()) {
758 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
759 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
760 continue;
761 }
762
Douglas Gregora7365242012-02-14 19:27:52 +0000763 // C++11 [expr.prim.lambda]p23:
764 // A capture followed by an ellipsis is a pack expansion (14.5.3).
765 SourceLocation EllipsisLoc;
766 if (C->EllipsisLoc.isValid()) {
767 if (Var->isParameterPack()) {
768 EllipsisLoc = C->EllipsisLoc;
769 } else {
770 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
771 << SourceRange(C->Loc);
772
773 // Just ignore the ellipsis.
774 }
775 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000776 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000777 }
778
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000779 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
780 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000781 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000782 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000783 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000784
Richard Smith612409e2012-07-25 03:56:55 +0000785 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
786
Douglas Gregorc6889e72012-02-14 22:28:59 +0000787 // Add lambda parameters into scope.
788 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000789
Douglas Gregordfca6f52012-02-13 22:00:16 +0000790 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000791 // cleanups from the enclosing full-expression.
792 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000793}
794
Douglas Gregordfca6f52012-02-13 22:00:16 +0000795void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
796 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000797 // Leave the expression-evaluation context.
798 DiscardCleanupsInEvaluationContext();
799 PopExpressionEvaluationContext();
800
801 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000802 if (!IsInstantiation)
803 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000804
805 // Finalize the lambda.
806 LambdaScopeInfo *LSI = getCurLambda();
807 CXXRecordDecl *Class = LSI->Lambda;
808 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000809 SmallVector<Decl*, 4> Fields;
810 for (RecordDecl::field_iterator i = Class->field_begin(),
811 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000812 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000813 ActOnFields(0, Class->getLocation(), Class, Fields,
814 SourceLocation(), SourceLocation(), 0);
815 CheckCompletedCXXClass(Class);
816
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000817 PopFunctionScopeInfo();
818}
819
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000820/// \brief Add a lambda's conversion to function pointer, as described in
821/// C++11 [expr.prim.lambda]p6.
822static void addFunctionPointerConversion(Sema &S,
823 SourceRange IntroducerRange,
824 CXXRecordDecl *Class,
825 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000826 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000827 const FunctionProtoType *Proto
828 = CallOperator->getType()->getAs<FunctionProtoType>();
829 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000830 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000831 {
832 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000833 CallingConv CC = S.Context.getDefaultCallingConvention(
834 Proto->isVariadic(), /*IsCXXMethod=*/false);
835 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000836 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000837 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
838 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000839 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
840 }
Reid Kleckneref072032013-08-27 23:08:25 +0000841
842 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
843 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000844 ExtInfo.TypeQuals = Qualifiers::Const;
Reid Kleckneref072032013-08-27 23:08:25 +0000845 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
846
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000847 SourceLocation Loc = IntroducerRange.getBegin();
848 DeclarationName Name
849 = S.Context.DeclarationNames.getCXXConversionFunctionName(
850 S.Context.getCanonicalType(FunctionPtrTy));
851 DeclarationNameLoc NameLoc;
852 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
853 Loc);
854 CXXConversionDecl *Conversion
855 = CXXConversionDecl::Create(S.Context, Class, Loc,
856 DeclarationNameInfo(Name, Loc, NameLoc),
857 ConvTy,
858 S.Context.getTrivialTypeSourceInfo(ConvTy,
859 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000860 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000861 /*isConstexpr=*/false,
862 CallOperator->getBody()->getLocEnd());
863 Conversion->setAccess(AS_public);
864 Conversion->setImplicit(true);
865 Class->addDecl(Conversion);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000866
867 // Add a non-static member function "__invoke" that will be the result of
868 // the conversion.
869 Name = &S.Context.Idents.get("__invoke");
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000870 CXXMethodDecl *Invoke
871 = CXXMethodDecl::Create(S.Context, Class, Loc,
872 DeclarationNameInfo(Name, Loc), FunctionTy,
873 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000874 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000875 /*IsConstexpr=*/false,
876 CallOperator->getBody()->getLocEnd());
877 SmallVector<ParmVarDecl *, 4> InvokeParams;
878 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
879 ParmVarDecl *From = CallOperator->getParamDecl(I);
880 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
881 From->getLocStart(),
882 From->getLocation(),
883 From->getIdentifier(),
884 From->getType(),
885 From->getTypeSourceInfo(),
886 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000887 /*DefaultArg=*/0));
888 }
889 Invoke->setParams(InvokeParams);
890 Invoke->setAccess(AS_private);
891 Invoke->setImplicit(true);
892 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000893}
894
Douglas Gregorc2956e52012-02-15 22:08:38 +0000895/// \brief Add a lambda's conversion to block pointer.
896static void addBlockPointerConversion(Sema &S,
897 SourceRange IntroducerRange,
898 CXXRecordDecl *Class,
899 CXXMethodDecl *CallOperator) {
900 const FunctionProtoType *Proto
901 = CallOperator->getType()->getAs<FunctionProtoType>();
902 QualType BlockPtrTy;
903 {
904 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
905 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000906 QualType FunctionTy = S.Context.getFunctionType(
907 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000908 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
909 }
Reid Kleckneref072032013-08-27 23:08:25 +0000910
911 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
912 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +0000913 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000914 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000915
916 SourceLocation Loc = IntroducerRange.getBegin();
917 DeclarationName Name
918 = S.Context.DeclarationNames.getCXXConversionFunctionName(
919 S.Context.getCanonicalType(BlockPtrTy));
920 DeclarationNameLoc NameLoc;
921 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
922 CXXConversionDecl *Conversion
923 = CXXConversionDecl::Create(S.Context, Class, Loc,
924 DeclarationNameInfo(Name, Loc, NameLoc),
925 ConvTy,
926 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000927 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000928 /*isConstexpr=*/false,
929 CallOperator->getBody()->getLocEnd());
930 Conversion->setAccess(AS_public);
931 Conversion->setImplicit(true);
932 Class->addDecl(Conversion);
933}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000934
Douglas Gregordfca6f52012-02-13 22:00:16 +0000935ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000936 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000937 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000938 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000939 SmallVector<LambdaExpr::Capture, 4> Captures;
940 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000941 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +0000942 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000943 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000944 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000945 SourceRange IntroducerRange;
946 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000947 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000948 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000949 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000950 SmallVector<VarDecl *, 4> ArrayIndexVars;
951 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000952 {
953 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000954 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000955 Class = LSI->Lambda;
956 IntroducerRange = LSI->IntroducerRange;
957 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000958 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000959 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000960 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000961 ArrayIndexVars.swap(LSI->ArrayIndexVars);
962 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
963
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000964 // Translate captures.
965 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
966 LambdaScopeInfo::Capture From = LSI->Captures[I];
967 assert(!From.isBlockCapture() && "Cannot capture __block variables");
968 bool IsImplicit = I >= LSI->NumExplicitCaptures;
969
970 // Handle 'this' capture.
971 if (From.isThisCapture()) {
972 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
973 IsImplicit,
974 LCK_This));
975 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
976 getCurrentThisType(),
977 /*isImplicit=*/true));
978 continue;
979 }
980
Richard Smith0d8e9642013-05-16 06:20:58 +0000981 if (From.isInitCapture()) {
982 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
983 CaptureInits.push_back(From.getInitExpr());
984 continue;
985 }
986
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000987 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000988 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
989 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000990 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000991 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000992 }
993
994 switch (LSI->ImpCaptureStyle) {
995 case CapturingScopeInfo::ImpCap_None:
996 CaptureDefault = LCD_None;
997 break;
998
999 case CapturingScopeInfo::ImpCap_LambdaByval:
1000 CaptureDefault = LCD_ByCopy;
1001 break;
1002
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001003 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001004 case CapturingScopeInfo::ImpCap_LambdaByref:
1005 CaptureDefault = LCD_ByRef;
1006 break;
1007
1008 case CapturingScopeInfo::ImpCap_Block:
1009 llvm_unreachable("block capture in lambda");
1010 break;
1011 }
James Dennettf68af642013-08-09 23:08:25 +00001012 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001013
Douglas Gregor54042f12012-02-09 10:18:50 +00001014 // C++11 [expr.prim.lambda]p4:
1015 // If a lambda-expression does not include a
1016 // trailing-return-type, it is as if the trailing-return-type
1017 // denotes the following type:
1018 // FIXME: Assumes current resolution to core issue 975.
Manuel Klimek152b4e42013-08-22 12:12:24 +00001019 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001020 deduceClosureReturnType(*LSI);
1021
Douglas Gregor54042f12012-02-09 10:18:50 +00001022 // - if there are no return statements in the
1023 // compound-statement, or all return statements return
1024 // either an expression of type void or no expression or
1025 // braced-init-list, the type void;
1026 if (LSI->ReturnType.isNull()) {
1027 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001028 }
1029
1030 // Create a function type with the inferred return type.
1031 const FunctionProtoType *Proto
1032 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001033 QualType FunctionTy = Context.getFunctionType(
1034 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001035 CallOperator->setType(FunctionTy);
1036 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001037
Douglas Gregor215e4e12012-02-12 17:34:23 +00001038 // C++ [expr.prim.lambda]p7:
1039 // The lambda-expression's compound-statement yields the
1040 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001041 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001042 CallOperator->setLexicalDeclContext(Class);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001043 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001044 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001045
Douglas Gregorb5559712012-02-10 16:13:20 +00001046 // C++11 [expr.prim.lambda]p6:
1047 // The closure type for a lambda-expression with no lambda-capture
1048 // has a public non-virtual non-explicit const conversion function
1049 // to pointer to function having the same parameter and return
1050 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001051 if (Captures.empty() && CaptureDefault == LCD_None)
1052 addFunctionPointerConversion(*this, IntroducerRange, Class,
1053 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001054
Douglas Gregorc2956e52012-02-15 22:08:38 +00001055 // Objective-C++:
1056 // The closure type for a lambda-expression has a public non-virtual
1057 // non-explicit const conversion function to a block pointer having the
1058 // same parameter and return types as the closure type's function call
1059 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001060 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001061 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1062
Douglas Gregorb5559712012-02-10 16:13:20 +00001063 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001064 SmallVector<Decl*, 4> Fields;
1065 for (RecordDecl::field_iterator i = Class->field_begin(),
1066 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001067 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001068 ActOnFields(0, Class->getLocation(), Class, Fields,
1069 SourceLocation(), SourceLocation(), 0);
1070 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001071 }
1072
Douglas Gregor503384f2012-02-09 00:47:04 +00001073 if (LambdaExprNeedsCleanups)
1074 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001075
Douglas Gregore2c59132012-02-09 08:14:43 +00001076 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001077 CaptureDefault, CaptureDefaultLoc,
1078 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001079 ExplicitParams, ExplicitResultType,
1080 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001081 ArrayIndexStarts, Body->getLocEnd(),
1082 ContainsUnexpandedParameterPack);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001083
Douglas Gregore2c59132012-02-09 08:14:43 +00001084 // C++11 [expr.prim.lambda]p2:
1085 // A lambda-expression shall not appear in an unevaluated operand
1086 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001087 if (!CurContext->isDependentContext()) {
1088 switch (ExprEvalContexts.back().Context) {
1089 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001090 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001091 // We don't actually diagnose this case immediately, because we
1092 // could be within a context where we might find out later that
1093 // the expression is potentially evaluated (e.g., for typeid).
1094 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1095 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001096
Douglas Gregord5387e82012-02-14 00:00:48 +00001097 case ConstantEvaluated:
1098 case PotentiallyEvaluated:
1099 case PotentiallyEvaluatedIfUsed:
1100 break;
1101 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001102 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001103
Douglas Gregor503384f2012-02-09 00:47:04 +00001104 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001105}
Eli Friedman23f02672012-03-01 04:01:32 +00001106
1107ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1108 SourceLocation ConvLocation,
1109 CXXConversionDecl *Conv,
1110 Expr *Src) {
1111 // Make sure that the lambda call operator is marked used.
1112 CXXRecordDecl *Lambda = Conv->getParent();
1113 CXXMethodDecl *CallOperator
1114 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001115 Lambda->lookup(
1116 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001117 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001118 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001119
1120 ExprResult Init = PerformCopyInitialization(
1121 InitializedEntity::InitializeBlock(ConvLocation,
1122 Src->getType(),
1123 /*NRVO=*/false),
1124 CurrentLocation, Src);
1125 if (!Init.isInvalid())
1126 Init = ActOnFinishFullExpr(Init.take());
1127
1128 if (Init.isInvalid())
1129 return ExprError();
1130
1131 // Create the new block to be returned.
1132 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1133
1134 // Set the type information.
1135 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1136 Block->setIsVariadic(CallOperator->isVariadic());
1137 Block->setBlockMissingReturnType(false);
1138
1139 // Add parameters.
1140 SmallVector<ParmVarDecl *, 4> BlockParams;
1141 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1142 ParmVarDecl *From = CallOperator->getParamDecl(I);
1143 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1144 From->getLocStart(),
1145 From->getLocation(),
1146 From->getIdentifier(),
1147 From->getType(),
1148 From->getTypeSourceInfo(),
1149 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001150 /*DefaultArg=*/0));
1151 }
1152 Block->setParams(BlockParams);
1153
1154 Block->setIsConversionFromLambda(true);
1155
1156 // Add capture. The capture uses a fake variable, which doesn't correspond
1157 // to any actual memory location. However, the initializer copy-initializes
1158 // the lambda object.
1159 TypeSourceInfo *CapVarTSI =
1160 Context.getTrivialTypeSourceInfo(Src->getType());
1161 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1162 ConvLocation, 0,
1163 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001164 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001165 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1166 /*Nested=*/false, /*Copy=*/Init.take());
1167 Block->setCaptures(Context, &Capture, &Capture + 1,
1168 /*CapturesCXXThis=*/false);
1169
1170 // Add a fake function body to the block. IR generation is responsible
1171 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001172 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001173
1174 // Create the block literal expression.
1175 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1176 ExprCleanupObjects.push_back(Block);
1177 ExprNeedsCleanups = true;
1178
1179 return BuildBlock;
1180}