1 //===--- 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/AST/ExprCXX.h" 15 #include "clang/Basic/TargetInfo.h" 16 #include "clang/Lex/Preprocessor.h" 17 #include "clang/Sema/Initialization.h" 18 #include "clang/Sema/Lookup.h" 19 #include "clang/Sema/Scope.h" 20 #include "clang/Sema/ScopeInfo.h" 21 #include "clang/Sema/SemaInternal.h" 22 #include "TypeLocBuilder.h" 23 using namespace clang; 24 using namespace sema; 25 26 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, 27 TypeSourceInfo *Info, 28 bool KnownDependent) { 29 DeclContext *DC = CurContext; 30 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 31 DC = DC->getParent(); 32 33 // Start constructing the lambda class. 34 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info, 35 IntroducerRange.getBegin(), 36 KnownDependent); 37 DC->addDecl(Class); 38 39 return Class; 40 } 41 42 /// \brief Determine whether the given context is or is enclosed in an inline 43 /// function. 44 static bool isInInlineFunction(const DeclContext *DC) { 45 while (!DC->isFileContext()) { 46 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 47 if (FD->isInlined()) 48 return true; 49 50 DC = DC->getLexicalParent(); 51 } 52 53 return false; 54 } 55 56 MangleNumberingContext * 57 Sema::getCurrentMangleNumberContext(const DeclContext *DC, 58 Decl *&ManglingContextDecl) { 59 // Compute the context for allocating mangling numbers in the current 60 // expression, if the ABI requires them. 61 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; 62 63 enum ContextKind { 64 Normal, 65 DefaultArgument, 66 DataMember, 67 StaticDataMember 68 } Kind = Normal; 69 70 // Default arguments of member function parameters that appear in a class 71 // definition, as well as the initializers of data members, receive special 72 // treatment. Identify them. 73 if (ManglingContextDecl) { 74 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { 75 if (const DeclContext *LexicalDC 76 = Param->getDeclContext()->getLexicalParent()) 77 if (LexicalDC->isRecord()) 78 Kind = DefaultArgument; 79 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) { 80 if (Var->getDeclContext()->isRecord()) 81 Kind = StaticDataMember; 82 } else if (isa<FieldDecl>(ManglingContextDecl)) { 83 Kind = DataMember; 84 } 85 } 86 87 // Itanium ABI [5.1.7]: 88 // In the following contexts [...] the one-definition rule requires closure 89 // types in different translation units to "correspond": 90 bool IsInNonspecializedTemplate = 91 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext(); 92 switch (Kind) { 93 case Normal: 94 // -- the bodies of non-exported nonspecialized template functions 95 // -- the bodies of inline functions 96 if ((IsInNonspecializedTemplate && 97 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) || 98 isInInlineFunction(CurContext)) { 99 ManglingContextDecl = 0; 100 return &Context.getManglingNumberContext(DC); 101 } 102 103 ManglingContextDecl = 0; 104 return 0; 105 106 case StaticDataMember: 107 // -- the initializers of nonspecialized static members of template classes 108 if (!IsInNonspecializedTemplate) { 109 ManglingContextDecl = 0; 110 return 0; 111 } 112 // Fall through to get the current context. 113 114 case DataMember: 115 // -- the in-class initializers of class members 116 case DefaultArgument: 117 // -- default arguments appearing in class definitions 118 return &ExprEvalContexts.back().getMangleNumberingContext(Context); 119 } 120 121 llvm_unreachable("unexpected context"); 122 } 123 124 MangleNumberingContext & 125 Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext( 126 ASTContext &Ctx) { 127 assert(ManglingContextDecl && "Need to have a context declaration"); 128 if (!MangleNumbering) 129 MangleNumbering = Ctx.createMangleNumberingContext(); 130 return *MangleNumbering; 131 } 132 133 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, 134 SourceRange IntroducerRange, 135 TypeSourceInfo *MethodTypeInfo, 136 SourceLocation EndLoc, 137 ArrayRef<ParmVarDecl *> Params) { 138 QualType MethodType = MethodTypeInfo->getType(); 139 140 // If a lambda appears in a dependent context and has an 'auto' return type, 141 // deduce it to a dependent type. 142 // FIXME: Generic lambda call operators should also get this treatment. 143 if (Class->isDependentContext()) { 144 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); 145 QualType Result = FPT->getResultType(); 146 if (Result->isUndeducedType()) { 147 Result = SubstAutoType(Result, Context.DependentTy); 148 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(), 149 FPT->getExtProtoInfo()); 150 } 151 } 152 153 // C++11 [expr.prim.lambda]p5: 154 // The closure type for a lambda-expression has a public inline function 155 // call operator (13.5.4) whose parameters and return type are described by 156 // the lambda-expression's parameter-declaration-clause and 157 // trailing-return-type respectively. 158 DeclarationName MethodName 159 = Context.DeclarationNames.getCXXOperatorName(OO_Call); 160 DeclarationNameLoc MethodNameLoc; 161 MethodNameLoc.CXXOperatorName.BeginOpNameLoc 162 = IntroducerRange.getBegin().getRawEncoding(); 163 MethodNameLoc.CXXOperatorName.EndOpNameLoc 164 = IntroducerRange.getEnd().getRawEncoding(); 165 CXXMethodDecl *Method 166 = CXXMethodDecl::Create(Context, Class, EndLoc, 167 DeclarationNameInfo(MethodName, 168 IntroducerRange.getBegin(), 169 MethodNameLoc), 170 MethodType, MethodTypeInfo, 171 SC_None, 172 /*isInline=*/true, 173 /*isConstExpr=*/false, 174 EndLoc); 175 Method->setAccess(AS_public); 176 177 // Temporarily set the lexical declaration context to the current 178 // context, so that the Scope stack matches the lexical nesting. 179 Method->setLexicalDeclContext(CurContext); 180 181 // Add parameters. 182 if (!Params.empty()) { 183 Method->setParams(Params); 184 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()), 185 const_cast<ParmVarDecl **>(Params.end()), 186 /*CheckParameterNames=*/false); 187 188 for (CXXMethodDecl::param_iterator P = Method->param_begin(), 189 PEnd = Method->param_end(); 190 P != PEnd; ++P) 191 (*P)->setOwningFunction(Method); 192 } 193 194 Decl *ManglingContextDecl; 195 if (MangleNumberingContext *MCtx = 196 getCurrentMangleNumberContext(Class->getDeclContext(), 197 ManglingContextDecl)) { 198 unsigned ManglingNumber = MCtx->getManglingNumber(Method); 199 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl); 200 } 201 202 return Method; 203 } 204 205 LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator, 206 SourceRange IntroducerRange, 207 LambdaCaptureDefault CaptureDefault, 208 SourceLocation CaptureDefaultLoc, 209 bool ExplicitParams, 210 bool ExplicitResultType, 211 bool Mutable) { 212 PushLambdaScope(CallOperator->getParent(), CallOperator); 213 LambdaScopeInfo *LSI = getCurLambda(); 214 if (CaptureDefault == LCD_ByCopy) 215 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 216 else if (CaptureDefault == LCD_ByRef) 217 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 218 LSI->CaptureDefaultLoc = CaptureDefaultLoc; 219 LSI->IntroducerRange = IntroducerRange; 220 LSI->ExplicitParams = ExplicitParams; 221 LSI->Mutable = Mutable; 222 223 if (ExplicitResultType) { 224 LSI->ReturnType = CallOperator->getResultType(); 225 226 if (!LSI->ReturnType->isDependentType() && 227 !LSI->ReturnType->isVoidType()) { 228 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType, 229 diag::err_lambda_incomplete_result)) { 230 // Do nothing. 231 } 232 } 233 } else { 234 LSI->HasImplicitReturnType = true; 235 } 236 237 return LSI; 238 } 239 240 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 241 LSI->finishedExplicitCaptures(); 242 } 243 244 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { 245 // Introduce our parameters into the function scope 246 for (unsigned p = 0, NumParams = CallOperator->getNumParams(); 247 p < NumParams; ++p) { 248 ParmVarDecl *Param = CallOperator->getParamDecl(p); 249 250 // If this has an identifier, add it to the scope stack. 251 if (CurScope && Param->getIdentifier()) { 252 CheckShadow(CurScope, Param); 253 254 PushOnScopeChains(Param, CurScope); 255 } 256 } 257 } 258 259 /// If this expression is an enumerator-like expression of some type 260 /// T, return the type T; otherwise, return null. 261 /// 262 /// Pointer comparisons on the result here should always work because 263 /// it's derived from either the parent of an EnumConstantDecl 264 /// (i.e. the definition) or the declaration returned by 265 /// EnumType::getDecl() (i.e. the definition). 266 static EnumDecl *findEnumForBlockReturn(Expr *E) { 267 // An expression is an enumerator-like expression of type T if, 268 // ignoring parens and parens-like expressions: 269 E = E->IgnoreParens(); 270 271 // - it is an enumerator whose enum type is T or 272 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 273 if (EnumConstantDecl *D 274 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 275 return cast<EnumDecl>(D->getDeclContext()); 276 } 277 return 0; 278 } 279 280 // - it is a comma expression whose RHS is an enumerator-like 281 // expression of type T or 282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 283 if (BO->getOpcode() == BO_Comma) 284 return findEnumForBlockReturn(BO->getRHS()); 285 return 0; 286 } 287 288 // - it is a statement-expression whose value expression is an 289 // enumerator-like expression of type T or 290 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 291 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) 292 return findEnumForBlockReturn(last); 293 return 0; 294 } 295 296 // - it is a ternary conditional operator (not the GNU ?: 297 // extension) whose second and third operands are 298 // enumerator-like expressions of type T or 299 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 300 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) 301 if (ED == findEnumForBlockReturn(CO->getFalseExpr())) 302 return ED; 303 return 0; 304 } 305 306 // (implicitly:) 307 // - it is an implicit integral conversion applied to an 308 // enumerator-like expression of type T or 309 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 310 // We can sometimes see integral conversions in valid 311 // enumerator-like expressions. 312 if (ICE->getCastKind() == CK_IntegralCast) 313 return findEnumForBlockReturn(ICE->getSubExpr()); 314 315 // Otherwise, just rely on the type. 316 } 317 318 // - it is an expression of that formal enum type. 319 if (const EnumType *ET = E->getType()->getAs<EnumType>()) { 320 return ET->getDecl(); 321 } 322 323 // Otherwise, nope. 324 return 0; 325 } 326 327 /// Attempt to find a type T for which the returned expression of the 328 /// given statement is an enumerator-like expression of that type. 329 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { 330 if (Expr *retValue = ret->getRetValue()) 331 return findEnumForBlockReturn(retValue); 332 return 0; 333 } 334 335 /// Attempt to find a common type T for which all of the returned 336 /// expressions in a block are enumerator-like expressions of that 337 /// type. 338 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { 339 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); 340 341 // Try to find one for the first return. 342 EnumDecl *ED = findEnumForBlockReturn(*i); 343 if (!ED) return 0; 344 345 // Check that the rest of the returns have the same enum. 346 for (++i; i != e; ++i) { 347 if (findEnumForBlockReturn(*i) != ED) 348 return 0; 349 } 350 351 // Never infer an anonymous enum type. 352 if (!ED->hasNameForLinkage()) return 0; 353 354 return ED; 355 } 356 357 /// Adjust the given return statements so that they formally return 358 /// the given type. It should require, at most, an IntegralCast. 359 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, 360 QualType returnType) { 361 for (ArrayRef<ReturnStmt*>::iterator 362 i = returns.begin(), e = returns.end(); i != e; ++i) { 363 ReturnStmt *ret = *i; 364 Expr *retValue = ret->getRetValue(); 365 if (S.Context.hasSameType(retValue->getType(), returnType)) 366 continue; 367 368 // Right now we only support integral fixup casts. 369 assert(returnType->isIntegralOrUnscopedEnumerationType()); 370 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); 371 372 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); 373 374 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue); 375 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, 376 E, /*base path*/ 0, VK_RValue); 377 if (cleanups) { 378 cleanups->setSubExpr(E); 379 } else { 380 ret->setRetValue(E); 381 } 382 } 383 } 384 385 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { 386 assert(CSI.HasImplicitReturnType); 387 388 // C++ Core Issue #975, proposed resolution: 389 // If a lambda-expression does not include a trailing-return-type, 390 // it is as if the trailing-return-type denotes the following type: 391 // - if there are no return statements in the compound-statement, 392 // or all return statements return either an expression of type 393 // void or no expression or braced-init-list, the type void; 394 // - otherwise, if all return statements return an expression 395 // and the types of the returned expressions after 396 // lvalue-to-rvalue conversion (4.1 [conv.lval]), 397 // array-to-pointer conversion (4.2 [conv.array]), and 398 // function-to-pointer conversion (4.3 [conv.func]) are the 399 // same, that common type; 400 // - otherwise, the program is ill-formed. 401 // 402 // In addition, in blocks in non-C++ modes, if all of the return 403 // statements are enumerator-like expressions of some type T, where 404 // T has a name for linkage, then we infer the return type of the 405 // block to be that type. 406 407 // First case: no return statements, implicit void return type. 408 ASTContext &Ctx = getASTContext(); 409 if (CSI.Returns.empty()) { 410 // It's possible there were simply no /valid/ return statements. 411 // In this case, the first one we found may have at least given us a type. 412 if (CSI.ReturnType.isNull()) 413 CSI.ReturnType = Ctx.VoidTy; 414 return; 415 } 416 417 // Second case: at least one return statement has dependent type. 418 // Delay type checking until instantiation. 419 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); 420 if (CSI.ReturnType->isDependentType()) 421 return; 422 423 // Try to apply the enum-fuzz rule. 424 if (!getLangOpts().CPlusPlus) { 425 assert(isa<BlockScopeInfo>(CSI)); 426 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); 427 if (ED) { 428 CSI.ReturnType = Context.getTypeDeclType(ED); 429 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); 430 return; 431 } 432 } 433 434 // Third case: only one return statement. Don't bother doing extra work! 435 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(), 436 E = CSI.Returns.end(); 437 if (I+1 == E) 438 return; 439 440 // General case: many return statements. 441 // Check that they all have compatible return types. 442 443 // We require the return types to strictly match here. 444 // Note that we've already done the required promotions as part of 445 // processing the return statement. 446 for (; I != E; ++I) { 447 const ReturnStmt *RS = *I; 448 const Expr *RetE = RS->getRetValue(); 449 450 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy); 451 if (Context.hasSameType(ReturnType, CSI.ReturnType)) 452 continue; 453 454 // FIXME: This is a poor diagnostic for ReturnStmts without expressions. 455 // TODO: It's possible that the *first* return is the divergent one. 456 Diag(RS->getLocStart(), 457 diag::err_typecheck_missing_return_type_incompatible) 458 << ReturnType << CSI.ReturnType 459 << isa<LambdaScopeInfo>(CSI); 460 // Continue iterating so that we keep emitting diagnostics. 461 } 462 } 463 464 FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef, 465 IdentifierInfo *Id, Expr *InitExpr) { 466 LambdaScopeInfo *LSI = getCurLambda(); 467 468 // C++1y [expr.prim.lambda]p11: 469 // The type of [the] member corresponds to the type of a hypothetical 470 // variable declaration of the form "auto init-capture;" 471 QualType DeductType = Context.getAutoDeductType(); 472 TypeLocBuilder TLB; 473 TLB.pushTypeSpec(DeductType).setNameLoc(Loc); 474 if (ByRef) { 475 DeductType = BuildReferenceType(DeductType, true, Loc, Id); 476 assert(!DeductType.isNull() && "can't build reference to auto"); 477 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); 478 } 479 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); 480 481 InitializationKind InitKind = InitializationKind::CreateDefault(Loc); 482 Expr *Init = InitExpr; 483 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) { 484 if (Parens->getNumExprs() == 1) { 485 Init = Parens->getExpr(0); 486 InitKind = InitializationKind::CreateDirect( 487 Loc, Parens->getLParenLoc(), Parens->getRParenLoc()); 488 } else { 489 // C++1y [dcl.spec.auto]p3: 490 // In an initializer of the form ( expression-list ), the 491 // expression-list shall be a single assignment-expression. 492 if (Parens->getNumExprs() == 0) 493 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression) 494 << Id; 495 else if (Parens->getNumExprs() > 1) 496 Diag(Parens->getExpr(1)->getLocStart(), 497 diag::err_init_capture_multiple_expressions) 498 << Id; 499 return 0; 500 } 501 } else if (isa<InitListExpr>(Init)) 502 // We do not need to distinguish between direct-list-initialization 503 // and copy-list-initialization here, because we will always deduce 504 // std::initializer_list<T>, and direct- and copy-list-initialization 505 // always behave the same for such a type. 506 // FIXME: We should model whether an '=' was present. 507 InitKind = InitializationKind::CreateDirectList(Loc); 508 else 509 InitKind = InitializationKind::CreateCopy(Loc, Loc); 510 QualType DeducedType; 511 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) { 512 if (isa<InitListExpr>(Init)) 513 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list) 514 << Id << Init->getSourceRange(); 515 else 516 Diag(Loc, diag::err_init_capture_deduction_failure) 517 << Id << Init->getType() << Init->getSourceRange(); 518 } 519 if (DeducedType.isNull()) 520 return 0; 521 522 // [...] a non-static data member named by the identifier is declared in 523 // the closure type. This member is not a bit-field and not mutable. 524 // Core issue: the member is (probably...) public. 525 FieldDecl *NewFD = CheckFieldDecl( 526 Id, DeducedType, TSI, LSI->Lambda, 527 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit, 528 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0); 529 LSI->Lambda->addDecl(NewFD); 530 531 if (CurContext->isDependentContext()) { 532 LSI->addInitCapture(NewFD, InitExpr); 533 } else { 534 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD); 535 InitializationSequence InitSeq(*this, Entity, InitKind, Init); 536 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) { 537 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init); 538 if (!InitResult.isInvalid()) 539 LSI->addInitCapture(NewFD, InitResult.take()); 540 } 541 } 542 543 return NewFD; 544 } 545 546 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 547 Declarator &ParamInfo, 548 Scope *CurScope) { 549 // Determine if we're within a context where we know that the lambda will 550 // be dependent, because there are template parameters in scope. 551 bool KnownDependent = false; 552 if (Scope *TmplScope = CurScope->getTemplateParamParent()) 553 if (!TmplScope->decl_empty()) 554 KnownDependent = true; 555 556 // Determine the signature of the call operator. 557 TypeSourceInfo *MethodTyInfo; 558 bool ExplicitParams = true; 559 bool ExplicitResultType = true; 560 bool ContainsUnexpandedParameterPack = false; 561 SourceLocation EndLoc; 562 SmallVector<ParmVarDecl *, 8> Params; 563 if (ParamInfo.getNumTypeObjects() == 0) { 564 // C++11 [expr.prim.lambda]p4: 565 // If a lambda-expression does not include a lambda-declarator, it is as 566 // if the lambda-declarator were (). 567 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 568 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 569 EPI.HasTrailingReturn = true; 570 EPI.TypeQuals |= DeclSpec::TQ_const; 571 // C++1y [expr.prim.lambda]: 572 // The lambda return type is 'auto', which is replaced by the 573 // trailing-return type if provided and/or deduced from 'return' 574 // statements 575 // We don't do this before C++1y, because we don't support deduced return 576 // types there. 577 QualType DefaultTypeForNoTrailingReturn = 578 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType() 579 : Context.DependentTy; 580 QualType MethodTy = 581 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI); 582 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy); 583 ExplicitParams = false; 584 ExplicitResultType = false; 585 EndLoc = Intro.Range.getEnd(); 586 } else { 587 assert(ParamInfo.isFunctionDeclarator() && 588 "lambda-declarator is a function"); 589 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 590 591 // C++11 [expr.prim.lambda]p5: 592 // This function call operator is declared const (9.3.1) if and only if 593 // the lambda-expression's parameter-declaration-clause is not followed 594 // by mutable. It is neither virtual nor declared volatile. [...] 595 if (!FTI.hasMutableQualifier()) 596 FTI.TypeQuals |= DeclSpec::TQ_const; 597 598 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope); 599 assert(MethodTyInfo && "no type from lambda-declarator"); 600 EndLoc = ParamInfo.getSourceRange().getEnd(); 601 602 ExplicitResultType = FTI.hasTrailingReturnType(); 603 604 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 605 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 606 // Empty arg list, don't push any params. 607 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 608 } else { 609 Params.reserve(FTI.NumArgs); 610 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 611 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param)); 612 } 613 614 // Check for unexpanded parameter packs in the method type. 615 if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) 616 ContainsUnexpandedParameterPack = true; 617 } 618 619 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo, 620 KnownDependent); 621 622 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range, 623 MethodTyInfo, EndLoc, Params); 624 625 if (ExplicitParams) 626 CheckCXXDefaultArguments(Method); 627 628 // Attributes on the lambda apply to the method. 629 ProcessDeclAttributes(CurScope, Method, ParamInfo); 630 631 // Introduce the function call operator as the current declaration context. 632 PushDeclContext(CurScope, Method); 633 634 // Introduce the lambda scope. 635 LambdaScopeInfo *LSI 636 = enterLambdaScope(Method, 637 Intro.Range, 638 Intro.Default, Intro.DefaultLoc, 639 ExplicitParams, 640 ExplicitResultType, 641 !Method->isConst()); 642 643 // Distinct capture names, for diagnostics. 644 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames; 645 646 // Handle explicit captures. 647 SourceLocation PrevCaptureLoc 648 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc; 649 for (SmallVectorImpl<LambdaCapture>::const_iterator 650 C = Intro.Captures.begin(), 651 E = Intro.Captures.end(); 652 C != E; 653 PrevCaptureLoc = C->Loc, ++C) { 654 if (C->Kind == LCK_This) { 655 // C++11 [expr.prim.lambda]p8: 656 // An identifier or this shall not appear more than once in a 657 // lambda-capture. 658 if (LSI->isCXXThisCaptured()) { 659 Diag(C->Loc, diag::err_capture_more_than_once) 660 << "'this'" 661 << SourceRange(LSI->getCXXThisCapture().getLocation()) 662 << FixItHint::CreateRemoval( 663 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 664 continue; 665 } 666 667 // C++11 [expr.prim.lambda]p8: 668 // If a lambda-capture includes a capture-default that is =, the 669 // lambda-capture shall not contain this [...]. 670 if (Intro.Default == LCD_ByCopy) { 671 Diag(C->Loc, diag::err_this_capture_with_copy_default) 672 << FixItHint::CreateRemoval( 673 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 674 continue; 675 } 676 677 // C++11 [expr.prim.lambda]p12: 678 // If this is captured by a local lambda expression, its nearest 679 // enclosing function shall be a non-static member function. 680 QualType ThisCaptureType = getCurrentThisType(); 681 if (ThisCaptureType.isNull()) { 682 Diag(C->Loc, diag::err_this_capture) << true; 683 continue; 684 } 685 686 CheckCXXThisCapture(C->Loc, /*Explicit=*/true); 687 continue; 688 } 689 690 assert(C->Id && "missing identifier for capture"); 691 692 if (C->Init.isInvalid()) 693 continue; 694 if (C->Init.isUsable()) { 695 // C++11 [expr.prim.lambda]p8: 696 // An identifier or this shall not appear more than once in a 697 // lambda-capture. 698 if (!CaptureNames.insert(C->Id)) 699 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; 700 701 if (C->Init.get()->containsUnexpandedParameterPack()) 702 ContainsUnexpandedParameterPack = true; 703 704 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef, 705 C->Id, C->Init.take()); 706 // C++1y [expr.prim.lambda]p11: 707 // Within the lambda-expression's lambda-declarator and 708 // compound-statement, the identifier in the init-capture 709 // hides any declaration of the same name in scopes enclosing 710 // the lambda-expression. 711 if (NewFD) 712 PushOnScopeChains(NewFD, CurScope, false); 713 continue; 714 } 715 716 // C++11 [expr.prim.lambda]p8: 717 // If a lambda-capture includes a capture-default that is &, the 718 // identifiers in the lambda-capture shall not be preceded by &. 719 // If a lambda-capture includes a capture-default that is =, [...] 720 // each identifier it contains shall be preceded by &. 721 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 722 Diag(C->Loc, diag::err_reference_capture_with_reference_default) 723 << FixItHint::CreateRemoval( 724 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 725 continue; 726 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 727 Diag(C->Loc, diag::err_copy_capture_with_copy_default) 728 << FixItHint::CreateRemoval( 729 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 730 continue; 731 } 732 733 // C++11 [expr.prim.lambda]p10: 734 // The identifiers in a capture-list are looked up using the usual 735 // rules for unqualified name lookup (3.4.1) 736 DeclarationNameInfo Name(C->Id, C->Loc); 737 LookupResult R(*this, Name, LookupOrdinaryName); 738 LookupName(R, CurScope); 739 if (R.isAmbiguous()) 740 continue; 741 if (R.empty()) { 742 // FIXME: Disable corrections that would add qualification? 743 CXXScopeSpec ScopeSpec; 744 DeclFilterCCC<VarDecl> Validator; 745 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) 746 continue; 747 } 748 749 VarDecl *Var = R.getAsSingle<VarDecl>(); 750 751 // C++11 [expr.prim.lambda]p8: 752 // An identifier or this shall not appear more than once in a 753 // lambda-capture. 754 if (!CaptureNames.insert(C->Id)) { 755 if (Var && LSI->isCaptured(Var)) { 756 Diag(C->Loc, diag::err_capture_more_than_once) 757 << C->Id << SourceRange(LSI->getCapture(Var).getLocation()) 758 << FixItHint::CreateRemoval( 759 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 760 } else 761 // Previous capture was an init-capture: no fixit. 762 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; 763 continue; 764 } 765 766 // C++11 [expr.prim.lambda]p10: 767 // [...] each such lookup shall find a variable with automatic storage 768 // duration declared in the reaching scope of the local lambda expression. 769 // Note that the 'reaching scope' check happens in tryCaptureVariable(). 770 if (!Var) { 771 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 772 continue; 773 } 774 775 // Ignore invalid decls; they'll just confuse the code later. 776 if (Var->isInvalidDecl()) 777 continue; 778 779 if (!Var->hasLocalStorage()) { 780 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 781 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 782 continue; 783 } 784 785 // C++11 [expr.prim.lambda]p23: 786 // A capture followed by an ellipsis is a pack expansion (14.5.3). 787 SourceLocation EllipsisLoc; 788 if (C->EllipsisLoc.isValid()) { 789 if (Var->isParameterPack()) { 790 EllipsisLoc = C->EllipsisLoc; 791 } else { 792 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 793 << SourceRange(C->Loc); 794 795 // Just ignore the ellipsis. 796 } 797 } else if (Var->isParameterPack()) { 798 ContainsUnexpandedParameterPack = true; 799 } 800 801 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef : 802 TryCapture_ExplicitByVal; 803 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); 804 } 805 finishLambdaExplicitCaptures(LSI); 806 807 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; 808 809 // Add lambda parameters into scope. 810 addLambdaParameters(Method, CurScope); 811 812 // Enter a new evaluation context to insulate the lambda from any 813 // cleanups from the enclosing full-expression. 814 PushExpressionEvaluationContext(PotentiallyEvaluated); 815 } 816 817 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 818 bool IsInstantiation) { 819 // Leave the expression-evaluation context. 820 DiscardCleanupsInEvaluationContext(); 821 PopExpressionEvaluationContext(); 822 823 // Leave the context of the lambda. 824 if (!IsInstantiation) 825 PopDeclContext(); 826 827 // Finalize the lambda. 828 LambdaScopeInfo *LSI = getCurLambda(); 829 CXXRecordDecl *Class = LSI->Lambda; 830 Class->setInvalidDecl(); 831 SmallVector<Decl*, 4> Fields; 832 for (RecordDecl::field_iterator i = Class->field_begin(), 833 e = Class->field_end(); i != e; ++i) 834 Fields.push_back(*i); 835 ActOnFields(0, Class->getLocation(), Class, Fields, 836 SourceLocation(), SourceLocation(), 0); 837 CheckCompletedCXXClass(Class); 838 839 PopFunctionScopeInfo(); 840 } 841 842 /// \brief Add a lambda's conversion to function pointer, as described in 843 /// C++11 [expr.prim.lambda]p6. 844 static void addFunctionPointerConversion(Sema &S, 845 SourceRange IntroducerRange, 846 CXXRecordDecl *Class, 847 CXXMethodDecl *CallOperator) { 848 // Add the conversion to function pointer. 849 const FunctionProtoType *Proto 850 = CallOperator->getType()->getAs<FunctionProtoType>(); 851 QualType FunctionPtrTy; 852 QualType FunctionTy; 853 { 854 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 855 CallingConv CC = S.Context.getDefaultCallingConvention( 856 Proto->isVariadic(), /*IsCXXMethod=*/false); 857 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC); 858 ExtInfo.TypeQuals = 0; 859 FunctionTy = S.Context.getFunctionType(Proto->getResultType(), 860 Proto->getArgTypes(), ExtInfo); 861 FunctionPtrTy = S.Context.getPointerType(FunctionTy); 862 } 863 864 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention( 865 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 866 ExtInfo.TypeQuals = Qualifiers::Const; 867 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo); 868 869 SourceLocation Loc = IntroducerRange.getBegin(); 870 DeclarationName Name 871 = S.Context.DeclarationNames.getCXXConversionFunctionName( 872 S.Context.getCanonicalType(FunctionPtrTy)); 873 DeclarationNameLoc NameLoc; 874 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy, 875 Loc); 876 CXXConversionDecl *Conversion 877 = CXXConversionDecl::Create(S.Context, Class, Loc, 878 DeclarationNameInfo(Name, Loc, NameLoc), 879 ConvTy, 880 S.Context.getTrivialTypeSourceInfo(ConvTy, 881 Loc), 882 /*isInline=*/true, /*isExplicit=*/false, 883 /*isConstexpr=*/false, 884 CallOperator->getBody()->getLocEnd()); 885 Conversion->setAccess(AS_public); 886 Conversion->setImplicit(true); 887 Class->addDecl(Conversion); 888 889 // Add a non-static member function "__invoke" that will be the result of 890 // the conversion. 891 Name = &S.Context.Idents.get("__invoke"); 892 CXXMethodDecl *Invoke 893 = CXXMethodDecl::Create(S.Context, Class, Loc, 894 DeclarationNameInfo(Name, Loc), FunctionTy, 895 CallOperator->getTypeSourceInfo(), 896 SC_Static, /*IsInline=*/true, 897 /*IsConstexpr=*/false, 898 CallOperator->getBody()->getLocEnd()); 899 SmallVector<ParmVarDecl *, 4> InvokeParams; 900 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 901 ParmVarDecl *From = CallOperator->getParamDecl(I); 902 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke, 903 From->getLocStart(), 904 From->getLocation(), 905 From->getIdentifier(), 906 From->getType(), 907 From->getTypeSourceInfo(), 908 From->getStorageClass(), 909 /*DefaultArg=*/0)); 910 } 911 Invoke->setParams(InvokeParams); 912 Invoke->setAccess(AS_private); 913 Invoke->setImplicit(true); 914 Class->addDecl(Invoke); 915 } 916 917 /// \brief Add a lambda's conversion to block pointer. 918 static void addBlockPointerConversion(Sema &S, 919 SourceRange IntroducerRange, 920 CXXRecordDecl *Class, 921 CXXMethodDecl *CallOperator) { 922 const FunctionProtoType *Proto 923 = CallOperator->getType()->getAs<FunctionProtoType>(); 924 QualType BlockPtrTy; 925 { 926 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 927 ExtInfo.TypeQuals = 0; 928 QualType FunctionTy = S.Context.getFunctionType( 929 Proto->getResultType(), Proto->getArgTypes(), ExtInfo); 930 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 931 } 932 933 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention( 934 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 935 ExtInfo.TypeQuals = Qualifiers::Const; 936 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo); 937 938 SourceLocation Loc = IntroducerRange.getBegin(); 939 DeclarationName Name 940 = S.Context.DeclarationNames.getCXXConversionFunctionName( 941 S.Context.getCanonicalType(BlockPtrTy)); 942 DeclarationNameLoc NameLoc; 943 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); 944 CXXConversionDecl *Conversion 945 = CXXConversionDecl::Create(S.Context, Class, Loc, 946 DeclarationNameInfo(Name, Loc, NameLoc), 947 ConvTy, 948 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 949 /*isInline=*/true, /*isExplicit=*/false, 950 /*isConstexpr=*/false, 951 CallOperator->getBody()->getLocEnd()); 952 Conversion->setAccess(AS_public); 953 Conversion->setImplicit(true); 954 Class->addDecl(Conversion); 955 } 956 957 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 958 Scope *CurScope, 959 bool IsInstantiation) { 960 // Collect information from the lambda scope. 961 SmallVector<LambdaExpr::Capture, 4> Captures; 962 SmallVector<Expr *, 4> CaptureInits; 963 LambdaCaptureDefault CaptureDefault; 964 SourceLocation CaptureDefaultLoc; 965 CXXRecordDecl *Class; 966 CXXMethodDecl *CallOperator; 967 SourceRange IntroducerRange; 968 bool ExplicitParams; 969 bool ExplicitResultType; 970 bool LambdaExprNeedsCleanups; 971 bool ContainsUnexpandedParameterPack; 972 SmallVector<VarDecl *, 4> ArrayIndexVars; 973 SmallVector<unsigned, 4> ArrayIndexStarts; 974 { 975 LambdaScopeInfo *LSI = getCurLambda(); 976 CallOperator = LSI->CallOperator; 977 Class = LSI->Lambda; 978 IntroducerRange = LSI->IntroducerRange; 979 ExplicitParams = LSI->ExplicitParams; 980 ExplicitResultType = !LSI->HasImplicitReturnType; 981 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups; 982 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; 983 ArrayIndexVars.swap(LSI->ArrayIndexVars); 984 ArrayIndexStarts.swap(LSI->ArrayIndexStarts); 985 986 // Translate captures. 987 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 988 LambdaScopeInfo::Capture From = LSI->Captures[I]; 989 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 990 bool IsImplicit = I >= LSI->NumExplicitCaptures; 991 992 // Handle 'this' capture. 993 if (From.isThisCapture()) { 994 Captures.push_back(LambdaExpr::Capture(From.getLocation(), 995 IsImplicit, 996 LCK_This)); 997 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(), 998 getCurrentThisType(), 999 /*isImplicit=*/true)); 1000 continue; 1001 } 1002 1003 if (From.isInitCapture()) { 1004 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField())); 1005 CaptureInits.push_back(From.getInitExpr()); 1006 continue; 1007 } 1008 1009 VarDecl *Var = From.getVariable(); 1010 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef; 1011 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit, 1012 Kind, Var, From.getEllipsisLoc())); 1013 CaptureInits.push_back(From.getInitExpr()); 1014 } 1015 1016 switch (LSI->ImpCaptureStyle) { 1017 case CapturingScopeInfo::ImpCap_None: 1018 CaptureDefault = LCD_None; 1019 break; 1020 1021 case CapturingScopeInfo::ImpCap_LambdaByval: 1022 CaptureDefault = LCD_ByCopy; 1023 break; 1024 1025 case CapturingScopeInfo::ImpCap_CapturedRegion: 1026 case CapturingScopeInfo::ImpCap_LambdaByref: 1027 CaptureDefault = LCD_ByRef; 1028 break; 1029 1030 case CapturingScopeInfo::ImpCap_Block: 1031 llvm_unreachable("block capture in lambda"); 1032 break; 1033 } 1034 CaptureDefaultLoc = LSI->CaptureDefaultLoc; 1035 1036 // C++11 [expr.prim.lambda]p4: 1037 // If a lambda-expression does not include a 1038 // trailing-return-type, it is as if the trailing-return-type 1039 // denotes the following type: 1040 // 1041 // Skip for C++1y return type deduction semantics which uses 1042 // different machinery. 1043 // FIXME: Refactor and Merge the return type deduction machinery. 1044 // FIXME: Assumes current resolution to core issue 975. 1045 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) { 1046 deduceClosureReturnType(*LSI); 1047 1048 // - if there are no return statements in the 1049 // compound-statement, or all return statements return 1050 // either an expression of type void or no expression or 1051 // braced-init-list, the type void; 1052 if (LSI->ReturnType.isNull()) { 1053 LSI->ReturnType = Context.VoidTy; 1054 } 1055 1056 // Create a function type with the inferred return type. 1057 const FunctionProtoType *Proto 1058 = CallOperator->getType()->getAs<FunctionProtoType>(); 1059 QualType FunctionTy = Context.getFunctionType( 1060 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo()); 1061 CallOperator->setType(FunctionTy); 1062 } 1063 1064 // C++ [expr.prim.lambda]p7: 1065 // The lambda-expression's compound-statement yields the 1066 // function-body (8.4) of the function call operator [...]. 1067 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation); 1068 CallOperator->setLexicalDeclContext(Class); 1069 Class->addDecl(CallOperator); 1070 PopExpressionEvaluationContext(); 1071 1072 // C++11 [expr.prim.lambda]p6: 1073 // The closure type for a lambda-expression with no lambda-capture 1074 // has a public non-virtual non-explicit const conversion function 1075 // to pointer to function having the same parameter and return 1076 // types as the closure type's function call operator. 1077 if (Captures.empty() && CaptureDefault == LCD_None) 1078 addFunctionPointerConversion(*this, IntroducerRange, Class, 1079 CallOperator); 1080 1081 // Objective-C++: 1082 // The closure type for a lambda-expression has a public non-virtual 1083 // non-explicit const conversion function to a block pointer having the 1084 // same parameter and return types as the closure type's function call 1085 // operator. 1086 if (getLangOpts().Blocks && getLangOpts().ObjC1) 1087 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 1088 1089 // Finalize the lambda class. 1090 SmallVector<Decl*, 4> Fields; 1091 for (RecordDecl::field_iterator i = Class->field_begin(), 1092 e = Class->field_end(); i != e; ++i) 1093 Fields.push_back(*i); 1094 ActOnFields(0, Class->getLocation(), Class, Fields, 1095 SourceLocation(), SourceLocation(), 0); 1096 CheckCompletedCXXClass(Class); 1097 } 1098 1099 if (LambdaExprNeedsCleanups) 1100 ExprNeedsCleanups = true; 1101 1102 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 1103 CaptureDefault, CaptureDefaultLoc, 1104 Captures, 1105 ExplicitParams, ExplicitResultType, 1106 CaptureInits, ArrayIndexVars, 1107 ArrayIndexStarts, Body->getLocEnd(), 1108 ContainsUnexpandedParameterPack); 1109 1110 // C++11 [expr.prim.lambda]p2: 1111 // A lambda-expression shall not appear in an unevaluated operand 1112 // (Clause 5). 1113 if (!CurContext->isDependentContext()) { 1114 switch (ExprEvalContexts.back().Context) { 1115 case Unevaluated: 1116 case UnevaluatedAbstract: 1117 // We don't actually diagnose this case immediately, because we 1118 // could be within a context where we might find out later that 1119 // the expression is potentially evaluated (e.g., for typeid). 1120 ExprEvalContexts.back().Lambdas.push_back(Lambda); 1121 break; 1122 1123 case ConstantEvaluated: 1124 case PotentiallyEvaluated: 1125 case PotentiallyEvaluatedIfUsed: 1126 break; 1127 } 1128 } 1129 1130 return MaybeBindToTemporary(Lambda); 1131 } 1132 1133 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 1134 SourceLocation ConvLocation, 1135 CXXConversionDecl *Conv, 1136 Expr *Src) { 1137 // Make sure that the lambda call operator is marked used. 1138 CXXRecordDecl *Lambda = Conv->getParent(); 1139 CXXMethodDecl *CallOperator 1140 = cast<CXXMethodDecl>( 1141 Lambda->lookup( 1142 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 1143 CallOperator->setReferenced(); 1144 CallOperator->markUsed(Context); 1145 1146 ExprResult Init = PerformCopyInitialization( 1147 InitializedEntity::InitializeBlock(ConvLocation, 1148 Src->getType(), 1149 /*NRVO=*/false), 1150 CurrentLocation, Src); 1151 if (!Init.isInvalid()) 1152 Init = ActOnFinishFullExpr(Init.take()); 1153 1154 if (Init.isInvalid()) 1155 return ExprError(); 1156 1157 // Create the new block to be returned. 1158 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); 1159 1160 // Set the type information. 1161 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); 1162 Block->setIsVariadic(CallOperator->isVariadic()); 1163 Block->setBlockMissingReturnType(false); 1164 1165 // Add parameters. 1166 SmallVector<ParmVarDecl *, 4> BlockParams; 1167 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 1168 ParmVarDecl *From = CallOperator->getParamDecl(I); 1169 BlockParams.push_back(ParmVarDecl::Create(Context, Block, 1170 From->getLocStart(), 1171 From->getLocation(), 1172 From->getIdentifier(), 1173 From->getType(), 1174 From->getTypeSourceInfo(), 1175 From->getStorageClass(), 1176 /*DefaultArg=*/0)); 1177 } 1178 Block->setParams(BlockParams); 1179 1180 Block->setIsConversionFromLambda(true); 1181 1182 // Add capture. The capture uses a fake variable, which doesn't correspond 1183 // to any actual memory location. However, the initializer copy-initializes 1184 // the lambda object. 1185 TypeSourceInfo *CapVarTSI = 1186 Context.getTrivialTypeSourceInfo(Src->getType()); 1187 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, 1188 ConvLocation, 0, 1189 Src->getType(), CapVarTSI, 1190 SC_None); 1191 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false, 1192 /*Nested=*/false, /*Copy=*/Init.take()); 1193 Block->setCaptures(Context, &Capture, &Capture + 1, 1194 /*CapturesCXXThis=*/false); 1195 1196 // Add a fake function body to the block. IR generation is responsible 1197 // for filling in the actual body, which cannot be expressed as an AST. 1198 Block->setBody(new (Context) CompoundStmt(ConvLocation)); 1199 1200 // Create the block literal expression. 1201 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); 1202 ExprCleanupObjects.push_back(Block); 1203 ExprNeedsCleanups = true; 1204 1205 return BuildBlock; 1206 } 1207