SemaLambda.cpp revision ac1303eca6cbe3e623fb5ec6fe7ec184ef4b0dfa
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/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" 21using namespace clang; 22using namespace sema; 23 24CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, 25 bool KnownDependent) { 26 DeclContext *DC = CurContext; 27 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 28 DC = DC->getParent(); 29 30 // Start constructing the lambda class. 31 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, 32 IntroducerRange.getBegin(), 33 KnownDependent); 34 DC->addDecl(Class); 35 36 return Class; 37} 38 39CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, 40 SourceRange IntroducerRange, 41 TypeSourceInfo *MethodType, 42 SourceLocation EndLoc, 43 llvm::ArrayRef<ParmVarDecl *> Params) { 44 // C++11 [expr.prim.lambda]p5: 45 // The closure type for a lambda-expression has a public inline function 46 // call operator (13.5.4) whose parameters and return type are described by 47 // the lambda-expression's parameter-declaration-clause and 48 // trailing-return-type respectively. 49 DeclarationName MethodName 50 = Context.DeclarationNames.getCXXOperatorName(OO_Call); 51 DeclarationNameLoc MethodNameLoc; 52 MethodNameLoc.CXXOperatorName.BeginOpNameLoc 53 = IntroducerRange.getBegin().getRawEncoding(); 54 MethodNameLoc.CXXOperatorName.EndOpNameLoc 55 = IntroducerRange.getEnd().getRawEncoding(); 56 CXXMethodDecl *Method 57 = CXXMethodDecl::Create(Context, Class, EndLoc, 58 DeclarationNameInfo(MethodName, 59 IntroducerRange.getBegin(), 60 MethodNameLoc), 61 MethodType->getType(), MethodType, 62 /*isStatic=*/false, 63 SC_None, 64 /*isInline=*/true, 65 /*isConstExpr=*/false, 66 EndLoc); 67 Method->setAccess(AS_public); 68 69 // Temporarily set the lexical declaration context to the current 70 // context, so that the Scope stack matches the lexical nesting. 71 Method->setLexicalDeclContext(CurContext); 72 73 // Add parameters. 74 if (!Params.empty()) { 75 Method->setParams(Params); 76 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()), 77 const_cast<ParmVarDecl **>(Params.end()), 78 /*CheckParameterNames=*/false); 79 80 for (CXXMethodDecl::param_iterator P = Method->param_begin(), 81 PEnd = Method->param_end(); 82 P != PEnd; ++P) 83 (*P)->setOwningFunction(Method); 84 } 85 86 return Method; 87} 88 89LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator, 90 SourceRange IntroducerRange, 91 LambdaCaptureDefault CaptureDefault, 92 bool ExplicitParams, 93 bool ExplicitResultType, 94 bool Mutable) { 95 PushLambdaScope(CallOperator->getParent(), CallOperator); 96 LambdaScopeInfo *LSI = getCurLambda(); 97 if (CaptureDefault == LCD_ByCopy) 98 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 99 else if (CaptureDefault == LCD_ByRef) 100 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 101 LSI->IntroducerRange = IntroducerRange; 102 LSI->ExplicitParams = ExplicitParams; 103 LSI->Mutable = Mutable; 104 105 if (ExplicitResultType) { 106 LSI->ReturnType = CallOperator->getResultType(); 107 108 if (!LSI->ReturnType->isDependentType() && 109 !LSI->ReturnType->isVoidType()) { 110 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType, 111 diag::err_lambda_incomplete_result)) { 112 // Do nothing. 113 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) { 114 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result) 115 << LSI->ReturnType; 116 } 117 } 118 } else { 119 LSI->HasImplicitReturnType = true; 120 } 121 122 return LSI; 123} 124 125void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 126 LSI->finishedExplicitCaptures(); 127} 128 129void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { 130 // Introduce our parameters into the function scope 131 for (unsigned p = 0, NumParams = CallOperator->getNumParams(); 132 p < NumParams; ++p) { 133 ParmVarDecl *Param = CallOperator->getParamDecl(p); 134 135 // If this has an identifier, add it to the scope stack. 136 if (CurScope && Param->getIdentifier()) { 137 CheckShadow(CurScope, Param); 138 139 PushOnScopeChains(Param, CurScope); 140 } 141 } 142} 143 144void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 145 Declarator &ParamInfo, 146 Scope *CurScope) { 147 // Determine if we're within a context where we know that the lambda will 148 // be dependent, because there are template parameters in scope. 149 bool KnownDependent = false; 150 if (Scope *TmplScope = CurScope->getTemplateParamParent()) 151 if (!TmplScope->decl_empty()) 152 KnownDependent = true; 153 154 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent); 155 156 // Determine the signature of the call operator. 157 TypeSourceInfo *MethodTyInfo; 158 bool ExplicitParams = true; 159 bool ExplicitResultType = true; 160 SourceLocation EndLoc; 161 llvm::ArrayRef<ParmVarDecl *> Params; 162 if (ParamInfo.getNumTypeObjects() == 0) { 163 // C++11 [expr.prim.lambda]p4: 164 // If a lambda-expression does not include a lambda-declarator, it is as 165 // if the lambda-declarator were (). 166 FunctionProtoType::ExtProtoInfo EPI; 167 EPI.HasTrailingReturn = true; 168 EPI.TypeQuals |= DeclSpec::TQ_const; 169 QualType MethodTy = Context.getFunctionType(Context.DependentTy, 170 /*Args=*/0, /*NumArgs=*/0, EPI); 171 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy); 172 ExplicitParams = false; 173 ExplicitResultType = false; 174 EndLoc = Intro.Range.getEnd(); 175 } else { 176 assert(ParamInfo.isFunctionDeclarator() && 177 "lambda-declarator is a function"); 178 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 179 180 // C++11 [expr.prim.lambda]p5: 181 // This function call operator is declared const (9.3.1) if and only if 182 // the lambda-expression's parameter-declaration-clause is not followed 183 // by mutable. It is neither virtual nor declared volatile. [...] 184 if (!FTI.hasMutableQualifier()) 185 FTI.TypeQuals |= DeclSpec::TQ_const; 186 187 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope); 188 assert(MethodTyInfo && "no type from lambda-declarator"); 189 EndLoc = ParamInfo.getSourceRange().getEnd(); 190 191 ExplicitResultType 192 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType() 193 != Context.DependentTy; 194 195 TypeLoc TL = MethodTyInfo->getTypeLoc(); 196 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL); 197 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(), 198 Proto.getNumArgs()); 199 } 200 201 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range, 202 MethodTyInfo, EndLoc, Params); 203 204 if (ExplicitParams) 205 CheckCXXDefaultArguments(Method); 206 207 // Attributes on the lambda apply to the method. 208 ProcessDeclAttributes(CurScope, Method, ParamInfo); 209 210 // Introduce the function call operator as the current declaration context. 211 PushDeclContext(CurScope, Method); 212 213 // Introduce the lambda scope. 214 LambdaScopeInfo *LSI 215 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams, 216 ExplicitResultType, 217 (Method->getTypeQualifiers() & Qualifiers::Const) == 0); 218 219 // Handle explicit captures. 220 SourceLocation PrevCaptureLoc 221 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc; 222 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator 223 C = Intro.Captures.begin(), 224 E = Intro.Captures.end(); 225 C != E; 226 PrevCaptureLoc = C->Loc, ++C) { 227 if (C->Kind == LCK_This) { 228 // C++11 [expr.prim.lambda]p8: 229 // An identifier or this shall not appear more than once in a 230 // lambda-capture. 231 if (LSI->isCXXThisCaptured()) { 232 Diag(C->Loc, diag::err_capture_more_than_once) 233 << "'this'" 234 << SourceRange(LSI->getCXXThisCapture().getLocation()) 235 << FixItHint::CreateRemoval( 236 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 237 continue; 238 } 239 240 // C++11 [expr.prim.lambda]p8: 241 // If a lambda-capture includes a capture-default that is =, the 242 // lambda-capture shall not contain this [...]. 243 if (Intro.Default == LCD_ByCopy) { 244 Diag(C->Loc, diag::err_this_capture_with_copy_default) 245 << FixItHint::CreateRemoval( 246 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 247 continue; 248 } 249 250 // C++11 [expr.prim.lambda]p12: 251 // If this is captured by a local lambda expression, its nearest 252 // enclosing function shall be a non-static member function. 253 QualType ThisCaptureType = getCurrentThisType(); 254 if (ThisCaptureType.isNull()) { 255 Diag(C->Loc, diag::err_this_capture) << true; 256 continue; 257 } 258 259 CheckCXXThisCapture(C->Loc, /*Explicit=*/true); 260 continue; 261 } 262 263 assert(C->Id && "missing identifier for capture"); 264 265 // C++11 [expr.prim.lambda]p8: 266 // If a lambda-capture includes a capture-default that is &, the 267 // identifiers in the lambda-capture shall not be preceded by &. 268 // If a lambda-capture includes a capture-default that is =, [...] 269 // each identifier it contains shall be preceded by &. 270 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 271 Diag(C->Loc, diag::err_reference_capture_with_reference_default) 272 << FixItHint::CreateRemoval( 273 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 274 continue; 275 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 276 Diag(C->Loc, diag::err_copy_capture_with_copy_default) 277 << FixItHint::CreateRemoval( 278 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 279 continue; 280 } 281 282 DeclarationNameInfo Name(C->Id, C->Loc); 283 LookupResult R(*this, Name, LookupOrdinaryName); 284 LookupName(R, CurScope); 285 if (R.isAmbiguous()) 286 continue; 287 if (R.empty()) { 288 // FIXME: Disable corrections that would add qualification? 289 CXXScopeSpec ScopeSpec; 290 DeclFilterCCC<VarDecl> Validator; 291 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) 292 continue; 293 } 294 295 // C++11 [expr.prim.lambda]p10: 296 // The identifiers in a capture-list are looked up using the usual rules 297 // for unqualified name lookup (3.4.1); each such lookup shall find a 298 // variable with automatic storage duration declared in the reaching 299 // scope of the local lambda expression. 300 // 301 // Note that the 'reaching scope' check happens in tryCaptureVariable(). 302 VarDecl *Var = R.getAsSingle<VarDecl>(); 303 if (!Var) { 304 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 305 continue; 306 } 307 308 if (!Var->hasLocalStorage()) { 309 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 310 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 311 continue; 312 } 313 314 // C++11 [expr.prim.lambda]p8: 315 // An identifier or this shall not appear more than once in a 316 // lambda-capture. 317 if (LSI->isCaptured(Var)) { 318 Diag(C->Loc, diag::err_capture_more_than_once) 319 << C->Id 320 << SourceRange(LSI->getCapture(Var).getLocation()) 321 << FixItHint::CreateRemoval( 322 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 323 continue; 324 } 325 326 // C++11 [expr.prim.lambda]p23: 327 // A capture followed by an ellipsis is a pack expansion (14.5.3). 328 SourceLocation EllipsisLoc; 329 if (C->EllipsisLoc.isValid()) { 330 if (Var->isParameterPack()) { 331 EllipsisLoc = C->EllipsisLoc; 332 } else { 333 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 334 << SourceRange(C->Loc); 335 336 // Just ignore the ellipsis. 337 } 338 } else if (Var->isParameterPack()) { 339 Diag(C->Loc, diag::err_lambda_unexpanded_pack); 340 continue; 341 } 342 343 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef : 344 TryCapture_ExplicitByVal; 345 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); 346 } 347 finishLambdaExplicitCaptures(LSI); 348 349 // Add lambda parameters into scope. 350 addLambdaParameters(Method, CurScope); 351 352 // Enter a new evaluation context to insulate the lambda from any 353 // cleanups from the enclosing full-expression. 354 PushExpressionEvaluationContext(PotentiallyEvaluated); 355} 356 357void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 358 bool IsInstantiation) { 359 // Leave the expression-evaluation context. 360 DiscardCleanupsInEvaluationContext(); 361 PopExpressionEvaluationContext(); 362 363 // Leave the context of the lambda. 364 if (!IsInstantiation) 365 PopDeclContext(); 366 367 // Finalize the lambda. 368 LambdaScopeInfo *LSI = getCurLambda(); 369 CXXRecordDecl *Class = LSI->Lambda; 370 Class->setInvalidDecl(); 371 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end()); 372 ActOnFields(0, Class->getLocation(), Class, Fields, 373 SourceLocation(), SourceLocation(), 0); 374 CheckCompletedCXXClass(Class); 375 376 PopFunctionScopeInfo(); 377} 378 379/// \brief Add a lambda's conversion to function pointer, as described in 380/// C++11 [expr.prim.lambda]p6. 381static void addFunctionPointerConversion(Sema &S, 382 SourceRange IntroducerRange, 383 CXXRecordDecl *Class, 384 CXXMethodDecl *CallOperator) { 385 // Add the conversion to function pointer. 386 const FunctionProtoType *Proto 387 = CallOperator->getType()->getAs<FunctionProtoType>(); 388 QualType FunctionPtrTy; 389 QualType FunctionTy; 390 { 391 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 392 ExtInfo.TypeQuals = 0; 393 FunctionTy = S.Context.getFunctionType(Proto->getResultType(), 394 Proto->arg_type_begin(), 395 Proto->getNumArgs(), 396 ExtInfo); 397 FunctionPtrTy = S.Context.getPointerType(FunctionTy); 398 } 399 400 FunctionProtoType::ExtProtoInfo ExtInfo; 401 ExtInfo.TypeQuals = Qualifiers::Const; 402 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo); 403 404 SourceLocation Loc = IntroducerRange.getBegin(); 405 DeclarationName Name 406 = S.Context.DeclarationNames.getCXXConversionFunctionName( 407 S.Context.getCanonicalType(FunctionPtrTy)); 408 DeclarationNameLoc NameLoc; 409 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy, 410 Loc); 411 CXXConversionDecl *Conversion 412 = CXXConversionDecl::Create(S.Context, Class, Loc, 413 DeclarationNameInfo(Name, Loc, NameLoc), 414 ConvTy, 415 S.Context.getTrivialTypeSourceInfo(ConvTy, 416 Loc), 417 /*isInline=*/false, /*isExplicit=*/false, 418 /*isConstexpr=*/false, 419 CallOperator->getBody()->getLocEnd()); 420 Conversion->setAccess(AS_public); 421 Conversion->setImplicit(true); 422 Class->addDecl(Conversion); 423 424 // Add a non-static member function "__invoke" that will be the result of 425 // the conversion. 426 Name = &S.Context.Idents.get("__invoke"); 427 CXXMethodDecl *Invoke 428 = CXXMethodDecl::Create(S.Context, Class, Loc, 429 DeclarationNameInfo(Name, Loc), FunctionTy, 430 CallOperator->getTypeSourceInfo(), 431 /*IsStatic=*/true, SC_Static, /*IsInline=*/true, 432 /*IsConstexpr=*/false, 433 CallOperator->getBody()->getLocEnd()); 434 SmallVector<ParmVarDecl *, 4> InvokeParams; 435 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 436 ParmVarDecl *From = CallOperator->getParamDecl(I); 437 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke, 438 From->getLocStart(), 439 From->getLocation(), 440 From->getIdentifier(), 441 From->getType(), 442 From->getTypeSourceInfo(), 443 From->getStorageClass(), 444 From->getStorageClassAsWritten(), 445 /*DefaultArg=*/0)); 446 } 447 Invoke->setParams(InvokeParams); 448 Invoke->setAccess(AS_private); 449 Invoke->setImplicit(true); 450 Class->addDecl(Invoke); 451} 452 453/// \brief Add a lambda's conversion to block pointer. 454static void addBlockPointerConversion(Sema &S, 455 SourceRange IntroducerRange, 456 CXXRecordDecl *Class, 457 CXXMethodDecl *CallOperator) { 458 const FunctionProtoType *Proto 459 = CallOperator->getType()->getAs<FunctionProtoType>(); 460 QualType BlockPtrTy; 461 { 462 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 463 ExtInfo.TypeQuals = 0; 464 QualType FunctionTy 465 = S.Context.getFunctionType(Proto->getResultType(), 466 Proto->arg_type_begin(), 467 Proto->getNumArgs(), 468 ExtInfo); 469 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 470 } 471 472 FunctionProtoType::ExtProtoInfo ExtInfo; 473 ExtInfo.TypeQuals = Qualifiers::Const; 474 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo); 475 476 SourceLocation Loc = IntroducerRange.getBegin(); 477 DeclarationName Name 478 = S.Context.DeclarationNames.getCXXConversionFunctionName( 479 S.Context.getCanonicalType(BlockPtrTy)); 480 DeclarationNameLoc NameLoc; 481 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); 482 CXXConversionDecl *Conversion 483 = CXXConversionDecl::Create(S.Context, Class, Loc, 484 DeclarationNameInfo(Name, Loc, NameLoc), 485 ConvTy, 486 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 487 /*isInline=*/false, /*isExplicit=*/false, 488 /*isConstexpr=*/false, 489 CallOperator->getBody()->getLocEnd()); 490 Conversion->setAccess(AS_public); 491 Conversion->setImplicit(true); 492 Class->addDecl(Conversion); 493} 494 495/// \brief Determine whether the given context is or is enclosed in an inline 496/// function. 497static bool isInInlineFunction(const DeclContext *DC) { 498 while (!DC->isFileContext()) { 499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 500 if (FD->isInlined()) 501 return true; 502 503 DC = DC->getLexicalParent(); 504 } 505 506 return false; 507} 508 509ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 510 Scope *CurScope, 511 llvm::Optional<unsigned> ManglingNumber, 512 Decl *ContextDecl, 513 bool IsInstantiation) { 514 // Collect information from the lambda scope. 515 llvm::SmallVector<LambdaExpr::Capture, 4> Captures; 516 llvm::SmallVector<Expr *, 4> CaptureInits; 517 LambdaCaptureDefault CaptureDefault; 518 CXXRecordDecl *Class; 519 CXXMethodDecl *CallOperator; 520 SourceRange IntroducerRange; 521 bool ExplicitParams; 522 bool ExplicitResultType; 523 bool LambdaExprNeedsCleanups; 524 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars; 525 llvm::SmallVector<unsigned, 4> ArrayIndexStarts; 526 { 527 LambdaScopeInfo *LSI = getCurLambda(); 528 CallOperator = LSI->CallOperator; 529 Class = LSI->Lambda; 530 IntroducerRange = LSI->IntroducerRange; 531 ExplicitParams = LSI->ExplicitParams; 532 ExplicitResultType = !LSI->HasImplicitReturnType; 533 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups; 534 ArrayIndexVars.swap(LSI->ArrayIndexVars); 535 ArrayIndexStarts.swap(LSI->ArrayIndexStarts); 536 537 // Translate captures. 538 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 539 LambdaScopeInfo::Capture From = LSI->Captures[I]; 540 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 541 bool IsImplicit = I >= LSI->NumExplicitCaptures; 542 543 // Handle 'this' capture. 544 if (From.isThisCapture()) { 545 Captures.push_back(LambdaExpr::Capture(From.getLocation(), 546 IsImplicit, 547 LCK_This)); 548 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(), 549 getCurrentThisType(), 550 /*isImplicit=*/true)); 551 continue; 552 } 553 554 VarDecl *Var = From.getVariable(); 555 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef; 556 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit, 557 Kind, Var, From.getEllipsisLoc())); 558 CaptureInits.push_back(From.getCopyExpr()); 559 } 560 561 switch (LSI->ImpCaptureStyle) { 562 case CapturingScopeInfo::ImpCap_None: 563 CaptureDefault = LCD_None; 564 break; 565 566 case CapturingScopeInfo::ImpCap_LambdaByval: 567 CaptureDefault = LCD_ByCopy; 568 break; 569 570 case CapturingScopeInfo::ImpCap_LambdaByref: 571 CaptureDefault = LCD_ByRef; 572 break; 573 574 case CapturingScopeInfo::ImpCap_Block: 575 llvm_unreachable("block capture in lambda"); 576 break; 577 } 578 579 // C++11 [expr.prim.lambda]p4: 580 // If a lambda-expression does not include a 581 // trailing-return-type, it is as if the trailing-return-type 582 // denotes the following type: 583 // FIXME: Assumes current resolution to core issue 975. 584 if (LSI->HasImplicitReturnType) { 585 // - if there are no return statements in the 586 // compound-statement, or all return statements return 587 // either an expression of type void or no expression or 588 // braced-init-list, the type void; 589 if (LSI->ReturnType.isNull()) { 590 LSI->ReturnType = Context.VoidTy; 591 } else { 592 // C++11 [expr.prim.lambda]p4: 593 // - if the compound-statement is of the form 594 // 595 // { attribute-specifier-seq[opt] return expression ; } 596 // 597 // the type of the returned expression after 598 // lvalue-to-rvalue conversion (4.1), array-to-pointer 599 // conver- sion (4.2), and function-to-pointer conversion 600 // (4.3); 601 // 602 // Since we're accepting the resolution to a post-C++11 core 603 // issue with a non-trivial extension, provide a warning (by 604 // default). 605 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body); 606 if (!(CompoundBody->size() == 1 && 607 isa<ReturnStmt>(*CompoundBody->body_begin())) && 608 !Context.hasSameType(LSI->ReturnType, Context.VoidTy)) 609 Diag(IntroducerRange.getBegin(), 610 diag::ext_lambda_implies_void_return); 611 } 612 613 // Create a function type with the inferred return type. 614 const FunctionProtoType *Proto 615 = CallOperator->getType()->getAs<FunctionProtoType>(); 616 QualType FunctionTy 617 = Context.getFunctionType(LSI->ReturnType, 618 Proto->arg_type_begin(), 619 Proto->getNumArgs(), 620 Proto->getExtProtoInfo()); 621 CallOperator->setType(FunctionTy); 622 } 623 624 // C++ [expr.prim.lambda]p7: 625 // The lambda-expression's compound-statement yields the 626 // function-body (8.4) of the function call operator [...]. 627 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation); 628 CallOperator->setLexicalDeclContext(Class); 629 Class->addDecl(CallOperator); 630 PopExpressionEvaluationContext(); 631 632 // C++11 [expr.prim.lambda]p6: 633 // The closure type for a lambda-expression with no lambda-capture 634 // has a public non-virtual non-explicit const conversion function 635 // to pointer to function having the same parameter and return 636 // types as the closure type's function call operator. 637 if (Captures.empty() && CaptureDefault == LCD_None) 638 addFunctionPointerConversion(*this, IntroducerRange, Class, 639 CallOperator); 640 641 // Objective-C++: 642 // The closure type for a lambda-expression has a public non-virtual 643 // non-explicit const conversion function to a block pointer having the 644 // same parameter and return types as the closure type's function call 645 // operator. 646 if (getLangOptions().Blocks && getLangOptions().ObjC1) 647 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 648 649 // Finalize the lambda class. 650 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end()); 651 ActOnFields(0, Class->getLocation(), Class, Fields, 652 SourceLocation(), SourceLocation(), 0); 653 CheckCompletedCXXClass(Class); 654 } 655 656 if (LambdaExprNeedsCleanups) 657 ExprNeedsCleanups = true; 658 659 // If we don't already have a mangling number for this lambda expression, 660 // allocate one now. 661 if (!ManglingNumber) { 662 ContextDecl = ExprEvalContexts.back().LambdaContextDecl; 663 664 enum ContextKind { 665 Normal, 666 DefaultArgument, 667 DataMember, 668 StaticDataMember 669 } Kind = Normal; 670 671 // Default arguments of member function parameters that appear in a class 672 // definition, as well as the initializers of data members, receive special 673 // treatment. Identify them. 674 if (ContextDecl) { 675 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) { 676 if (const DeclContext *LexicalDC 677 = Param->getDeclContext()->getLexicalParent()) 678 if (LexicalDC->isRecord()) 679 Kind = DefaultArgument; 680 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) { 681 if (Var->getDeclContext()->isRecord()) 682 Kind = StaticDataMember; 683 } else if (isa<FieldDecl>(ContextDecl)) { 684 Kind = DataMember; 685 } 686 } 687 688 switch (Kind) { 689 case Normal: 690 if (CurContext->isDependentContext() || isInInlineFunction(CurContext)) 691 ManglingNumber = Context.getLambdaManglingNumber(CallOperator); 692 else 693 ManglingNumber = 0; 694 695 // There is no special context for this lambda. 696 ContextDecl = 0; 697 break; 698 699 case StaticDataMember: 700 if (!CurContext->isDependentContext()) { 701 ManglingNumber = 0; 702 ContextDecl = 0; 703 break; 704 } 705 // Fall through to assign a mangling number. 706 707 case DataMember: 708 case DefaultArgument: 709 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext() 710 .getManglingNumber(CallOperator); 711 break; 712 } 713 } 714 715 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 716 CaptureDefault, Captures, 717 ExplicitParams, ExplicitResultType, 718 CaptureInits, ArrayIndexVars, 719 ArrayIndexStarts, Body->getLocEnd(), 720 *ManglingNumber, ContextDecl); 721 722 // C++11 [expr.prim.lambda]p2: 723 // A lambda-expression shall not appear in an unevaluated operand 724 // (Clause 5). 725 if (!CurContext->isDependentContext()) { 726 switch (ExprEvalContexts.back().Context) { 727 case Unevaluated: 728 // We don't actually diagnose this case immediately, because we 729 // could be within a context where we might find out later that 730 // the expression is potentially evaluated (e.g., for typeid). 731 ExprEvalContexts.back().Lambdas.push_back(Lambda); 732 break; 733 734 case ConstantEvaluated: 735 case PotentiallyEvaluated: 736 case PotentiallyEvaluatedIfUsed: 737 break; 738 } 739 } 740 741 return MaybeBindToTemporary(Lambda); 742} 743