blob: 51a44a9542e9f22125ab49cab82d267049561ef7 [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 Gregore2a7ad02012-02-08 21:18:48 +0000272 }
273
Douglas Gregordfca6f52012-02-13 22:00:16 +0000274 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000275 MethodTyInfo, EndLoc, Params);
276
277 if (ExplicitParams)
278 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000279
Douglas Gregor503384f2012-02-09 00:47:04 +0000280 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000281 ProcessDeclAttributes(CurScope, Method, ParamInfo);
282
Douglas Gregor503384f2012-02-09 00:47:04 +0000283 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000284 PushDeclContext(CurScope, Method);
285
286 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000287 LambdaScopeInfo *LSI
288 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
289 ExplicitResultType,
290 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000291
292 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000293 SourceLocation PrevCaptureLoc
294 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000295 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
296 C = Intro.Captures.begin(),
297 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000298 C != E;
299 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000300 if (C->Kind == LCK_This) {
301 // C++11 [expr.prim.lambda]p8:
302 // An identifier or this shall not appear more than once in a
303 // lambda-capture.
304 if (LSI->isCXXThisCaptured()) {
305 Diag(C->Loc, diag::err_capture_more_than_once)
306 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000307 << SourceRange(LSI->getCXXThisCapture().getLocation())
308 << FixItHint::CreateRemoval(
309 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000310 continue;
311 }
312
313 // C++11 [expr.prim.lambda]p8:
314 // If a lambda-capture includes a capture-default that is =, the
315 // lambda-capture shall not contain this [...].
316 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000317 Diag(C->Loc, diag::err_this_capture_with_copy_default)
318 << FixItHint::CreateRemoval(
319 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000320 continue;
321 }
322
323 // C++11 [expr.prim.lambda]p12:
324 // If this is captured by a local lambda expression, its nearest
325 // enclosing function shall be a non-static member function.
326 QualType ThisCaptureType = getCurrentThisType();
327 if (ThisCaptureType.isNull()) {
328 Diag(C->Loc, diag::err_this_capture) << true;
329 continue;
330 }
331
332 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
333 continue;
334 }
335
336 assert(C->Id && "missing identifier for capture");
337
338 // C++11 [expr.prim.lambda]p8:
339 // If a lambda-capture includes a capture-default that is &, the
340 // identifiers in the lambda-capture shall not be preceded by &.
341 // If a lambda-capture includes a capture-default that is =, [...]
342 // each identifier it contains shall be preceded by &.
343 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000344 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
345 << FixItHint::CreateRemoval(
346 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000347 continue;
348 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000349 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
350 << FixItHint::CreateRemoval(
351 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000352 continue;
353 }
354
355 DeclarationNameInfo Name(C->Id, C->Loc);
356 LookupResult R(*this, Name, LookupOrdinaryName);
357 LookupName(R, CurScope);
358 if (R.isAmbiguous())
359 continue;
360 if (R.empty()) {
361 // FIXME: Disable corrections that would add qualification?
362 CXXScopeSpec ScopeSpec;
363 DeclFilterCCC<VarDecl> Validator;
364 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
365 continue;
366 }
367
368 // C++11 [expr.prim.lambda]p10:
369 // The identifiers in a capture-list are looked up using the usual rules
370 // for unqualified name lookup (3.4.1); each such lookup shall find a
371 // variable with automatic storage duration declared in the reaching
372 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000373 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000374 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000375 VarDecl *Var = R.getAsSingle<VarDecl>();
376 if (!Var) {
377 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
378 continue;
379 }
380
381 if (!Var->hasLocalStorage()) {
382 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
383 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
384 continue;
385 }
386
387 // C++11 [expr.prim.lambda]p8:
388 // An identifier or this shall not appear more than once in a
389 // lambda-capture.
390 if (LSI->isCaptured(Var)) {
391 Diag(C->Loc, diag::err_capture_more_than_once)
392 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000393 << SourceRange(LSI->getCapture(Var).getLocation())
394 << FixItHint::CreateRemoval(
395 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000396 continue;
397 }
398
Douglas Gregora7365242012-02-14 19:27:52 +0000399 // C++11 [expr.prim.lambda]p23:
400 // A capture followed by an ellipsis is a pack expansion (14.5.3).
401 SourceLocation EllipsisLoc;
402 if (C->EllipsisLoc.isValid()) {
403 if (Var->isParameterPack()) {
404 EllipsisLoc = C->EllipsisLoc;
405 } else {
406 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
407 << SourceRange(C->Loc);
408
409 // Just ignore the ellipsis.
410 }
411 } else if (Var->isParameterPack()) {
412 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
413 continue;
414 }
415
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000416 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
417 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000418 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000419 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000420 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000421
Douglas Gregorc6889e72012-02-14 22:28:59 +0000422 // Add lambda parameters into scope.
423 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000424
Douglas Gregordfca6f52012-02-13 22:00:16 +0000425 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000426 // cleanups from the enclosing full-expression.
427 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000428}
429
Douglas Gregordfca6f52012-02-13 22:00:16 +0000430void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
431 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000432 // Leave the expression-evaluation context.
433 DiscardCleanupsInEvaluationContext();
434 PopExpressionEvaluationContext();
435
436 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000437 if (!IsInstantiation)
438 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000439
440 // Finalize the lambda.
441 LambdaScopeInfo *LSI = getCurLambda();
442 CXXRecordDecl *Class = LSI->Lambda;
443 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000444 SmallVector<Decl*, 4> Fields;
445 for (RecordDecl::field_iterator i = Class->field_begin(),
446 e = Class->field_end(); i != e; ++i)
447 Fields.push_back(&*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000448 ActOnFields(0, Class->getLocation(), Class, Fields,
449 SourceLocation(), SourceLocation(), 0);
450 CheckCompletedCXXClass(Class);
451
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000452 PopFunctionScopeInfo();
453}
454
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000455/// \brief Add a lambda's conversion to function pointer, as described in
456/// C++11 [expr.prim.lambda]p6.
457static void addFunctionPointerConversion(Sema &S,
458 SourceRange IntroducerRange,
459 CXXRecordDecl *Class,
460 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000461 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000462 const FunctionProtoType *Proto
463 = CallOperator->getType()->getAs<FunctionProtoType>();
464 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000465 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000466 {
467 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
468 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000469 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
470 Proto->arg_type_begin(),
471 Proto->getNumArgs(),
472 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000473 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
474 }
475
476 FunctionProtoType::ExtProtoInfo ExtInfo;
477 ExtInfo.TypeQuals = Qualifiers::Const;
478 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
479
480 SourceLocation Loc = IntroducerRange.getBegin();
481 DeclarationName Name
482 = S.Context.DeclarationNames.getCXXConversionFunctionName(
483 S.Context.getCanonicalType(FunctionPtrTy));
484 DeclarationNameLoc NameLoc;
485 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
486 Loc);
487 CXXConversionDecl *Conversion
488 = CXXConversionDecl::Create(S.Context, Class, Loc,
489 DeclarationNameInfo(Name, Loc, NameLoc),
490 ConvTy,
491 S.Context.getTrivialTypeSourceInfo(ConvTy,
492 Loc),
493 /*isInline=*/false, /*isExplicit=*/false,
494 /*isConstexpr=*/false,
495 CallOperator->getBody()->getLocEnd());
496 Conversion->setAccess(AS_public);
497 Conversion->setImplicit(true);
498 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000499
500 // Add a non-static member function "__invoke" that will be the result of
501 // the conversion.
502 Name = &S.Context.Idents.get("__invoke");
503 CXXMethodDecl *Invoke
504 = CXXMethodDecl::Create(S.Context, Class, Loc,
505 DeclarationNameInfo(Name, Loc), FunctionTy,
506 CallOperator->getTypeSourceInfo(),
507 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
508 /*IsConstexpr=*/false,
509 CallOperator->getBody()->getLocEnd());
510 SmallVector<ParmVarDecl *, 4> InvokeParams;
511 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
512 ParmVarDecl *From = CallOperator->getParamDecl(I);
513 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
514 From->getLocStart(),
515 From->getLocation(),
516 From->getIdentifier(),
517 From->getType(),
518 From->getTypeSourceInfo(),
519 From->getStorageClass(),
520 From->getStorageClassAsWritten(),
521 /*DefaultArg=*/0));
522 }
523 Invoke->setParams(InvokeParams);
524 Invoke->setAccess(AS_private);
525 Invoke->setImplicit(true);
526 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000527}
528
Douglas Gregorc2956e52012-02-15 22:08:38 +0000529/// \brief Add a lambda's conversion to block pointer.
530static void addBlockPointerConversion(Sema &S,
531 SourceRange IntroducerRange,
532 CXXRecordDecl *Class,
533 CXXMethodDecl *CallOperator) {
534 const FunctionProtoType *Proto
535 = CallOperator->getType()->getAs<FunctionProtoType>();
536 QualType BlockPtrTy;
537 {
538 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
539 ExtInfo.TypeQuals = 0;
540 QualType FunctionTy
541 = S.Context.getFunctionType(Proto->getResultType(),
542 Proto->arg_type_begin(),
543 Proto->getNumArgs(),
544 ExtInfo);
545 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
546 }
547
548 FunctionProtoType::ExtProtoInfo ExtInfo;
549 ExtInfo.TypeQuals = Qualifiers::Const;
550 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
551
552 SourceLocation Loc = IntroducerRange.getBegin();
553 DeclarationName Name
554 = S.Context.DeclarationNames.getCXXConversionFunctionName(
555 S.Context.getCanonicalType(BlockPtrTy));
556 DeclarationNameLoc NameLoc;
557 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
558 CXXConversionDecl *Conversion
559 = CXXConversionDecl::Create(S.Context, Class, Loc,
560 DeclarationNameInfo(Name, Loc, NameLoc),
561 ConvTy,
562 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
563 /*isInline=*/false, /*isExplicit=*/false,
564 /*isConstexpr=*/false,
565 CallOperator->getBody()->getLocEnd());
566 Conversion->setAccess(AS_public);
567 Conversion->setImplicit(true);
568 Class->addDecl(Conversion);
569}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000570
Douglas Gregordfca6f52012-02-13 22:00:16 +0000571ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000572 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000573 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000574 // Collect information from the lambda scope.
575 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
576 llvm::SmallVector<Expr *, 4> CaptureInits;
577 LambdaCaptureDefault CaptureDefault;
578 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000579 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580 SourceRange IntroducerRange;
581 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000582 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000583 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000584 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
585 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000586 {
587 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000588 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000589 Class = LSI->Lambda;
590 IntroducerRange = LSI->IntroducerRange;
591 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000592 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000593 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000594 ArrayIndexVars.swap(LSI->ArrayIndexVars);
595 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
596
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000597 // Translate captures.
598 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
599 LambdaScopeInfo::Capture From = LSI->Captures[I];
600 assert(!From.isBlockCapture() && "Cannot capture __block variables");
601 bool IsImplicit = I >= LSI->NumExplicitCaptures;
602
603 // Handle 'this' capture.
604 if (From.isThisCapture()) {
605 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
606 IsImplicit,
607 LCK_This));
608 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
609 getCurrentThisType(),
610 /*isImplicit=*/true));
611 continue;
612 }
613
614 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000615 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
616 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000617 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000618 CaptureInits.push_back(From.getCopyExpr());
619 }
620
621 switch (LSI->ImpCaptureStyle) {
622 case CapturingScopeInfo::ImpCap_None:
623 CaptureDefault = LCD_None;
624 break;
625
626 case CapturingScopeInfo::ImpCap_LambdaByval:
627 CaptureDefault = LCD_ByCopy;
628 break;
629
630 case CapturingScopeInfo::ImpCap_LambdaByref:
631 CaptureDefault = LCD_ByRef;
632 break;
633
634 case CapturingScopeInfo::ImpCap_Block:
635 llvm_unreachable("block capture in lambda");
636 break;
637 }
638
Douglas Gregor54042f12012-02-09 10:18:50 +0000639 // C++11 [expr.prim.lambda]p4:
640 // If a lambda-expression does not include a
641 // trailing-return-type, it is as if the trailing-return-type
642 // denotes the following type:
643 // FIXME: Assumes current resolution to core issue 975.
644 if (LSI->HasImplicitReturnType) {
645 // - if there are no return statements in the
646 // compound-statement, or all return statements return
647 // either an expression of type void or no expression or
648 // braced-init-list, the type void;
649 if (LSI->ReturnType.isNull()) {
650 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000651 }
652
653 // Create a function type with the inferred return type.
654 const FunctionProtoType *Proto
655 = CallOperator->getType()->getAs<FunctionProtoType>();
656 QualType FunctionTy
657 = Context.getFunctionType(LSI->ReturnType,
658 Proto->arg_type_begin(),
659 Proto->getNumArgs(),
660 Proto->getExtProtoInfo());
661 CallOperator->setType(FunctionTy);
662 }
663
Douglas Gregor215e4e12012-02-12 17:34:23 +0000664 // C++ [expr.prim.lambda]p7:
665 // The lambda-expression's compound-statement yields the
666 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000667 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000668 CallOperator->setLexicalDeclContext(Class);
669 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000670 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000671
Douglas Gregorb5559712012-02-10 16:13:20 +0000672 // C++11 [expr.prim.lambda]p6:
673 // The closure type for a lambda-expression with no lambda-capture
674 // has a public non-virtual non-explicit const conversion function
675 // to pointer to function having the same parameter and return
676 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000677 if (Captures.empty() && CaptureDefault == LCD_None)
678 addFunctionPointerConversion(*this, IntroducerRange, Class,
679 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000680
Douglas Gregorc2956e52012-02-15 22:08:38 +0000681 // Objective-C++:
682 // The closure type for a lambda-expression has a public non-virtual
683 // non-explicit const conversion function to a block pointer having the
684 // same parameter and return types as the closure type's function call
685 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000686 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000687 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
688
Douglas Gregorb5559712012-02-10 16:13:20 +0000689 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000690 SmallVector<Decl*, 4> Fields;
691 for (RecordDecl::field_iterator i = Class->field_begin(),
692 e = Class->field_end(); i != e; ++i)
693 Fields.push_back(&*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000694 ActOnFields(0, Class->getLocation(), Class, Fields,
695 SourceLocation(), SourceLocation(), 0);
696 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000697 }
698
Douglas Gregor503384f2012-02-09 00:47:04 +0000699 if (LambdaExprNeedsCleanups)
700 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000701
Douglas Gregore2c59132012-02-09 08:14:43 +0000702 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
703 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000704 ExplicitParams, ExplicitResultType,
705 CaptureInits, ArrayIndexVars,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000706 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000707
708 // C++11 [expr.prim.lambda]p2:
709 // A lambda-expression shall not appear in an unevaluated operand
710 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000711 if (!CurContext->isDependentContext()) {
712 switch (ExprEvalContexts.back().Context) {
713 case Unevaluated:
714 // We don't actually diagnose this case immediately, because we
715 // could be within a context where we might find out later that
716 // the expression is potentially evaluated (e.g., for typeid).
717 ExprEvalContexts.back().Lambdas.push_back(Lambda);
718 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000719
Douglas Gregord5387e82012-02-14 00:00:48 +0000720 case ConstantEvaluated:
721 case PotentiallyEvaluated:
722 case PotentiallyEvaluatedIfUsed:
723 break;
724 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000725 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000726
Douglas Gregor503384f2012-02-09 00:47:04 +0000727 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000728}
Eli Friedman23f02672012-03-01 04:01:32 +0000729
730ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
731 SourceLocation ConvLocation,
732 CXXConversionDecl *Conv,
733 Expr *Src) {
734 // Make sure that the lambda call operator is marked used.
735 CXXRecordDecl *Lambda = Conv->getParent();
736 CXXMethodDecl *CallOperator
737 = cast<CXXMethodDecl>(
738 *Lambda->lookup(
739 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
740 CallOperator->setReferenced();
741 CallOperator->setUsed();
742
743 ExprResult Init = PerformCopyInitialization(
744 InitializedEntity::InitializeBlock(ConvLocation,
745 Src->getType(),
746 /*NRVO=*/false),
747 CurrentLocation, Src);
748 if (!Init.isInvalid())
749 Init = ActOnFinishFullExpr(Init.take());
750
751 if (Init.isInvalid())
752 return ExprError();
753
754 // Create the new block to be returned.
755 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
756
757 // Set the type information.
758 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
759 Block->setIsVariadic(CallOperator->isVariadic());
760 Block->setBlockMissingReturnType(false);
761
762 // Add parameters.
763 SmallVector<ParmVarDecl *, 4> BlockParams;
764 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
765 ParmVarDecl *From = CallOperator->getParamDecl(I);
766 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
767 From->getLocStart(),
768 From->getLocation(),
769 From->getIdentifier(),
770 From->getType(),
771 From->getTypeSourceInfo(),
772 From->getStorageClass(),
773 From->getStorageClassAsWritten(),
774 /*DefaultArg=*/0));
775 }
776 Block->setParams(BlockParams);
777
778 Block->setIsConversionFromLambda(true);
779
780 // Add capture. The capture uses a fake variable, which doesn't correspond
781 // to any actual memory location. However, the initializer copy-initializes
782 // the lambda object.
783 TypeSourceInfo *CapVarTSI =
784 Context.getTrivialTypeSourceInfo(Src->getType());
785 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
786 ConvLocation, 0,
787 Src->getType(), CapVarTSI,
788 SC_None, SC_None);
789 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
790 /*Nested=*/false, /*Copy=*/Init.take());
791 Block->setCaptures(Context, &Capture, &Capture + 1,
792 /*CapturesCXXThis=*/false);
793
794 // Add a fake function body to the block. IR generation is responsible
795 // for filling in the actual body, which cannot be expressed as an AST.
796 Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
797 ConvLocation,
798 ConvLocation));
799
800 // Create the block literal expression.
801 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
802 ExprCleanupObjects.push_back(Block);
803 ExprNeedsCleanups = true;
804
805 return BuildBlock;
806}