blob: 016322fe5237c749fca54ded047d1635042df6c1 [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 Gregordfca6f52012-02-13 22:00:16 +000039CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
40 SourceRange IntroducerRange,
41 TypeSourceInfo *MethodType,
Douglas Gregorc6889e72012-02-14 22:28:59 +000042 SourceLocation EndLoc,
43 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000044 // C++11 [expr.prim.lambda]p5:
45 // The closure type for a lambda-expression has a public inline function
46 // call operator (13.5.4) whose parameters and return type are described by
47 // the lambda-expression's parameter-declaration-clause and
48 // trailing-return-type respectively.
49 DeclarationName MethodName
50 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
51 DeclarationNameLoc MethodNameLoc;
52 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
53 = IntroducerRange.getBegin().getRawEncoding();
54 MethodNameLoc.CXXOperatorName.EndOpNameLoc
55 = IntroducerRange.getEnd().getRawEncoding();
56 CXXMethodDecl *Method
57 = CXXMethodDecl::Create(Context, Class, EndLoc,
58 DeclarationNameInfo(MethodName,
59 IntroducerRange.getBegin(),
60 MethodNameLoc),
61 MethodType->getType(), MethodType,
62 /*isStatic=*/false,
63 SC_None,
64 /*isInline=*/true,
65 /*isConstExpr=*/false,
66 EndLoc);
67 Method->setAccess(AS_public);
68
69 // Temporarily set the lexical declaration context to the current
70 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000071 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000072
Douglas Gregorc6889e72012-02-14 22:28:59 +000073 // Add parameters.
74 if (!Params.empty()) {
75 Method->setParams(Params);
76 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
77 const_cast<ParmVarDecl **>(Params.end()),
78 /*CheckParameterNames=*/false);
79
80 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
81 PEnd = Method->param_end();
82 P != PEnd; ++P)
83 (*P)->setOwningFunction(Method);
84 }
85
Douglas Gregordfca6f52012-02-13 22:00:16 +000086 return Method;
87}
88
89LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
90 SourceRange IntroducerRange,
91 LambdaCaptureDefault CaptureDefault,
92 bool ExplicitParams,
93 bool ExplicitResultType,
94 bool Mutable) {
95 PushLambdaScope(CallOperator->getParent(), CallOperator);
96 LambdaScopeInfo *LSI = getCurLambda();
97 if (CaptureDefault == LCD_ByCopy)
98 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
99 else if (CaptureDefault == LCD_ByRef)
100 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
101 LSI->IntroducerRange = IntroducerRange;
102 LSI->ExplicitParams = ExplicitParams;
103 LSI->Mutable = Mutable;
104
105 if (ExplicitResultType) {
106 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000107
108 if (!LSI->ReturnType->isDependentType() &&
109 !LSI->ReturnType->isVoidType()) {
110 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
111 diag::err_lambda_incomplete_result)) {
112 // Do nothing.
113 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
114 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
115 << LSI->ReturnType;
116 }
117 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000118 } else {
119 LSI->HasImplicitReturnType = true;
120 }
121
122 return LSI;
123}
124
125void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
126 LSI->finishedExplicitCaptures();
127}
128
Douglas Gregorc6889e72012-02-14 22:28:59 +0000129void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000130 // Introduce our parameters into the function scope
131 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
132 p < NumParams; ++p) {
133 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000134
135 // If this has an identifier, add it to the scope stack.
136 if (CurScope && Param->getIdentifier()) {
137 CheckShadow(CurScope, Param);
138
139 PushOnScopeChains(Param, CurScope);
140 }
141 }
142}
143
144void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
145 Declarator &ParamInfo,
146 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000147 // Determine if we're within a context where we know that the lambda will
148 // be dependent, because there are template parameters in scope.
149 bool KnownDependent = false;
150 if (Scope *TmplScope = CurScope->getTemplateParamParent())
151 if (!TmplScope->decl_empty())
152 KnownDependent = true;
153
154 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000155
156 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000157 TypeSourceInfo *MethodTyInfo;
158 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000160 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000161 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000162 if (ParamInfo.getNumTypeObjects() == 0) {
163 // C++11 [expr.prim.lambda]p4:
164 // If a lambda-expression does not include a lambda-declarator, it is as
165 // if the lambda-declarator were ().
166 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000167 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000168 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000169 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
170 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000171 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
172 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000173 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000174 EndLoc = Intro.Range.getEnd();
175 } else {
176 assert(ParamInfo.isFunctionDeclarator() &&
177 "lambda-declarator is a function");
178 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
179
180 // C++11 [expr.prim.lambda]p5:
181 // This function call operator is declared const (9.3.1) if and only if
182 // the lambda-expression's parameter-declaration-clause is not followed
183 // by mutable. It is neither virtual nor declared volatile. [...]
184 if (!FTI.hasMutableQualifier())
185 FTI.TypeQuals |= DeclSpec::TQ_const;
186
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000187 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000188 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000189 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000190
191 ExplicitResultType
192 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
193 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000194
195 TypeLoc TL = MethodTyInfo->getTypeLoc();
196 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
197 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
198 Proto.getNumArgs());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000199 }
200
Douglas Gregordfca6f52012-02-13 22:00:16 +0000201 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000202 MethodTyInfo, EndLoc, Params);
203
204 if (ExplicitParams)
205 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000206
Douglas Gregor503384f2012-02-09 00:47:04 +0000207 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000208 ProcessDeclAttributes(CurScope, Method, ParamInfo);
209
Douglas Gregor503384f2012-02-09 00:47:04 +0000210 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000211 PushDeclContext(CurScope, Method);
212
213 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000214 LambdaScopeInfo *LSI
215 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
216 ExplicitResultType,
217 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000218
219 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000220 SourceLocation PrevCaptureLoc
221 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000222 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
223 C = Intro.Captures.begin(),
224 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000225 C != E;
226 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000227 if (C->Kind == LCK_This) {
228 // C++11 [expr.prim.lambda]p8:
229 // An identifier or this shall not appear more than once in a
230 // lambda-capture.
231 if (LSI->isCXXThisCaptured()) {
232 Diag(C->Loc, diag::err_capture_more_than_once)
233 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000234 << SourceRange(LSI->getCXXThisCapture().getLocation())
235 << FixItHint::CreateRemoval(
236 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000237 continue;
238 }
239
240 // C++11 [expr.prim.lambda]p8:
241 // If a lambda-capture includes a capture-default that is =, the
242 // lambda-capture shall not contain this [...].
243 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000244 Diag(C->Loc, diag::err_this_capture_with_copy_default)
245 << FixItHint::CreateRemoval(
246 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000247 continue;
248 }
249
250 // C++11 [expr.prim.lambda]p12:
251 // If this is captured by a local lambda expression, its nearest
252 // enclosing function shall be a non-static member function.
253 QualType ThisCaptureType = getCurrentThisType();
254 if (ThisCaptureType.isNull()) {
255 Diag(C->Loc, diag::err_this_capture) << true;
256 continue;
257 }
258
259 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
260 continue;
261 }
262
263 assert(C->Id && "missing identifier for capture");
264
265 // C++11 [expr.prim.lambda]p8:
266 // If a lambda-capture includes a capture-default that is &, the
267 // identifiers in the lambda-capture shall not be preceded by &.
268 // If a lambda-capture includes a capture-default that is =, [...]
269 // each identifier it contains shall be preceded by &.
270 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000271 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
272 << FixItHint::CreateRemoval(
273 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000274 continue;
275 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000276 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
277 << FixItHint::CreateRemoval(
278 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000279 continue;
280 }
281
282 DeclarationNameInfo Name(C->Id, C->Loc);
283 LookupResult R(*this, Name, LookupOrdinaryName);
284 LookupName(R, CurScope);
285 if (R.isAmbiguous())
286 continue;
287 if (R.empty()) {
288 // FIXME: Disable corrections that would add qualification?
289 CXXScopeSpec ScopeSpec;
290 DeclFilterCCC<VarDecl> Validator;
291 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
292 continue;
293 }
294
295 // C++11 [expr.prim.lambda]p10:
296 // The identifiers in a capture-list are looked up using the usual rules
297 // for unqualified name lookup (3.4.1); each such lookup shall find a
298 // variable with automatic storage duration declared in the reaching
299 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000300 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000301 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000302 VarDecl *Var = R.getAsSingle<VarDecl>();
303 if (!Var) {
304 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
305 continue;
306 }
307
308 if (!Var->hasLocalStorage()) {
309 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
310 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
311 continue;
312 }
313
314 // C++11 [expr.prim.lambda]p8:
315 // An identifier or this shall not appear more than once in a
316 // lambda-capture.
317 if (LSI->isCaptured(Var)) {
318 Diag(C->Loc, diag::err_capture_more_than_once)
319 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000320 << SourceRange(LSI->getCapture(Var).getLocation())
321 << FixItHint::CreateRemoval(
322 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000323 continue;
324 }
325
Douglas Gregora7365242012-02-14 19:27:52 +0000326 // C++11 [expr.prim.lambda]p23:
327 // A capture followed by an ellipsis is a pack expansion (14.5.3).
328 SourceLocation EllipsisLoc;
329 if (C->EllipsisLoc.isValid()) {
330 if (Var->isParameterPack()) {
331 EllipsisLoc = C->EllipsisLoc;
332 } else {
333 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
334 << SourceRange(C->Loc);
335
336 // Just ignore the ellipsis.
337 }
338 } else if (Var->isParameterPack()) {
339 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
340 continue;
341 }
342
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000343 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
344 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000345 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000346 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000347 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000348
Douglas Gregorc6889e72012-02-14 22:28:59 +0000349 // Add lambda parameters into scope.
350 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000351
Douglas Gregordfca6f52012-02-13 22:00:16 +0000352 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000353 // cleanups from the enclosing full-expression.
354 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000355}
356
Douglas Gregordfca6f52012-02-13 22:00:16 +0000357void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
358 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000359 // Leave the expression-evaluation context.
360 DiscardCleanupsInEvaluationContext();
361 PopExpressionEvaluationContext();
362
363 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000364 if (!IsInstantiation)
365 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000366
367 // Finalize the lambda.
368 LambdaScopeInfo *LSI = getCurLambda();
369 CXXRecordDecl *Class = LSI->Lambda;
370 Class->setInvalidDecl();
371 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
372 ActOnFields(0, Class->getLocation(), Class, Fields,
373 SourceLocation(), SourceLocation(), 0);
374 CheckCompletedCXXClass(Class);
375
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000376 PopFunctionScopeInfo();
377}
378
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000379/// \brief Add a lambda's conversion to function pointer, as described in
380/// C++11 [expr.prim.lambda]p6.
381static void addFunctionPointerConversion(Sema &S,
382 SourceRange IntroducerRange,
383 CXXRecordDecl *Class,
384 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000385 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000386 const FunctionProtoType *Proto
387 = CallOperator->getType()->getAs<FunctionProtoType>();
388 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000389 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000390 {
391 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
392 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000393 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
394 Proto->arg_type_begin(),
395 Proto->getNumArgs(),
396 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000397 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
398 }
399
400 FunctionProtoType::ExtProtoInfo ExtInfo;
401 ExtInfo.TypeQuals = Qualifiers::Const;
402 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
403
404 SourceLocation Loc = IntroducerRange.getBegin();
405 DeclarationName Name
406 = S.Context.DeclarationNames.getCXXConversionFunctionName(
407 S.Context.getCanonicalType(FunctionPtrTy));
408 DeclarationNameLoc NameLoc;
409 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
410 Loc);
411 CXXConversionDecl *Conversion
412 = CXXConversionDecl::Create(S.Context, Class, Loc,
413 DeclarationNameInfo(Name, Loc, NameLoc),
414 ConvTy,
415 S.Context.getTrivialTypeSourceInfo(ConvTy,
416 Loc),
417 /*isInline=*/false, /*isExplicit=*/false,
418 /*isConstexpr=*/false,
419 CallOperator->getBody()->getLocEnd());
420 Conversion->setAccess(AS_public);
421 Conversion->setImplicit(true);
422 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000423
424 // Add a non-static member function "__invoke" that will be the result of
425 // the conversion.
426 Name = &S.Context.Idents.get("__invoke");
427 CXXMethodDecl *Invoke
428 = CXXMethodDecl::Create(S.Context, Class, Loc,
429 DeclarationNameInfo(Name, Loc), FunctionTy,
430 CallOperator->getTypeSourceInfo(),
431 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
432 /*IsConstexpr=*/false,
433 CallOperator->getBody()->getLocEnd());
434 SmallVector<ParmVarDecl *, 4> InvokeParams;
435 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
436 ParmVarDecl *From = CallOperator->getParamDecl(I);
437 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
438 From->getLocStart(),
439 From->getLocation(),
440 From->getIdentifier(),
441 From->getType(),
442 From->getTypeSourceInfo(),
443 From->getStorageClass(),
444 From->getStorageClassAsWritten(),
445 /*DefaultArg=*/0));
446 }
447 Invoke->setParams(InvokeParams);
448 Invoke->setAccess(AS_private);
449 Invoke->setImplicit(true);
450 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000451}
452
Douglas Gregorc2956e52012-02-15 22:08:38 +0000453/// \brief Add a lambda's conversion to block pointer.
454static void addBlockPointerConversion(Sema &S,
455 SourceRange IntroducerRange,
456 CXXRecordDecl *Class,
457 CXXMethodDecl *CallOperator) {
458 const FunctionProtoType *Proto
459 = CallOperator->getType()->getAs<FunctionProtoType>();
460 QualType BlockPtrTy;
461 {
462 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
463 ExtInfo.TypeQuals = 0;
464 QualType FunctionTy
465 = S.Context.getFunctionType(Proto->getResultType(),
466 Proto->arg_type_begin(),
467 Proto->getNumArgs(),
468 ExtInfo);
469 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
470 }
471
472 FunctionProtoType::ExtProtoInfo ExtInfo;
473 ExtInfo.TypeQuals = Qualifiers::Const;
474 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
475
476 SourceLocation Loc = IntroducerRange.getBegin();
477 DeclarationName Name
478 = S.Context.DeclarationNames.getCXXConversionFunctionName(
479 S.Context.getCanonicalType(BlockPtrTy));
480 DeclarationNameLoc NameLoc;
481 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
482 CXXConversionDecl *Conversion
483 = CXXConversionDecl::Create(S.Context, Class, Loc,
484 DeclarationNameInfo(Name, Loc, NameLoc),
485 ConvTy,
486 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
487 /*isInline=*/false, /*isExplicit=*/false,
488 /*isConstexpr=*/false,
489 CallOperator->getBody()->getLocEnd());
490 Conversion->setAccess(AS_public);
491 Conversion->setImplicit(true);
492 Class->addDecl(Conversion);
493}
494
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000495/// \brief Determine whether the given context is or is enclosed in an inline
496/// function.
497static bool isInInlineFunction(const DeclContext *DC) {
498 while (!DC->isFileContext()) {
499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
500 if (FD->isInlined())
501 return true;
502
503 DC = DC->getLexicalParent();
504 }
505
506 return false;
507}
508
Douglas Gregordfca6f52012-02-13 22:00:16 +0000509ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000510 Scope *CurScope,
511 llvm::Optional<unsigned> ManglingNumber,
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000512 Decl *ContextDecl,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000513 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000514 // Collect information from the lambda scope.
515 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
516 llvm::SmallVector<Expr *, 4> CaptureInits;
517 LambdaCaptureDefault CaptureDefault;
518 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000519 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000520 SourceRange IntroducerRange;
521 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000522 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000523 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000524 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
525 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000526 {
527 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000528 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000529 Class = LSI->Lambda;
530 IntroducerRange = LSI->IntroducerRange;
531 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000532 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000533 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000534 ArrayIndexVars.swap(LSI->ArrayIndexVars);
535 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
536
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000537 // Translate captures.
538 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
539 LambdaScopeInfo::Capture From = LSI->Captures[I];
540 assert(!From.isBlockCapture() && "Cannot capture __block variables");
541 bool IsImplicit = I >= LSI->NumExplicitCaptures;
542
543 // Handle 'this' capture.
544 if (From.isThisCapture()) {
545 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
546 IsImplicit,
547 LCK_This));
548 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
549 getCurrentThisType(),
550 /*isImplicit=*/true));
551 continue;
552 }
553
554 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000555 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
556 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000557 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000558 CaptureInits.push_back(From.getCopyExpr());
559 }
560
561 switch (LSI->ImpCaptureStyle) {
562 case CapturingScopeInfo::ImpCap_None:
563 CaptureDefault = LCD_None;
564 break;
565
566 case CapturingScopeInfo::ImpCap_LambdaByval:
567 CaptureDefault = LCD_ByCopy;
568 break;
569
570 case CapturingScopeInfo::ImpCap_LambdaByref:
571 CaptureDefault = LCD_ByRef;
572 break;
573
574 case CapturingScopeInfo::ImpCap_Block:
575 llvm_unreachable("block capture in lambda");
576 break;
577 }
578
Douglas Gregor54042f12012-02-09 10:18:50 +0000579 // C++11 [expr.prim.lambda]p4:
580 // If a lambda-expression does not include a
581 // trailing-return-type, it is as if the trailing-return-type
582 // denotes the following type:
583 // FIXME: Assumes current resolution to core issue 975.
584 if (LSI->HasImplicitReturnType) {
585 // - if there are no return statements in the
586 // compound-statement, or all return statements return
587 // either an expression of type void or no expression or
588 // braced-init-list, the type void;
589 if (LSI->ReturnType.isNull()) {
590 LSI->ReturnType = Context.VoidTy;
591 } else {
592 // C++11 [expr.prim.lambda]p4:
593 // - if the compound-statement is of the form
594 //
595 // { attribute-specifier-seq[opt] return expression ; }
596 //
597 // the type of the returned expression after
598 // lvalue-to-rvalue conversion (4.1), array-to-pointer
599 // conver- sion (4.2), and function-to-pointer conversion
600 // (4.3);
601 //
602 // Since we're accepting the resolution to a post-C++11 core
603 // issue with a non-trivial extension, provide a warning (by
604 // default).
605 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
606 if (!(CompoundBody->size() == 1 &&
607 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
608 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
609 Diag(IntroducerRange.getBegin(),
610 diag::ext_lambda_implies_void_return);
611 }
612
613 // Create a function type with the inferred return type.
614 const FunctionProtoType *Proto
615 = CallOperator->getType()->getAs<FunctionProtoType>();
616 QualType FunctionTy
617 = Context.getFunctionType(LSI->ReturnType,
618 Proto->arg_type_begin(),
619 Proto->getNumArgs(),
620 Proto->getExtProtoInfo());
621 CallOperator->setType(FunctionTy);
622 }
623
Douglas Gregor215e4e12012-02-12 17:34:23 +0000624 // C++ [expr.prim.lambda]p7:
625 // The lambda-expression's compound-statement yields the
626 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000627 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000628 CallOperator->setLexicalDeclContext(Class);
629 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000630 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000631
Douglas Gregorb5559712012-02-10 16:13:20 +0000632 // C++11 [expr.prim.lambda]p6:
633 // The closure type for a lambda-expression with no lambda-capture
634 // has a public non-virtual non-explicit const conversion function
635 // to pointer to function having the same parameter and return
636 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000637 if (Captures.empty() && CaptureDefault == LCD_None)
638 addFunctionPointerConversion(*this, IntroducerRange, Class,
639 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000640
Douglas Gregorc2956e52012-02-15 22:08:38 +0000641 // Objective-C++:
642 // The closure type for a lambda-expression has a public non-virtual
643 // non-explicit const conversion function to a block pointer having the
644 // same parameter and return types as the closure type's function call
645 // operator.
646 if (getLangOptions().Blocks)
647 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
648
Douglas Gregorb5559712012-02-10 16:13:20 +0000649 // Finalize the lambda class.
650 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000651 ActOnFields(0, Class->getLocation(), Class, Fields,
652 SourceLocation(), SourceLocation(), 0);
653 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000654 }
655
Douglas Gregor503384f2012-02-09 00:47:04 +0000656 if (LambdaExprNeedsCleanups)
657 ExprNeedsCleanups = true;
658
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000659 // If we don't already have a mangling number for this lambda expression,
660 // allocate one now.
661 if (!ManglingNumber) {
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000662 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
663
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000664 enum ContextKind {
665 Normal,
Douglas Gregor552e2992012-02-21 02:22:07 +0000666 DefaultArgument,
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000667 DataMember,
Craig Toppera7b07fd2012-02-21 05:39:57 +0000668 StaticDataMember
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000669 } Kind = Normal;
670
671 // Default arguments of member function parameters that appear in a class
Douglas Gregor552e2992012-02-21 02:22:07 +0000672 // definition, as well as the initializers of data members, receive special
673 // treatment. Identify them.
674 if (ContextDecl) {
675 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
676 if (const DeclContext *LexicalDC
677 = Param->getDeclContext()->getLexicalParent())
678 if (LexicalDC->isRecord())
679 Kind = DefaultArgument;
680 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
681 if (Var->getDeclContext()->isRecord())
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000682 Kind = StaticDataMember;
Douglas Gregor552e2992012-02-21 02:22:07 +0000683 } else if (isa<FieldDecl>(ContextDecl)) {
684 Kind = DataMember;
685 }
686 }
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000687
688 switch (Kind) {
689 case Normal:
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000690 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
691 ManglingNumber = Context.getLambdaManglingNumber(CallOperator);
692 else
693 ManglingNumber = 0;
694
695 // There is no special context for this lambda.
696 ContextDecl = 0;
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000697 break;
698
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000699 case StaticDataMember:
700 if (!CurContext->isDependentContext()) {
701 ManglingNumber = 0;
702 ContextDecl = 0;
703 break;
704 }
705 // Fall through to assign a mangling number.
706
Douglas Gregor552e2992012-02-21 02:22:07 +0000707 case DataMember:
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000708 case DefaultArgument:
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000709 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
710 .getManglingNumber(CallOperator);
711 break;
712 }
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000713 }
714
Douglas Gregore2c59132012-02-09 08:14:43 +0000715 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
716 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000717 ExplicitParams, ExplicitResultType,
718 CaptureInits, ArrayIndexVars,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000719 ArrayIndexStarts, Body->getLocEnd(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000720 *ManglingNumber, ContextDecl);
Douglas Gregore2c59132012-02-09 08:14:43 +0000721
722 // C++11 [expr.prim.lambda]p2:
723 // A lambda-expression shall not appear in an unevaluated operand
724 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000725 if (!CurContext->isDependentContext()) {
726 switch (ExprEvalContexts.back().Context) {
727 case Unevaluated:
728 // We don't actually diagnose this case immediately, because we
729 // could be within a context where we might find out later that
730 // the expression is potentially evaluated (e.g., for typeid).
731 ExprEvalContexts.back().Lambdas.push_back(Lambda);
732 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000733
Douglas Gregord5387e82012-02-14 00:00:48 +0000734 case ConstantEvaluated:
735 case PotentiallyEvaluated:
736 case PotentiallyEvaluatedIfUsed:
737 break;
738 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000739 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000740
Douglas Gregor503384f2012-02-09 00:47:04 +0000741 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000742}