1 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ lambda expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 #include "clang/Sema/DeclSpec.h" 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTLambda.h" 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/Basic/TargetInfo.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 "clang/Sema/SemaLambda.h" 23 #include "llvm/ADT/STLExtras.h" 24 using namespace clang; 25 using namespace sema; 26 27 /// Examines the FunctionScopeInfo stack to determine the nearest 28 /// enclosing lambda (to the current lambda) that is 'capture-ready' for 29 /// the variable referenced in the current lambda (i.e. \p VarToCapture). 30 /// If successful, returns the index into Sema's FunctionScopeInfo stack 31 /// of the capture-ready lambda's LambdaScopeInfo. 32 /// 33 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current 34 /// lambda - is on top) to determine the index of the nearest enclosing/outer 35 /// lambda that is ready to capture the \p VarToCapture being referenced in 36 /// the current lambda. 37 /// As we climb down the stack, we want the index of the first such lambda - 38 /// that is the lambda with the highest index that is 'capture-ready'. 39 /// 40 /// A lambda 'L' is capture-ready for 'V' (var or this) if: 41 /// - its enclosing context is non-dependent 42 /// - and if the chain of lambdas between L and the lambda in which 43 /// V is potentially used (i.e. the lambda at the top of the scope info 44 /// stack), can all capture or have already captured V. 45 /// If \p VarToCapture is 'null' then we are trying to capture 'this'. 46 /// 47 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked 48 /// for whether it is 'capture-capable' (see 49 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly 50 /// capture. 51 /// 52 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a 53 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda 54 /// is at the top of the stack and has the highest index. 55 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. 56 /// 57 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains 58 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda 59 /// which is capture-ready. If the return value evaluates to 'false' then 60 /// no lambda is capture-ready for \p VarToCapture. 61 62 static inline Optional<unsigned> 63 getStackIndexOfNearestEnclosingCaptureReadyLambda( 64 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes, 65 VarDecl *VarToCapture) { 66 // Label failure to capture. 67 const Optional<unsigned> NoLambdaIsCaptureReady; 68 69 // Ignore all inner captured regions. 70 unsigned CurScopeIndex = FunctionScopes.size() - 1; 71 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>( 72 FunctionScopes[CurScopeIndex])) 73 --CurScopeIndex; 74 assert( 75 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && 76 "The function on the top of sema's function-info stack must be a lambda"); 77 78 // If VarToCapture is null, we are attempting to capture 'this'. 79 const bool IsCapturingThis = !VarToCapture; 80 const bool IsCapturingVariable = !IsCapturingThis; 81 82 // Start with the current lambda at the top of the stack (highest index). 83 DeclContext *EnclosingDC = 84 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator; 85 86 do { 87 const clang::sema::LambdaScopeInfo *LSI = 88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]); 89 // IF we have climbed down to an intervening enclosing lambda that contains 90 // the variable declaration - it obviously can/must not capture the 91 // variable. 92 // Since its enclosing DC is dependent, all the lambdas between it and the 93 // innermost nested lambda are dependent (otherwise we wouldn't have 94 // arrived here) - so we don't yet have a lambda that can capture the 95 // variable. 96 if (IsCapturingVariable && 97 VarToCapture->getDeclContext()->Equals(EnclosingDC)) 98 return NoLambdaIsCaptureReady; 99 100 // For an enclosing lambda to be capture ready for an entity, all 101 // intervening lambda's have to be able to capture that entity. If even 102 // one of the intervening lambda's is not capable of capturing the entity 103 // then no enclosing lambda can ever capture that entity. 104 // For e.g. 105 // const int x = 10; 106 // [=](auto a) { #1 107 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x' 108 // [=](auto c) { #3 109 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2 110 // }; }; }; 111 // If they do not have a default implicit capture, check to see 112 // if the entity has already been explicitly captured. 113 // If even a single dependent enclosing lambda lacks the capability 114 // to ever capture this variable, there is no further enclosing 115 // non-dependent lambda that can capture this variable. 116 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) { 117 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture)) 118 return NoLambdaIsCaptureReady; 119 if (IsCapturingThis && !LSI->isCXXThisCaptured()) 120 return NoLambdaIsCaptureReady; 121 } 122 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); 123 124 assert(CurScopeIndex); 125 --CurScopeIndex; 126 } while (!EnclosingDC->isTranslationUnit() && 127 EnclosingDC->isDependentContext() && 128 isLambdaCallOperator(EnclosingDC)); 129 130 assert(CurScopeIndex < (FunctionScopes.size() - 1)); 131 // If the enclosingDC is not dependent, then the immediately nested lambda 132 // (one index above) is capture-ready. 133 if (!EnclosingDC->isDependentContext()) 134 return CurScopeIndex + 1; 135 return NoLambdaIsCaptureReady; 136 } 137 138 /// Examines the FunctionScopeInfo stack to determine the nearest 139 /// enclosing lambda (to the current lambda) that is 'capture-capable' for 140 /// the variable referenced in the current lambda (i.e. \p VarToCapture). 141 /// If successful, returns the index into Sema's FunctionScopeInfo stack 142 /// of the capture-capable lambda's LambdaScopeInfo. 143 /// 144 /// Given the current stack of lambdas being processed by Sema and 145 /// the variable of interest, to identify the nearest enclosing lambda (to the 146 /// current lambda at the top of the stack) that can truly capture 147 /// a variable, it has to have the following two properties: 148 /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': 149 /// - climb down the stack (i.e. starting from the innermost and examining 150 /// each outer lambda step by step) checking if each enclosing 151 /// lambda can either implicitly or explicitly capture the variable. 152 /// Record the first such lambda that is enclosed in a non-dependent 153 /// context. If no such lambda currently exists return failure. 154 /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly 155 /// capture the variable by checking all its enclosing lambdas: 156 /// - check if all outer lambdas enclosing the 'capture-ready' lambda 157 /// identified above in 'a' can also capture the variable (this is done 158 /// via tryCaptureVariable for variables and CheckCXXThisCapture for 159 /// 'this' by passing in the index of the Lambda identified in step 'a') 160 /// 161 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a 162 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda 163 /// is at the top of the stack. 164 /// 165 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. 166 /// 167 /// 168 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains 169 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda 170 /// which is capture-capable. If the return value evaluates to 'false' then 171 /// no lambda is capture-capable for \p VarToCapture. 172 173 Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( 174 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, 175 VarDecl *VarToCapture, Sema &S) { 176 177 const Optional<unsigned> NoLambdaIsCaptureCapable; 178 179 const Optional<unsigned> OptionalStackIndex = 180 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, 181 VarToCapture); 182 if (!OptionalStackIndex) 183 return NoLambdaIsCaptureCapable; 184 185 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue(); 186 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || 187 S.getCurGenericLambda()) && 188 "The capture ready lambda for a potential capture can only be the " 189 "current lambda if it is a generic lambda"); 190 191 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = 192 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); 193 194 // If VarToCapture is null, we are attempting to capture 'this' 195 const bool IsCapturingThis = !VarToCapture; 196 const bool IsCapturingVariable = !IsCapturingThis; 197 198 if (IsCapturingVariable) { 199 // Check if the capture-ready lambda can truly capture the variable, by 200 // checking whether all enclosing lambdas of the capture-ready lambda allow 201 // the capture - i.e. make sure it is capture-capable. 202 QualType CaptureType, DeclRefType; 203 const bool CanCaptureVariable = 204 !S.tryCaptureVariable(VarToCapture, 205 /*ExprVarIsUsedInLoc*/ SourceLocation(), 206 clang::Sema::TryCapture_Implicit, 207 /*EllipsisLoc*/ SourceLocation(), 208 /*BuildAndDiagnose*/ false, CaptureType, 209 DeclRefType, &IndexOfCaptureReadyLambda); 210 if (!CanCaptureVariable) 211 return NoLambdaIsCaptureCapable; 212 } else { 213 // Check if the capture-ready lambda can truly capture 'this' by checking 214 // whether all enclosing lambdas of the capture-ready lambda can capture 215 // 'this'. 216 const bool CanCaptureThis = 217 !S.CheckCXXThisCapture( 218 CaptureReadyLambdaLSI->PotentialThisCaptureLocation, 219 /*Explicit*/ false, /*BuildAndDiagnose*/ false, 220 &IndexOfCaptureReadyLambda); 221 if (!CanCaptureThis) 222 return NoLambdaIsCaptureCapable; 223 } 224 return IndexOfCaptureReadyLambda; 225 } 226 227 static inline TemplateParameterList * 228 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { 229 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) { 230 LSI->GLTemplateParameterList = TemplateParameterList::Create( 231 SemaRef.Context, 232 /*Template kw loc*/ SourceLocation(), 233 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(), 234 LSI->TemplateParams, 235 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(), 236 LSI->RequiresClause.get()); 237 } 238 return LSI->GLTemplateParameterList; 239 } 240 241 CXXRecordDecl * 242 Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, 243 unsigned LambdaDependencyKind, 244 LambdaCaptureDefault CaptureDefault) { 245 DeclContext *DC = CurContext; 246 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 247 DC = DC->getParent(); 248 249 bool IsGenericLambda = 250 Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this); 251 // Start constructing the lambda class. 252 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda( 253 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind, 254 IsGenericLambda, CaptureDefault); 255 DC->addDecl(Class); 256 257 return Class; 258 } 259 260 /// Determine whether the given context is or is enclosed in an inline 261 /// function. 262 static bool isInInlineFunction(const DeclContext *DC) { 263 while (!DC->isFileContext()) { 264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 265 if (FD->isInlined()) 266 return true; 267 268 DC = DC->getLexicalParent(); 269 } 270 271 return false; 272 } 273 274 std::tuple<MangleNumberingContext *, Decl *> 275 Sema::getCurrentMangleNumberContext(const DeclContext *DC) { 276 // Compute the context for allocating mangling numbers in the current 277 // expression, if the ABI requires them. 278 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; 279 280 enum ContextKind { 281 Normal, 282 DefaultArgument, 283 DataMember, 284 StaticDataMember, 285 InlineVariable, 286 VariableTemplate 287 } Kind = Normal; 288 289 // Default arguments of member function parameters that appear in a class 290 // definition, as well as the initializers of data members, receive special 291 // treatment. Identify them. 292 if (ManglingContextDecl) { 293 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { 294 if (const DeclContext *LexicalDC 295 = Param->getDeclContext()->getLexicalParent()) 296 if (LexicalDC->isRecord()) 297 Kind = DefaultArgument; 298 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) { 299 if (Var->getDeclContext()->isRecord()) 300 Kind = StaticDataMember; 301 else if (Var->getMostRecentDecl()->isInline()) 302 Kind = InlineVariable; 303 else if (Var->getDescribedVarTemplate()) 304 Kind = VariableTemplate; 305 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 306 if (!VTS->isExplicitSpecialization()) 307 Kind = VariableTemplate; 308 } 309 } else if (isa<FieldDecl>(ManglingContextDecl)) { 310 Kind = DataMember; 311 } 312 } 313 314 // Itanium ABI [5.1.7]: 315 // In the following contexts [...] the one-definition rule requires closure 316 // types in different translation units to "correspond": 317 bool IsInNonspecializedTemplate = 318 inTemplateInstantiation() || CurContext->isDependentContext(); 319 switch (Kind) { 320 case Normal: { 321 // -- the bodies of non-exported nonspecialized template functions 322 // -- the bodies of inline functions 323 if ((IsInNonspecializedTemplate && 324 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) || 325 isInInlineFunction(CurContext)) { 326 while (auto *CD = dyn_cast<CapturedDecl>(DC)) 327 DC = CD->getParent(); 328 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr); 329 } 330 331 return std::make_tuple(nullptr, nullptr); 332 } 333 334 case StaticDataMember: 335 // -- the initializers of nonspecialized static members of template classes 336 if (!IsInNonspecializedTemplate) 337 return std::make_tuple(nullptr, ManglingContextDecl); 338 // Fall through to get the current context. 339 LLVM_FALLTHROUGH; 340 341 case DataMember: 342 // -- the in-class initializers of class members 343 case DefaultArgument: 344 // -- default arguments appearing in class definitions 345 case InlineVariable: 346 // -- the initializers of inline variables 347 case VariableTemplate: 348 // -- the initializers of templated variables 349 return std::make_tuple( 350 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl, 351 ManglingContextDecl), 352 ManglingContextDecl); 353 } 354 355 llvm_unreachable("unexpected context"); 356 } 357 358 static QualType 359 buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, 360 TemplateParameterList *TemplateParams, 361 TypeSourceInfo *MethodTypeInfo) { 362 assert(MethodTypeInfo && "expected a non null type"); 363 364 QualType MethodType = MethodTypeInfo->getType(); 365 // If a lambda appears in a dependent context or is a generic lambda (has 366 // template parameters) and has an 'auto' return type, deduce it to a 367 // dependent type. 368 if (Class->isDependentContext() || TemplateParams) { 369 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); 370 QualType Result = FPT->getReturnType(); 371 if (Result->isUndeducedType()) { 372 Result = S.SubstAutoTypeDependent(Result); 373 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(), 374 FPT->getExtProtoInfo()); 375 } 376 } 377 return MethodType; 378 } 379 380 void Sema::handleLambdaNumbering( 381 CXXRecordDecl *Class, CXXMethodDecl *Method, 382 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) { 383 if (Mangling) { 384 bool HasKnownInternalLinkage; 385 unsigned ManglingNumber, DeviceManglingNumber; 386 Decl *ManglingContextDecl; 387 std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber, 388 ManglingContextDecl) = Mangling.getValue(); 389 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl, 390 HasKnownInternalLinkage); 391 Class->setDeviceLambdaManglingNumber(DeviceManglingNumber); 392 return; 393 } 394 395 auto getMangleNumberingContext = 396 [this](CXXRecordDecl *Class, 397 Decl *ManglingContextDecl) -> MangleNumberingContext * { 398 // Get mangle numbering context if there's any extra decl context. 399 if (ManglingContextDecl) 400 return &Context.getManglingNumberContext( 401 ASTContext::NeedExtraManglingDecl, ManglingContextDecl); 402 // Otherwise, from that lambda's decl context. 403 auto DC = Class->getDeclContext(); 404 while (auto *CD = dyn_cast<CapturedDecl>(DC)) 405 DC = CD->getParent(); 406 return &Context.getManglingNumberContext(DC); 407 }; 408 409 MangleNumberingContext *MCtx; 410 Decl *ManglingContextDecl; 411 std::tie(MCtx, ManglingContextDecl) = 412 getCurrentMangleNumberContext(Class->getDeclContext()); 413 bool HasKnownInternalLinkage = false; 414 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice || 415 getLangOpts().SYCLIsHost)) { 416 // Force lambda numbering in CUDA/HIP as we need to name lambdas following 417 // ODR. Both device- and host-compilation need to have a consistent naming 418 // on kernel functions. As lambdas are potential part of these `__global__` 419 // function names, they needs numbering following ODR. 420 // Also force for SYCL, since we need this for the 421 // __builtin_sycl_unique_stable_name implementation, which depends on lambda 422 // mangling. 423 MCtx = getMangleNumberingContext(Class, ManglingContextDecl); 424 assert(MCtx && "Retrieving mangle numbering context failed!"); 425 HasKnownInternalLinkage = true; 426 } 427 if (MCtx) { 428 unsigned ManglingNumber = MCtx->getManglingNumber(Method); 429 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl, 430 HasKnownInternalLinkage); 431 Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method)); 432 } 433 } 434 435 static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, 436 CXXMethodDecl *CallOperator, 437 bool ExplicitResultType) { 438 if (ExplicitResultType) { 439 LSI->HasImplicitReturnType = false; 440 LSI->ReturnType = CallOperator->getReturnType(); 441 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType()) { 442 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType, 443 diag::err_lambda_incomplete_result); 444 } 445 } else { 446 LSI->HasImplicitReturnType = true; 447 } 448 } 449 450 void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, 451 SourceRange IntroducerRange, 452 LambdaCaptureDefault CaptureDefault, 453 SourceLocation CaptureDefaultLoc, 454 bool ExplicitParams, bool Mutable) { 455 LSI->CallOperator = CallOperator; 456 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 457 LSI->Lambda = LambdaClass; 458 if (CaptureDefault == LCD_ByCopy) 459 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 460 else if (CaptureDefault == LCD_ByRef) 461 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 462 LSI->CaptureDefaultLoc = CaptureDefaultLoc; 463 LSI->IntroducerRange = IntroducerRange; 464 LSI->ExplicitParams = ExplicitParams; 465 LSI->Mutable = Mutable; 466 } 467 468 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 469 LSI->finishedExplicitCaptures(); 470 } 471 472 void Sema::ActOnLambdaExplicitTemplateParameterList( 473 LambdaIntroducer &Intro, SourceLocation LAngleLoc, 474 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, 475 ExprResult RequiresClause) { 476 LambdaScopeInfo *LSI = getCurLambda(); 477 assert(LSI && "Expected a lambda scope"); 478 assert(LSI->NumExplicitTemplateParams == 0 && 479 "Already acted on explicit template parameters"); 480 assert(LSI->TemplateParams.empty() && 481 "Explicit template parameters should come " 482 "before invented (auto) ones"); 483 assert(!TParams.empty() && 484 "No template parameters to act on"); 485 LSI->TemplateParams.append(TParams.begin(), TParams.end()); 486 LSI->NumExplicitTemplateParams = TParams.size(); 487 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc}; 488 LSI->RequiresClause = RequiresClause; 489 } 490 491 /// If this expression is an enumerator-like expression of some type 492 /// T, return the type T; otherwise, return null. 493 /// 494 /// Pointer comparisons on the result here should always work because 495 /// it's derived from either the parent of an EnumConstantDecl 496 /// (i.e. the definition) or the declaration returned by 497 /// EnumType::getDecl() (i.e. the definition). 498 static EnumDecl *findEnumForBlockReturn(Expr *E) { 499 // An expression is an enumerator-like expression of type T if, 500 // ignoring parens and parens-like expressions: 501 E = E->IgnoreParens(); 502 503 // - it is an enumerator whose enum type is T or 504 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 505 if (EnumConstantDecl *D 506 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 507 return cast<EnumDecl>(D->getDeclContext()); 508 } 509 return nullptr; 510 } 511 512 // - it is a comma expression whose RHS is an enumerator-like 513 // expression of type T or 514 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 515 if (BO->getOpcode() == BO_Comma) 516 return findEnumForBlockReturn(BO->getRHS()); 517 return nullptr; 518 } 519 520 // - it is a statement-expression whose value expression is an 521 // enumerator-like expression of type T or 522 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 523 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) 524 return findEnumForBlockReturn(last); 525 return nullptr; 526 } 527 528 // - it is a ternary conditional operator (not the GNU ?: 529 // extension) whose second and third operands are 530 // enumerator-like expressions of type T or 531 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 532 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) 533 if (ED == findEnumForBlockReturn(CO->getFalseExpr())) 534 return ED; 535 return nullptr; 536 } 537 538 // (implicitly:) 539 // - it is an implicit integral conversion applied to an 540 // enumerator-like expression of type T or 541 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 542 // We can sometimes see integral conversions in valid 543 // enumerator-like expressions. 544 if (ICE->getCastKind() == CK_IntegralCast) 545 return findEnumForBlockReturn(ICE->getSubExpr()); 546 547 // Otherwise, just rely on the type. 548 } 549 550 // - it is an expression of that formal enum type. 551 if (const EnumType *ET = E->getType()->getAs<EnumType>()) { 552 return ET->getDecl(); 553 } 554 555 // Otherwise, nope. 556 return nullptr; 557 } 558 559 /// Attempt to find a type T for which the returned expression of the 560 /// given statement is an enumerator-like expression of that type. 561 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { 562 if (Expr *retValue = ret->getRetValue()) 563 return findEnumForBlockReturn(retValue); 564 return nullptr; 565 } 566 567 /// Attempt to find a common type T for which all of the returned 568 /// expressions in a block are enumerator-like expressions of that 569 /// type. 570 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { 571 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); 572 573 // Try to find one for the first return. 574 EnumDecl *ED = findEnumForBlockReturn(*i); 575 if (!ED) return nullptr; 576 577 // Check that the rest of the returns have the same enum. 578 for (++i; i != e; ++i) { 579 if (findEnumForBlockReturn(*i) != ED) 580 return nullptr; 581 } 582 583 // Never infer an anonymous enum type. 584 if (!ED->hasNameForLinkage()) return nullptr; 585 586 return ED; 587 } 588 589 /// Adjust the given return statements so that they formally return 590 /// the given type. It should require, at most, an IntegralCast. 591 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, 592 QualType returnType) { 593 for (ArrayRef<ReturnStmt*>::iterator 594 i = returns.begin(), e = returns.end(); i != e; ++i) { 595 ReturnStmt *ret = *i; 596 Expr *retValue = ret->getRetValue(); 597 if (S.Context.hasSameType(retValue->getType(), returnType)) 598 continue; 599 600 // Right now we only support integral fixup casts. 601 assert(returnType->isIntegralOrUnscopedEnumerationType()); 602 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); 603 604 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); 605 606 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue); 607 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E, 608 /*base path*/ nullptr, VK_PRValue, 609 FPOptionsOverride()); 610 if (cleanups) { 611 cleanups->setSubExpr(E); 612 } else { 613 ret->setRetValue(E); 614 } 615 } 616 } 617 618 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { 619 assert(CSI.HasImplicitReturnType); 620 // If it was ever a placeholder, it had to been deduced to DependentTy. 621 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); 622 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && 623 "lambda expressions use auto deduction in C++14 onwards"); 624 625 // C++ core issue 975: 626 // If a lambda-expression does not include a trailing-return-type, 627 // it is as if the trailing-return-type denotes the following type: 628 // - if there are no return statements in the compound-statement, 629 // or all return statements return either an expression of type 630 // void or no expression or braced-init-list, the type void; 631 // - otherwise, if all return statements return an expression 632 // and the types of the returned expressions after 633 // lvalue-to-rvalue conversion (4.1 [conv.lval]), 634 // array-to-pointer conversion (4.2 [conv.array]), and 635 // function-to-pointer conversion (4.3 [conv.func]) are the 636 // same, that common type; 637 // - otherwise, the program is ill-formed. 638 // 639 // C++ core issue 1048 additionally removes top-level cv-qualifiers 640 // from the types of returned expressions to match the C++14 auto 641 // deduction rules. 642 // 643 // In addition, in blocks in non-C++ modes, if all of the return 644 // statements are enumerator-like expressions of some type T, where 645 // T has a name for linkage, then we infer the return type of the 646 // block to be that type. 647 648 // First case: no return statements, implicit void return type. 649 ASTContext &Ctx = getASTContext(); 650 if (CSI.Returns.empty()) { 651 // It's possible there were simply no /valid/ return statements. 652 // In this case, the first one we found may have at least given us a type. 653 if (CSI.ReturnType.isNull()) 654 CSI.ReturnType = Ctx.VoidTy; 655 return; 656 } 657 658 // Second case: at least one return statement has dependent type. 659 // Delay type checking until instantiation. 660 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); 661 if (CSI.ReturnType->isDependentType()) 662 return; 663 664 // Try to apply the enum-fuzz rule. 665 if (!getLangOpts().CPlusPlus) { 666 assert(isa<BlockScopeInfo>(CSI)); 667 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); 668 if (ED) { 669 CSI.ReturnType = Context.getTypeDeclType(ED); 670 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); 671 return; 672 } 673 } 674 675 // Third case: only one return statement. Don't bother doing extra work! 676 if (CSI.Returns.size() == 1) 677 return; 678 679 // General case: many return statements. 680 // Check that they all have compatible return types. 681 682 // We require the return types to strictly match here. 683 // Note that we've already done the required promotions as part of 684 // processing the return statement. 685 for (const ReturnStmt *RS : CSI.Returns) { 686 const Expr *RetE = RS->getRetValue(); 687 688 QualType ReturnType = 689 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType(); 690 if (Context.getCanonicalFunctionResultType(ReturnType) == 691 Context.getCanonicalFunctionResultType(CSI.ReturnType)) { 692 // Use the return type with the strictest possible nullability annotation. 693 auto RetTyNullability = ReturnType->getNullability(Ctx); 694 auto BlockNullability = CSI.ReturnType->getNullability(Ctx); 695 if (BlockNullability && 696 (!RetTyNullability || 697 hasWeakerNullability(*RetTyNullability, *BlockNullability))) 698 CSI.ReturnType = ReturnType; 699 continue; 700 } 701 702 // FIXME: This is a poor diagnostic for ReturnStmts without expressions. 703 // TODO: It's possible that the *first* return is the divergent one. 704 Diag(RS->getBeginLoc(), 705 diag::err_typecheck_missing_return_type_incompatible) 706 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI); 707 // Continue iterating so that we keep emitting diagnostics. 708 } 709 } 710 711 QualType Sema::buildLambdaInitCaptureInitialization( 712 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 713 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit, 714 Expr *&Init) { 715 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to 716 // deduce against. 717 QualType DeductType = Context.getAutoDeductType(); 718 TypeLocBuilder TLB; 719 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType); 720 TL.setNameLoc(Loc); 721 if (ByRef) { 722 DeductType = BuildReferenceType(DeductType, true, Loc, Id); 723 assert(!DeductType.isNull() && "can't build reference to auto"); 724 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); 725 } 726 if (EllipsisLoc.isValid()) { 727 if (Init->containsUnexpandedParameterPack()) { 728 Diag(EllipsisLoc, getLangOpts().CPlusPlus20 729 ? diag::warn_cxx17_compat_init_capture_pack 730 : diag::ext_init_capture_pack); 731 DeductType = Context.getPackExpansionType(DeductType, NumExpansions, 732 /*ExpectPackInType=*/false); 733 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc); 734 } else { 735 // Just ignore the ellipsis for now and form a non-pack variable. We'll 736 // diagnose this later when we try to capture it. 737 } 738 } 739 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); 740 741 // Deduce the type of the init capture. 742 QualType DeducedType = deduceVarTypeFromInitializer( 743 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI, 744 SourceRange(Loc, Loc), IsDirectInit, Init); 745 if (DeducedType.isNull()) 746 return QualType(); 747 748 // Are we a non-list direct initialization? 749 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 750 751 // Perform initialization analysis and ensure any implicit conversions 752 // (such as lvalue-to-rvalue) are enforced. 753 InitializedEntity Entity = 754 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc); 755 InitializationKind Kind = 756 IsDirectInit 757 ? (CXXDirectInit ? InitializationKind::CreateDirect( 758 Loc, Init->getBeginLoc(), Init->getEndLoc()) 759 : InitializationKind::CreateDirectList(Loc)) 760 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc()); 761 762 MultiExprArg Args = Init; 763 if (CXXDirectInit) 764 Args = 765 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); 766 QualType DclT; 767 InitializationSequence InitSeq(*this, Entity, Kind, Args); 768 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 769 770 if (Result.isInvalid()) 771 return QualType(); 772 773 Init = Result.getAs<Expr>(); 774 return DeducedType; 775 } 776 777 VarDecl *Sema::createLambdaInitCaptureVarDecl( 778 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, 779 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) { 780 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization 781 // rather than reconstructing it here. 782 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc); 783 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>()) 784 PETL.setEllipsisLoc(EllipsisLoc); 785 786 // Create a dummy variable representing the init-capture. This is not actually 787 // used as a variable, and only exists as a way to name and refer to the 788 // init-capture. 789 // FIXME: Pass in separate source locations for '&' and identifier. 790 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id, 791 InitCaptureType, TSI, SC_Auto); 792 NewVD->setInitCapture(true); 793 NewVD->setReferenced(true); 794 // FIXME: Pass in a VarDecl::InitializationStyle. 795 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle)); 796 NewVD->markUsed(Context); 797 NewVD->setInit(Init); 798 if (NewVD->isParameterPack()) 799 getCurLambda()->LocalPacks.push_back(NewVD); 800 return NewVD; 801 } 802 803 void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) { 804 assert(Var->isInitCapture() && "init capture flag should be set"); 805 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(), 806 /*isNested*/false, Var->getLocation(), SourceLocation(), 807 Var->getType(), /*Invalid*/false); 808 } 809 810 // Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't 811 // check that the current lambda is in a consistent or fully constructed state. 812 static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) { 813 assert(!S.FunctionScopes.empty()); 814 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]); 815 } 816 817 static TypeSourceInfo * 818 getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) { 819 // C++11 [expr.prim.lambda]p4: 820 // If a lambda-expression does not include a lambda-declarator, it is as 821 // if the lambda-declarator were (). 822 FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention( 823 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 824 EPI.HasTrailingReturn = true; 825 EPI.TypeQuals.addConst(); 826 LangAS AS = S.getDefaultCXXMethodAddrSpace(); 827 if (AS != LangAS::Default) 828 EPI.TypeQuals.addAddressSpace(AS); 829 830 // C++1y [expr.prim.lambda]: 831 // The lambda return type is 'auto', which is replaced by the 832 // trailing-return type if provided and/or deduced from 'return' 833 // statements 834 // We don't do this before C++1y, because we don't support deduced return 835 // types there. 836 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14 837 ? S.Context.getAutoDeductType() 838 : S.Context.DependentTy; 839 QualType MethodTy = 840 S.Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI); 841 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc); 842 } 843 844 static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro, 845 Declarator &ParamInfo, Scope *CurScope, 846 SourceLocation Loc, 847 bool &ExplicitResultType) { 848 849 ExplicitResultType = false; 850 851 TypeSourceInfo *MethodTyInfo; 852 853 if (ParamInfo.getNumTypeObjects() == 0) { 854 MethodTyInfo = getDummyLambdaType(S, Loc); 855 } else { 856 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 857 ExplicitResultType = FTI.hasTrailingReturnType(); 858 if (!FTI.hasMutableQualifier()) { 859 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, Loc); 860 } 861 862 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo, CurScope); 863 864 assert(MethodTyInfo && "no type from lambda-declarator"); 865 866 // Check for unexpanded parameter packs in the method type. 867 if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) 868 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo, 869 S.UPPC_DeclarationType); 870 } 871 return MethodTyInfo; 872 } 873 874 CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange, 875 CXXRecordDecl *Class) { 876 877 // C++11 [expr.prim.lambda]p5: 878 // The closure type for a lambda-expression has a public inline function 879 // call operator (13.5.4) whose parameters and return type are described 880 // by the lambda-expression's parameter-declaration-clause and 881 // trailing-return-type respectively. 882 DeclarationName MethodName = 883 Context.DeclarationNames.getCXXOperatorName(OO_Call); 884 DeclarationNameLoc MethodNameLoc = 885 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange.getBegin()); 886 CXXMethodDecl *Method = CXXMethodDecl::Create( 887 Context, Class, SourceLocation(), 888 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(), 889 MethodNameLoc), 890 QualType(), nullptr, SC_None, getCurFPFeatures().isFPConstrained(), 891 /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(), 892 nullptr); 893 Method->setAccess(AS_public); 894 return Method; 895 } 896 897 void Sema::CompleteLambdaCallOperator( 898 CXXMethodDecl *Method, SourceLocation LambdaLoc, 899 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, 900 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, 901 ArrayRef<ParmVarDecl *> Params, bool HasExplicitResultType) { 902 903 LambdaScopeInfo *const LSI = getCurrentLambdaScopeUnsafe(*this); 904 905 if (TrailingRequiresClause) 906 Method->setTrailingRequiresClause(TrailingRequiresClause); 907 908 TemplateParameterList *TemplateParams = 909 getGenericLambdaTemplateParameterList(LSI, *this); 910 911 auto DC = Method->getLexicalDeclContext(); 912 Method->setLexicalDeclContext(LSI->Lambda); 913 if (TemplateParams) { 914 FunctionTemplateDecl *const TemplateMethod = FunctionTemplateDecl::Create( 915 Context, LSI->Lambda, Method->getLocation(), Method->getDeclName(), 916 TemplateParams, Method); 917 TemplateMethod->setAccess(AS_public); 918 Method->setDescribedFunctionTemplate(TemplateMethod); 919 LSI->Lambda->addDecl(TemplateMethod); 920 TemplateMethod->setLexicalDeclContext(DC); 921 } else { 922 LSI->Lambda->addDecl(Method); 923 } 924 LSI->Lambda->setLambdaIsGeneric(TemplateParams); 925 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo); 926 927 Method->setLexicalDeclContext(DC); 928 Method->setLocation(LambdaLoc); 929 Method->setInnerLocStart(CallOperatorLoc); 930 Method->setTypeSourceInfo(MethodTyInfo); 931 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda, 932 TemplateParams, MethodTyInfo)); 933 Method->setConstexprKind(ConstexprKind); 934 if (!Params.empty()) { 935 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false); 936 Method->setParams(Params); 937 for (auto P : Method->parameters()) 938 P->setOwningFunction(Method); 939 } 940 941 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType); 942 } 943 944 void Sema::ActOnLambdaIntroducer(LambdaIntroducer &Intro, Scope *CurrentScope) { 945 946 LambdaScopeInfo *const LSI = getCurLambda(); 947 assert(LSI && "LambdaScopeInfo should be on stack!"); 948 949 if (Intro.Default == LCD_ByCopy) 950 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 951 else if (Intro.Default == LCD_ByRef) 952 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 953 LSI->CaptureDefaultLoc = Intro.DefaultLoc; 954 LSI->IntroducerRange = Intro.Range; 955 LSI->BeforeLambdaQualifiersScope = true; 956 957 assert(LSI->NumExplicitTemplateParams == 0); 958 959 // Determine if we're within a context where we know that the lambda will 960 // be dependent, because there are template parameters in scope. 961 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind = 962 CXXRecordDecl::LDK_Unknown; 963 if (LSI->NumExplicitTemplateParams > 0) { 964 auto *TemplateParamScope = CurScope->getTemplateParamParent(); 965 assert(TemplateParamScope && 966 "Lambda with explicit template param list should establish a " 967 "template param scope"); 968 assert(TemplateParamScope->getParent()); 969 if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr) 970 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent; 971 } else if (CurScope->getTemplateParamParent() != nullptr) { 972 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent; 973 } 974 975 CXXRecordDecl *Class = createLambdaClosureType( 976 Intro.Range, nullptr, LambdaDependencyKind, Intro.Default); 977 LSI->Lambda = Class; 978 979 // C++11 [expr.prim.lambda]p5: 980 // The closure type for a lambda-expression has a public inline function 981 // call operator (13.5.4) whose parameters and return type are described 982 // by the lambda-expression's parameter-declaration-clause and 983 // trailing-return-type respectively. 984 985 CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class); 986 LSI->CallOperator = Method; 987 Method->setLexicalDeclContext(CurContext); 988 989 PushDeclContext(CurScope, Method); 990 991 bool ContainsUnexpandedParameterPack = false; 992 993 // Distinct capture names, for diagnostics. 994 llvm::SmallSet<IdentifierInfo *, 8> CaptureNames; 995 996 // Handle explicit captures. 997 SourceLocation PrevCaptureLoc = 998 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc; 999 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; 1000 PrevCaptureLoc = C->Loc, ++C) { 1001 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) { 1002 continue; 1003 } 1004 1005 assert(C->Id && "missing identifier for capture"); 1006 if (C->Init.isInvalid()) 1007 continue; 1008 1009 VarDecl *Var = nullptr; 1010 if (C->Init.isUsable()) { 1011 Diag(C->Loc, getLangOpts().CPlusPlus14 1012 ? diag::warn_cxx11_compat_init_capture 1013 : diag::ext_init_capture); 1014 1015 // If the initializer expression is usable, but the InitCaptureType 1016 // is not, then an error has occurred - so ignore the capture for now. 1017 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. 1018 // FIXME: we should create the init capture variable and mark it invalid 1019 // in this case. 1020 if (C->InitCaptureType.get().isNull()) 1021 continue; 1022 1023 if (C->Init.get()->containsUnexpandedParameterPack() && 1024 !C->InitCaptureType.get()->getAs<PackExpansionType>()) 1025 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer); 1026 1027 unsigned InitStyle; 1028 switch (C->InitKind) { 1029 case LambdaCaptureInitKind::NoInit: 1030 llvm_unreachable("not an init-capture?"); 1031 case LambdaCaptureInitKind::CopyInit: 1032 InitStyle = VarDecl::CInit; 1033 break; 1034 case LambdaCaptureInitKind::DirectInit: 1035 InitStyle = VarDecl::CallInit; 1036 break; 1037 case LambdaCaptureInitKind::ListInit: 1038 InitStyle = VarDecl::ListInit; 1039 break; 1040 } 1041 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(), 1042 C->EllipsisLoc, C->Id, InitStyle, 1043 C->Init.get(), Method); 1044 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?"); 1045 CheckShadow(CurrentScope, Var); 1046 PushOnScopeChains(Var, CurrentScope, false); 1047 } else { 1048 assert(C->InitKind == LambdaCaptureInitKind::NoInit && 1049 "init capture has valid but null init?"); 1050 1051 // C++11 [expr.prim.lambda]p8: 1052 // If a lambda-capture includes a capture-default that is &, the 1053 // identifiers in the lambda-capture shall not be preceded by &. 1054 // If a lambda-capture includes a capture-default that is =, [...] 1055 // each identifier it contains shall be preceded by &. 1056 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 1057 Diag(C->Loc, diag::err_reference_capture_with_reference_default) 1058 << FixItHint::CreateRemoval( 1059 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1060 continue; 1061 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 1062 Diag(C->Loc, diag::err_copy_capture_with_copy_default) 1063 << FixItHint::CreateRemoval( 1064 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1065 continue; 1066 } 1067 1068 // C++11 [expr.prim.lambda]p10: 1069 // The identifiers in a capture-list are looked up using the usual 1070 // rules for unqualified name lookup (3.4.1) 1071 DeclarationNameInfo Name(C->Id, C->Loc); 1072 LookupResult R(*this, Name, LookupOrdinaryName); 1073 LookupName(R, CurScope); 1074 if (R.isAmbiguous()) 1075 continue; 1076 if (R.empty()) { 1077 // FIXME: Disable corrections that would add qualification? 1078 CXXScopeSpec ScopeSpec; 1079 DeclFilterCCC<VarDecl> Validator{}; 1080 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) 1081 continue; 1082 } 1083 1084 Var = R.getAsSingle<VarDecl>(); 1085 if (Var && DiagnoseUseOfDecl(Var, C->Loc)) 1086 continue; 1087 } 1088 1089 // C++11 [expr.prim.lambda]p10: 1090 // [...] each such lookup shall find a variable with automatic storage 1091 // duration declared in the reaching scope of the local lambda expression. 1092 // Note that the 'reaching scope' check happens in tryCaptureVariable(). 1093 if (!Var) { 1094 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 1095 continue; 1096 } 1097 1098 // C++11 [expr.prim.lambda]p8: 1099 // An identifier or this shall not appear more than once in a 1100 // lambda-capture. 1101 if (!CaptureNames.insert(C->Id).second) { 1102 auto It = llvm::find_if(LSI->DelayedCaptures, [&Var](auto &&Pair) { 1103 return Pair.second.Var == Var; 1104 }); 1105 if (It != LSI->DelayedCaptures.end()) { 1106 Diag(C->Loc, diag::err_capture_more_than_once) 1107 << C->Id << SourceRange(It->second.Loc) 1108 << FixItHint::CreateRemoval( 1109 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1110 } else 1111 // Previous capture captured something different (one or both was 1112 // an init-cpature): no fixit. 1113 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; 1114 continue; 1115 } 1116 1117 // Ignore invalid decls; they'll just confuse the code later. 1118 if (Var->isInvalidDecl()) 1119 continue; 1120 1121 if (!Var->hasLocalStorage()) { 1122 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 1123 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 1124 continue; 1125 } 1126 1127 // C++11 [expr.prim.lambda]p23: 1128 // A capture followed by an ellipsis is a pack expansion (14.5.3). 1129 SourceLocation EllipsisLoc; 1130 if (C->EllipsisLoc.isValid()) { 1131 if (Var->isParameterPack()) { 1132 EllipsisLoc = C->EllipsisLoc; 1133 } else { 1134 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1135 << (C->Init.isUsable() ? C->Init.get()->getSourceRange() 1136 : SourceRange(C->Loc)); 1137 1138 // Just ignore the ellipsis. 1139 } 1140 } else if (Var->isParameterPack()) { 1141 ContainsUnexpandedParameterPack = true; 1142 } 1143 1144 if (Var) 1145 LSI->DelayedCaptures[std::distance(Intro.Captures.begin(), C)] = 1146 LambdaScopeInfo::DelayedCapture{Var, C->ExplicitRange.getBegin(), 1147 C->Kind}; 1148 } 1149 1150 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack; 1151 PopDeclContext(); 1152 } 1153 1154 static void AddExplicitCapturesToContext(Sema &S, LambdaScopeInfo *LSI, 1155 LambdaIntroducer &Intro) { 1156 SourceLocation PrevCaptureLoc; 1157 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; 1158 PrevCaptureLoc = C->Loc, ++C) { 1159 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) { 1160 if (C->Kind == LCK_StarThis) 1161 S.Diag(C->Loc, !S.getLangOpts().CPlusPlus17 1162 ? diag::ext_star_this_lambda_capture_cxx17 1163 : diag::warn_cxx14_compat_star_this_lambda_capture); 1164 1165 // C++11 [expr.prim.lambda]p8: 1166 // An identifier or this shall not appear more than once in a 1167 // lambda-capture. 1168 if (LSI->isCXXThisCaptured()) { 1169 S.Diag(C->Loc, diag::err_capture_more_than_once) 1170 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation()) 1171 << FixItHint::CreateRemoval( 1172 SourceRange(S.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1173 continue; 1174 } 1175 1176 // C++20 [expr.prim.lambda]p8: 1177 // If a lambda-capture includes a capture-default that is =, 1178 // each simple-capture of that lambda-capture shall be of the form 1179 // "&identifier", "this", or "* this". [ Note: The form [&,this] is 1180 // redundant but accepted for compatibility with ISO C++14. --end note ] 1181 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis) 1182 S.Diag(C->Loc, 1183 !S.getLangOpts().CPlusPlus20 1184 ? diag::ext_equals_this_lambda_capture_cxx20 1185 : diag::warn_cxx17_compat_equals_this_lambda_capture); 1186 1187 // C++11 [expr.prim.lambda]p12: 1188 // If this is captured by a local lambda expression, its nearest 1189 // enclosing function shall be a non-static member function. 1190 QualType ThisCaptureType = S.getCurrentThisType(); 1191 if (ThisCaptureType.isNull()) { 1192 S.Diag(C->Loc, diag::err_this_capture) << true; 1193 continue; 1194 } 1195 S.CheckCXXThisCapture(C->Loc, true, true, nullptr, 1196 C->Kind == LCK_StarThis); 1197 } else { 1198 VarDecl *Var = 1199 LSI->DelayedCaptures[std::distance(Intro.Captures.begin(), C)].Var; 1200 if (!Var) 1201 continue; 1202 if (Var->isInitCapture() && C->Init.isUsable()) { 1203 S.addInitCapture(LSI, Var); 1204 S.PushOnScopeChains(Var, S.getCurScope(), false); 1205 } else { 1206 Sema::TryCaptureKind Kind = C->Kind == LCK_ByRef 1207 ? Sema::TryCapture_ExplicitByRef 1208 : Sema::TryCapture_ExplicitByVal; 1209 S.tryCaptureVariable(Var, C->Loc, Kind, C->EllipsisLoc); 1210 } 1211 } 1212 if (!LSI->Captures.empty()) 1213 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; 1214 } 1215 S.finishLambdaExplicitCaptures(LSI); 1216 } 1217 1218 void Sema::ActOnLambdaClosureQualifiers( 1219 LambdaIntroducer &Intro, SourceLocation MutableLoc, SourceLocation EndLoc, 1220 MutableArrayRef<DeclaratorChunk::ParamInfo> Params, const DeclSpec &DS) { 1221 1222 LambdaScopeInfo *const LSI = getCurrentLambdaScopeUnsafe(*this); 1223 LSI->Mutable = MutableLoc.isValid(); 1224 LSI->BeforeLambdaQualifiersScope = false; 1225 LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier()); 1226 1227 // C++11 [expr.prim.lambda]p9: 1228 // A lambda-expression whose smallest enclosing scope is a block scope is a 1229 // local lambda expression; any other lambda expression shall not have a 1230 // capture-default or simple-capture in its lambda-introducer. 1231 // 1232 // For simple-captures, this is covered by the check below that any named 1233 // entity is a variable that can be captured. 1234 // 1235 // For DR1632, we also allow a capture-default in any context where we can 1236 // odr-use 'this' (in particular, in a default initializer for a non-static 1237 // data member). 1238 if (Intro.Default != LCD_None && 1239 !LSI->Lambda->getParent()->isFunctionOrMethod() && 1240 (getCurrentThisType().isNull() || 1241 CheckCXXThisCapture(SourceLocation(), /*Explicit*/ true, 1242 /*BuildAndDiagnose*/ false))) 1243 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local); 1244 1245 PushDeclContext(CurScope, LSI->CallOperator); 1246 1247 for (const DeclaratorChunk::ParamInfo &P : Params) { 1248 auto *Param = cast<ParmVarDecl>(P.Param); 1249 Param->setOwningFunction(LSI->CallOperator); 1250 if (Param->getIdentifier()) 1251 PushOnScopeChains(Param, CurScope, false); 1252 } 1253 1254 AddExplicitCapturesToContext(*this, LSI, Intro); 1255 } 1256 1257 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 1258 Declarator &ParamInfo, 1259 Scope *CurScope) { 1260 1261 LambdaScopeInfo *const LSI = getCurrentLambdaScopeUnsafe(*this); 1262 1263 SmallVector<ParmVarDecl *, 8> Params; 1264 bool ExplicitResultType; 1265 1266 SourceLocation TypeLoc, CallOperatorLoc; 1267 if (ParamInfo.getNumTypeObjects() == 0) { 1268 CallOperatorLoc = TypeLoc = Intro.Range.getEnd(); 1269 } else { 1270 unsigned index; 1271 ParamInfo.isFunctionDeclarator(index); 1272 const auto &Object = ParamInfo.getTypeObject(index); 1273 TypeLoc = 1274 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd(); 1275 CallOperatorLoc = ParamInfo.getSourceRange().getEnd(); 1276 } 1277 1278 CXXRecordDecl *Class = LSI->Lambda; 1279 CXXMethodDecl *Method = LSI->CallOperator; 1280 1281 TypeSourceInfo *MethodTyInfo = getLambdaType( 1282 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType); 1283 1284 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0; 1285 1286 if (ParamInfo.isFunctionDeclarator() != 0 && 1287 !FTIHasSingleVoidParameter(ParamInfo.getFunctionTypeInfo())) { 1288 const auto &FTI = ParamInfo.getFunctionTypeInfo(); 1289 Params.reserve(Params.size()); 1290 for (unsigned I = 0; I < FTI.NumParams; ++I) { 1291 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param); 1292 Param->setScopeInfo(0, Params.size()); 1293 Params.push_back(Param); 1294 } 1295 } 1296 1297 CompleteLambdaCallOperator(Method, Intro.Range.getBegin(), CallOperatorLoc, 1298 ParamInfo.getTrailingRequiresClause(), 1299 MethodTyInfo, 1300 ParamInfo.getDeclSpec().getConstexprSpecifier(), 1301 Params, ExplicitResultType); 1302 1303 ContextRAII ManglingContext(*this, Class->getDeclContext()); 1304 1305 CheckCXXDefaultArguments(Method); 1306 1307 // This represents the function body for the lambda function, check if we 1308 // have to apply optnone due to a pragma. 1309 AddRangeBasedOptnone(Method); 1310 1311 // code_seg attribute on lambda apply to the method. 1312 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction( 1313 Method, /*IsDefinition=*/true)) 1314 Method->addAttr(A); 1315 1316 // Attributes on the lambda apply to the method. 1317 ProcessDeclAttributes(CurScope, Method, ParamInfo); 1318 1319 // CUDA lambdas get implicit host and device attributes. 1320 if (getLangOpts().CUDA) 1321 CUDASetLambdaAttrs(Method); 1322 1323 // OpenMP lambdas might get assumumption attributes. 1324 if (LangOpts.OpenMP) 1325 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method); 1326 1327 handleLambdaNumbering(Class, Method); 1328 1329 ManglingContext.pop(); 1330 1331 for (auto &&C : LSI->DelayedCaptures) { 1332 VarDecl *Var = C.second.Var; 1333 if (Var && Var->isInitCapture()) { 1334 PushOnScopeChains(Var, CurScope, false); 1335 } 1336 } 1337 1338 LSI->DelayedCaptures.clear(); 1339 1340 auto CheckRedefinition = [&](ParmVarDecl *Param) { 1341 for (const auto &Capture : Intro.Captures) { 1342 if (Capture.Id == Param->getIdentifier()) { 1343 Diag(Param->getLocation(), diag::err_parameter_shadow_capture); 1344 Diag(Capture.Loc, diag::note_var_explicitly_captured_here) 1345 << Capture.Id << true; 1346 return false; 1347 } 1348 } 1349 return true; 1350 }; 1351 for (ParmVarDecl *P : Params) { 1352 if (!P->getIdentifier()) 1353 continue; 1354 if (CheckRedefinition(P)) 1355 CheckShadow(CurScope, P); 1356 PushOnScopeChains(P, CurScope); 1357 } 1358 1359 // Enter a new evaluation context to insulate the lambda from any 1360 // cleanups from the enclosing full-expression. 1361 PushExpressionEvaluationContext( 1362 LSI->CallOperator->isConsteval() 1363 ? ExpressionEvaluationContext::ImmediateFunctionContext 1364 : ExpressionEvaluationContext::PotentiallyEvaluated); 1365 } 1366 1367 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 1368 bool IsInstantiation) { 1369 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back()); 1370 1371 // Leave the expression-evaluation context. 1372 DiscardCleanupsInEvaluationContext(); 1373 PopExpressionEvaluationContext(); 1374 1375 // Leave the context of the lambda. 1376 if (!IsInstantiation) 1377 PopDeclContext(); 1378 1379 // Finalize the lambda. 1380 CXXRecordDecl *Class = LSI->Lambda; 1381 Class->setInvalidDecl(); 1382 SmallVector<Decl*, 4> Fields(Class->fields()); 1383 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 1384 SourceLocation(), ParsedAttributesView()); 1385 CheckCompletedCXXClass(nullptr, Class); 1386 1387 PopFunctionScopeInfo(); 1388 } 1389 1390 template <typename Func> 1391 static void repeatForLambdaConversionFunctionCallingConvs( 1392 Sema &S, const FunctionProtoType &CallOpProto, Func F) { 1393 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 1394 CallOpProto.isVariadic(), /*IsCXXMethod=*/false); 1395 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 1396 CallOpProto.isVariadic(), /*IsCXXMethod=*/true); 1397 CallingConv CallOpCC = CallOpProto.getCallConv(); 1398 1399 /// Implement emitting a version of the operator for many of the calling 1400 /// conventions for MSVC, as described here: 1401 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623. 1402 /// Experimentally, we determined that cdecl, stdcall, fastcall, and 1403 /// vectorcall are generated by MSVC when it is supported by the target. 1404 /// Additionally, we are ensuring that the default-free/default-member and 1405 /// call-operator calling convention are generated as well. 1406 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the 1407 /// 'member default', despite MSVC not doing so. We do this in order to ensure 1408 /// that someone who intentionally places 'thiscall' on the lambda call 1409 /// operator will still get that overload, since we don't have the a way of 1410 /// detecting the attribute by the time we get here. 1411 if (S.getLangOpts().MSVCCompat) { 1412 CallingConv Convs[] = { 1413 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall, 1414 DefaultFree, DefaultMember, CallOpCC}; 1415 llvm::sort(Convs); 1416 llvm::iterator_range<CallingConv *> Range( 1417 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs))); 1418 const TargetInfo &TI = S.getASTContext().getTargetInfo(); 1419 1420 for (CallingConv C : Range) { 1421 if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK) 1422 F(C); 1423 } 1424 return; 1425 } 1426 1427 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) { 1428 F(DefaultFree); 1429 F(DefaultMember); 1430 } else { 1431 F(CallOpCC); 1432 } 1433 } 1434 1435 // Returns the 'standard' calling convention to be used for the lambda 1436 // conversion function, that is, the 'free' function calling convention unless 1437 // it is overridden by a non-default calling convention attribute. 1438 static CallingConv 1439 getLambdaConversionFunctionCallConv(Sema &S, 1440 const FunctionProtoType *CallOpProto) { 1441 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 1442 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 1443 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 1444 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 1445 CallingConv CallOpCC = CallOpProto->getCallConv(); 1446 1447 // If the call-operator hasn't been changed, return both the 'free' and 1448 // 'member' function calling convention. 1449 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) 1450 return DefaultFree; 1451 return CallOpCC; 1452 } 1453 1454 QualType Sema::getLambdaConversionFunctionResultType( 1455 const FunctionProtoType *CallOpProto, CallingConv CC) { 1456 const FunctionProtoType::ExtProtoInfo CallOpExtInfo = 1457 CallOpProto->getExtProtoInfo(); 1458 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; 1459 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); 1460 InvokerExtInfo.TypeQuals = Qualifiers(); 1461 assert(InvokerExtInfo.RefQualifier == RQ_None && 1462 "Lambda's call operator should not have a reference qualifier"); 1463 return Context.getFunctionType(CallOpProto->getReturnType(), 1464 CallOpProto->getParamTypes(), InvokerExtInfo); 1465 } 1466 1467 /// Add a lambda's conversion to function pointer, as described in 1468 /// C++11 [expr.prim.lambda]p6. 1469 static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, 1470 CXXRecordDecl *Class, 1471 CXXMethodDecl *CallOperator, 1472 QualType InvokerFunctionTy) { 1473 // This conversion is explicitly disabled if the lambda's function has 1474 // pass_object_size attributes on any of its parameters. 1475 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) { 1476 return P->hasAttr<PassObjectSizeAttr>(); 1477 }; 1478 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr)) 1479 return; 1480 1481 // Add the conversion to function pointer. 1482 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy); 1483 1484 // Create the type of the conversion function. 1485 FunctionProtoType::ExtProtoInfo ConvExtInfo( 1486 S.Context.getDefaultCallingConvention( 1487 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 1488 // The conversion function is always const and noexcept. 1489 ConvExtInfo.TypeQuals = Qualifiers(); 1490 ConvExtInfo.TypeQuals.addConst(); 1491 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept; 1492 QualType ConvTy = 1493 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo); 1494 1495 SourceLocation Loc = IntroducerRange.getBegin(); 1496 DeclarationName ConversionName 1497 = S.Context.DeclarationNames.getCXXConversionFunctionName( 1498 S.Context.getCanonicalType(PtrToFunctionTy)); 1499 // Construct a TypeSourceInfo for the conversion function, and wire 1500 // all the parameters appropriately for the FunctionProtoTypeLoc 1501 // so that everything works during transformation/instantiation of 1502 // generic lambdas. 1503 // The main reason for wiring up the parameters of the conversion 1504 // function with that of the call operator is so that constructs 1505 // like the following work: 1506 // auto L = [](auto b) { <-- 1 1507 // return [](auto a) -> decltype(a) { <-- 2 1508 // return a; 1509 // }; 1510 // }; 1511 // int (*fp)(int) = L(5); 1512 // Because the trailing return type can contain DeclRefExprs that refer 1513 // to the original call operator's variables, we hijack the call 1514 // operators ParmVarDecls below. 1515 TypeSourceInfo *ConvNamePtrToFunctionTSI = 1516 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); 1517 DeclarationNameLoc ConvNameLoc = 1518 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI); 1519 1520 // The conversion function is a conversion to a pointer-to-function. 1521 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); 1522 FunctionProtoTypeLoc ConvTL = 1523 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); 1524 // Get the result of the conversion function which is a pointer-to-function. 1525 PointerTypeLoc PtrToFunctionTL = 1526 ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); 1527 // Do the same for the TypeSourceInfo that is used to name the conversion 1528 // operator. 1529 PointerTypeLoc ConvNamePtrToFunctionTL = 1530 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); 1531 1532 // Get the underlying function types that the conversion function will 1533 // be converting to (should match the type of the call operator). 1534 FunctionProtoTypeLoc CallOpConvTL = 1535 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 1536 FunctionProtoTypeLoc CallOpConvNameTL = 1537 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 1538 1539 // Wire up the FunctionProtoTypeLocs with the call operator's parameters. 1540 // These parameter's are essentially used to transform the name and 1541 // the type of the conversion operator. By using the same parameters 1542 // as the call operator's we don't have to fix any back references that 1543 // the trailing return type of the call operator's uses (such as 1544 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) 1545 // - we can simply use the return type of the call operator, and 1546 // everything should work. 1547 SmallVector<ParmVarDecl *, 4> InvokerParams; 1548 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 1549 ParmVarDecl *From = CallOperator->getParamDecl(I); 1550 1551 InvokerParams.push_back(ParmVarDecl::Create( 1552 S.Context, 1553 // Temporarily add to the TU. This is set to the invoker below. 1554 S.Context.getTranslationUnitDecl(), From->getBeginLoc(), 1555 From->getLocation(), From->getIdentifier(), From->getType(), 1556 From->getTypeSourceInfo(), From->getStorageClass(), 1557 /*DefArg=*/nullptr)); 1558 CallOpConvTL.setParam(I, From); 1559 CallOpConvNameTL.setParam(I, From); 1560 } 1561 1562 CXXConversionDecl *Conversion = CXXConversionDecl::Create( 1563 S.Context, Class, Loc, 1564 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI, 1565 S.getCurFPFeatures().isFPConstrained(), 1566 /*isInline=*/true, ExplicitSpecifier(), 1567 S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr 1568 : ConstexprSpecKind::Unspecified, 1569 CallOperator->getBody()->getEndLoc()); 1570 Conversion->setAccess(AS_public); 1571 Conversion->setImplicit(true); 1572 1573 if (Class->isGenericLambda()) { 1574 // Create a template version of the conversion operator, using the template 1575 // parameter list of the function call operator. 1576 FunctionTemplateDecl *TemplateCallOperator = 1577 CallOperator->getDescribedFunctionTemplate(); 1578 FunctionTemplateDecl *ConversionTemplate = 1579 FunctionTemplateDecl::Create(S.Context, Class, 1580 Loc, ConversionName, 1581 TemplateCallOperator->getTemplateParameters(), 1582 Conversion); 1583 ConversionTemplate->setAccess(AS_public); 1584 ConversionTemplate->setImplicit(true); 1585 Conversion->setDescribedFunctionTemplate(ConversionTemplate); 1586 Class->addDecl(ConversionTemplate); 1587 } else 1588 Class->addDecl(Conversion); 1589 // Add a non-static member function that will be the result of 1590 // the conversion with a certain unique ID. 1591 DeclarationName InvokerName = &S.Context.Idents.get( 1592 getLambdaStaticInvokerName()); 1593 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo() 1594 // we should get a prebuilt TrivialTypeSourceInfo from Context 1595 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc 1596 // then rewire the parameters accordingly, by hoisting up the InvokeParams 1597 // loop below and then use its Params to set Invoke->setParams(...) below. 1598 // This would avoid the 'const' qualifier of the calloperator from 1599 // contaminating the type of the invoker, which is currently adjusted 1600 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the 1601 // trailing return type of the invoker would require a visitor to rebuild 1602 // the trailing return type and adjusting all back DeclRefExpr's to refer 1603 // to the new static invoker parameters - not the call operator's. 1604 CXXMethodDecl *Invoke = CXXMethodDecl::Create( 1605 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc), 1606 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static, 1607 S.getCurFPFeatures().isFPConstrained(), 1608 /*isInline=*/true, ConstexprSpecKind::Unspecified, 1609 CallOperator->getBody()->getEndLoc()); 1610 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) 1611 InvokerParams[I]->setOwningFunction(Invoke); 1612 Invoke->setParams(InvokerParams); 1613 Invoke->setAccess(AS_private); 1614 Invoke->setImplicit(true); 1615 if (Class->isGenericLambda()) { 1616 FunctionTemplateDecl *TemplateCallOperator = 1617 CallOperator->getDescribedFunctionTemplate(); 1618 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create( 1619 S.Context, Class, Loc, InvokerName, 1620 TemplateCallOperator->getTemplateParameters(), 1621 Invoke); 1622 StaticInvokerTemplate->setAccess(AS_private); 1623 StaticInvokerTemplate->setImplicit(true); 1624 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate); 1625 Class->addDecl(StaticInvokerTemplate); 1626 } else 1627 Class->addDecl(Invoke); 1628 } 1629 1630 /// Add a lambda's conversion to function pointers, as described in 1631 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a 1632 /// single pointer conversion. In the event that the default calling convention 1633 /// for free and member functions is different, it will emit both conventions. 1634 static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, 1635 CXXRecordDecl *Class, 1636 CXXMethodDecl *CallOperator) { 1637 const FunctionProtoType *CallOpProto = 1638 CallOperator->getType()->castAs<FunctionProtoType>(); 1639 1640 repeatForLambdaConversionFunctionCallingConvs( 1641 S, *CallOpProto, [&](CallingConv CC) { 1642 QualType InvokerFunctionTy = 1643 S.getLambdaConversionFunctionResultType(CallOpProto, CC); 1644 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator, 1645 InvokerFunctionTy); 1646 }); 1647 } 1648 1649 /// Add a lambda's conversion to block pointer. 1650 static void addBlockPointerConversion(Sema &S, 1651 SourceRange IntroducerRange, 1652 CXXRecordDecl *Class, 1653 CXXMethodDecl *CallOperator) { 1654 const FunctionProtoType *CallOpProto = 1655 CallOperator->getType()->castAs<FunctionProtoType>(); 1656 QualType FunctionTy = S.getLambdaConversionFunctionResultType( 1657 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto)); 1658 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 1659 1660 FunctionProtoType::ExtProtoInfo ConversionEPI( 1661 S.Context.getDefaultCallingConvention( 1662 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 1663 ConversionEPI.TypeQuals = Qualifiers(); 1664 ConversionEPI.TypeQuals.addConst(); 1665 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI); 1666 1667 SourceLocation Loc = IntroducerRange.getBegin(); 1668 DeclarationName Name 1669 = S.Context.DeclarationNames.getCXXConversionFunctionName( 1670 S.Context.getCanonicalType(BlockPtrTy)); 1671 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc( 1672 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc)); 1673 CXXConversionDecl *Conversion = CXXConversionDecl::Create( 1674 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy, 1675 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 1676 S.getCurFPFeatures().isFPConstrained(), 1677 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, 1678 CallOperator->getBody()->getEndLoc()); 1679 Conversion->setAccess(AS_public); 1680 Conversion->setImplicit(true); 1681 Class->addDecl(Conversion); 1682 } 1683 1684 ExprResult Sema::BuildCaptureInit(const Capture &Cap, 1685 SourceLocation ImplicitCaptureLoc, 1686 bool IsOpenMPMapping) { 1687 // VLA captures don't have a stored initialization expression. 1688 if (Cap.isVLATypeCapture()) 1689 return ExprResult(); 1690 1691 // An init-capture is initialized directly from its stored initializer. 1692 if (Cap.isInitCapture()) 1693 return Cap.getVariable()->getInit(); 1694 1695 // For anything else, build an initialization expression. For an implicit 1696 // capture, the capture notionally happens at the capture-default, so use 1697 // that location here. 1698 SourceLocation Loc = 1699 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation(); 1700 1701 // C++11 [expr.prim.lambda]p21: 1702 // When the lambda-expression is evaluated, the entities that 1703 // are captured by copy are used to direct-initialize each 1704 // corresponding non-static data member of the resulting closure 1705 // object. (For array members, the array elements are 1706 // direct-initialized in increasing subscript order.) These 1707 // initializations are performed in the (unspecified) order in 1708 // which the non-static data members are declared. 1709 1710 // C++ [expr.prim.lambda]p12: 1711 // An entity captured by a lambda-expression is odr-used (3.2) in 1712 // the scope containing the lambda-expression. 1713 ExprResult Init; 1714 IdentifierInfo *Name = nullptr; 1715 if (Cap.isThisCapture()) { 1716 QualType ThisTy = getCurrentThisType(); 1717 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid()); 1718 if (Cap.isCopyCapture()) 1719 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 1720 else 1721 Init = This; 1722 } else { 1723 assert(Cap.isVariableCapture() && "unknown kind of capture"); 1724 VarDecl *Var = Cap.getVariable(); 1725 Name = Var->getIdentifier(); 1726 Init = BuildDeclarationNameExpr( 1727 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 1728 } 1729 1730 // In OpenMP, the capture kind doesn't actually describe how to capture: 1731 // variables are "mapped" onto the device in a process that does not formally 1732 // make a copy, even for a "copy capture". 1733 if (IsOpenMPMapping) 1734 return Init; 1735 1736 if (Init.isInvalid()) 1737 return ExprError(); 1738 1739 Expr *InitExpr = Init.get(); 1740 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture( 1741 Name, Cap.getCaptureType(), Loc); 1742 InitializationKind InitKind = 1743 InitializationKind::CreateDirect(Loc, Loc, Loc); 1744 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr); 1745 return InitSeq.Perform(*this, Entity, InitKind, InitExpr); 1746 } 1747 1748 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 1749 Scope *CurScope) { 1750 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); 1751 ActOnFinishFunctionBody(LSI.CallOperator, Body); 1752 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); 1753 } 1754 1755 static LambdaCaptureDefault 1756 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) { 1757 switch (ICS) { 1758 case CapturingScopeInfo::ImpCap_None: 1759 return LCD_None; 1760 case CapturingScopeInfo::ImpCap_LambdaByval: 1761 return LCD_ByCopy; 1762 case CapturingScopeInfo::ImpCap_CapturedRegion: 1763 case CapturingScopeInfo::ImpCap_LambdaByref: 1764 return LCD_ByRef; 1765 case CapturingScopeInfo::ImpCap_Block: 1766 llvm_unreachable("block capture in lambda"); 1767 } 1768 llvm_unreachable("Unknown implicit capture style"); 1769 } 1770 1771 bool Sema::CaptureHasSideEffects(const Capture &From) { 1772 if (From.isInitCapture()) { 1773 Expr *Init = From.getVariable()->getInit(); 1774 if (Init && Init->HasSideEffects(Context)) 1775 return true; 1776 } 1777 1778 if (!From.isCopyCapture()) 1779 return false; 1780 1781 const QualType T = From.isThisCapture() 1782 ? getCurrentThisType()->getPointeeType() 1783 : From.getCaptureType(); 1784 1785 if (T.isVolatileQualified()) 1786 return true; 1787 1788 const Type *BaseT = T->getBaseElementTypeUnsafe(); 1789 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl()) 1790 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() || 1791 !RD->hasTrivialDestructor(); 1792 1793 return false; 1794 } 1795 1796 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 1797 const Capture &From) { 1798 if (CaptureHasSideEffects(From)) 1799 return false; 1800 1801 if (From.isVLATypeCapture()) 1802 return false; 1803 1804 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture); 1805 if (From.isThisCapture()) 1806 diag << "'this'"; 1807 else 1808 diag << From.getVariable(); 1809 diag << From.isNonODRUsed(); 1810 diag << FixItHint::CreateRemoval(CaptureRange); 1811 return true; 1812 } 1813 1814 /// Create a field within the lambda class or captured statement record for the 1815 /// given capture. 1816 FieldDecl *Sema::BuildCaptureField(RecordDecl *RD, 1817 const sema::Capture &Capture) { 1818 SourceLocation Loc = Capture.getLocation(); 1819 QualType FieldType = Capture.getCaptureType(); 1820 1821 TypeSourceInfo *TSI = nullptr; 1822 if (Capture.isVariableCapture()) { 1823 auto *Var = Capture.getVariable(); 1824 if (Var->isInitCapture()) 1825 TSI = Capture.getVariable()->getTypeSourceInfo(); 1826 } 1827 1828 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more 1829 // appropriate, at least for an implicit capture. 1830 if (!TSI) 1831 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc); 1832 1833 // Build the non-static data member. 1834 FieldDecl *Field = 1835 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc, 1836 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr, 1837 /*Mutable=*/false, ICIS_NoInit); 1838 // If the variable being captured has an invalid type, mark the class as 1839 // invalid as well. 1840 if (!FieldType->isDependentType()) { 1841 if (RequireCompleteSizedType(Loc, FieldType, 1842 diag::err_field_incomplete_or_sizeless)) { 1843 RD->setInvalidDecl(); 1844 Field->setInvalidDecl(); 1845 } else { 1846 NamedDecl *Def; 1847 FieldType->isIncompleteType(&Def); 1848 if (Def && Def->isInvalidDecl()) { 1849 RD->setInvalidDecl(); 1850 Field->setInvalidDecl(); 1851 } 1852 } 1853 } 1854 Field->setImplicit(true); 1855 Field->setAccess(AS_private); 1856 RD->addDecl(Field); 1857 1858 if (Capture.isVLATypeCapture()) 1859 Field->setCapturedVLAType(Capture.getCapturedVLAType()); 1860 1861 return Field; 1862 } 1863 1864 ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 1865 LambdaScopeInfo *LSI) { 1866 // Collect information from the lambda scope. 1867 SmallVector<LambdaCapture, 4> Captures; 1868 SmallVector<Expr *, 4> CaptureInits; 1869 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc; 1870 LambdaCaptureDefault CaptureDefault = 1871 mapImplicitCaptureStyle(LSI->ImpCaptureStyle); 1872 CXXRecordDecl *Class; 1873 CXXMethodDecl *CallOperator; 1874 SourceRange IntroducerRange; 1875 bool ExplicitParams; 1876 bool ExplicitResultType; 1877 CleanupInfo LambdaCleanup; 1878 bool ContainsUnexpandedParameterPack; 1879 bool IsGenericLambda; 1880 { 1881 CallOperator = LSI->CallOperator; 1882 Class = LSI->Lambda; 1883 IntroducerRange = LSI->IntroducerRange; 1884 ExplicitParams = LSI->ExplicitParams; 1885 ExplicitResultType = !LSI->HasImplicitReturnType; 1886 LambdaCleanup = LSI->Cleanup; 1887 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; 1888 IsGenericLambda = Class->isGenericLambda(); 1889 1890 CallOperator->setLexicalDeclContext(Class); 1891 Decl *TemplateOrNonTemplateCallOperatorDecl = 1892 CallOperator->getDescribedFunctionTemplate() 1893 ? CallOperator->getDescribedFunctionTemplate() 1894 : cast<Decl>(CallOperator); 1895 1896 // FIXME: Is this really the best choice? Keeping the lexical decl context 1897 // set as CurContext seems more faithful to the source. 1898 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); 1899 1900 PopExpressionEvaluationContext(); 1901 1902 // True if the current capture has a used capture or default before it. 1903 bool CurHasPreviousCapture = CaptureDefault != LCD_None; 1904 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ? 1905 CaptureDefaultLoc : IntroducerRange.getBegin(); 1906 1907 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 1908 const Capture &From = LSI->Captures[I]; 1909 1910 if (From.isInvalid()) 1911 return ExprError(); 1912 1913 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 1914 bool IsImplicit = I >= LSI->NumExplicitCaptures; 1915 SourceLocation ImplicitCaptureLoc = 1916 IsImplicit ? CaptureDefaultLoc : SourceLocation(); 1917 1918 // Use source ranges of explicit captures for fixits where available. 1919 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I]; 1920 1921 // Warn about unused explicit captures. 1922 bool IsCaptureUsed = true; 1923 if (!CurContext->isDependentContext() && !IsImplicit && 1924 !From.isODRUsed()) { 1925 // Initialized captures that are non-ODR used may not be eliminated. 1926 // FIXME: Where did the IsGenericLambda here come from? 1927 bool NonODRUsedInitCapture = 1928 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture(); 1929 if (!NonODRUsedInitCapture) { 1930 bool IsLast = (I + 1) == LSI->NumExplicitCaptures; 1931 SourceRange FixItRange; 1932 if (CaptureRange.isValid()) { 1933 if (!CurHasPreviousCapture && !IsLast) { 1934 // If there are no captures preceding this capture, remove the 1935 // following comma. 1936 FixItRange = SourceRange(CaptureRange.getBegin(), 1937 getLocForEndOfToken(CaptureRange.getEnd())); 1938 } else { 1939 // Otherwise, remove the comma since the last used capture. 1940 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc), 1941 CaptureRange.getEnd()); 1942 } 1943 } 1944 1945 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From); 1946 } 1947 } 1948 1949 if (CaptureRange.isValid()) { 1950 CurHasPreviousCapture |= IsCaptureUsed; 1951 PrevCaptureLoc = CaptureRange.getEnd(); 1952 } 1953 1954 // Map the capture to our AST representation. 1955 LambdaCapture Capture = [&] { 1956 if (From.isThisCapture()) { 1957 // Capturing 'this' implicitly with a default of '[=]' is deprecated, 1958 // because it results in a reference capture. Don't warn prior to 1959 // C++2a; there's nothing that can be done about it before then. 1960 if (getLangOpts().CPlusPlus20 && IsImplicit && 1961 CaptureDefault == LCD_ByCopy) { 1962 Diag(From.getLocation(), diag::warn_deprecated_this_capture); 1963 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture) 1964 << FixItHint::CreateInsertion( 1965 getLocForEndOfToken(CaptureDefaultLoc), ", this"); 1966 } 1967 return LambdaCapture(From.getLocation(), IsImplicit, 1968 From.isCopyCapture() ? LCK_StarThis : LCK_This); 1969 } else if (From.isVLATypeCapture()) { 1970 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType); 1971 } else { 1972 assert(From.isVariableCapture() && "unknown kind of capture"); 1973 VarDecl *Var = From.getVariable(); 1974 LambdaCaptureKind Kind = 1975 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef; 1976 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var, 1977 From.getEllipsisLoc()); 1978 } 1979 }(); 1980 1981 // Form the initializer for the capture field. 1982 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc); 1983 1984 // FIXME: Skip this capture if the capture is not used, the initializer 1985 // has no side-effects, the type of the capture is trivial, and the 1986 // lambda is not externally visible. 1987 1988 // Add a FieldDecl for the capture and form its initializer. 1989 BuildCaptureField(Class, From); 1990 Captures.push_back(Capture); 1991 CaptureInits.push_back(Init.get()); 1992 1993 if (LangOpts.CUDA) 1994 CUDACheckLambdaCapture(CallOperator, From); 1995 } 1996 1997 Class->setCaptures(Context, Captures); 1998 1999 // C++11 [expr.prim.lambda]p6: 2000 // The closure type for a lambda-expression with no lambda-capture 2001 // has a public non-virtual non-explicit const conversion function 2002 // to pointer to function having the same parameter and return 2003 // types as the closure type's function call operator. 2004 if (Captures.empty() && CaptureDefault == LCD_None) 2005 addFunctionPointerConversions(*this, IntroducerRange, Class, 2006 CallOperator); 2007 2008 // Objective-C++: 2009 // The closure type for a lambda-expression has a public non-virtual 2010 // non-explicit const conversion function to a block pointer having the 2011 // same parameter and return types as the closure type's function call 2012 // operator. 2013 // FIXME: Fix generic lambda to block conversions. 2014 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda) 2015 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 2016 2017 // Finalize the lambda class. 2018 SmallVector<Decl*, 4> Fields(Class->fields()); 2019 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 2020 SourceLocation(), ParsedAttributesView()); 2021 CheckCompletedCXXClass(nullptr, Class); 2022 } 2023 2024 Cleanup.mergeFrom(LambdaCleanup); 2025 2026 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 2027 CaptureDefault, CaptureDefaultLoc, 2028 ExplicitParams, ExplicitResultType, 2029 CaptureInits, EndLoc, 2030 ContainsUnexpandedParameterPack); 2031 // If the lambda expression's call operator is not explicitly marked constexpr 2032 // and we are not in a dependent context, analyze the call operator to infer 2033 // its constexpr-ness, suppressing diagnostics while doing so. 2034 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() && 2035 !CallOperator->isConstexpr() && 2036 !isa<CoroutineBodyStmt>(CallOperator->getBody()) && 2037 !Class->getDeclContext()->isDependentContext()) { 2038 CallOperator->setConstexprKind( 2039 CheckConstexprFunctionDefinition(CallOperator, 2040 CheckConstexprKind::CheckValid) 2041 ? ConstexprSpecKind::Constexpr 2042 : ConstexprSpecKind::Unspecified); 2043 } 2044 2045 // Emit delayed shadowing warnings now that the full capture list is known. 2046 DiagnoseShadowingLambdaDecls(LSI); 2047 2048 if (!CurContext->isDependentContext()) { 2049 switch (ExprEvalContexts.back().Context) { 2050 // C++11 [expr.prim.lambda]p2: 2051 // A lambda-expression shall not appear in an unevaluated operand 2052 // (Clause 5). 2053 case ExpressionEvaluationContext::Unevaluated: 2054 case ExpressionEvaluationContext::UnevaluatedList: 2055 case ExpressionEvaluationContext::UnevaluatedAbstract: 2056 // C++1y [expr.const]p2: 2057 // A conditional-expression e is a core constant expression unless the 2058 // evaluation of e, following the rules of the abstract machine, would 2059 // evaluate [...] a lambda-expression. 2060 // 2061 // This is technically incorrect, there are some constant evaluated contexts 2062 // where this should be allowed. We should probably fix this when DR1607 is 2063 // ratified, it lays out the exact set of conditions where we shouldn't 2064 // allow a lambda-expression. 2065 case ExpressionEvaluationContext::ConstantEvaluated: 2066 case ExpressionEvaluationContext::ImmediateFunctionContext: 2067 // We don't actually diagnose this case immediately, because we 2068 // could be within a context where we might find out later that 2069 // the expression is potentially evaluated (e.g., for typeid). 2070 ExprEvalContexts.back().Lambdas.push_back(Lambda); 2071 break; 2072 2073 case ExpressionEvaluationContext::DiscardedStatement: 2074 case ExpressionEvaluationContext::PotentiallyEvaluated: 2075 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 2076 break; 2077 } 2078 } 2079 2080 return MaybeBindToTemporary(Lambda); 2081 } 2082 2083 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 2084 SourceLocation ConvLocation, 2085 CXXConversionDecl *Conv, 2086 Expr *Src) { 2087 // Make sure that the lambda call operator is marked used. 2088 CXXRecordDecl *Lambda = Conv->getParent(); 2089 CXXMethodDecl *CallOperator 2090 = cast<CXXMethodDecl>( 2091 Lambda->lookup( 2092 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 2093 CallOperator->setReferenced(); 2094 CallOperator->markUsed(Context); 2095 2096 ExprResult Init = PerformCopyInitialization( 2097 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()), 2098 CurrentLocation, Src); 2099 if (!Init.isInvalid()) 2100 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 2101 2102 if (Init.isInvalid()) 2103 return ExprError(); 2104 2105 // Create the new block to be returned. 2106 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); 2107 2108 // Set the type information. 2109 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); 2110 Block->setIsVariadic(CallOperator->isVariadic()); 2111 Block->setBlockMissingReturnType(false); 2112 2113 // Add parameters. 2114 SmallVector<ParmVarDecl *, 4> BlockParams; 2115 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 2116 ParmVarDecl *From = CallOperator->getParamDecl(I); 2117 BlockParams.push_back(ParmVarDecl::Create( 2118 Context, Block, From->getBeginLoc(), From->getLocation(), 2119 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(), 2120 From->getStorageClass(), 2121 /*DefArg=*/nullptr)); 2122 } 2123 Block->setParams(BlockParams); 2124 2125 Block->setIsConversionFromLambda(true); 2126 2127 // Add capture. The capture uses a fake variable, which doesn't correspond 2128 // to any actual memory location. However, the initializer copy-initializes 2129 // the lambda object. 2130 TypeSourceInfo *CapVarTSI = 2131 Context.getTrivialTypeSourceInfo(Src->getType()); 2132 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, 2133 ConvLocation, nullptr, 2134 Src->getType(), CapVarTSI, 2135 SC_None); 2136 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false, 2137 /*nested=*/false, /*copy=*/Init.get()); 2138 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false); 2139 2140 // Add a fake function body to the block. IR generation is responsible 2141 // for filling in the actual body, which cannot be expressed as an AST. 2142 Block->setBody(new (Context) CompoundStmt(ConvLocation)); 2143 2144 // Create the block literal expression. 2145 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); 2146 ExprCleanupObjects.push_back(Block); 2147 Cleanup.setExprNeedsCleanups(true); 2148 2149 return BuildBlock; 2150 } 2151