1 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ lambda expressions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/DeclSpec.h"
14 #include "clang/Sema/Initialization.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Sema/SemaInternal.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/AST/ExprCXX.h"
21 using namespace clang;
24 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25 bool KnownDependent) {
26 DeclContext *DC = CurContext;
27 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
30 // Start constructing the lambda class.
31 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
32 IntroducerRange.getBegin(),
39 /// \brief Determine whether the given context is or is enclosed in an inline
41 static bool isInInlineFunction(const DeclContext *DC) {
42 while (!DC->isFileContext()) {
43 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
47 DC = DC->getLexicalParent();
53 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
54 SourceRange IntroducerRange,
55 TypeSourceInfo *MethodType,
56 SourceLocation EndLoc,
57 llvm::ArrayRef<ParmVarDecl *> Params,
58 llvm::Optional<unsigned> ManglingNumber,
60 // 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();
73 = CXXMethodDecl::Create(Context, Class, EndLoc,
74 DeclarationNameInfo(MethodName,
75 IntroducerRange.getBegin(),
77 MethodType->getType(), MethodType,
81 /*isConstExpr=*/false,
83 Method->setAccess(AS_public);
85 // Temporarily set the lexical declaration context to the current
86 // context, so that the Scope stack matches the lexical nesting.
87 Method->setLexicalDeclContext(CurContext);
90 if (!Params.empty()) {
91 Method->setParams(Params);
92 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
93 const_cast<ParmVarDecl **>(Params.end()),
94 /*CheckParameterNames=*/false);
96 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
97 PEnd = Method->param_end();
99 (*P)->setOwningFunction(Method);
102 // If we don't already have a mangling number for this lambda expression,
104 if (!ManglingNumber) {
105 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
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.
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)) {
133 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
134 ManglingNumber = Context.getLambdaManglingNumber(Method);
138 // There is no special context for this lambda.
142 case StaticDataMember:
143 if (!CurContext->isDependentContext()) {
148 // Fall through to assign a mangling number.
151 case DefaultArgument:
152 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
153 .getManglingNumber(Method);
158 Class->setLambdaMangling(*ManglingNumber, ContextDecl);
162 LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
163 SourceRange IntroducerRange,
164 LambdaCaptureDefault CaptureDefault,
166 bool ExplicitResultType,
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;
178 if (ExplicitResultType) {
179 LSI->ReturnType = CallOperator->getResultType();
181 if (!LSI->ReturnType->isDependentType() &&
182 !LSI->ReturnType->isVoidType()) {
183 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
184 diag::err_lambda_incomplete_result)) {
186 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
187 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
192 LSI->HasImplicitReturnType = true;
198 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
199 LSI->finishedExplicitCaptures();
202 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
203 // 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);
208 // If this has an identifier, add it to the scope stack.
209 if (CurScope && Param->getIdentifier()) {
210 CheckShadow(CurScope, Param);
212 PushOnScopeChains(Param, CurScope);
217 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
218 Declarator &ParamInfo,
220 // 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;
227 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
229 // Determine the signature of the call operator.
230 TypeSourceInfo *MethodTyInfo;
231 bool ExplicitParams = true;
232 bool ExplicitResultType = true;
233 SourceLocation EndLoc;
234 llvm::ArrayRef<ParmVarDecl *> Params;
235 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;
240 EPI.HasTrailingReturn = true;
241 EPI.TypeQuals |= DeclSpec::TQ_const;
242 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
243 /*Args=*/0, /*NumArgs=*/0, EPI);
244 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
245 ExplicitParams = false;
246 ExplicitResultType = false;
247 EndLoc = Intro.Range.getEnd();
249 assert(ParamInfo.isFunctionDeclarator() &&
250 "lambda-declarator is a function");
251 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
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;
260 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
261 assert(MethodTyInfo && "no type from lambda-declarator");
262 EndLoc = ParamInfo.getSourceRange().getEnd();
265 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
266 != Context.DependentTy;
268 TypeLoc TL = MethodTyInfo->getTypeLoc();
269 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
270 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
274 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
275 MethodTyInfo, EndLoc, Params);
278 CheckCXXDefaultArguments(Method);
280 // Attributes on the lambda apply to the method.
281 ProcessDeclAttributes(CurScope, Method, ParamInfo);
283 // Introduce the function call operator as the current declaration context.
284 PushDeclContext(CurScope, Method);
286 // Introduce the lambda scope.
288 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
290 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
292 // Handle explicit captures.
293 SourceLocation PrevCaptureLoc
294 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
295 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
296 C = Intro.Captures.begin(),
297 E = Intro.Captures.end();
299 PrevCaptureLoc = C->Loc, ++C) {
300 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
304 if (LSI->isCXXThisCaptured()) {
305 Diag(C->Loc, diag::err_capture_more_than_once)
307 << SourceRange(LSI->getCXXThisCapture().getLocation())
308 << FixItHint::CreateRemoval(
309 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
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) {
317 Diag(C->Loc, diag::err_this_capture_with_copy_default)
318 << FixItHint::CreateRemoval(
319 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
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;
332 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
336 assert(C->Id && "missing identifier for capture");
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) {
344 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
345 << FixItHint::CreateRemoval(
346 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
348 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
349 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
350 << FixItHint::CreateRemoval(
351 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
355 DeclarationNameInfo Name(C->Id, C->Loc);
356 LookupResult R(*this, Name, LookupOrdinaryName);
357 LookupName(R, CurScope);
361 // FIXME: Disable corrections that would add qualification?
362 CXXScopeSpec ScopeSpec;
363 DeclFilterCCC<VarDecl> Validator;
364 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
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.
374 // Note that the 'reaching scope' check happens in tryCaptureVariable().
375 VarDecl *Var = R.getAsSingle<VarDecl>();
377 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
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;
387 // C++11 [expr.prim.lambda]p8:
388 // An identifier or this shall not appear more than once in a
390 if (LSI->isCaptured(Var)) {
391 Diag(C->Loc, diag::err_capture_more_than_once)
393 << SourceRange(LSI->getCapture(Var).getLocation())
394 << FixItHint::CreateRemoval(
395 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
399 // 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;
406 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
407 << SourceRange(C->Loc);
409 // Just ignore the ellipsis.
411 } else if (Var->isParameterPack()) {
412 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
416 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
417 TryCapture_ExplicitByVal;
418 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
420 finishLambdaExplicitCaptures(LSI);
422 // Add lambda parameters into scope.
423 addLambdaParameters(Method, CurScope);
425 // Enter a new evaluation context to insulate the lambda from any
426 // cleanups from the enclosing full-expression.
427 PushExpressionEvaluationContext(PotentiallyEvaluated);
430 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
431 bool IsInstantiation) {
432 // Leave the expression-evaluation context.
433 DiscardCleanupsInEvaluationContext();
434 PopExpressionEvaluationContext();
436 // Leave the context of the lambda.
437 if (!IsInstantiation)
440 // Finalize the lambda.
441 LambdaScopeInfo *LSI = getCurLambda();
442 CXXRecordDecl *Class = LSI->Lambda;
443 Class->setInvalidDecl();
444 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
445 ActOnFields(0, Class->getLocation(), Class, Fields,
446 SourceLocation(), SourceLocation(), 0);
447 CheckCompletedCXXClass(Class);
449 PopFunctionScopeInfo();
452 /// \brief Add a lambda's conversion to function pointer, as described in
453 /// C++11 [expr.prim.lambda]p6.
454 static void addFunctionPointerConversion(Sema &S,
455 SourceRange IntroducerRange,
456 CXXRecordDecl *Class,
457 CXXMethodDecl *CallOperator) {
458 // Add the conversion to function pointer.
459 const FunctionProtoType *Proto
460 = CallOperator->getType()->getAs<FunctionProtoType>();
461 QualType FunctionPtrTy;
464 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
465 ExtInfo.TypeQuals = 0;
466 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
467 Proto->arg_type_begin(),
470 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
473 FunctionProtoType::ExtProtoInfo ExtInfo;
474 ExtInfo.TypeQuals = Qualifiers::Const;
475 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
477 SourceLocation Loc = IntroducerRange.getBegin();
479 = S.Context.DeclarationNames.getCXXConversionFunctionName(
480 S.Context.getCanonicalType(FunctionPtrTy));
481 DeclarationNameLoc NameLoc;
482 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
484 CXXConversionDecl *Conversion
485 = CXXConversionDecl::Create(S.Context, Class, Loc,
486 DeclarationNameInfo(Name, Loc, NameLoc),
488 S.Context.getTrivialTypeSourceInfo(ConvTy,
490 /*isInline=*/false, /*isExplicit=*/false,
491 /*isConstexpr=*/false,
492 CallOperator->getBody()->getLocEnd());
493 Conversion->setAccess(AS_public);
494 Conversion->setImplicit(true);
495 Class->addDecl(Conversion);
497 // Add a non-static member function "__invoke" that will be the result of
499 Name = &S.Context.Idents.get("__invoke");
500 CXXMethodDecl *Invoke
501 = CXXMethodDecl::Create(S.Context, Class, Loc,
502 DeclarationNameInfo(Name, Loc), FunctionTy,
503 CallOperator->getTypeSourceInfo(),
504 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
505 /*IsConstexpr=*/false,
506 CallOperator->getBody()->getLocEnd());
507 SmallVector<ParmVarDecl *, 4> InvokeParams;
508 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
509 ParmVarDecl *From = CallOperator->getParamDecl(I);
510 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
513 From->getIdentifier(),
515 From->getTypeSourceInfo(),
516 From->getStorageClass(),
517 From->getStorageClassAsWritten(),
520 Invoke->setParams(InvokeParams);
521 Invoke->setAccess(AS_private);
522 Invoke->setImplicit(true);
523 Class->addDecl(Invoke);
526 /// \brief Add a lambda's conversion to block pointer.
527 static void addBlockPointerConversion(Sema &S,
528 SourceRange IntroducerRange,
529 CXXRecordDecl *Class,
530 CXXMethodDecl *CallOperator) {
531 const FunctionProtoType *Proto
532 = CallOperator->getType()->getAs<FunctionProtoType>();
535 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
536 ExtInfo.TypeQuals = 0;
538 = S.Context.getFunctionType(Proto->getResultType(),
539 Proto->arg_type_begin(),
542 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
545 FunctionProtoType::ExtProtoInfo ExtInfo;
546 ExtInfo.TypeQuals = Qualifiers::Const;
547 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
549 SourceLocation Loc = IntroducerRange.getBegin();
551 = S.Context.DeclarationNames.getCXXConversionFunctionName(
552 S.Context.getCanonicalType(BlockPtrTy));
553 DeclarationNameLoc NameLoc;
554 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
555 CXXConversionDecl *Conversion
556 = CXXConversionDecl::Create(S.Context, Class, Loc,
557 DeclarationNameInfo(Name, Loc, NameLoc),
559 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
560 /*isInline=*/false, /*isExplicit=*/false,
561 /*isConstexpr=*/false,
562 CallOperator->getBody()->getLocEnd());
563 Conversion->setAccess(AS_public);
564 Conversion->setImplicit(true);
565 Class->addDecl(Conversion);
568 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
570 bool IsInstantiation) {
571 // Collect information from the lambda scope.
572 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
573 llvm::SmallVector<Expr *, 4> CaptureInits;
574 LambdaCaptureDefault CaptureDefault;
575 CXXRecordDecl *Class;
576 CXXMethodDecl *CallOperator;
577 SourceRange IntroducerRange;
579 bool ExplicitResultType;
580 bool LambdaExprNeedsCleanups;
581 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
582 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
584 LambdaScopeInfo *LSI = getCurLambda();
585 CallOperator = LSI->CallOperator;
587 IntroducerRange = LSI->IntroducerRange;
588 ExplicitParams = LSI->ExplicitParams;
589 ExplicitResultType = !LSI->HasImplicitReturnType;
590 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
591 ArrayIndexVars.swap(LSI->ArrayIndexVars);
592 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
594 // Translate captures.
595 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
596 LambdaScopeInfo::Capture From = LSI->Captures[I];
597 assert(!From.isBlockCapture() && "Cannot capture __block variables");
598 bool IsImplicit = I >= LSI->NumExplicitCaptures;
600 // Handle 'this' capture.
601 if (From.isThisCapture()) {
602 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
605 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
606 getCurrentThisType(),
607 /*isImplicit=*/true));
611 VarDecl *Var = From.getVariable();
612 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
613 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
614 Kind, Var, From.getEllipsisLoc()));
615 CaptureInits.push_back(From.getCopyExpr());
618 switch (LSI->ImpCaptureStyle) {
619 case CapturingScopeInfo::ImpCap_None:
620 CaptureDefault = LCD_None;
623 case CapturingScopeInfo::ImpCap_LambdaByval:
624 CaptureDefault = LCD_ByCopy;
627 case CapturingScopeInfo::ImpCap_LambdaByref:
628 CaptureDefault = LCD_ByRef;
631 case CapturingScopeInfo::ImpCap_Block:
632 llvm_unreachable("block capture in lambda");
636 // C++11 [expr.prim.lambda]p4:
637 // If a lambda-expression does not include a
638 // trailing-return-type, it is as if the trailing-return-type
639 // denotes the following type:
640 // FIXME: Assumes current resolution to core issue 975.
641 if (LSI->HasImplicitReturnType) {
642 // - if there are no return statements in the
643 // compound-statement, or all return statements return
644 // either an expression of type void or no expression or
645 // braced-init-list, the type void;
646 if (LSI->ReturnType.isNull()) {
647 LSI->ReturnType = Context.VoidTy;
649 // C++11 [expr.prim.lambda]p4:
650 // - if the compound-statement is of the form
652 // { attribute-specifier-seq[opt] return expression ; }
654 // the type of the returned expression after
655 // lvalue-to-rvalue conversion (4.1), array-to-pointer
656 // conver- sion (4.2), and function-to-pointer conversion
659 // Since we're accepting the resolution to a post-C++11 core
660 // issue with a non-trivial extension, provide a warning (by
662 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
663 if (!(CompoundBody->size() == 1 &&
664 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
665 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
666 Diag(IntroducerRange.getBegin(),
667 diag::ext_lambda_implies_void_return);
670 // Create a function type with the inferred return type.
671 const FunctionProtoType *Proto
672 = CallOperator->getType()->getAs<FunctionProtoType>();
674 = Context.getFunctionType(LSI->ReturnType,
675 Proto->arg_type_begin(),
677 Proto->getExtProtoInfo());
678 CallOperator->setType(FunctionTy);
681 // C++ [expr.prim.lambda]p7:
682 // The lambda-expression's compound-statement yields the
683 // function-body (8.4) of the function call operator [...].
684 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
685 CallOperator->setLexicalDeclContext(Class);
686 Class->addDecl(CallOperator);
687 PopExpressionEvaluationContext();
689 // C++11 [expr.prim.lambda]p6:
690 // The closure type for a lambda-expression with no lambda-capture
691 // has a public non-virtual non-explicit const conversion function
692 // to pointer to function having the same parameter and return
693 // types as the closure type's function call operator.
694 if (Captures.empty() && CaptureDefault == LCD_None)
695 addFunctionPointerConversion(*this, IntroducerRange, Class,
699 // The closure type for a lambda-expression has a public non-virtual
700 // non-explicit const conversion function to a block pointer having the
701 // same parameter and return types as the closure type's function call
703 if (getLangOpts().Blocks && getLangOpts().ObjC1)
704 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
706 // Finalize the lambda class.
707 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
708 ActOnFields(0, Class->getLocation(), Class, Fields,
709 SourceLocation(), SourceLocation(), 0);
710 CheckCompletedCXXClass(Class);
713 if (LambdaExprNeedsCleanups)
714 ExprNeedsCleanups = true;
716 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
717 CaptureDefault, Captures,
718 ExplicitParams, ExplicitResultType,
719 CaptureInits, ArrayIndexVars,
720 ArrayIndexStarts, Body->getLocEnd());
722 // C++11 [expr.prim.lambda]p2:
723 // A lambda-expression shall not appear in an unevaluated operand
725 if (!CurContext->isDependentContext()) {
726 switch (ExprEvalContexts.back().Context) {
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);
734 case ConstantEvaluated:
735 case PotentiallyEvaluated:
736 case PotentiallyEvaluatedIfUsed:
741 return MaybeBindToTemporary(Lambda);
744 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
745 SourceLocation ConvLocation,
746 CXXConversionDecl *Conv,
748 // Make sure that the lambda call operator is marked used.
749 CXXRecordDecl *Lambda = Conv->getParent();
750 CXXMethodDecl *CallOperator
751 = cast<CXXMethodDecl>(
753 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
754 CallOperator->setReferenced();
755 CallOperator->setUsed();
757 ExprResult Init = PerformCopyInitialization(
758 InitializedEntity::InitializeBlock(ConvLocation,
761 CurrentLocation, Src);
762 if (!Init.isInvalid())
763 Init = ActOnFinishFullExpr(Init.take());
765 if (Init.isInvalid())
768 // Create the new block to be returned.
769 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
771 // Set the type information.
772 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
773 Block->setIsVariadic(CallOperator->isVariadic());
774 Block->setBlockMissingReturnType(false);
777 SmallVector<ParmVarDecl *, 4> BlockParams;
778 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
779 ParmVarDecl *From = CallOperator->getParamDecl(I);
780 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
783 From->getIdentifier(),
785 From->getTypeSourceInfo(),
786 From->getStorageClass(),
787 From->getStorageClassAsWritten(),
790 Block->setParams(BlockParams);
792 Block->setIsConversionFromLambda(true);
794 // Add capture. The capture uses a fake variable, which doesn't correspond
795 // to any actual memory location. However, the initializer copy-initializes
796 // the lambda object.
797 TypeSourceInfo *CapVarTSI =
798 Context.getTrivialTypeSourceInfo(Src->getType());
799 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
801 Src->getType(), CapVarTSI,
803 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
804 /*Nested=*/false, /*Copy=*/Init.take());
805 Block->setCaptures(Context, &Capture, &Capture + 1,
806 /*CapturesCXXThis=*/false);
808 // Add a fake function body to the block. IR generation is responsible
809 // for filling in the actual body, which cannot be expressed as an AST.
810 Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
814 // Create the block literal expression.
815 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
816 ExprCleanupObjects.push_back(Block);
817 ExprNeedsCleanups = true;