blob: 07ee8905629bbc49ccc4dc8f31a3a04fcb838233 [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"
14#include "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000016#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000017#include "clang/Sema/ScopeInfo.h"
18#include "clang/Sema/SemaInternal.h"
Douglas Gregor3ac109c2012-02-10 17:46:20 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/AST/ExprCXX.h"
21using namespace clang;
22using namespace sema;
23
Douglas Gregorf4b7de12012-02-21 19:11:17 +000024CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000026 DeclContext *DC = CurContext;
27 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
28 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000029
Douglas Gregore2a7ad02012-02-08 21:18:48 +000030 // Start constructing the lambda class.
Douglas Gregorda8962a2012-02-13 15:44:47 +000031 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000032 IntroducerRange.getBegin(),
33 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000034 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000035
36 return Class;
37}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000038
Douglas Gregorf54486a2012-04-04 17:40:10 +000039/// \brief Determine whether the given context is or is enclosed in an inline
40/// function.
41static bool isInInlineFunction(const DeclContext *DC) {
42 while (!DC->isFileContext()) {
43 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
44 if (FD->isInlined())
45 return true;
46
47 DC = DC->getLexicalParent();
48 }
49
50 return false;
51}
52
Douglas Gregordfca6f52012-02-13 22:00:16 +000053CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +000054 SourceRange IntroducerRange,
55 TypeSourceInfo *MethodType,
56 SourceLocation EndLoc,
57 llvm::ArrayRef<ParmVarDecl *> Params,
58 llvm::Optional<unsigned> ManglingNumber,
59 Decl *ContextDecl) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000060 // C++11 [expr.prim.lambda]p5:
61 // The closure type for a lambda-expression has a public inline function
62 // call operator (13.5.4) whose parameters and return type are described by
63 // the lambda-expression's parameter-declaration-clause and
64 // trailing-return-type respectively.
65 DeclarationName MethodName
66 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67 DeclarationNameLoc MethodNameLoc;
68 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69 = IntroducerRange.getBegin().getRawEncoding();
70 MethodNameLoc.CXXOperatorName.EndOpNameLoc
71 = IntroducerRange.getEnd().getRawEncoding();
72 CXXMethodDecl *Method
73 = CXXMethodDecl::Create(Context, Class, EndLoc,
74 DeclarationNameInfo(MethodName,
75 IntroducerRange.getBegin(),
76 MethodNameLoc),
77 MethodType->getType(), MethodType,
78 /*isStatic=*/false,
79 SC_None,
80 /*isInline=*/true,
81 /*isConstExpr=*/false,
82 EndLoc);
83 Method->setAccess(AS_public);
84
85 // Temporarily set the lexical declaration context to the current
86 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000087 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000088
Douglas Gregorc6889e72012-02-14 22:28:59 +000089 // Add parameters.
90 if (!Params.empty()) {
91 Method->setParams(Params);
92 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
93 const_cast<ParmVarDecl **>(Params.end()),
94 /*CheckParameterNames=*/false);
95
96 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
97 PEnd = Method->param_end();
98 P != PEnd; ++P)
99 (*P)->setOwningFunction(Method);
100 }
101
Douglas Gregorf54486a2012-04-04 17:40:10 +0000102 // If we don't already have a mangling number for this lambda expression,
103 // allocate one now.
104 if (!ManglingNumber) {
105 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
106
107 enum ContextKind {
108 Normal,
109 DefaultArgument,
110 DataMember,
111 StaticDataMember
112 } Kind = Normal;
113
114 // Default arguments of member function parameters that appear in a class
115 // definition, as well as the initializers of data members, receive special
116 // treatment. Identify them.
117 if (ContextDecl) {
118 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
119 if (const DeclContext *LexicalDC
120 = Param->getDeclContext()->getLexicalParent())
121 if (LexicalDC->isRecord())
122 Kind = DefaultArgument;
123 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
124 if (Var->getDeclContext()->isRecord())
125 Kind = StaticDataMember;
126 } else if (isa<FieldDecl>(ContextDecl)) {
127 Kind = DataMember;
128 }
129 }
130
131 switch (Kind) {
132 case Normal:
133 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
134 ManglingNumber = Context.getLambdaManglingNumber(Method);
135 else
136 ManglingNumber = 0;
137
138 // There is no special context for this lambda.
139 ContextDecl = 0;
140 break;
141
142 case StaticDataMember:
143 if (!CurContext->isDependentContext()) {
144 ManglingNumber = 0;
145 ContextDecl = 0;
146 break;
147 }
148 // Fall through to assign a mangling number.
149
150 case DataMember:
151 case DefaultArgument:
152 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
153 .getManglingNumber(Method);
154 break;
155 }
156 }
157
158 Class->setLambdaMangling(*ManglingNumber, ContextDecl);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 return Method;
160}
161
162LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
163 SourceRange IntroducerRange,
164 LambdaCaptureDefault CaptureDefault,
165 bool ExplicitParams,
166 bool ExplicitResultType,
167 bool Mutable) {
168 PushLambdaScope(CallOperator->getParent(), CallOperator);
169 LambdaScopeInfo *LSI = getCurLambda();
170 if (CaptureDefault == LCD_ByCopy)
171 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
172 else if (CaptureDefault == LCD_ByRef)
173 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
174 LSI->IntroducerRange = IntroducerRange;
175 LSI->ExplicitParams = ExplicitParams;
176 LSI->Mutable = Mutable;
177
178 if (ExplicitResultType) {
179 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000180
181 if (!LSI->ReturnType->isDependentType() &&
182 !LSI->ReturnType->isVoidType()) {
183 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
184 diag::err_lambda_incomplete_result)) {
185 // Do nothing.
186 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
187 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
188 << LSI->ReturnType;
189 }
190 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000191 } else {
192 LSI->HasImplicitReturnType = true;
193 }
194
195 return LSI;
196}
197
198void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
199 LSI->finishedExplicitCaptures();
200}
201
Douglas Gregorc6889e72012-02-14 22:28:59 +0000202void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000203 // Introduce our parameters into the function scope
204 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
205 p < NumParams; ++p) {
206 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000207
208 // If this has an identifier, add it to the scope stack.
209 if (CurScope && Param->getIdentifier()) {
210 CheckShadow(CurScope, Param);
211
212 PushOnScopeChains(Param, CurScope);
213 }
214 }
215}
216
217void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
218 Declarator &ParamInfo,
219 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000220 // Determine if we're within a context where we know that the lambda will
221 // be dependent, because there are template parameters in scope.
222 bool KnownDependent = false;
223 if (Scope *TmplScope = CurScope->getTemplateParamParent())
224 if (!TmplScope->decl_empty())
225 KnownDependent = true;
226
227 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000228
229 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000230 TypeSourceInfo *MethodTyInfo;
231 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000232 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000233 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000234 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000235 if (ParamInfo.getNumTypeObjects() == 0) {
236 // C++11 [expr.prim.lambda]p4:
237 // If a lambda-expression does not include a lambda-declarator, it is as
238 // if the lambda-declarator were ().
239 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000240 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000241 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000242 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
243 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000244 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
245 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000246 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000247 EndLoc = Intro.Range.getEnd();
248 } else {
249 assert(ParamInfo.isFunctionDeclarator() &&
250 "lambda-declarator is a function");
251 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
252
253 // C++11 [expr.prim.lambda]p5:
254 // This function call operator is declared const (9.3.1) if and only if
255 // the lambda-expression's parameter-declaration-clause is not followed
256 // by mutable. It is neither virtual nor declared volatile. [...]
257 if (!FTI.hasMutableQualifier())
258 FTI.TypeQuals |= DeclSpec::TQ_const;
259
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000260 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000261 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000262 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000263
264 ExplicitResultType
265 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
266 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000267
268 TypeLoc TL = MethodTyInfo->getTypeLoc();
269 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
270 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
271 Proto.getNumArgs());
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000272
273 // Check for unexpanded parameter packs in the method type.
274 // FIXME: We should allow unexpanded parameter packs here, but that would,
275 // in turn, make the lambda expression contain unexpanded parameter packs.
276 if (DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
277 UPPC_Lambda)) {
278 // Drop the parameters.
279 Params = llvm::ArrayRef<ParmVarDecl *>();
280 FunctionProtoType::ExtProtoInfo EPI;
281 EPI.HasTrailingReturn = false;
282 EPI.TypeQuals |= DeclSpec::TQ_const;
283 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
284 /*Args=*/0, /*NumArgs=*/0, EPI);
285 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
286 ExplicitParams = false;
287 ExplicitResultType = false;
288 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000289 }
290
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000291 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000292 MethodTyInfo, EndLoc, Params);
293
294 if (ExplicitParams)
295 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000296
Douglas Gregor503384f2012-02-09 00:47:04 +0000297 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000298 ProcessDeclAttributes(CurScope, Method, ParamInfo);
299
Douglas Gregor503384f2012-02-09 00:47:04 +0000300 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000301 PushDeclContext(CurScope, Method);
302
303 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000304 LambdaScopeInfo *LSI
305 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
306 ExplicitResultType,
307 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000308
309 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000310 SourceLocation PrevCaptureLoc
311 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000312 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
313 C = Intro.Captures.begin(),
314 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000315 C != E;
316 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000317 if (C->Kind == LCK_This) {
318 // C++11 [expr.prim.lambda]p8:
319 // An identifier or this shall not appear more than once in a
320 // lambda-capture.
321 if (LSI->isCXXThisCaptured()) {
322 Diag(C->Loc, diag::err_capture_more_than_once)
323 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000324 << SourceRange(LSI->getCXXThisCapture().getLocation())
325 << FixItHint::CreateRemoval(
326 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000327 continue;
328 }
329
330 // C++11 [expr.prim.lambda]p8:
331 // If a lambda-capture includes a capture-default that is =, the
332 // lambda-capture shall not contain this [...].
333 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000334 Diag(C->Loc, diag::err_this_capture_with_copy_default)
335 << FixItHint::CreateRemoval(
336 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000337 continue;
338 }
339
340 // C++11 [expr.prim.lambda]p12:
341 // If this is captured by a local lambda expression, its nearest
342 // enclosing function shall be a non-static member function.
343 QualType ThisCaptureType = getCurrentThisType();
344 if (ThisCaptureType.isNull()) {
345 Diag(C->Loc, diag::err_this_capture) << true;
346 continue;
347 }
348
349 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
350 continue;
351 }
352
353 assert(C->Id && "missing identifier for capture");
354
355 // C++11 [expr.prim.lambda]p8:
356 // If a lambda-capture includes a capture-default that is &, the
357 // identifiers in the lambda-capture shall not be preceded by &.
358 // If a lambda-capture includes a capture-default that is =, [...]
359 // each identifier it contains shall be preceded by &.
360 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000361 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
362 << FixItHint::CreateRemoval(
363 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000364 continue;
365 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000366 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
367 << FixItHint::CreateRemoval(
368 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000369 continue;
370 }
371
372 DeclarationNameInfo Name(C->Id, C->Loc);
373 LookupResult R(*this, Name, LookupOrdinaryName);
374 LookupName(R, CurScope);
375 if (R.isAmbiguous())
376 continue;
377 if (R.empty()) {
378 // FIXME: Disable corrections that would add qualification?
379 CXXScopeSpec ScopeSpec;
380 DeclFilterCCC<VarDecl> Validator;
381 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
382 continue;
383 }
384
385 // C++11 [expr.prim.lambda]p10:
386 // The identifiers in a capture-list are looked up using the usual rules
387 // for unqualified name lookup (3.4.1); each such lookup shall find a
388 // variable with automatic storage duration declared in the reaching
389 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000390 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000391 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000392 VarDecl *Var = R.getAsSingle<VarDecl>();
393 if (!Var) {
394 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
395 continue;
396 }
397
398 if (!Var->hasLocalStorage()) {
399 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
400 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
401 continue;
402 }
403
404 // C++11 [expr.prim.lambda]p8:
405 // An identifier or this shall not appear more than once in a
406 // lambda-capture.
407 if (LSI->isCaptured(Var)) {
408 Diag(C->Loc, diag::err_capture_more_than_once)
409 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000410 << SourceRange(LSI->getCapture(Var).getLocation())
411 << FixItHint::CreateRemoval(
412 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000413 continue;
414 }
415
Douglas Gregora7365242012-02-14 19:27:52 +0000416 // C++11 [expr.prim.lambda]p23:
417 // A capture followed by an ellipsis is a pack expansion (14.5.3).
418 SourceLocation EllipsisLoc;
419 if (C->EllipsisLoc.isValid()) {
420 if (Var->isParameterPack()) {
421 EllipsisLoc = C->EllipsisLoc;
422 } else {
423 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
424 << SourceRange(C->Loc);
425
426 // Just ignore the ellipsis.
427 }
428 } else if (Var->isParameterPack()) {
429 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
430 continue;
431 }
432
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000433 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
434 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000435 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000436 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000437 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000438
Douglas Gregorc6889e72012-02-14 22:28:59 +0000439 // Add lambda parameters into scope.
440 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000441
Douglas Gregordfca6f52012-02-13 22:00:16 +0000442 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000443 // cleanups from the enclosing full-expression.
444 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000445}
446
Douglas Gregordfca6f52012-02-13 22:00:16 +0000447void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
448 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000449 // Leave the expression-evaluation context.
450 DiscardCleanupsInEvaluationContext();
451 PopExpressionEvaluationContext();
452
453 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000454 if (!IsInstantiation)
455 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000456
457 // Finalize the lambda.
458 LambdaScopeInfo *LSI = getCurLambda();
459 CXXRecordDecl *Class = LSI->Lambda;
460 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000461 SmallVector<Decl*, 4> Fields;
462 for (RecordDecl::field_iterator i = Class->field_begin(),
463 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000464 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000465 ActOnFields(0, Class->getLocation(), Class, Fields,
466 SourceLocation(), SourceLocation(), 0);
467 CheckCompletedCXXClass(Class);
468
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000469 PopFunctionScopeInfo();
470}
471
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000472/// \brief Add a lambda's conversion to function pointer, as described in
473/// C++11 [expr.prim.lambda]p6.
474static void addFunctionPointerConversion(Sema &S,
475 SourceRange IntroducerRange,
476 CXXRecordDecl *Class,
477 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000478 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000479 const FunctionProtoType *Proto
480 = CallOperator->getType()->getAs<FunctionProtoType>();
481 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000482 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000483 {
484 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
485 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000486 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
487 Proto->arg_type_begin(),
488 Proto->getNumArgs(),
489 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000490 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
491 }
492
493 FunctionProtoType::ExtProtoInfo ExtInfo;
494 ExtInfo.TypeQuals = Qualifiers::Const;
495 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
496
497 SourceLocation Loc = IntroducerRange.getBegin();
498 DeclarationName Name
499 = S.Context.DeclarationNames.getCXXConversionFunctionName(
500 S.Context.getCanonicalType(FunctionPtrTy));
501 DeclarationNameLoc NameLoc;
502 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
503 Loc);
504 CXXConversionDecl *Conversion
505 = CXXConversionDecl::Create(S.Context, Class, Loc,
506 DeclarationNameInfo(Name, Loc, NameLoc),
507 ConvTy,
508 S.Context.getTrivialTypeSourceInfo(ConvTy,
509 Loc),
510 /*isInline=*/false, /*isExplicit=*/false,
511 /*isConstexpr=*/false,
512 CallOperator->getBody()->getLocEnd());
513 Conversion->setAccess(AS_public);
514 Conversion->setImplicit(true);
515 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000516
517 // Add a non-static member function "__invoke" that will be the result of
518 // the conversion.
519 Name = &S.Context.Idents.get("__invoke");
520 CXXMethodDecl *Invoke
521 = CXXMethodDecl::Create(S.Context, Class, Loc,
522 DeclarationNameInfo(Name, Loc), FunctionTy,
523 CallOperator->getTypeSourceInfo(),
524 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
525 /*IsConstexpr=*/false,
526 CallOperator->getBody()->getLocEnd());
527 SmallVector<ParmVarDecl *, 4> InvokeParams;
528 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
529 ParmVarDecl *From = CallOperator->getParamDecl(I);
530 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
531 From->getLocStart(),
532 From->getLocation(),
533 From->getIdentifier(),
534 From->getType(),
535 From->getTypeSourceInfo(),
536 From->getStorageClass(),
537 From->getStorageClassAsWritten(),
538 /*DefaultArg=*/0));
539 }
540 Invoke->setParams(InvokeParams);
541 Invoke->setAccess(AS_private);
542 Invoke->setImplicit(true);
543 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000544}
545
Douglas Gregorc2956e52012-02-15 22:08:38 +0000546/// \brief Add a lambda's conversion to block pointer.
547static void addBlockPointerConversion(Sema &S,
548 SourceRange IntroducerRange,
549 CXXRecordDecl *Class,
550 CXXMethodDecl *CallOperator) {
551 const FunctionProtoType *Proto
552 = CallOperator->getType()->getAs<FunctionProtoType>();
553 QualType BlockPtrTy;
554 {
555 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
556 ExtInfo.TypeQuals = 0;
557 QualType FunctionTy
558 = S.Context.getFunctionType(Proto->getResultType(),
559 Proto->arg_type_begin(),
560 Proto->getNumArgs(),
561 ExtInfo);
562 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
563 }
564
565 FunctionProtoType::ExtProtoInfo ExtInfo;
566 ExtInfo.TypeQuals = Qualifiers::Const;
567 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
568
569 SourceLocation Loc = IntroducerRange.getBegin();
570 DeclarationName Name
571 = S.Context.DeclarationNames.getCXXConversionFunctionName(
572 S.Context.getCanonicalType(BlockPtrTy));
573 DeclarationNameLoc NameLoc;
574 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
575 CXXConversionDecl *Conversion
576 = CXXConversionDecl::Create(S.Context, Class, Loc,
577 DeclarationNameInfo(Name, Loc, NameLoc),
578 ConvTy,
579 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
580 /*isInline=*/false, /*isExplicit=*/false,
581 /*isConstexpr=*/false,
582 CallOperator->getBody()->getLocEnd());
583 Conversion->setAccess(AS_public);
584 Conversion->setImplicit(true);
585 Class->addDecl(Conversion);
586}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000587
Douglas Gregordfca6f52012-02-13 22:00:16 +0000588ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000589 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000590 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000591 // Collect information from the lambda scope.
592 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
593 llvm::SmallVector<Expr *, 4> CaptureInits;
594 LambdaCaptureDefault CaptureDefault;
595 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000596 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000597 SourceRange IntroducerRange;
598 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000599 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000600 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000601 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
602 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000603 {
604 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000605 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000606 Class = LSI->Lambda;
607 IntroducerRange = LSI->IntroducerRange;
608 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000609 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000610 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000611 ArrayIndexVars.swap(LSI->ArrayIndexVars);
612 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
613
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000614 // Translate captures.
615 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
616 LambdaScopeInfo::Capture From = LSI->Captures[I];
617 assert(!From.isBlockCapture() && "Cannot capture __block variables");
618 bool IsImplicit = I >= LSI->NumExplicitCaptures;
619
620 // Handle 'this' capture.
621 if (From.isThisCapture()) {
622 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
623 IsImplicit,
624 LCK_This));
625 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
626 getCurrentThisType(),
627 /*isImplicit=*/true));
628 continue;
629 }
630
631 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000632 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
633 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000634 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000635 CaptureInits.push_back(From.getCopyExpr());
636 }
637
638 switch (LSI->ImpCaptureStyle) {
639 case CapturingScopeInfo::ImpCap_None:
640 CaptureDefault = LCD_None;
641 break;
642
643 case CapturingScopeInfo::ImpCap_LambdaByval:
644 CaptureDefault = LCD_ByCopy;
645 break;
646
647 case CapturingScopeInfo::ImpCap_LambdaByref:
648 CaptureDefault = LCD_ByRef;
649 break;
650
651 case CapturingScopeInfo::ImpCap_Block:
652 llvm_unreachable("block capture in lambda");
653 break;
654 }
655
Douglas Gregor54042f12012-02-09 10:18:50 +0000656 // C++11 [expr.prim.lambda]p4:
657 // If a lambda-expression does not include a
658 // trailing-return-type, it is as if the trailing-return-type
659 // denotes the following type:
660 // FIXME: Assumes current resolution to core issue 975.
661 if (LSI->HasImplicitReturnType) {
662 // - if there are no return statements in the
663 // compound-statement, or all return statements return
664 // either an expression of type void or no expression or
665 // braced-init-list, the type void;
666 if (LSI->ReturnType.isNull()) {
667 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000668 }
669
670 // Create a function type with the inferred return type.
671 const FunctionProtoType *Proto
672 = CallOperator->getType()->getAs<FunctionProtoType>();
673 QualType FunctionTy
674 = Context.getFunctionType(LSI->ReturnType,
675 Proto->arg_type_begin(),
676 Proto->getNumArgs(),
677 Proto->getExtProtoInfo());
678 CallOperator->setType(FunctionTy);
679 }
680
Douglas Gregor215e4e12012-02-12 17:34:23 +0000681 // C++ [expr.prim.lambda]p7:
682 // The lambda-expression's compound-statement yields the
683 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000684 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000685 CallOperator->setLexicalDeclContext(Class);
686 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000687 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000688
Douglas Gregorb5559712012-02-10 16:13:20 +0000689 // C++11 [expr.prim.lambda]p6:
690 // The closure type for a lambda-expression with no lambda-capture
691 // has a public non-virtual non-explicit const conversion function
692 // to pointer to function having the same parameter and return
693 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000694 if (Captures.empty() && CaptureDefault == LCD_None)
695 addFunctionPointerConversion(*this, IntroducerRange, Class,
696 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000697
Douglas Gregorc2956e52012-02-15 22:08:38 +0000698 // Objective-C++:
699 // The closure type for a lambda-expression has a public non-virtual
700 // non-explicit const conversion function to a block pointer having the
701 // same parameter and return types as the closure type's function call
702 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000703 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000704 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
705
Douglas Gregorb5559712012-02-10 16:13:20 +0000706 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000707 SmallVector<Decl*, 4> Fields;
708 for (RecordDecl::field_iterator i = Class->field_begin(),
709 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000710 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000711 ActOnFields(0, Class->getLocation(), Class, Fields,
712 SourceLocation(), SourceLocation(), 0);
713 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000714 }
715
Douglas Gregor503384f2012-02-09 00:47:04 +0000716 if (LambdaExprNeedsCleanups)
717 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000718
Douglas Gregore2c59132012-02-09 08:14:43 +0000719 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
720 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000721 ExplicitParams, ExplicitResultType,
722 CaptureInits, ArrayIndexVars,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000723 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000724
725 // C++11 [expr.prim.lambda]p2:
726 // A lambda-expression shall not appear in an unevaluated operand
727 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000728 if (!CurContext->isDependentContext()) {
729 switch (ExprEvalContexts.back().Context) {
730 case Unevaluated:
731 // We don't actually diagnose this case immediately, because we
732 // could be within a context where we might find out later that
733 // the expression is potentially evaluated (e.g., for typeid).
734 ExprEvalContexts.back().Lambdas.push_back(Lambda);
735 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000736
Douglas Gregord5387e82012-02-14 00:00:48 +0000737 case ConstantEvaluated:
738 case PotentiallyEvaluated:
739 case PotentiallyEvaluatedIfUsed:
740 break;
741 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000742 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000743
Douglas Gregor503384f2012-02-09 00:47:04 +0000744 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000745}
Eli Friedman23f02672012-03-01 04:01:32 +0000746
747ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
748 SourceLocation ConvLocation,
749 CXXConversionDecl *Conv,
750 Expr *Src) {
751 // Make sure that the lambda call operator is marked used.
752 CXXRecordDecl *Lambda = Conv->getParent();
753 CXXMethodDecl *CallOperator
754 = cast<CXXMethodDecl>(
755 *Lambda->lookup(
756 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
757 CallOperator->setReferenced();
758 CallOperator->setUsed();
759
760 ExprResult Init = PerformCopyInitialization(
761 InitializedEntity::InitializeBlock(ConvLocation,
762 Src->getType(),
763 /*NRVO=*/false),
764 CurrentLocation, Src);
765 if (!Init.isInvalid())
766 Init = ActOnFinishFullExpr(Init.take());
767
768 if (Init.isInvalid())
769 return ExprError();
770
771 // Create the new block to be returned.
772 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
773
774 // Set the type information.
775 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
776 Block->setIsVariadic(CallOperator->isVariadic());
777 Block->setBlockMissingReturnType(false);
778
779 // Add parameters.
780 SmallVector<ParmVarDecl *, 4> BlockParams;
781 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
782 ParmVarDecl *From = CallOperator->getParamDecl(I);
783 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
784 From->getLocStart(),
785 From->getLocation(),
786 From->getIdentifier(),
787 From->getType(),
788 From->getTypeSourceInfo(),
789 From->getStorageClass(),
790 From->getStorageClassAsWritten(),
791 /*DefaultArg=*/0));
792 }
793 Block->setParams(BlockParams);
794
795 Block->setIsConversionFromLambda(true);
796
797 // Add capture. The capture uses a fake variable, which doesn't correspond
798 // to any actual memory location. However, the initializer copy-initializes
799 // the lambda object.
800 TypeSourceInfo *CapVarTSI =
801 Context.getTrivialTypeSourceInfo(Src->getType());
802 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
803 ConvLocation, 0,
804 Src->getType(), CapVarTSI,
805 SC_None, SC_None);
806 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
807 /*Nested=*/false, /*Copy=*/Init.take());
808 Block->setCaptures(Context, &Capture, &Capture + 1,
809 /*CapturesCXXThis=*/false);
810
811 // Add a fake function body to the block. IR generation is responsible
812 // for filling in the actual body, which cannot be expressed as an AST.
813 Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
814 ConvLocation,
815 ConvLocation));
816
817 // Create the block literal expression.
818 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
819 ExprCleanupObjects.push_back(Block);
820 ExprNeedsCleanups = true;
821
822 return BuildBlock;
823}