blob: 2e1cd105a98fa098e48f517afe950225eb3b80d2 [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"
Faisal Valifad9e132013-09-26 19:54:12 +000014#include "clang/AST/ASTLambda.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ExprCXX.h"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000016#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000018#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000020#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000021#include "clang/Sema/ScopeInfo.h"
22#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000023#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000024using namespace clang;
25using namespace sema;
26
Faisal Valibef582b2013-10-23 16:10:50 +000027
28static inline TemplateParameterList *
29getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
30 if (LSI->GLTemplateParameterList)
31 return LSI->GLTemplateParameterList;
32
33 if (LSI->AutoTemplateParams.size()) {
34 SourceRange IntroRange = LSI->IntroducerRange;
35 SourceLocation LAngleLoc = IntroRange.getBegin();
36 SourceLocation RAngleLoc = IntroRange.getEnd();
37 LSI->GLTemplateParameterList = TemplateParameterList::Create(
38 SemaRef.Context,
39 /*Template kw loc*/SourceLocation(),
40 LAngleLoc,
41 (NamedDecl**)LSI->AutoTemplateParams.data(),
42 LSI->AutoTemplateParams.size(), RAngleLoc);
43 }
44 return LSI->GLTemplateParameterList;
45}
46
47
48
Douglas Gregorf4b7de12012-02-21 19:11:17 +000049CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000050 TypeSourceInfo *Info,
Faisal Valibef582b2013-10-23 16:10:50 +000051 bool KnownDependent,
52 LambdaCaptureDefault CaptureDefault) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000053 DeclContext *DC = CurContext;
54 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
55 DC = DC->getParent();
Faisal Valibef582b2013-10-23 16:10:50 +000056 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
57 *this);
Douglas Gregore2a7ad02012-02-08 21:18:48 +000058 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000059 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000060 IntroducerRange.getBegin(),
Faisal Valibef582b2013-10-23 16:10:50 +000061 KnownDependent,
62 IsGenericLambda,
63 CaptureDefault);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000064 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000065
66 return Class;
67}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000068
Douglas Gregorf54486a2012-04-04 17:40:10 +000069/// \brief Determine whether the given context is or is enclosed in an inline
70/// function.
71static bool isInInlineFunction(const DeclContext *DC) {
72 while (!DC->isFileContext()) {
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
74 if (FD->isInlined())
75 return true;
76
77 DC = DC->getLexicalParent();
78 }
79
80 return false;
81}
82
Eli Friedman07369dd2013-07-01 20:22:57 +000083MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000084Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000085 Decl *&ManglingContextDecl) {
86 // Compute the context for allocating mangling numbers in the current
87 // expression, if the ABI requires them.
88 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
89
90 enum ContextKind {
91 Normal,
92 DefaultArgument,
93 DataMember,
94 StaticDataMember
95 } Kind = Normal;
96
97 // Default arguments of member function parameters that appear in a class
98 // definition, as well as the initializers of data members, receive special
99 // treatment. Identify them.
100 if (ManglingContextDecl) {
101 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
102 if (const DeclContext *LexicalDC
103 = Param->getDeclContext()->getLexicalParent())
104 if (LexicalDC->isRecord())
105 Kind = DefaultArgument;
106 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
107 if (Var->getDeclContext()->isRecord())
108 Kind = StaticDataMember;
109 } else if (isa<FieldDecl>(ManglingContextDecl)) {
110 Kind = DataMember;
111 }
112 }
113
114 // Itanium ABI [5.1.7]:
115 // In the following contexts [...] the one-definition rule requires closure
116 // types in different translation units to "correspond":
117 bool IsInNonspecializedTemplate =
118 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
119 switch (Kind) {
120 case Normal:
121 // -- the bodies of non-exported nonspecialized template functions
122 // -- the bodies of inline functions
123 if ((IsInNonspecializedTemplate &&
124 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
125 isInInlineFunction(CurContext)) {
126 ManglingContextDecl = 0;
127 return &Context.getManglingNumberContext(DC);
128 }
129
130 ManglingContextDecl = 0;
131 return 0;
132
133 case StaticDataMember:
134 // -- the initializers of nonspecialized static members of template classes
135 if (!IsInNonspecializedTemplate) {
136 ManglingContextDecl = 0;
137 return 0;
138 }
139 // Fall through to get the current context.
140
141 case DataMember:
142 // -- the in-class initializers of class members
143 case DefaultArgument:
144 // -- default arguments appearing in class definitions
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000145 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman07369dd2013-07-01 20:22:57 +0000146 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000147
148 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000149}
150
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000151MangleNumberingContext &
152Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
153 ASTContext &Ctx) {
154 assert(ManglingContextDecl && "Need to have a context declaration");
155 if (!MangleNumbering)
156 MangleNumbering = Ctx.createMangleNumberingContext();
157 return *MangleNumbering;
158}
159
Douglas Gregordfca6f52012-02-13 22:00:16 +0000160CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith41d09582013-09-25 05:02:54 +0000161 SourceRange IntroducerRange,
162 TypeSourceInfo *MethodTypeInfo,
163 SourceLocation EndLoc,
164 ArrayRef<ParmVarDecl *> Params) {
165 QualType MethodType = MethodTypeInfo->getType();
Faisal Valifad9e132013-09-26 19:54:12 +0000166 TemplateParameterList *TemplateParams =
167 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
168 // If a lambda appears in a dependent context or is a generic lambda (has
169 // template parameters) and has an 'auto' return type, deduce it to a
170 // dependent type.
171 if (Class->isDependentContext() || TemplateParams) {
Richard Smith41d09582013-09-25 05:02:54 +0000172 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
173 QualType Result = FPT->getResultType();
174 if (Result->isUndeducedType()) {
175 Result = SubstAutoType(Result, Context.DependentTy);
176 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
177 FPT->getExtProtoInfo());
178 }
179 }
180
Douglas Gregordfca6f52012-02-13 22:00:16 +0000181 // C++11 [expr.prim.lambda]p5:
182 // The closure type for a lambda-expression has a public inline function
183 // call operator (13.5.4) whose parameters and return type are described by
184 // the lambda-expression's parameter-declaration-clause and
185 // trailing-return-type respectively.
186 DeclarationName MethodName
187 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
188 DeclarationNameLoc MethodNameLoc;
189 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
190 = IntroducerRange.getBegin().getRawEncoding();
191 MethodNameLoc.CXXOperatorName.EndOpNameLoc
192 = IntroducerRange.getEnd().getRawEncoding();
193 CXXMethodDecl *Method
194 = CXXMethodDecl::Create(Context, Class, EndLoc,
195 DeclarationNameInfo(MethodName,
196 IntroducerRange.getBegin(),
197 MethodNameLoc),
Richard Smith41d09582013-09-25 05:02:54 +0000198 MethodType, MethodTypeInfo,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000199 SC_None,
200 /*isInline=*/true,
201 /*isConstExpr=*/false,
202 EndLoc);
203 Method->setAccess(AS_public);
204
205 // Temporarily set the lexical declaration context to the current
206 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000207 Method->setLexicalDeclContext(CurContext);
Faisal Valifad9e132013-09-26 19:54:12 +0000208 // Create a function template if we have a template parameter list
209 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
210 FunctionTemplateDecl::Create(Context, Class,
211 Method->getLocation(), MethodName,
212 TemplateParams,
213 Method) : 0;
214 if (TemplateMethod) {
215 TemplateMethod->setLexicalDeclContext(CurContext);
216 TemplateMethod->setAccess(AS_public);
217 Method->setDescribedFunctionTemplate(TemplateMethod);
218 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000219
Douglas Gregorc6889e72012-02-14 22:28:59 +0000220 // Add parameters.
221 if (!Params.empty()) {
222 Method->setParams(Params);
223 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
224 const_cast<ParmVarDecl **>(Params.end()),
225 /*CheckParameterNames=*/false);
226
227 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
228 PEnd = Method->param_end();
229 P != PEnd; ++P)
230 (*P)->setOwningFunction(Method);
231 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000232
Eli Friedman07369dd2013-07-01 20:22:57 +0000233 Decl *ManglingContextDecl;
234 if (MangleNumberingContext *MCtx =
235 getCurrentMangleNumberContext(Class->getDeclContext(),
236 ManglingContextDecl)) {
237 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
238 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000239 }
240
Douglas Gregordfca6f52012-02-13 22:00:16 +0000241 return Method;
242}
243
Faisal Valifad9e132013-09-26 19:54:12 +0000244void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
245 CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000246 SourceRange IntroducerRange,
247 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000248 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000249 bool ExplicitParams,
250 bool ExplicitResultType,
251 bool Mutable) {
Faisal Valifad9e132013-09-26 19:54:12 +0000252 LSI->CallOperator = CallOperator;
Faisal Valibef582b2013-10-23 16:10:50 +0000253 CXXRecordDecl *LambdaClass = CallOperator->getParent();
254 LSI->Lambda = LambdaClass;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000255 if (CaptureDefault == LCD_ByCopy)
256 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
257 else if (CaptureDefault == LCD_ByRef)
258 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000259 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000260 LSI->IntroducerRange = IntroducerRange;
261 LSI->ExplicitParams = ExplicitParams;
262 LSI->Mutable = Mutable;
263
264 if (ExplicitResultType) {
265 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000266
267 if (!LSI->ReturnType->isDependentType() &&
268 !LSI->ReturnType->isVoidType()) {
269 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
270 diag::err_lambda_incomplete_result)) {
271 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000272 }
273 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000274 } else {
275 LSI->HasImplicitReturnType = true;
276 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000277}
278
279void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
280 LSI->finishedExplicitCaptures();
281}
282
Douglas Gregorc6889e72012-02-14 22:28:59 +0000283void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000284 // Introduce our parameters into the function scope
285 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
286 p < NumParams; ++p) {
287 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000288
289 // If this has an identifier, add it to the scope stack.
290 if (CurScope && Param->getIdentifier()) {
291 CheckShadow(CurScope, Param);
292
293 PushOnScopeChains(Param, CurScope);
294 }
295 }
296}
297
John McCall41d01642013-03-09 00:54:31 +0000298/// If this expression is an enumerator-like expression of some type
299/// T, return the type T; otherwise, return null.
300///
301/// Pointer comparisons on the result here should always work because
302/// it's derived from either the parent of an EnumConstantDecl
303/// (i.e. the definition) or the declaration returned by
304/// EnumType::getDecl() (i.e. the definition).
305static EnumDecl *findEnumForBlockReturn(Expr *E) {
306 // An expression is an enumerator-like expression of type T if,
307 // ignoring parens and parens-like expressions:
308 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000309
John McCall41d01642013-03-09 00:54:31 +0000310 // - it is an enumerator whose enum type is T or
311 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
312 if (EnumConstantDecl *D
313 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
314 return cast<EnumDecl>(D->getDeclContext());
315 }
316 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000317 }
318
John McCall41d01642013-03-09 00:54:31 +0000319 // - it is a comma expression whose RHS is an enumerator-like
320 // expression of type T or
321 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
322 if (BO->getOpcode() == BO_Comma)
323 return findEnumForBlockReturn(BO->getRHS());
324 return 0;
325 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000326
John McCall41d01642013-03-09 00:54:31 +0000327 // - it is a statement-expression whose value expression is an
328 // enumerator-like expression of type T or
329 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
330 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
331 return findEnumForBlockReturn(last);
332 return 0;
333 }
334
335 // - it is a ternary conditional operator (not the GNU ?:
336 // extension) whose second and third operands are
337 // enumerator-like expressions of type T or
338 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
339 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
340 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
341 return ED;
342 return 0;
343 }
344
345 // (implicitly:)
346 // - it is an implicit integral conversion applied to an
347 // enumerator-like expression of type T or
348 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000349 // We can sometimes see integral conversions in valid
350 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000351 if (ICE->getCastKind() == CK_IntegralCast)
352 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000353
354 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000355 }
356
357 // - it is an expression of that formal enum type.
358 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
359 return ET->getDecl();
360 }
361
362 // Otherwise, nope.
363 return 0;
364}
365
366/// Attempt to find a type T for which the returned expression of the
367/// given statement is an enumerator-like expression of that type.
368static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
369 if (Expr *retValue = ret->getRetValue())
370 return findEnumForBlockReturn(retValue);
371 return 0;
372}
373
374/// Attempt to find a common type T for which all of the returned
375/// expressions in a block are enumerator-like expressions of that
376/// type.
377static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
378 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
379
380 // Try to find one for the first return.
381 EnumDecl *ED = findEnumForBlockReturn(*i);
382 if (!ED) return 0;
383
384 // Check that the rest of the returns have the same enum.
385 for (++i; i != e; ++i) {
386 if (findEnumForBlockReturn(*i) != ED)
387 return 0;
388 }
389
390 // Never infer an anonymous enum type.
391 if (!ED->hasNameForLinkage()) return 0;
392
393 return ED;
394}
395
396/// Adjust the given return statements so that they formally return
397/// the given type. It should require, at most, an IntegralCast.
398static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
399 QualType returnType) {
400 for (ArrayRef<ReturnStmt*>::iterator
401 i = returns.begin(), e = returns.end(); i != e; ++i) {
402 ReturnStmt *ret = *i;
403 Expr *retValue = ret->getRetValue();
404 if (S.Context.hasSameType(retValue->getType(), returnType))
405 continue;
406
407 // Right now we only support integral fixup casts.
408 assert(returnType->isIntegralOrUnscopedEnumerationType());
409 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
410
411 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
412
413 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
414 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
415 E, /*base path*/ 0, VK_RValue);
416 if (cleanups) {
417 cleanups->setSubExpr(E);
418 } else {
419 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000420 }
421 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000422}
423
424void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000425 assert(CSI.HasImplicitReturnType);
Faisal Valifad9e132013-09-26 19:54:12 +0000426 // If it was ever a placeholder, it had to been deduced to DependentTy.
427 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rose7dd900e2012-07-02 21:19:23 +0000428
John McCall41d01642013-03-09 00:54:31 +0000429 // C++ Core Issue #975, proposed resolution:
430 // If a lambda-expression does not include a trailing-return-type,
431 // it is as if the trailing-return-type denotes the following type:
432 // - if there are no return statements in the compound-statement,
433 // or all return statements return either an expression of type
434 // void or no expression or braced-init-list, the type void;
435 // - otherwise, if all return statements return an expression
436 // and the types of the returned expressions after
437 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
438 // array-to-pointer conversion (4.2 [conv.array]), and
439 // function-to-pointer conversion (4.3 [conv.func]) are the
440 // same, that common type;
441 // - otherwise, the program is ill-formed.
442 //
443 // In addition, in blocks in non-C++ modes, if all of the return
444 // statements are enumerator-like expressions of some type T, where
445 // T has a name for linkage, then we infer the return type of the
446 // block to be that type.
447
Jordan Rose7dd900e2012-07-02 21:19:23 +0000448 // First case: no return statements, implicit void return type.
449 ASTContext &Ctx = getASTContext();
450 if (CSI.Returns.empty()) {
451 // It's possible there were simply no /valid/ return statements.
452 // In this case, the first one we found may have at least given us a type.
453 if (CSI.ReturnType.isNull())
454 CSI.ReturnType = Ctx.VoidTy;
455 return;
456 }
457
458 // Second case: at least one return statement has dependent type.
459 // Delay type checking until instantiation.
460 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000461 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000462 return;
463
John McCall41d01642013-03-09 00:54:31 +0000464 // Try to apply the enum-fuzz rule.
465 if (!getLangOpts().CPlusPlus) {
466 assert(isa<BlockScopeInfo>(CSI));
467 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
468 if (ED) {
469 CSI.ReturnType = Context.getTypeDeclType(ED);
470 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
471 return;
472 }
473 }
474
Jordan Rose7dd900e2012-07-02 21:19:23 +0000475 // Third case: only one return statement. Don't bother doing extra work!
476 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
477 E = CSI.Returns.end();
478 if (I+1 == E)
479 return;
480
481 // General case: many return statements.
482 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000483
484 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000485 // Note that we've already done the required promotions as part of
486 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000487 for (; I != E; ++I) {
488 const ReturnStmt *RS = *I;
489 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000490
John McCall41d01642013-03-09 00:54:31 +0000491 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
492 if (Context.hasSameType(ReturnType, CSI.ReturnType))
493 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000494
John McCall41d01642013-03-09 00:54:31 +0000495 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
496 // TODO: It's possible that the *first* return is the divergent one.
497 Diag(RS->getLocStart(),
498 diag::err_typecheck_missing_return_type_incompatible)
499 << ReturnType << CSI.ReturnType
500 << isa<LambdaScopeInfo>(CSI);
501 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000502 }
503}
504
Richard Smith04fa7a32013-09-28 04:02:39 +0000505VarDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
506 IdentifierInfo *Id, Expr *Init) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000507 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000508 // An init-capture behaves as if it declares and explicitly captures
509 // a variable of the form
510 // "auto init-capture;"
Richard Smith0d8e9642013-05-16 06:20:58 +0000511 QualType DeductType = Context.getAutoDeductType();
512 TypeLocBuilder TLB;
513 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
514 if (ByRef) {
515 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
516 assert(!DeductType.isNull() && "can't build reference to auto");
517 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
518 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000519 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000520
Richard Smith04fa7a32013-09-28 04:02:39 +0000521 // Create a dummy variable representing the init-capture. This is not actually
522 // used as a variable, and only exists as a way to name and refer to the
523 // init-capture.
524 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith39edfeb2013-09-28 04:31:26 +0000525 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Richard Smith04fa7a32013-09-28 04:02:39 +0000526 Loc, Id, TSI->getType(), TSI, SC_Auto);
527 NewVD->setInitCapture(true);
528 NewVD->setReferenced(true);
529 NewVD->markUsed(Context);
Richard Smith0d8e9642013-05-16 06:20:58 +0000530
Richard Smith04fa7a32013-09-28 04:02:39 +0000531 // We do not need to distinguish between direct-list-initialization
532 // and copy-list-initialization here, because we will always deduce
533 // std::initializer_list<T>, and direct- and copy-list-initialization
534 // always behave the same for such a type.
535 // FIXME: We should model whether an '=' was present.
536 bool DirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
537 AddInitializerToDecl(NewVD, Init, DirectInit, /*ContainsAuto*/true);
538 return NewVD;
539}
Richard Smith0d8e9642013-05-16 06:20:58 +0000540
Richard Smith04fa7a32013-09-28 04:02:39 +0000541FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
542 FieldDecl *Field = FieldDecl::Create(
543 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
544 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
545 Field->setImplicit(true);
546 Field->setAccess(AS_private);
547 LSI->Lambda->addDecl(Field);
Richard Smith0d8e9642013-05-16 06:20:58 +0000548
Richard Smith04fa7a32013-09-28 04:02:39 +0000549 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
550 /*isNested*/false, Var->getLocation(), SourceLocation(),
551 Var->getType(), Var->getInit());
552 return Field;
Richard Smith0d8e9642013-05-16 06:20:58 +0000553}
554
Douglas Gregordfca6f52012-02-13 22:00:16 +0000555void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valifad9e132013-09-26 19:54:12 +0000556 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000557 // Determine if we're within a context where we know that the lambda will
558 // be dependent, because there are template parameters in scope.
559 bool KnownDependent = false;
Faisal Valifad9e132013-09-26 19:54:12 +0000560 LambdaScopeInfo *const LSI = getCurLambda();
561 assert(LSI && "LambdaScopeInfo should be on stack!");
562 TemplateParameterList *TemplateParams =
563 getGenericLambdaTemplateParameterList(LSI, *this);
564
565 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
566 // Since we have our own TemplateParams, so check if an outer scope
567 // has template params, only then are we in a dependent scope.
568 if (TemplateParams) {
569 TmplScope = TmplScope->getParent();
570 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
571 }
572 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000573 KnownDependent = true;
Faisal Valifad9e132013-09-26 19:54:12 +0000574 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000575 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000576 TypeSourceInfo *MethodTyInfo;
577 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000578 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000579 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000581 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000582 if (ParamInfo.getNumTypeObjects() == 0) {
583 // C++11 [expr.prim.lambda]p4:
584 // If a lambda-expression does not include a lambda-declarator, it is as
585 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000586 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
587 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000588 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000589 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000590 // C++1y [expr.prim.lambda]:
591 // The lambda return type is 'auto', which is replaced by the
592 // trailing-return type if provided and/or deduced from 'return'
593 // statements
594 // We don't do this before C++1y, because we don't support deduced return
595 // types there.
596 QualType DefaultTypeForNoTrailingReturn =
597 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
598 : Context.DependentTy;
599 QualType MethodTy =
600 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000601 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
602 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000603 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000604 EndLoc = Intro.Range.getEnd();
605 } else {
606 assert(ParamInfo.isFunctionDeclarator() &&
607 "lambda-declarator is a function");
608 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith41d09582013-09-25 05:02:54 +0000609
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 // C++11 [expr.prim.lambda]p5:
611 // This function call operator is declared const (9.3.1) if and only if
612 // the lambda-expression's parameter-declaration-clause is not followed
613 // by mutable. It is neither virtual nor declared volatile. [...]
614 if (!FTI.hasMutableQualifier())
615 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000616
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000617 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000618 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000619 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith41d09582013-09-25 05:02:54 +0000620
621 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek152b4e42013-08-22 12:12:24 +0000622
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000623 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
624 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
625 // Empty arg list, don't push any params.
626 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
627 } else {
628 Params.reserve(FTI.NumArgs);
629 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
630 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
631 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000632
633 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000634 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
635 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000636 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000637
638 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
Faisal Valibef582b2013-10-23 16:10:50 +0000639 KnownDependent, Intro.Default);
Eli Friedman8da8a662012-09-19 01:18:11 +0000640
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000641 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000642 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000643 if (ExplicitParams)
644 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000645
Bill Wendlingad017fa2012-12-20 19:22:21 +0000646 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000647 ProcessDeclAttributes(CurScope, Method, ParamInfo);
648
Douglas Gregor503384f2012-02-09 00:47:04 +0000649 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000650 PushDeclContext(CurScope, Method);
651
Faisal Valifad9e132013-09-26 19:54:12 +0000652 // Build the lambda scope.
653 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000654 Intro.Range,
655 Intro.Default, Intro.DefaultLoc,
656 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000657 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000658 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000659
660 // Distinct capture names, for diagnostics.
661 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
662
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000663 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000664 SourceLocation PrevCaptureLoc
665 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000666 for (SmallVectorImpl<LambdaCapture>::const_iterator
667 C = Intro.Captures.begin(),
668 E = Intro.Captures.end();
669 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000670 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000671 if (C->Kind == LCK_This) {
672 // C++11 [expr.prim.lambda]p8:
673 // An identifier or this shall not appear more than once in a
674 // lambda-capture.
675 if (LSI->isCXXThisCaptured()) {
676 Diag(C->Loc, diag::err_capture_more_than_once)
677 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000678 << SourceRange(LSI->getCXXThisCapture().getLocation())
679 << FixItHint::CreateRemoval(
680 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000681 continue;
682 }
683
684 // C++11 [expr.prim.lambda]p8:
685 // If a lambda-capture includes a capture-default that is =, the
686 // lambda-capture shall not contain this [...].
687 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000688 Diag(C->Loc, diag::err_this_capture_with_copy_default)
689 << FixItHint::CreateRemoval(
690 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000691 continue;
692 }
693
694 // C++11 [expr.prim.lambda]p12:
695 // If this is captured by a local lambda expression, its nearest
696 // enclosing function shall be a non-static member function.
697 QualType ThisCaptureType = getCurrentThisType();
698 if (ThisCaptureType.isNull()) {
699 Diag(C->Loc, diag::err_this_capture) << true;
700 continue;
701 }
702
703 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
704 continue;
705 }
706
Richard Smith0d8e9642013-05-16 06:20:58 +0000707 assert(C->Id && "missing identifier for capture");
708
Richard Smith0a664b82013-05-09 21:36:41 +0000709 if (C->Init.isInvalid())
710 continue;
Richard Smith0d8e9642013-05-16 06:20:58 +0000711
Richard Smith04fa7a32013-09-28 04:02:39 +0000712 VarDecl *Var;
713 if (C->Init.isUsable()) {
Richard Smith9beaf202013-09-28 05:38:27 +0000714 Diag(C->Loc, getLangOpts().CPlusPlus1y
715 ? diag::warn_cxx11_compat_init_capture
716 : diag::ext_init_capture);
717
Richard Smith0d8e9642013-05-16 06:20:58 +0000718 if (C->Init.get()->containsUnexpandedParameterPack())
719 ContainsUnexpandedParameterPack = true;
720
Richard Smith04fa7a32013-09-28 04:02:39 +0000721 Var = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
722 C->Id, C->Init.take());
Richard Smith0d8e9642013-05-16 06:20:58 +0000723 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000724 // An init-capture behaves as if it declares and explicitly
725 // captures a variable [...] whose declarative region is the
726 // lambda-expression's compound-statement
727 if (Var)
728 PushOnScopeChains(Var, CurScope, false);
729 } else {
730 // C++11 [expr.prim.lambda]p8:
731 // If a lambda-capture includes a capture-default that is &, the
732 // identifiers in the lambda-capture shall not be preceded by &.
733 // If a lambda-capture includes a capture-default that is =, [...]
734 // each identifier it contains shall be preceded by &.
735 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
736 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
737 << FixItHint::CreateRemoval(
738 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000739 continue;
Richard Smith04fa7a32013-09-28 04:02:39 +0000740 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
741 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
742 << FixItHint::CreateRemoval(
743 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
744 continue;
745 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000746
Richard Smith04fa7a32013-09-28 04:02:39 +0000747 // C++11 [expr.prim.lambda]p10:
748 // The identifiers in a capture-list are looked up using the usual
749 // rules for unqualified name lookup (3.4.1)
750 DeclarationNameInfo Name(C->Id, C->Loc);
751 LookupResult R(*this, Name, LookupOrdinaryName);
752 LookupName(R, CurScope);
753 if (R.isAmbiguous())
754 continue;
755 if (R.empty()) {
756 // FIXME: Disable corrections that would add qualification?
757 CXXScopeSpec ScopeSpec;
758 DeclFilterCCC<VarDecl> Validator;
759 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
760 continue;
761 }
762
763 Var = R.getAsSingle<VarDecl>();
764 }
Richard Smith0d8e9642013-05-16 06:20:58 +0000765
766 // C++11 [expr.prim.lambda]p8:
767 // An identifier or this shall not appear more than once in a
768 // lambda-capture.
769 if (!CaptureNames.insert(C->Id)) {
770 if (Var && LSI->isCaptured(Var)) {
771 Diag(C->Loc, diag::err_capture_more_than_once)
772 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
773 << FixItHint::CreateRemoval(
774 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
775 } else
Richard Smith04fa7a32013-09-28 04:02:39 +0000776 // Previous capture captured something different (one or both was
777 // an init-cpature): no fixit.
Richard Smith0d8e9642013-05-16 06:20:58 +0000778 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
779 continue;
780 }
781
782 // C++11 [expr.prim.lambda]p10:
783 // [...] each such lookup shall find a variable with automatic storage
784 // duration declared in the reaching scope of the local lambda expression.
785 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000786 if (!Var) {
787 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
788 continue;
789 }
790
Eli Friedman9cd5b242012-09-18 21:11:30 +0000791 // Ignore invalid decls; they'll just confuse the code later.
792 if (Var->isInvalidDecl())
793 continue;
794
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000795 if (!Var->hasLocalStorage()) {
796 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
797 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
798 continue;
799 }
800
Douglas Gregora7365242012-02-14 19:27:52 +0000801 // C++11 [expr.prim.lambda]p23:
802 // A capture followed by an ellipsis is a pack expansion (14.5.3).
803 SourceLocation EllipsisLoc;
804 if (C->EllipsisLoc.isValid()) {
805 if (Var->isParameterPack()) {
806 EllipsisLoc = C->EllipsisLoc;
807 } else {
808 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
809 << SourceRange(C->Loc);
810
811 // Just ignore the ellipsis.
812 }
813 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000814 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000815 }
Richard Smith04fa7a32013-09-28 04:02:39 +0000816
817 if (C->Init.isUsable()) {
818 buildInitCaptureField(LSI, Var);
819 } else {
820 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
821 TryCapture_ExplicitByVal;
822 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
823 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000824 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000825 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000826
Richard Smith612409e2012-07-25 03:56:55 +0000827 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
828
Douglas Gregorc6889e72012-02-14 22:28:59 +0000829 // Add lambda parameters into scope.
830 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000831
Douglas Gregordfca6f52012-02-13 22:00:16 +0000832 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000833 // cleanups from the enclosing full-expression.
834 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000835}
836
Douglas Gregordfca6f52012-02-13 22:00:16 +0000837void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
838 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000839 // Leave the expression-evaluation context.
840 DiscardCleanupsInEvaluationContext();
841 PopExpressionEvaluationContext();
842
843 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000844 if (!IsInstantiation)
845 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000846
847 // Finalize the lambda.
848 LambdaScopeInfo *LSI = getCurLambda();
849 CXXRecordDecl *Class = LSI->Lambda;
850 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000851 SmallVector<Decl*, 4> Fields;
852 for (RecordDecl::field_iterator i = Class->field_begin(),
853 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000854 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000855 ActOnFields(0, Class->getLocation(), Class, Fields,
856 SourceLocation(), SourceLocation(), 0);
857 CheckCompletedCXXClass(Class);
858
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000859 PopFunctionScopeInfo();
860}
861
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000862/// \brief Add a lambda's conversion to function pointer, as described in
863/// C++11 [expr.prim.lambda]p6.
864static void addFunctionPointerConversion(Sema &S,
865 SourceRange IntroducerRange,
866 CXXRecordDecl *Class,
867 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000868 // Add the conversion to function pointer.
Faisal Vali605f91f2013-10-24 01:05:22 +0000869 const FunctionProtoType *CallOpProto =
870 CallOperator->getType()->getAs<FunctionProtoType>();
871 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
872 CallOpProto->getExtProtoInfo();
873 QualType PtrToFunctionTy;
874 QualType InvokerFunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000875 {
Faisal Vali605f91f2013-10-24 01:05:22 +0000876 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
Reid Kleckneref072032013-08-27 23:08:25 +0000877 CallingConv CC = S.Context.getDefaultCallingConvention(
Faisal Vali605f91f2013-10-24 01:05:22 +0000878 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
879 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
880 InvokerExtInfo.TypeQuals = 0;
881 assert(InvokerExtInfo.RefQualifier == RQ_None &&
882 "Lambda's call operator should not have a reference qualifier");
883 InvokerFunctionTy = S.Context.getFunctionType(CallOpProto->getResultType(),
884 CallOpProto->getArgTypes(), InvokerExtInfo);
885 PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000886 }
Reid Kleckneref072032013-08-27 23:08:25 +0000887
Faisal Vali605f91f2013-10-24 01:05:22 +0000888 // Create the type of the conversion function.
889 FunctionProtoType::ExtProtoInfo ConvExtInfo(
890 S.Context.getDefaultCallingConvention(
Reid Kleckneref072032013-08-27 23:08:25 +0000891 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Faisal Vali605f91f2013-10-24 01:05:22 +0000892 // The conversion function is always const.
893 ConvExtInfo.TypeQuals = Qualifiers::Const;
894 QualType ConvTy =
895 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
Reid Kleckneref072032013-08-27 23:08:25 +0000896
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000897 SourceLocation Loc = IntroducerRange.getBegin();
Faisal Vali605f91f2013-10-24 01:05:22 +0000898 DeclarationName ConversionName
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000899 = S.Context.DeclarationNames.getCXXConversionFunctionName(
Faisal Vali605f91f2013-10-24 01:05:22 +0000900 S.Context.getCanonicalType(PtrToFunctionTy));
901 DeclarationNameLoc ConvNameLoc;
902 // Construct a TypeSourceInfo for the conversion function, and wire
903 // all the parameters appropriately for the FunctionProtoTypeLoc
904 // so that everything works during transformation/instantiation of
905 // generic lambdas.
906 // The main reason for wiring up the parameters of the conversion
907 // function with that of the call operator is so that constructs
908 // like the following work:
909 // auto L = [](auto b) { <-- 1
910 // return [](auto a) -> decltype(a) { <-- 2
911 // return a;
912 // };
913 // };
914 // int (*fp)(int) = L(5);
915 // Because the trailing return type can contain DeclRefExprs that refer
916 // to the original call operator's variables, we hijack the call
917 // operators ParmVarDecls below.
918 TypeSourceInfo *ConvNamePtrToFunctionTSI =
919 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
920 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
921
922 // The conversion function is a conversion to a pointer-to-function.
923 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
924 FunctionProtoTypeLoc ConvTL =
925 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
926 // Get the result of the conversion function which is a pointer-to-function.
927 PointerTypeLoc PtrToFunctionTL =
928 ConvTL.getResultLoc().getAs<PointerTypeLoc>();
929 // Do the same for the TypeSourceInfo that is used to name the conversion
930 // operator.
931 PointerTypeLoc ConvNamePtrToFunctionTL =
932 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
933
934 // Get the underlying function types that the conversion function will
935 // be converting to (should match the type of the call operator).
936 FunctionProtoTypeLoc CallOpConvTL =
937 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
938 FunctionProtoTypeLoc CallOpConvNameTL =
939 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
940
941 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
942 // These parameter's are essentially used to transform the name and
943 // the type of the conversion operator. By using the same parameters
944 // as the call operator's we don't have to fix any back references that
945 // the trailing return type of the call operator's uses (such as
946 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
947 // - we can simply use the return type of the call operator, and
948 // everything should work.
949 SmallVector<ParmVarDecl *, 4> InvokerParams;
950 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
951 ParmVarDecl *From = CallOperator->getParamDecl(I);
952
953 InvokerParams.push_back(ParmVarDecl::Create(S.Context,
954 // Temporarily add to the TU. This is set to the invoker below.
955 S.Context.getTranslationUnitDecl(),
956 From->getLocStart(),
957 From->getLocation(),
958 From->getIdentifier(),
959 From->getType(),
960 From->getTypeSourceInfo(),
961 From->getStorageClass(),
962 /*DefaultArg=*/0));
963 CallOpConvTL.setArg(I, From);
964 CallOpConvNameTL.setArg(I, From);
965 }
966
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000967 CXXConversionDecl *Conversion
968 = CXXConversionDecl::Create(S.Context, Class, Loc,
Faisal Vali605f91f2013-10-24 01:05:22 +0000969 DeclarationNameInfo(ConversionName,
970 Loc, ConvNameLoc),
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000971 ConvTy,
Faisal Vali605f91f2013-10-24 01:05:22 +0000972 ConvTSI,
Eli Friedman38fa9612013-06-13 19:39:48 +0000973 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000974 /*isConstexpr=*/false,
975 CallOperator->getBody()->getLocEnd());
976 Conversion->setAccess(AS_public);
977 Conversion->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +0000978
979 if (Class->isGenericLambda()) {
980 // Create a template version of the conversion operator, using the template
981 // parameter list of the function call operator.
982 FunctionTemplateDecl *TemplateCallOperator =
983 CallOperator->getDescribedFunctionTemplate();
984 FunctionTemplateDecl *ConversionTemplate =
985 FunctionTemplateDecl::Create(S.Context, Class,
Faisal Vali605f91f2013-10-24 01:05:22 +0000986 Loc, ConversionName,
Faisal Valid6992ab2013-09-29 08:45:24 +0000987 TemplateCallOperator->getTemplateParameters(),
988 Conversion);
989 ConversionTemplate->setAccess(AS_public);
990 ConversionTemplate->setImplicit(true);
991 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
992 Class->addDecl(ConversionTemplate);
993 } else
994 Class->addDecl(Conversion);
Faisal Valifad9e132013-09-26 19:54:12 +0000995 // Add a non-static member function that will be the result of
996 // the conversion with a certain unique ID.
Faisal Vali605f91f2013-10-24 01:05:22 +0000997 DeclarationName InvokerName = &S.Context.Idents.get(
998 getLambdaStaticInvokerName());
Faisal Valid6992ab2013-09-29 08:45:24 +0000999 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1000 // we should get a prebuilt TrivialTypeSourceInfo from Context
1001 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1002 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1003 // loop below and then use its Params to set Invoke->setParams(...) below.
1004 // This would avoid the 'const' qualifier of the calloperator from
1005 // contaminating the type of the invoker, which is currently adjusted
Faisal Vali605f91f2013-10-24 01:05:22 +00001006 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1007 // trailing return type of the invoker would require a visitor to rebuild
1008 // the trailing return type and adjusting all back DeclRefExpr's to refer
1009 // to the new static invoker parameters - not the call operator's.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001010 CXXMethodDecl *Invoke
1011 = CXXMethodDecl::Create(S.Context, Class, Loc,
Faisal Vali605f91f2013-10-24 01:05:22 +00001012 DeclarationNameInfo(InvokerName, Loc),
1013 InvokerFunctionTy,
1014 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001015 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001016 /*IsConstexpr=*/false,
1017 CallOperator->getBody()->getLocEnd());
Faisal Vali605f91f2013-10-24 01:05:22 +00001018 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1019 InvokerParams[I]->setOwningFunction(Invoke);
1020 Invoke->setParams(InvokerParams);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001021 Invoke->setAccess(AS_private);
1022 Invoke->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +00001023 if (Class->isGenericLambda()) {
1024 FunctionTemplateDecl *TemplateCallOperator =
1025 CallOperator->getDescribedFunctionTemplate();
1026 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
Faisal Vali605f91f2013-10-24 01:05:22 +00001027 S.Context, Class, Loc, InvokerName,
Faisal Valid6992ab2013-09-29 08:45:24 +00001028 TemplateCallOperator->getTemplateParameters(),
1029 Invoke);
1030 StaticInvokerTemplate->setAccess(AS_private);
1031 StaticInvokerTemplate->setImplicit(true);
1032 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1033 Class->addDecl(StaticInvokerTemplate);
1034 } else
1035 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001036}
1037
Douglas Gregorc2956e52012-02-15 22:08:38 +00001038/// \brief Add a lambda's conversion to block pointer.
1039static void addBlockPointerConversion(Sema &S,
1040 SourceRange IntroducerRange,
1041 CXXRecordDecl *Class,
1042 CXXMethodDecl *CallOperator) {
1043 const FunctionProtoType *Proto
1044 = CallOperator->getType()->getAs<FunctionProtoType>();
1045 QualType BlockPtrTy;
1046 {
1047 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1048 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +00001049 QualType FunctionTy = S.Context.getFunctionType(
1050 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +00001051 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1052 }
Reid Kleckneref072032013-08-27 23:08:25 +00001053
1054 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1055 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +00001056 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +00001057 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +00001058
1059 SourceLocation Loc = IntroducerRange.getBegin();
1060 DeclarationName Name
1061 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1062 S.Context.getCanonicalType(BlockPtrTy));
1063 DeclarationNameLoc NameLoc;
1064 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1065 CXXConversionDecl *Conversion
1066 = CXXConversionDecl::Create(S.Context, Class, Loc,
1067 DeclarationNameInfo(Name, Loc, NameLoc),
1068 ConvTy,
1069 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +00001070 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +00001071 /*isConstexpr=*/false,
1072 CallOperator->getBody()->getLocEnd());
1073 Conversion->setAccess(AS_public);
1074 Conversion->setImplicit(true);
1075 Class->addDecl(Conversion);
1076}
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001077
Douglas Gregordfca6f52012-02-13 22:00:16 +00001078ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001079 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001080 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001081 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001082 SmallVector<LambdaExpr::Capture, 4> Captures;
1083 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001084 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001085 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001086 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001087 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001088 SourceRange IntroducerRange;
1089 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001090 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001091 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001092 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001093 SmallVector<VarDecl *, 4> ArrayIndexVars;
1094 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001095 {
1096 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001097 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001098 Class = LSI->Lambda;
1099 IntroducerRange = LSI->IntroducerRange;
1100 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001101 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001102 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001103 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001104 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1105 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1106
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001107 // Translate captures.
1108 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1109 LambdaScopeInfo::Capture From = LSI->Captures[I];
1110 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1111 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1112
1113 // Handle 'this' capture.
1114 if (From.isThisCapture()) {
1115 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1116 IsImplicit,
1117 LCK_This));
1118 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1119 getCurrentThisType(),
1120 /*isImplicit=*/true));
1121 continue;
1122 }
1123
1124 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001125 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1126 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001127 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001128 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001129 }
1130
1131 switch (LSI->ImpCaptureStyle) {
1132 case CapturingScopeInfo::ImpCap_None:
1133 CaptureDefault = LCD_None;
1134 break;
1135
1136 case CapturingScopeInfo::ImpCap_LambdaByval:
1137 CaptureDefault = LCD_ByCopy;
1138 break;
1139
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001140 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001141 case CapturingScopeInfo::ImpCap_LambdaByref:
1142 CaptureDefault = LCD_ByRef;
1143 break;
1144
1145 case CapturingScopeInfo::ImpCap_Block:
1146 llvm_unreachable("block capture in lambda");
1147 break;
1148 }
James Dennettf68af642013-08-09 23:08:25 +00001149 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001150
Douglas Gregor54042f12012-02-09 10:18:50 +00001151 // C++11 [expr.prim.lambda]p4:
1152 // If a lambda-expression does not include a
1153 // trailing-return-type, it is as if the trailing-return-type
1154 // denotes the following type:
Richard Smith41d09582013-09-25 05:02:54 +00001155 //
1156 // Skip for C++1y return type deduction semantics which uses
1157 // different machinery.
1158 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001159 // FIXME: Assumes current resolution to core issue 975.
Richard Smith41d09582013-09-25 05:02:54 +00001160 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001161 deduceClosureReturnType(*LSI);
1162
Douglas Gregor54042f12012-02-09 10:18:50 +00001163 // - if there are no return statements in the
1164 // compound-statement, or all return statements return
1165 // either an expression of type void or no expression or
1166 // braced-init-list, the type void;
1167 if (LSI->ReturnType.isNull()) {
1168 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001169 }
1170
1171 // Create a function type with the inferred return type.
1172 const FunctionProtoType *Proto
1173 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001174 QualType FunctionTy = Context.getFunctionType(
1175 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001176 CallOperator->setType(FunctionTy);
1177 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001178 // C++ [expr.prim.lambda]p7:
1179 // The lambda-expression's compound-statement yields the
1180 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001181 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001182 CallOperator->setLexicalDeclContext(Class);
Faisal Valifad9e132013-09-26 19:54:12 +00001183 Decl *TemplateOrNonTemplateCallOperatorDecl =
1184 CallOperator->getDescribedFunctionTemplate()
1185 ? CallOperator->getDescribedFunctionTemplate()
1186 : cast<Decl>(CallOperator);
1187
1188 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1189 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1190
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001191 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001192
Douglas Gregorb5559712012-02-10 16:13:20 +00001193 // C++11 [expr.prim.lambda]p6:
1194 // The closure type for a lambda-expression with no lambda-capture
1195 // has a public non-virtual non-explicit const conversion function
1196 // to pointer to function having the same parameter and return
1197 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001198 if (Captures.empty() && CaptureDefault == LCD_None)
1199 addFunctionPointerConversion(*this, IntroducerRange, Class,
1200 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001201
Douglas Gregorc2956e52012-02-15 22:08:38 +00001202 // Objective-C++:
1203 // The closure type for a lambda-expression has a public non-virtual
1204 // non-explicit const conversion function to a block pointer having the
1205 // same parameter and return types as the closure type's function call
1206 // operator.
Faisal Valid6992ab2013-09-29 08:45:24 +00001207 // FIXME: Fix generic lambda to block conversions.
1208 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1209 !Class->isGenericLambda())
Douglas Gregorc2956e52012-02-15 22:08:38 +00001210 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1211
Douglas Gregorb5559712012-02-10 16:13:20 +00001212 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001213 SmallVector<Decl*, 4> Fields;
1214 for (RecordDecl::field_iterator i = Class->field_begin(),
1215 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001216 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001217 ActOnFields(0, Class->getLocation(), Class, Fields,
1218 SourceLocation(), SourceLocation(), 0);
1219 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001220 }
1221
Douglas Gregor503384f2012-02-09 00:47:04 +00001222 if (LambdaExprNeedsCleanups)
1223 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001224
Douglas Gregore2c59132012-02-09 08:14:43 +00001225 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001226 CaptureDefault, CaptureDefaultLoc,
1227 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001228 ExplicitParams, ExplicitResultType,
1229 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001230 ArrayIndexStarts, Body->getLocEnd(),
1231 ContainsUnexpandedParameterPack);
David Majnemer9d33c402013-10-25 09:12:52 +00001232
Douglas Gregord5387e82012-02-14 00:00:48 +00001233 if (!CurContext->isDependentContext()) {
1234 switch (ExprEvalContexts.back().Context) {
David Majnemer9d33c402013-10-25 09:12:52 +00001235 // C++11 [expr.prim.lambda]p2:
1236 // A lambda-expression shall not appear in an unevaluated operand
1237 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001238 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001239 case UnevaluatedAbstract:
David Majnemer9d33c402013-10-25 09:12:52 +00001240 // C++1y [expr.const]p2:
1241 // A conditional-expression e is a core constant expression unless the
1242 // evaluation of e, following the rules of the abstract machine, would
1243 // evaluate [...] a lambda-expression.
1244 case ConstantEvaluated:
Douglas Gregord5387e82012-02-14 00:00:48 +00001245 // We don't actually diagnose this case immediately, because we
1246 // could be within a context where we might find out later that
1247 // the expression is potentially evaluated (e.g., for typeid).
1248 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1249 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001250
Douglas Gregord5387e82012-02-14 00:00:48 +00001251 case PotentiallyEvaluated:
1252 case PotentiallyEvaluatedIfUsed:
1253 break;
1254 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001255 }
Faisal Valifad9e132013-09-26 19:54:12 +00001256 // TODO: Implement capturing.
1257 if (Lambda->isGenericLambda()) {
Faisal Valid6992ab2013-09-29 08:45:24 +00001258 if (!Captures.empty() || Lambda->getCaptureDefault() != LCD_None) {
Faisal Valifad9e132013-09-26 19:54:12 +00001259 Diag(Lambda->getIntroducerRange().getBegin(),
1260 diag::err_glambda_not_fully_implemented)
1261 << " capturing not implemented yet";
1262 return ExprError();
1263 }
1264 }
Douglas Gregor503384f2012-02-09 00:47:04 +00001265 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001266}
Eli Friedman23f02672012-03-01 04:01:32 +00001267
1268ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1269 SourceLocation ConvLocation,
1270 CXXConversionDecl *Conv,
1271 Expr *Src) {
1272 // Make sure that the lambda call operator is marked used.
1273 CXXRecordDecl *Lambda = Conv->getParent();
1274 CXXMethodDecl *CallOperator
1275 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001276 Lambda->lookup(
1277 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001278 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001279 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001280
1281 ExprResult Init = PerformCopyInitialization(
1282 InitializedEntity::InitializeBlock(ConvLocation,
1283 Src->getType(),
1284 /*NRVO=*/false),
1285 CurrentLocation, Src);
1286 if (!Init.isInvalid())
1287 Init = ActOnFinishFullExpr(Init.take());
1288
1289 if (Init.isInvalid())
1290 return ExprError();
1291
1292 // Create the new block to be returned.
1293 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1294
1295 // Set the type information.
1296 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1297 Block->setIsVariadic(CallOperator->isVariadic());
1298 Block->setBlockMissingReturnType(false);
1299
1300 // Add parameters.
1301 SmallVector<ParmVarDecl *, 4> BlockParams;
1302 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1303 ParmVarDecl *From = CallOperator->getParamDecl(I);
1304 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1305 From->getLocStart(),
1306 From->getLocation(),
1307 From->getIdentifier(),
1308 From->getType(),
1309 From->getTypeSourceInfo(),
1310 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001311 /*DefaultArg=*/0));
1312 }
1313 Block->setParams(BlockParams);
1314
1315 Block->setIsConversionFromLambda(true);
1316
1317 // Add capture. The capture uses a fake variable, which doesn't correspond
1318 // to any actual memory location. However, the initializer copy-initializes
1319 // the lambda object.
1320 TypeSourceInfo *CapVarTSI =
1321 Context.getTrivialTypeSourceInfo(Src->getType());
1322 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1323 ConvLocation, 0,
1324 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001325 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001326 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1327 /*Nested=*/false, /*Copy=*/Init.take());
1328 Block->setCaptures(Context, &Capture, &Capture + 1,
1329 /*CapturesCXXThis=*/false);
1330
1331 // Add a fake function body to the block. IR generation is responsible
1332 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001333 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001334
1335 // Create the block literal expression.
1336 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1337 ExprCleanupObjects.push_back(Block);
1338 ExprNeedsCleanups = true;
1339
1340 return BuildBlock;
1341}