blob: 694fee6776234d1b7bbc91e6db5b7a5a6dac297b [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 Gregordfca6f52012-02-13 22:00:16 +000024CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000025 DeclContext *DC = CurContext;
26 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
27 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000028
Douglas Gregore2a7ad02012-02-08 21:18:48 +000029 // Start constructing the lambda class.
Douglas Gregorda8962a2012-02-13 15:44:47 +000030 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
Douglas Gregordfca6f52012-02-13 22:00:16 +000031 IntroducerRange.getBegin());
Douglas Gregorfa07ab52012-02-20 20:47:06 +000032 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000033
34 return Class;
35}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000036
Douglas Gregordfca6f52012-02-13 22:00:16 +000037CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
38 SourceRange IntroducerRange,
39 TypeSourceInfo *MethodType,
Douglas Gregorc6889e72012-02-14 22:28:59 +000040 SourceLocation EndLoc,
41 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000042 // C++11 [expr.prim.lambda]p5:
43 // The closure type for a lambda-expression has a public inline function
44 // call operator (13.5.4) whose parameters and return type are described by
45 // the lambda-expression's parameter-declaration-clause and
46 // trailing-return-type respectively.
47 DeclarationName MethodName
48 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
49 DeclarationNameLoc MethodNameLoc;
50 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
51 = IntroducerRange.getBegin().getRawEncoding();
52 MethodNameLoc.CXXOperatorName.EndOpNameLoc
53 = IntroducerRange.getEnd().getRawEncoding();
54 CXXMethodDecl *Method
55 = CXXMethodDecl::Create(Context, Class, EndLoc,
56 DeclarationNameInfo(MethodName,
57 IntroducerRange.getBegin(),
58 MethodNameLoc),
59 MethodType->getType(), MethodType,
60 /*isStatic=*/false,
61 SC_None,
62 /*isInline=*/true,
63 /*isConstExpr=*/false,
64 EndLoc);
65 Method->setAccess(AS_public);
66
67 // Temporarily set the lexical declaration context to the current
68 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000069 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000070
Douglas Gregorc6889e72012-02-14 22:28:59 +000071 // Add parameters.
72 if (!Params.empty()) {
73 Method->setParams(Params);
74 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
75 const_cast<ParmVarDecl **>(Params.end()),
76 /*CheckParameterNames=*/false);
77
78 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
79 PEnd = Method->param_end();
80 P != PEnd; ++P)
81 (*P)->setOwningFunction(Method);
82 }
83
Douglas Gregordfca6f52012-02-13 22:00:16 +000084 return Method;
85}
86
87LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
88 SourceRange IntroducerRange,
89 LambdaCaptureDefault CaptureDefault,
90 bool ExplicitParams,
91 bool ExplicitResultType,
92 bool Mutable) {
93 PushLambdaScope(CallOperator->getParent(), CallOperator);
94 LambdaScopeInfo *LSI = getCurLambda();
95 if (CaptureDefault == LCD_ByCopy)
96 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
97 else if (CaptureDefault == LCD_ByRef)
98 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
99 LSI->IntroducerRange = IntroducerRange;
100 LSI->ExplicitParams = ExplicitParams;
101 LSI->Mutable = Mutable;
102
103 if (ExplicitResultType) {
104 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000105
106 if (!LSI->ReturnType->isDependentType() &&
107 !LSI->ReturnType->isVoidType()) {
108 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
109 diag::err_lambda_incomplete_result)) {
110 // Do nothing.
111 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
112 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
113 << LSI->ReturnType;
114 }
115 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000116 } else {
117 LSI->HasImplicitReturnType = true;
118 }
119
120 return LSI;
121}
122
123void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
124 LSI->finishedExplicitCaptures();
125}
126
Douglas Gregorc6889e72012-02-14 22:28:59 +0000127void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000128 // Introduce our parameters into the function scope
129 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
130 p < NumParams; ++p) {
131 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000132
133 // If this has an identifier, add it to the scope stack.
134 if (CurScope && Param->getIdentifier()) {
135 CheckShadow(CurScope, Param);
136
137 PushOnScopeChains(Param, CurScope);
138 }
139 }
140}
141
142void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
143 Declarator &ParamInfo,
144 Scope *CurScope) {
145 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range);
146
147 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000148 TypeSourceInfo *MethodTyInfo;
149 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000150 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000151 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000152 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000153 if (ParamInfo.getNumTypeObjects() == 0) {
154 // C++11 [expr.prim.lambda]p4:
155 // If a lambda-expression does not include a lambda-declarator, it is as
156 // if the lambda-declarator were ().
157 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000158 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000159 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000160 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
161 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000162 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
163 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000164 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000165 EndLoc = Intro.Range.getEnd();
166 } else {
167 assert(ParamInfo.isFunctionDeclarator() &&
168 "lambda-declarator is a function");
169 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
170
171 // C++11 [expr.prim.lambda]p5:
172 // This function call operator is declared const (9.3.1) if and only if
173 // the lambda-expression's parameter-declaration-clause is not followed
174 // by mutable. It is neither virtual nor declared volatile. [...]
175 if (!FTI.hasMutableQualifier())
176 FTI.TypeQuals |= DeclSpec::TQ_const;
177
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000178 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000179 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000180 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000181
182 ExplicitResultType
183 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
184 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000185
186 TypeLoc TL = MethodTyInfo->getTypeLoc();
187 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
188 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
189 Proto.getNumArgs());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000190 }
191
Douglas Gregordfca6f52012-02-13 22:00:16 +0000192 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000193 MethodTyInfo, EndLoc, Params);
194
195 if (ExplicitParams)
196 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000197
Douglas Gregor503384f2012-02-09 00:47:04 +0000198 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000199 ProcessDeclAttributes(CurScope, Method, ParamInfo);
200
Douglas Gregor503384f2012-02-09 00:47:04 +0000201 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000202 PushDeclContext(CurScope, Method);
203
204 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000205 LambdaScopeInfo *LSI
206 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
207 ExplicitResultType,
208 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000209
210 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000211 SourceLocation PrevCaptureLoc
212 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000213 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
214 C = Intro.Captures.begin(),
215 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000216 C != E;
217 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000218 if (C->Kind == LCK_This) {
219 // C++11 [expr.prim.lambda]p8:
220 // An identifier or this shall not appear more than once in a
221 // lambda-capture.
222 if (LSI->isCXXThisCaptured()) {
223 Diag(C->Loc, diag::err_capture_more_than_once)
224 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000225 << SourceRange(LSI->getCXXThisCapture().getLocation())
226 << FixItHint::CreateRemoval(
227 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000228 continue;
229 }
230
231 // C++11 [expr.prim.lambda]p8:
232 // If a lambda-capture includes a capture-default that is =, the
233 // lambda-capture shall not contain this [...].
234 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000235 Diag(C->Loc, diag::err_this_capture_with_copy_default)
236 << FixItHint::CreateRemoval(
237 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000238 continue;
239 }
240
241 // C++11 [expr.prim.lambda]p12:
242 // If this is captured by a local lambda expression, its nearest
243 // enclosing function shall be a non-static member function.
244 QualType ThisCaptureType = getCurrentThisType();
245 if (ThisCaptureType.isNull()) {
246 Diag(C->Loc, diag::err_this_capture) << true;
247 continue;
248 }
249
250 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
251 continue;
252 }
253
254 assert(C->Id && "missing identifier for capture");
255
256 // C++11 [expr.prim.lambda]p8:
257 // If a lambda-capture includes a capture-default that is &, the
258 // identifiers in the lambda-capture shall not be preceded by &.
259 // If a lambda-capture includes a capture-default that is =, [...]
260 // each identifier it contains shall be preceded by &.
261 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000262 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
263 << FixItHint::CreateRemoval(
264 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000265 continue;
266 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000267 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
268 << FixItHint::CreateRemoval(
269 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000270 continue;
271 }
272
273 DeclarationNameInfo Name(C->Id, C->Loc);
274 LookupResult R(*this, Name, LookupOrdinaryName);
275 LookupName(R, CurScope);
276 if (R.isAmbiguous())
277 continue;
278 if (R.empty()) {
279 // FIXME: Disable corrections that would add qualification?
280 CXXScopeSpec ScopeSpec;
281 DeclFilterCCC<VarDecl> Validator;
282 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
283 continue;
284 }
285
286 // C++11 [expr.prim.lambda]p10:
287 // The identifiers in a capture-list are looked up using the usual rules
288 // for unqualified name lookup (3.4.1); each such lookup shall find a
289 // variable with automatic storage duration declared in the reaching
290 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000291 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000292 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000293 VarDecl *Var = R.getAsSingle<VarDecl>();
294 if (!Var) {
295 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
296 continue;
297 }
298
299 if (!Var->hasLocalStorage()) {
300 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
301 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
302 continue;
303 }
304
305 // C++11 [expr.prim.lambda]p8:
306 // An identifier or this shall not appear more than once in a
307 // lambda-capture.
308 if (LSI->isCaptured(Var)) {
309 Diag(C->Loc, diag::err_capture_more_than_once)
310 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000311 << SourceRange(LSI->getCapture(Var).getLocation())
312 << FixItHint::CreateRemoval(
313 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000314 continue;
315 }
316
Douglas Gregora7365242012-02-14 19:27:52 +0000317 // C++11 [expr.prim.lambda]p23:
318 // A capture followed by an ellipsis is a pack expansion (14.5.3).
319 SourceLocation EllipsisLoc;
320 if (C->EllipsisLoc.isValid()) {
321 if (Var->isParameterPack()) {
322 EllipsisLoc = C->EllipsisLoc;
323 } else {
324 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
325 << SourceRange(C->Loc);
326
327 // Just ignore the ellipsis.
328 }
329 } else if (Var->isParameterPack()) {
330 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
331 continue;
332 }
333
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000334 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
335 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000336 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000337 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000338 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000339
Douglas Gregorc6889e72012-02-14 22:28:59 +0000340 // Add lambda parameters into scope.
341 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000342
Douglas Gregordfca6f52012-02-13 22:00:16 +0000343 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000344 // cleanups from the enclosing full-expression.
345 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000346}
347
Douglas Gregordfca6f52012-02-13 22:00:16 +0000348void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
349 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000350 // Leave the expression-evaluation context.
351 DiscardCleanupsInEvaluationContext();
352 PopExpressionEvaluationContext();
353
354 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000355 if (!IsInstantiation)
356 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000357
358 // Finalize the lambda.
359 LambdaScopeInfo *LSI = getCurLambda();
360 CXXRecordDecl *Class = LSI->Lambda;
361 Class->setInvalidDecl();
362 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
363 ActOnFields(0, Class->getLocation(), Class, Fields,
364 SourceLocation(), SourceLocation(), 0);
365 CheckCompletedCXXClass(Class);
366
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000367 PopFunctionScopeInfo();
368}
369
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000370/// \brief Add a lambda's conversion to function pointer, as described in
371/// C++11 [expr.prim.lambda]p6.
372static void addFunctionPointerConversion(Sema &S,
373 SourceRange IntroducerRange,
374 CXXRecordDecl *Class,
375 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000376 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000377 const FunctionProtoType *Proto
378 = CallOperator->getType()->getAs<FunctionProtoType>();
379 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000380 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000381 {
382 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
383 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000384 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
385 Proto->arg_type_begin(),
386 Proto->getNumArgs(),
387 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000388 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
389 }
390
391 FunctionProtoType::ExtProtoInfo ExtInfo;
392 ExtInfo.TypeQuals = Qualifiers::Const;
393 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
394
395 SourceLocation Loc = IntroducerRange.getBegin();
396 DeclarationName Name
397 = S.Context.DeclarationNames.getCXXConversionFunctionName(
398 S.Context.getCanonicalType(FunctionPtrTy));
399 DeclarationNameLoc NameLoc;
400 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
401 Loc);
402 CXXConversionDecl *Conversion
403 = CXXConversionDecl::Create(S.Context, Class, Loc,
404 DeclarationNameInfo(Name, Loc, NameLoc),
405 ConvTy,
406 S.Context.getTrivialTypeSourceInfo(ConvTy,
407 Loc),
408 /*isInline=*/false, /*isExplicit=*/false,
409 /*isConstexpr=*/false,
410 CallOperator->getBody()->getLocEnd());
411 Conversion->setAccess(AS_public);
412 Conversion->setImplicit(true);
413 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000414
415 // Add a non-static member function "__invoke" that will be the result of
416 // the conversion.
417 Name = &S.Context.Idents.get("__invoke");
418 CXXMethodDecl *Invoke
419 = CXXMethodDecl::Create(S.Context, Class, Loc,
420 DeclarationNameInfo(Name, Loc), FunctionTy,
421 CallOperator->getTypeSourceInfo(),
422 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
423 /*IsConstexpr=*/false,
424 CallOperator->getBody()->getLocEnd());
425 SmallVector<ParmVarDecl *, 4> InvokeParams;
426 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
427 ParmVarDecl *From = CallOperator->getParamDecl(I);
428 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
429 From->getLocStart(),
430 From->getLocation(),
431 From->getIdentifier(),
432 From->getType(),
433 From->getTypeSourceInfo(),
434 From->getStorageClass(),
435 From->getStorageClassAsWritten(),
436 /*DefaultArg=*/0));
437 }
438 Invoke->setParams(InvokeParams);
439 Invoke->setAccess(AS_private);
440 Invoke->setImplicit(true);
441 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000442}
443
Douglas Gregorc2956e52012-02-15 22:08:38 +0000444/// \brief Add a lambda's conversion to block pointer.
445static void addBlockPointerConversion(Sema &S,
446 SourceRange IntroducerRange,
447 CXXRecordDecl *Class,
448 CXXMethodDecl *CallOperator) {
449 const FunctionProtoType *Proto
450 = CallOperator->getType()->getAs<FunctionProtoType>();
451 QualType BlockPtrTy;
452 {
453 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
454 ExtInfo.TypeQuals = 0;
455 QualType FunctionTy
456 = S.Context.getFunctionType(Proto->getResultType(),
457 Proto->arg_type_begin(),
458 Proto->getNumArgs(),
459 ExtInfo);
460 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
461 }
462
463 FunctionProtoType::ExtProtoInfo ExtInfo;
464 ExtInfo.TypeQuals = Qualifiers::Const;
465 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
466
467 SourceLocation Loc = IntroducerRange.getBegin();
468 DeclarationName Name
469 = S.Context.DeclarationNames.getCXXConversionFunctionName(
470 S.Context.getCanonicalType(BlockPtrTy));
471 DeclarationNameLoc NameLoc;
472 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
473 CXXConversionDecl *Conversion
474 = CXXConversionDecl::Create(S.Context, Class, Loc,
475 DeclarationNameInfo(Name, Loc, NameLoc),
476 ConvTy,
477 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
478 /*isInline=*/false, /*isExplicit=*/false,
479 /*isConstexpr=*/false,
480 CallOperator->getBody()->getLocEnd());
481 Conversion->setAccess(AS_public);
482 Conversion->setImplicit(true);
483 Class->addDecl(Conversion);
484}
485
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000486/// \brief Determine whether the given context is or is enclosed in an inline
487/// function.
488static bool isInInlineFunction(const DeclContext *DC) {
489 while (!DC->isFileContext()) {
490 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
491 if (FD->isInlined())
492 return true;
493
494 DC = DC->getLexicalParent();
495 }
496
497 return false;
498}
499
Douglas Gregordfca6f52012-02-13 22:00:16 +0000500ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000501 Scope *CurScope,
502 llvm::Optional<unsigned> ManglingNumber,
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000503 Decl *ContextDecl,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000504 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000505 // Leave the expression-evaluation context.
506 DiscardCleanupsInEvaluationContext();
507 PopExpressionEvaluationContext();
508
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000509 // Collect information from the lambda scope.
510 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
511 llvm::SmallVector<Expr *, 4> CaptureInits;
512 LambdaCaptureDefault CaptureDefault;
513 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000514 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000515 SourceRange IntroducerRange;
516 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000517 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000518 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000519 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
520 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000521 {
522 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000523 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000524 Class = LSI->Lambda;
525 IntroducerRange = LSI->IntroducerRange;
526 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000527 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000528 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000529 ArrayIndexVars.swap(LSI->ArrayIndexVars);
530 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
531
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000532 // Translate captures.
533 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
534 LambdaScopeInfo::Capture From = LSI->Captures[I];
535 assert(!From.isBlockCapture() && "Cannot capture __block variables");
536 bool IsImplicit = I >= LSI->NumExplicitCaptures;
537
538 // Handle 'this' capture.
539 if (From.isThisCapture()) {
540 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
541 IsImplicit,
542 LCK_This));
543 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
544 getCurrentThisType(),
545 /*isImplicit=*/true));
546 continue;
547 }
548
549 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000550 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
551 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000552 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000553 CaptureInits.push_back(From.getCopyExpr());
554 }
555
556 switch (LSI->ImpCaptureStyle) {
557 case CapturingScopeInfo::ImpCap_None:
558 CaptureDefault = LCD_None;
559 break;
560
561 case CapturingScopeInfo::ImpCap_LambdaByval:
562 CaptureDefault = LCD_ByCopy;
563 break;
564
565 case CapturingScopeInfo::ImpCap_LambdaByref:
566 CaptureDefault = LCD_ByRef;
567 break;
568
569 case CapturingScopeInfo::ImpCap_Block:
570 llvm_unreachable("block capture in lambda");
571 break;
572 }
573
Douglas Gregor54042f12012-02-09 10:18:50 +0000574 // C++11 [expr.prim.lambda]p4:
575 // If a lambda-expression does not include a
576 // trailing-return-type, it is as if the trailing-return-type
577 // denotes the following type:
578 // FIXME: Assumes current resolution to core issue 975.
579 if (LSI->HasImplicitReturnType) {
580 // - if there are no return statements in the
581 // compound-statement, or all return statements return
582 // either an expression of type void or no expression or
583 // braced-init-list, the type void;
584 if (LSI->ReturnType.isNull()) {
585 LSI->ReturnType = Context.VoidTy;
586 } else {
587 // C++11 [expr.prim.lambda]p4:
588 // - if the compound-statement is of the form
589 //
590 // { attribute-specifier-seq[opt] return expression ; }
591 //
592 // the type of the returned expression after
593 // lvalue-to-rvalue conversion (4.1), array-to-pointer
594 // conver- sion (4.2), and function-to-pointer conversion
595 // (4.3);
596 //
597 // Since we're accepting the resolution to a post-C++11 core
598 // issue with a non-trivial extension, provide a warning (by
599 // default).
600 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
601 if (!(CompoundBody->size() == 1 &&
602 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
603 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
604 Diag(IntroducerRange.getBegin(),
605 diag::ext_lambda_implies_void_return);
606 }
607
608 // Create a function type with the inferred return type.
609 const FunctionProtoType *Proto
610 = CallOperator->getType()->getAs<FunctionProtoType>();
611 QualType FunctionTy
612 = Context.getFunctionType(LSI->ReturnType,
613 Proto->arg_type_begin(),
614 Proto->getNumArgs(),
615 Proto->getExtProtoInfo());
616 CallOperator->setType(FunctionTy);
617 }
618
Douglas Gregor215e4e12012-02-12 17:34:23 +0000619 // C++ [expr.prim.lambda]p7:
620 // The lambda-expression's compound-statement yields the
621 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000622 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000623 CallOperator->setLexicalDeclContext(Class);
624 Class->addDecl(CallOperator);
625
Douglas Gregorb5559712012-02-10 16:13:20 +0000626 // C++11 [expr.prim.lambda]p6:
627 // The closure type for a lambda-expression with no lambda-capture
628 // has a public non-virtual non-explicit const conversion function
629 // to pointer to function having the same parameter and return
630 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000631 if (Captures.empty() && CaptureDefault == LCD_None)
632 addFunctionPointerConversion(*this, IntroducerRange, Class,
633 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000634
Douglas Gregorc2956e52012-02-15 22:08:38 +0000635 // Objective-C++:
636 // The closure type for a lambda-expression has a public non-virtual
637 // non-explicit const conversion function to a block pointer having the
638 // same parameter and return types as the closure type's function call
639 // operator.
640 if (getLangOptions().Blocks)
641 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
642
Douglas Gregorb5559712012-02-10 16:13:20 +0000643 // Finalize the lambda class.
644 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000645 ActOnFields(0, Class->getLocation(), Class, Fields,
646 SourceLocation(), SourceLocation(), 0);
647 CheckCompletedCXXClass(Class);
648
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000649 }
650
Douglas Gregor503384f2012-02-09 00:47:04 +0000651 if (LambdaExprNeedsCleanups)
652 ExprNeedsCleanups = true;
653
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000654 // If we don't already have a mangling number for this lambda expression,
655 // allocate one now.
656 if (!ManglingNumber) {
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000657 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
658
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000659 enum ContextKind {
660 Normal,
Douglas Gregor552e2992012-02-21 02:22:07 +0000661 DefaultArgument,
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000662 DataMember,
Craig Toppera7b07fd2012-02-21 05:39:57 +0000663 StaticDataMember
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000664 } Kind = Normal;
665
666 // Default arguments of member function parameters that appear in a class
Douglas Gregor552e2992012-02-21 02:22:07 +0000667 // definition, as well as the initializers of data members, receive special
668 // treatment. Identify them.
669 if (ContextDecl) {
670 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
671 if (const DeclContext *LexicalDC
672 = Param->getDeclContext()->getLexicalParent())
673 if (LexicalDC->isRecord())
674 Kind = DefaultArgument;
675 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
676 if (Var->getDeclContext()->isRecord())
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000677 Kind = StaticDataMember;
Douglas Gregor552e2992012-02-21 02:22:07 +0000678 } else if (isa<FieldDecl>(ContextDecl)) {
679 Kind = DataMember;
680 }
681 }
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000682
683 switch (Kind) {
684 case Normal:
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000685 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
686 ManglingNumber = Context.getLambdaManglingNumber(CallOperator);
687 else
688 ManglingNumber = 0;
689
690 // There is no special context for this lambda.
691 ContextDecl = 0;
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000692 break;
693
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000694 case StaticDataMember:
695 if (!CurContext->isDependentContext()) {
696 ManglingNumber = 0;
697 ContextDecl = 0;
698 break;
699 }
700 // Fall through to assign a mangling number.
701
Douglas Gregor552e2992012-02-21 02:22:07 +0000702 case DataMember:
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000703 case DefaultArgument:
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000704 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
705 .getManglingNumber(CallOperator);
706 break;
707 }
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000708 }
709
Douglas Gregore2c59132012-02-09 08:14:43 +0000710 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
711 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000712 ExplicitParams, ExplicitResultType,
713 CaptureInits, ArrayIndexVars,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000714 ArrayIndexStarts, Body->getLocEnd(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000715 *ManglingNumber, ContextDecl);
Douglas Gregore2c59132012-02-09 08:14:43 +0000716
717 // C++11 [expr.prim.lambda]p2:
718 // A lambda-expression shall not appear in an unevaluated operand
719 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000720 if (!CurContext->isDependentContext()) {
721 switch (ExprEvalContexts.back().Context) {
722 case Unevaluated:
723 // We don't actually diagnose this case immediately, because we
724 // could be within a context where we might find out later that
725 // the expression is potentially evaluated (e.g., for typeid).
726 ExprEvalContexts.back().Lambdas.push_back(Lambda);
727 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000728
Douglas Gregord5387e82012-02-14 00:00:48 +0000729 case ConstantEvaluated:
730 case PotentiallyEvaluated:
731 case PotentiallyEvaluatedIfUsed:
732 break;
733 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000734 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000735
Douglas Gregor503384f2012-02-09 00:47:04 +0000736 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000737}