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 nullptr); 237 } 238 return LSI->GLTemplateParameterList; 239 } 240 241 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, 242 TypeSourceInfo *Info, 243 bool KnownDependent, 244 LambdaCaptureDefault CaptureDefault) { 245 DeclContext *DC = CurContext; 246 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 247 DC = DC->getParent(); 248 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(), 249 *this); 250 // Start constructing the lambda class. 251 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info, 252 IntroducerRange.getBegin(), 253 KnownDependent, 254 IsGenericLambda, 255 CaptureDefault); 256 DC->addDecl(Class); 257 258 return Class; 259 } 260 261 /// Determine whether the given context is or is enclosed in an inline 262 /// function. 263 static bool isInInlineFunction(const DeclContext *DC) { 264 while (!DC->isFileContext()) { 265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 266 if (FD->isInlined()) 267 return true; 268 269 DC = DC->getLexicalParent(); 270 } 271 272 return false; 273 } 274 275 MangleNumberingContext * 276 Sema::getCurrentMangleNumberContext(const DeclContext *DC, 277 Decl *&ManglingContextDecl) { 278 // Compute the context for allocating mangling numbers in the current 279 // expression, if the ABI requires them. 280 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; 281 282 enum ContextKind { 283 Normal, 284 DefaultArgument, 285 DataMember, 286 StaticDataMember, 287 InlineVariable, 288 VariableTemplate 289 } Kind = Normal; 290 291 // Default arguments of member function parameters that appear in a class 292 // definition, as well as the initializers of data members, receive special 293 // treatment. Identify them. 294 if (ManglingContextDecl) { 295 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { 296 if (const DeclContext *LexicalDC 297 = Param->getDeclContext()->getLexicalParent()) 298 if (LexicalDC->isRecord()) 299 Kind = DefaultArgument; 300 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) { 301 if (Var->getDeclContext()->isRecord()) 302 Kind = StaticDataMember; 303 else if (Var->getMostRecentDecl()->isInline()) 304 Kind = InlineVariable; 305 else if (Var->getDescribedVarTemplate()) 306 Kind = VariableTemplate; 307 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 308 if (!VTS->isExplicitSpecialization()) 309 Kind = VariableTemplate; 310 } 311 } else if (isa<FieldDecl>(ManglingContextDecl)) { 312 Kind = DataMember; 313 } 314 } 315 316 // Itanium ABI [5.1.7]: 317 // In the following contexts [...] the one-definition rule requires closure 318 // types in different translation units to "correspond": 319 bool IsInNonspecializedTemplate = 320 inTemplateInstantiation() || CurContext->isDependentContext(); 321 switch (Kind) { 322 case Normal: { 323 // -- the bodies of non-exported nonspecialized template functions 324 // -- the bodies of inline functions 325 if ((IsInNonspecializedTemplate && 326 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) || 327 isInInlineFunction(CurContext)) { 328 ManglingContextDecl = nullptr; 329 while (auto *CD = dyn_cast<CapturedDecl>(DC)) 330 DC = CD->getParent(); 331 return &Context.getManglingNumberContext(DC); 332 } 333 334 ManglingContextDecl = nullptr; 335 return nullptr; 336 } 337 338 case StaticDataMember: 339 // -- the initializers of nonspecialized static members of template classes 340 if (!IsInNonspecializedTemplate) { 341 ManglingContextDecl = nullptr; 342 return nullptr; 343 } 344 // Fall through to get the current context. 345 LLVM_FALLTHROUGH; 346 347 case DataMember: 348 // -- the in-class initializers of class members 349 case DefaultArgument: 350 // -- default arguments appearing in class definitions 351 case InlineVariable: 352 // -- the initializers of inline variables 353 case VariableTemplate: 354 // -- the initializers of templated variables 355 return &ExprEvalContexts.back().getMangleNumberingContext(Context); 356 } 357 358 llvm_unreachable("unexpected context"); 359 } 360 361 MangleNumberingContext & 362 Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext( 363 ASTContext &Ctx) { 364 assert(ManglingContextDecl && "Need to have a context declaration"); 365 if (!MangleNumbering) 366 MangleNumbering = Ctx.createMangleNumberingContext(); 367 return *MangleNumbering; 368 } 369 370 CXXMethodDecl *Sema::startLambdaDefinition( 371 CXXRecordDecl *Class, SourceRange IntroducerRange, 372 TypeSourceInfo *MethodTypeInfo, SourceLocation EndLoc, 373 ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, 374 Optional<std::pair<unsigned, Decl *>> Mangling) { 375 QualType MethodType = MethodTypeInfo->getType(); 376 TemplateParameterList *TemplateParams = 377 getGenericLambdaTemplateParameterList(getCurLambda(), *this); 378 // If a lambda appears in a dependent context or is a generic lambda (has 379 // template parameters) and has an 'auto' return type, deduce it to a 380 // dependent type. 381 if (Class->isDependentContext() || TemplateParams) { 382 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); 383 QualType Result = FPT->getReturnType(); 384 if (Result->isUndeducedType()) { 385 Result = SubstAutoType(Result, Context.DependentTy); 386 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(), 387 FPT->getExtProtoInfo()); 388 } 389 } 390 391 // C++11 [expr.prim.lambda]p5: 392 // The closure type for a lambda-expression has a public inline function 393 // call operator (13.5.4) whose parameters and return type are described by 394 // the lambda-expression's parameter-declaration-clause and 395 // trailing-return-type respectively. 396 DeclarationName MethodName 397 = Context.DeclarationNames.getCXXOperatorName(OO_Call); 398 DeclarationNameLoc MethodNameLoc; 399 MethodNameLoc.CXXOperatorName.BeginOpNameLoc 400 = IntroducerRange.getBegin().getRawEncoding(); 401 MethodNameLoc.CXXOperatorName.EndOpNameLoc 402 = IntroducerRange.getEnd().getRawEncoding(); 403 CXXMethodDecl *Method = CXXMethodDecl::Create( 404 Context, Class, EndLoc, 405 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(), 406 MethodNameLoc), 407 MethodType, MethodTypeInfo, SC_None, 408 /*isInline=*/true, ConstexprKind, EndLoc); 409 Method->setAccess(AS_public); 410 if (!TemplateParams) 411 Class->addDecl(Method); 412 413 // Temporarily set the lexical declaration context to the current 414 // context, so that the Scope stack matches the lexical nesting. 415 Method->setLexicalDeclContext(CurContext); 416 // Create a function template if we have a template parameter list 417 FunctionTemplateDecl *const TemplateMethod = TemplateParams ? 418 FunctionTemplateDecl::Create(Context, Class, 419 Method->getLocation(), MethodName, 420 TemplateParams, 421 Method) : nullptr; 422 if (TemplateMethod) { 423 TemplateMethod->setAccess(AS_public); 424 Method->setDescribedFunctionTemplate(TemplateMethod); 425 Class->addDecl(TemplateMethod); 426 TemplateMethod->setLexicalDeclContext(CurContext); 427 } 428 429 // Add parameters. 430 if (!Params.empty()) { 431 Method->setParams(Params); 432 CheckParmsForFunctionDef(Params, 433 /*CheckParameterNames=*/false); 434 435 for (auto P : Method->parameters()) 436 P->setOwningFunction(Method); 437 } 438 439 if (Mangling) { 440 Class->setLambdaMangling(Mangling->first, Mangling->second); 441 } else { 442 Decl *ManglingContextDecl; 443 if (MangleNumberingContext *MCtx = 444 getCurrentMangleNumberContext(Class->getDeclContext(), 445 ManglingContextDecl)) { 446 unsigned ManglingNumber = MCtx->getManglingNumber(Method); 447 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl); 448 } 449 } 450 451 return Method; 452 } 453 454 void Sema::buildLambdaScope(LambdaScopeInfo *LSI, 455 CXXMethodDecl *CallOperator, 456 SourceRange IntroducerRange, 457 LambdaCaptureDefault CaptureDefault, 458 SourceLocation CaptureDefaultLoc, 459 bool ExplicitParams, 460 bool ExplicitResultType, 461 bool Mutable) { 462 LSI->CallOperator = CallOperator; 463 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 464 LSI->Lambda = LambdaClass; 465 if (CaptureDefault == LCD_ByCopy) 466 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 467 else if (CaptureDefault == LCD_ByRef) 468 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 469 LSI->CaptureDefaultLoc = CaptureDefaultLoc; 470 LSI->IntroducerRange = IntroducerRange; 471 LSI->ExplicitParams = ExplicitParams; 472 LSI->Mutable = Mutable; 473 474 if (ExplicitResultType) { 475 LSI->ReturnType = CallOperator->getReturnType(); 476 477 if (!LSI->ReturnType->isDependentType() && 478 !LSI->ReturnType->isVoidType()) { 479 if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType, 480 diag::err_lambda_incomplete_result)) { 481 // Do nothing. 482 } 483 } 484 } else { 485 LSI->HasImplicitReturnType = true; 486 } 487 } 488 489 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 490 LSI->finishedExplicitCaptures(); 491 } 492 493 void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, 494 ArrayRef<NamedDecl *> TParams, 495 SourceLocation RAngleLoc) { 496 LambdaScopeInfo *LSI = getCurLambda(); 497 assert(LSI && "Expected a lambda scope"); 498 assert(LSI->NumExplicitTemplateParams == 0 && 499 "Already acted on explicit template parameters"); 500 assert(LSI->TemplateParams.empty() && 501 "Explicit template parameters should come " 502 "before invented (auto) ones"); 503 assert(!TParams.empty() && 504 "No template parameters to act on"); 505 LSI->TemplateParams.append(TParams.begin(), TParams.end()); 506 LSI->NumExplicitTemplateParams = TParams.size(); 507 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc}; 508 } 509 510 void Sema::addLambdaParameters( 511 ArrayRef<LambdaIntroducer::LambdaCapture> Captures, 512 CXXMethodDecl *CallOperator, Scope *CurScope) { 513 // Introduce our parameters into the function scope 514 for (unsigned p = 0, NumParams = CallOperator->getNumParams(); 515 p < NumParams; ++p) { 516 ParmVarDecl *Param = CallOperator->getParamDecl(p); 517 518 // If this has an identifier, add it to the scope stack. 519 if (CurScope && Param->getIdentifier()) { 520 bool Error = false; 521 // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we 522 // retroactively apply it. 523 for (const auto &Capture : Captures) { 524 if (Capture.Id == Param->getIdentifier()) { 525 Error = true; 526 Diag(Param->getLocation(), diag::err_parameter_shadow_capture); 527 Diag(Capture.Loc, diag::note_var_explicitly_captured_here) 528 << Capture.Id << true; 529 } 530 } 531 if (!Error) 532 CheckShadow(CurScope, Param); 533 534 PushOnScopeChains(Param, CurScope); 535 } 536 } 537 } 538 539 /// If this expression is an enumerator-like expression of some type 540 /// T, return the type T; otherwise, return null. 541 /// 542 /// Pointer comparisons on the result here should always work because 543 /// it's derived from either the parent of an EnumConstantDecl 544 /// (i.e. the definition) or the declaration returned by 545 /// EnumType::getDecl() (i.e. the definition). 546 static EnumDecl *findEnumForBlockReturn(Expr *E) { 547 // An expression is an enumerator-like expression of type T if, 548 // ignoring parens and parens-like expressions: 549 E = E->IgnoreParens(); 550 551 // - it is an enumerator whose enum type is T or 552 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 553 if (EnumConstantDecl *D 554 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 555 return cast<EnumDecl>(D->getDeclContext()); 556 } 557 return nullptr; 558 } 559 560 // - it is a comma expression whose RHS is an enumerator-like 561 // expression of type T or 562 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 563 if (BO->getOpcode() == BO_Comma) 564 return findEnumForBlockReturn(BO->getRHS()); 565 return nullptr; 566 } 567 568 // - it is a statement-expression whose value expression is an 569 // enumerator-like expression of type T or 570 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 571 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) 572 return findEnumForBlockReturn(last); 573 return nullptr; 574 } 575 576 // - it is a ternary conditional operator (not the GNU ?: 577 // extension) whose second and third operands are 578 // enumerator-like expressions of type T or 579 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 580 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) 581 if (ED == findEnumForBlockReturn(CO->getFalseExpr())) 582 return ED; 583 return nullptr; 584 } 585 586 // (implicitly:) 587 // - it is an implicit integral conversion applied to an 588 // enumerator-like expression of type T or 589 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 590 // We can sometimes see integral conversions in valid 591 // enumerator-like expressions. 592 if (ICE->getCastKind() == CK_IntegralCast) 593 return findEnumForBlockReturn(ICE->getSubExpr()); 594 595 // Otherwise, just rely on the type. 596 } 597 598 // - it is an expression of that formal enum type. 599 if (const EnumType *ET = E->getType()->getAs<EnumType>()) { 600 return ET->getDecl(); 601 } 602 603 // Otherwise, nope. 604 return nullptr; 605 } 606 607 /// Attempt to find a type T for which the returned expression of the 608 /// given statement is an enumerator-like expression of that type. 609 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { 610 if (Expr *retValue = ret->getRetValue()) 611 return findEnumForBlockReturn(retValue); 612 return nullptr; 613 } 614 615 /// Attempt to find a common type T for which all of the returned 616 /// expressions in a block are enumerator-like expressions of that 617 /// type. 618 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { 619 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); 620 621 // Try to find one for the first return. 622 EnumDecl *ED = findEnumForBlockReturn(*i); 623 if (!ED) return nullptr; 624 625 // Check that the rest of the returns have the same enum. 626 for (++i; i != e; ++i) { 627 if (findEnumForBlockReturn(*i) != ED) 628 return nullptr; 629 } 630 631 // Never infer an anonymous enum type. 632 if (!ED->hasNameForLinkage()) return nullptr; 633 634 return ED; 635 } 636 637 /// Adjust the given return statements so that they formally return 638 /// the given type. It should require, at most, an IntegralCast. 639 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, 640 QualType returnType) { 641 for (ArrayRef<ReturnStmt*>::iterator 642 i = returns.begin(), e = returns.end(); i != e; ++i) { 643 ReturnStmt *ret = *i; 644 Expr *retValue = ret->getRetValue(); 645 if (S.Context.hasSameType(retValue->getType(), returnType)) 646 continue; 647 648 // Right now we only support integral fixup casts. 649 assert(returnType->isIntegralOrUnscopedEnumerationType()); 650 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); 651 652 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); 653 654 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue); 655 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, 656 E, /*base path*/ nullptr, VK_RValue); 657 if (cleanups) { 658 cleanups->setSubExpr(E); 659 } else { 660 ret->setRetValue(E); 661 } 662 } 663 } 664 665 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { 666 assert(CSI.HasImplicitReturnType); 667 // If it was ever a placeholder, it had to been deduced to DependentTy. 668 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); 669 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && 670 "lambda expressions use auto deduction in C++14 onwards"); 671 672 // C++ core issue 975: 673 // If a lambda-expression does not include a trailing-return-type, 674 // it is as if the trailing-return-type denotes the following type: 675 // - if there are no return statements in the compound-statement, 676 // or all return statements return either an expression of type 677 // void or no expression or braced-init-list, the type void; 678 // - otherwise, if all return statements return an expression 679 // and the types of the returned expressions after 680 // lvalue-to-rvalue conversion (4.1 [conv.lval]), 681 // array-to-pointer conversion (4.2 [conv.array]), and 682 // function-to-pointer conversion (4.3 [conv.func]) are the 683 // same, that common type; 684 // - otherwise, the program is ill-formed. 685 // 686 // C++ core issue 1048 additionally removes top-level cv-qualifiers 687 // from the types of returned expressions to match the C++14 auto 688 // deduction rules. 689 // 690 // In addition, in blocks in non-C++ modes, if all of the return 691 // statements are enumerator-like expressions of some type T, where 692 // T has a name for linkage, then we infer the return type of the 693 // block to be that type. 694 695 // First case: no return statements, implicit void return type. 696 ASTContext &Ctx = getASTContext(); 697 if (CSI.Returns.empty()) { 698 // It's possible there were simply no /valid/ return statements. 699 // In this case, the first one we found may have at least given us a type. 700 if (CSI.ReturnType.isNull()) 701 CSI.ReturnType = Ctx.VoidTy; 702 return; 703 } 704 705 // Second case: at least one return statement has dependent type. 706 // Delay type checking until instantiation. 707 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); 708 if (CSI.ReturnType->isDependentType()) 709 return; 710 711 // Try to apply the enum-fuzz rule. 712 if (!getLangOpts().CPlusPlus) { 713 assert(isa<BlockScopeInfo>(CSI)); 714 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); 715 if (ED) { 716 CSI.ReturnType = Context.getTypeDeclType(ED); 717 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); 718 return; 719 } 720 } 721 722 // Third case: only one return statement. Don't bother doing extra work! 723 if (CSI.Returns.size() == 1) 724 return; 725 726 // General case: many return statements. 727 // Check that they all have compatible return types. 728 729 // We require the return types to strictly match here. 730 // Note that we've already done the required promotions as part of 731 // processing the return statement. 732 for (const ReturnStmt *RS : CSI.Returns) { 733 const Expr *RetE = RS->getRetValue(); 734 735 QualType ReturnType = 736 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType(); 737 if (Context.getCanonicalFunctionResultType(ReturnType) == 738 Context.getCanonicalFunctionResultType(CSI.ReturnType)) { 739 // Use the return type with the strictest possible nullability annotation. 740 auto RetTyNullability = ReturnType->getNullability(Ctx); 741 auto BlockNullability = CSI.ReturnType->getNullability(Ctx); 742 if (BlockNullability && 743 (!RetTyNullability || 744 hasWeakerNullability(*RetTyNullability, *BlockNullability))) 745 CSI.ReturnType = ReturnType; 746 continue; 747 } 748 749 // FIXME: This is a poor diagnostic for ReturnStmts without expressions. 750 // TODO: It's possible that the *first* return is the divergent one. 751 Diag(RS->getBeginLoc(), 752 diag::err_typecheck_missing_return_type_incompatible) 753 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI); 754 // Continue iterating so that we keep emitting diagnostics. 755 } 756 } 757 758 QualType Sema::buildLambdaInitCaptureInitialization( 759 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 760 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit, 761 Expr *&Init) { 762 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to 763 // deduce against. 764 QualType DeductType = Context.getAutoDeductType(); 765 TypeLocBuilder TLB; 766 TLB.pushTypeSpec(DeductType).setNameLoc(Loc); 767 if (ByRef) { 768 DeductType = BuildReferenceType(DeductType, true, Loc, Id); 769 assert(!DeductType.isNull() && "can't build reference to auto"); 770 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); 771 } 772 if (EllipsisLoc.isValid()) { 773 if (Init->containsUnexpandedParameterPack()) { 774 Diag(EllipsisLoc, getLangOpts().CPlusPlus2a 775 ? diag::warn_cxx17_compat_init_capture_pack 776 : diag::ext_init_capture_pack); 777 DeductType = Context.getPackExpansionType(DeductType, NumExpansions); 778 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc); 779 } else { 780 // Just ignore the ellipsis for now and form a non-pack variable. We'll 781 // diagnose this later when we try to capture it. 782 } 783 } 784 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); 785 786 // Deduce the type of the init capture. 787 QualType DeducedType = deduceVarTypeFromInitializer( 788 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI, 789 SourceRange(Loc, Loc), IsDirectInit, Init); 790 if (DeducedType.isNull()) 791 return QualType(); 792 793 // Are we a non-list direct initialization? 794 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 795 796 // Perform initialization analysis and ensure any implicit conversions 797 // (such as lvalue-to-rvalue) are enforced. 798 InitializedEntity Entity = 799 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc); 800 InitializationKind Kind = 801 IsDirectInit 802 ? (CXXDirectInit ? InitializationKind::CreateDirect( 803 Loc, Init->getBeginLoc(), Init->getEndLoc()) 804 : InitializationKind::CreateDirectList(Loc)) 805 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc()); 806 807 MultiExprArg Args = Init; 808 if (CXXDirectInit) 809 Args = 810 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); 811 QualType DclT; 812 InitializationSequence InitSeq(*this, Entity, Kind, Args); 813 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 814 815 if (Result.isInvalid()) 816 return QualType(); 817 818 Init = Result.getAs<Expr>(); 819 return DeducedType; 820 } 821 822 VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc, 823 QualType InitCaptureType, 824 SourceLocation EllipsisLoc, 825 IdentifierInfo *Id, 826 unsigned InitStyle, Expr *Init) { 827 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization 828 // rather than reconstructing it here. 829 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc); 830 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>()) 831 PETL.setEllipsisLoc(EllipsisLoc); 832 833 // Create a dummy variable representing the init-capture. This is not actually 834 // used as a variable, and only exists as a way to name and refer to the 835 // init-capture. 836 // FIXME: Pass in separate source locations for '&' and identifier. 837 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc, 838 Loc, Id, InitCaptureType, TSI, SC_Auto); 839 NewVD->setInitCapture(true); 840 NewVD->setReferenced(true); 841 // FIXME: Pass in a VarDecl::InitializationStyle. 842 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle)); 843 NewVD->markUsed(Context); 844 NewVD->setInit(Init); 845 if (NewVD->isParameterPack()) 846 getCurLambda()->LocalPacks.push_back(NewVD); 847 return NewVD; 848 } 849 850 void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) { 851 assert(Var->isInitCapture() && "init capture flag should be set"); 852 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(), 853 /*isNested*/false, Var->getLocation(), SourceLocation(), 854 Var->getType(), /*Invalid*/false); 855 } 856 857 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 858 Declarator &ParamInfo, 859 Scope *CurScope) { 860 LambdaScopeInfo *const LSI = getCurLambda(); 861 assert(LSI && "LambdaScopeInfo should be on stack!"); 862 863 // Determine if we're within a context where we know that the lambda will 864 // be dependent, because there are template parameters in scope. 865 bool KnownDependent; 866 if (LSI->NumExplicitTemplateParams > 0) { 867 auto *TemplateParamScope = CurScope->getTemplateParamParent(); 868 assert(TemplateParamScope && 869 "Lambda with explicit template param list should establish a " 870 "template param scope"); 871 assert(TemplateParamScope->getParent()); 872 KnownDependent = TemplateParamScope->getParent() 873 ->getTemplateParamParent() != nullptr; 874 } else { 875 KnownDependent = CurScope->getTemplateParamParent() != nullptr; 876 } 877 878 // Determine the signature of the call operator. 879 TypeSourceInfo *MethodTyInfo; 880 bool ExplicitParams = true; 881 bool ExplicitResultType = true; 882 bool ContainsUnexpandedParameterPack = false; 883 SourceLocation EndLoc; 884 SmallVector<ParmVarDecl *, 8> Params; 885 if (ParamInfo.getNumTypeObjects() == 0) { 886 // C++11 [expr.prim.lambda]p4: 887 // If a lambda-expression does not include a lambda-declarator, it is as 888 // if the lambda-declarator were (). 889 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 890 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 891 EPI.HasTrailingReturn = true; 892 EPI.TypeQuals.addConst(); 893 // C++1y [expr.prim.lambda]: 894 // The lambda return type is 'auto', which is replaced by the 895 // trailing-return type if provided and/or deduced from 'return' 896 // statements 897 // We don't do this before C++1y, because we don't support deduced return 898 // types there. 899 QualType DefaultTypeForNoTrailingReturn = 900 getLangOpts().CPlusPlus14 ? Context.getAutoDeductType() 901 : Context.DependentTy; 902 QualType MethodTy = 903 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI); 904 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy); 905 ExplicitParams = false; 906 ExplicitResultType = false; 907 EndLoc = Intro.Range.getEnd(); 908 } else { 909 assert(ParamInfo.isFunctionDeclarator() && 910 "lambda-declarator is a function"); 911 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 912 913 // C++11 [expr.prim.lambda]p5: 914 // This function call operator is declared const (9.3.1) if and only if 915 // the lambda-expression's parameter-declaration-clause is not followed 916 // by mutable. It is neither virtual nor declared volatile. [...] 917 if (!FTI.hasMutableQualifier()) { 918 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, 919 SourceLocation()); 920 } 921 922 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope); 923 assert(MethodTyInfo && "no type from lambda-declarator"); 924 EndLoc = ParamInfo.getSourceRange().getEnd(); 925 926 ExplicitResultType = FTI.hasTrailingReturnType(); 927 928 if (FTIHasNonVoidParameters(FTI)) { 929 Params.reserve(FTI.NumParams); 930 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) 931 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param)); 932 } 933 934 // Check for unexpanded parameter packs in the method type. 935 if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) 936 DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo, 937 UPPC_DeclarationType); 938 } 939 940 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo, 941 KnownDependent, Intro.Default); 942 CXXMethodDecl *Method = 943 startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params, 944 ParamInfo.getDeclSpec().getConstexprSpecifier()); 945 if (ExplicitParams) 946 CheckCXXDefaultArguments(Method); 947 948 // This represents the function body for the lambda function, check if we 949 // have to apply optnone due to a pragma. 950 AddRangeBasedOptnone(Method); 951 952 // code_seg attribute on lambda apply to the method. 953 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 954 Method->addAttr(A); 955 956 // Attributes on the lambda apply to the method. 957 ProcessDeclAttributes(CurScope, Method, ParamInfo); 958 959 // CUDA lambdas get implicit attributes based on the scope in which they're 960 // declared. 961 if (getLangOpts().CUDA) 962 CUDASetLambdaAttrs(Method); 963 964 // Introduce the function call operator as the current declaration context. 965 PushDeclContext(CurScope, Method); 966 967 // Build the lambda scope. 968 buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc, 969 ExplicitParams, ExplicitResultType, !Method->isConst()); 970 971 // C++11 [expr.prim.lambda]p9: 972 // A lambda-expression whose smallest enclosing scope is a block scope is a 973 // local lambda expression; any other lambda expression shall not have a 974 // capture-default or simple-capture in its lambda-introducer. 975 // 976 // For simple-captures, this is covered by the check below that any named 977 // entity is a variable that can be captured. 978 // 979 // For DR1632, we also allow a capture-default in any context where we can 980 // odr-use 'this' (in particular, in a default initializer for a non-static 981 // data member). 982 if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() && 983 (getCurrentThisType().isNull() || 984 CheckCXXThisCapture(SourceLocation(), /*Explicit*/true, 985 /*BuildAndDiagnose*/false))) 986 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local); 987 988 // Distinct capture names, for diagnostics. 989 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames; 990 991 // Handle explicit captures. 992 SourceLocation PrevCaptureLoc 993 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc; 994 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; 995 PrevCaptureLoc = C->Loc, ++C) { 996 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) { 997 if (C->Kind == LCK_StarThis) 998 Diag(C->Loc, !getLangOpts().CPlusPlus17 999 ? diag::ext_star_this_lambda_capture_cxx17 1000 : diag::warn_cxx14_compat_star_this_lambda_capture); 1001 1002 // C++11 [expr.prim.lambda]p8: 1003 // An identifier or this shall not appear more than once in a 1004 // lambda-capture. 1005 if (LSI->isCXXThisCaptured()) { 1006 Diag(C->Loc, diag::err_capture_more_than_once) 1007 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation()) 1008 << FixItHint::CreateRemoval( 1009 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1010 continue; 1011 } 1012 1013 // C++2a [expr.prim.lambda]p8: 1014 // If a lambda-capture includes a capture-default that is =, 1015 // each simple-capture of that lambda-capture shall be of the form 1016 // "&identifier", "this", or "* this". [ Note: The form [&,this] is 1017 // redundant but accepted for compatibility with ISO C++14. --end note ] 1018 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis) 1019 Diag(C->Loc, !getLangOpts().CPlusPlus2a 1020 ? diag::ext_equals_this_lambda_capture_cxx2a 1021 : diag::warn_cxx17_compat_equals_this_lambda_capture); 1022 1023 // C++11 [expr.prim.lambda]p12: 1024 // If this is captured by a local lambda expression, its nearest 1025 // enclosing function shall be a non-static member function. 1026 QualType ThisCaptureType = getCurrentThisType(); 1027 if (ThisCaptureType.isNull()) { 1028 Diag(C->Loc, diag::err_this_capture) << true; 1029 continue; 1030 } 1031 1032 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true, 1033 /*FunctionScopeIndexToStopAtPtr*/ nullptr, 1034 C->Kind == LCK_StarThis); 1035 if (!LSI->Captures.empty()) 1036 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; 1037 continue; 1038 } 1039 1040 assert(C->Id && "missing identifier for capture"); 1041 1042 if (C->Init.isInvalid()) 1043 continue; 1044 1045 VarDecl *Var = nullptr; 1046 if (C->Init.isUsable()) { 1047 Diag(C->Loc, getLangOpts().CPlusPlus14 1048 ? diag::warn_cxx11_compat_init_capture 1049 : diag::ext_init_capture); 1050 1051 // If the initializer expression is usable, but the InitCaptureType 1052 // is not, then an error has occurred - so ignore the capture for now. 1053 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. 1054 // FIXME: we should create the init capture variable and mark it invalid 1055 // in this case. 1056 if (C->InitCaptureType.get().isNull()) 1057 continue; 1058 1059 if (C->Init.get()->containsUnexpandedParameterPack() && 1060 !C->InitCaptureType.get()->getAs<PackExpansionType>()) 1061 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer); 1062 1063 unsigned InitStyle; 1064 switch (C->InitKind) { 1065 case LambdaCaptureInitKind::NoInit: 1066 llvm_unreachable("not an init-capture?"); 1067 case LambdaCaptureInitKind::CopyInit: 1068 InitStyle = VarDecl::CInit; 1069 break; 1070 case LambdaCaptureInitKind::DirectInit: 1071 InitStyle = VarDecl::CallInit; 1072 break; 1073 case LambdaCaptureInitKind::ListInit: 1074 InitStyle = VarDecl::ListInit; 1075 break; 1076 } 1077 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(), 1078 C->EllipsisLoc, C->Id, InitStyle, 1079 C->Init.get()); 1080 // C++1y [expr.prim.lambda]p11: 1081 // An init-capture behaves as if it declares and explicitly 1082 // captures a variable [...] whose declarative region is the 1083 // lambda-expression's compound-statement 1084 if (Var) 1085 PushOnScopeChains(Var, CurScope, false); 1086 } else { 1087 assert(C->InitKind == LambdaCaptureInitKind::NoInit && 1088 "init capture has valid but null init?"); 1089 1090 // C++11 [expr.prim.lambda]p8: 1091 // If a lambda-capture includes a capture-default that is &, the 1092 // identifiers in the lambda-capture shall not be preceded by &. 1093 // If a lambda-capture includes a capture-default that is =, [...] 1094 // each identifier it contains shall be preceded by &. 1095 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 1096 Diag(C->Loc, diag::err_reference_capture_with_reference_default) 1097 << FixItHint::CreateRemoval( 1098 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1099 continue; 1100 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 1101 Diag(C->Loc, diag::err_copy_capture_with_copy_default) 1102 << FixItHint::CreateRemoval( 1103 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1104 continue; 1105 } 1106 1107 // C++11 [expr.prim.lambda]p10: 1108 // The identifiers in a capture-list are looked up using the usual 1109 // rules for unqualified name lookup (3.4.1) 1110 DeclarationNameInfo Name(C->Id, C->Loc); 1111 LookupResult R(*this, Name, LookupOrdinaryName); 1112 LookupName(R, CurScope); 1113 if (R.isAmbiguous()) 1114 continue; 1115 if (R.empty()) { 1116 // FIXME: Disable corrections that would add qualification? 1117 CXXScopeSpec ScopeSpec; 1118 DeclFilterCCC<VarDecl> Validator{}; 1119 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) 1120 continue; 1121 } 1122 1123 Var = R.getAsSingle<VarDecl>(); 1124 if (Var && DiagnoseUseOfDecl(Var, C->Loc)) 1125 continue; 1126 } 1127 1128 // C++11 [expr.prim.lambda]p8: 1129 // An identifier or this shall not appear more than once in a 1130 // lambda-capture. 1131 if (!CaptureNames.insert(C->Id).second) { 1132 if (Var && LSI->isCaptured(Var)) { 1133 Diag(C->Loc, diag::err_capture_more_than_once) 1134 << C->Id << SourceRange(LSI->getCapture(Var).getLocation()) 1135 << FixItHint::CreateRemoval( 1136 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1137 } else 1138 // Previous capture captured something different (one or both was 1139 // an init-cpature): no fixit. 1140 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; 1141 continue; 1142 } 1143 1144 // C++11 [expr.prim.lambda]p10: 1145 // [...] each such lookup shall find a variable with automatic storage 1146 // duration declared in the reaching scope of the local lambda expression. 1147 // Note that the 'reaching scope' check happens in tryCaptureVariable(). 1148 if (!Var) { 1149 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 1150 continue; 1151 } 1152 1153 // Ignore invalid decls; they'll just confuse the code later. 1154 if (Var->isInvalidDecl()) 1155 continue; 1156 1157 if (!Var->hasLocalStorage()) { 1158 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 1159 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 1160 continue; 1161 } 1162 1163 // C++11 [expr.prim.lambda]p23: 1164 // A capture followed by an ellipsis is a pack expansion (14.5.3). 1165 SourceLocation EllipsisLoc; 1166 if (C->EllipsisLoc.isValid()) { 1167 if (Var->isParameterPack()) { 1168 EllipsisLoc = C->EllipsisLoc; 1169 } else { 1170 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1171 << (C->Init.isUsable() ? C->Init.get()->getSourceRange() 1172 : SourceRange(C->Loc)); 1173 1174 // Just ignore the ellipsis. 1175 } 1176 } else if (Var->isParameterPack()) { 1177 ContainsUnexpandedParameterPack = true; 1178 } 1179 1180 if (C->Init.isUsable()) { 1181 addInitCapture(LSI, Var); 1182 } else { 1183 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef : 1184 TryCapture_ExplicitByVal; 1185 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); 1186 } 1187 if (!LSI->Captures.empty()) 1188 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; 1189 } 1190 finishLambdaExplicitCaptures(LSI); 1191 1192 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack; 1193 1194 // Add lambda parameters into scope. 1195 addLambdaParameters(Intro.Captures, Method, CurScope); 1196 1197 // Enter a new evaluation context to insulate the lambda from any 1198 // cleanups from the enclosing full-expression. 1199 PushExpressionEvaluationContext( 1200 ExpressionEvaluationContext::PotentiallyEvaluated); 1201 } 1202 1203 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 1204 bool IsInstantiation) { 1205 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back()); 1206 1207 // Leave the expression-evaluation context. 1208 DiscardCleanupsInEvaluationContext(); 1209 PopExpressionEvaluationContext(); 1210 1211 // Leave the context of the lambda. 1212 if (!IsInstantiation) 1213 PopDeclContext(); 1214 1215 // Finalize the lambda. 1216 CXXRecordDecl *Class = LSI->Lambda; 1217 Class->setInvalidDecl(); 1218 SmallVector<Decl*, 4> Fields(Class->fields()); 1219 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 1220 SourceLocation(), ParsedAttributesView()); 1221 CheckCompletedCXXClass(Class); 1222 1223 PopFunctionScopeInfo(); 1224 } 1225 1226 QualType Sema::getLambdaConversionFunctionResultType( 1227 const FunctionProtoType *CallOpProto) { 1228 // The function type inside the pointer type is the same as the call 1229 // operator with some tweaks. The calling convention is the default free 1230 // function convention, and the type qualifications are lost. 1231 const FunctionProtoType::ExtProtoInfo CallOpExtInfo = 1232 CallOpProto->getExtProtoInfo(); 1233 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; 1234 CallingConv CC = Context.getDefaultCallingConvention( 1235 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 1236 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); 1237 InvokerExtInfo.TypeQuals = Qualifiers(); 1238 assert(InvokerExtInfo.RefQualifier == RQ_None && 1239 "Lambda's call operator should not have a reference qualifier"); 1240 return Context.getFunctionType(CallOpProto->getReturnType(), 1241 CallOpProto->getParamTypes(), InvokerExtInfo); 1242 } 1243 1244 /// Add a lambda's conversion to function pointer, as described in 1245 /// C++11 [expr.prim.lambda]p6. 1246 static void addFunctionPointerConversion(Sema &S, 1247 SourceRange IntroducerRange, 1248 CXXRecordDecl *Class, 1249 CXXMethodDecl *CallOperator) { 1250 // This conversion is explicitly disabled if the lambda's function has 1251 // pass_object_size attributes on any of its parameters. 1252 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) { 1253 return P->hasAttr<PassObjectSizeAttr>(); 1254 }; 1255 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr)) 1256 return; 1257 1258 // Add the conversion to function pointer. 1259 QualType InvokerFunctionTy = S.getLambdaConversionFunctionResultType( 1260 CallOperator->getType()->castAs<FunctionProtoType>()); 1261 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy); 1262 1263 // Create the type of the conversion function. 1264 FunctionProtoType::ExtProtoInfo ConvExtInfo( 1265 S.Context.getDefaultCallingConvention( 1266 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 1267 // The conversion function is always const and noexcept. 1268 ConvExtInfo.TypeQuals = Qualifiers(); 1269 ConvExtInfo.TypeQuals.addConst(); 1270 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept; 1271 QualType ConvTy = 1272 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo); 1273 1274 SourceLocation Loc = IntroducerRange.getBegin(); 1275 DeclarationName ConversionName 1276 = S.Context.DeclarationNames.getCXXConversionFunctionName( 1277 S.Context.getCanonicalType(PtrToFunctionTy)); 1278 DeclarationNameLoc ConvNameLoc; 1279 // Construct a TypeSourceInfo for the conversion function, and wire 1280 // all the parameters appropriately for the FunctionProtoTypeLoc 1281 // so that everything works during transformation/instantiation of 1282 // generic lambdas. 1283 // The main reason for wiring up the parameters of the conversion 1284 // function with that of the call operator is so that constructs 1285 // like the following work: 1286 // auto L = [](auto b) { <-- 1 1287 // return [](auto a) -> decltype(a) { <-- 2 1288 // return a; 1289 // }; 1290 // }; 1291 // int (*fp)(int) = L(5); 1292 // Because the trailing return type can contain DeclRefExprs that refer 1293 // to the original call operator's variables, we hijack the call 1294 // operators ParmVarDecls below. 1295 TypeSourceInfo *ConvNamePtrToFunctionTSI = 1296 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); 1297 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI; 1298 1299 // The conversion function is a conversion to a pointer-to-function. 1300 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); 1301 FunctionProtoTypeLoc ConvTL = 1302 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); 1303 // Get the result of the conversion function which is a pointer-to-function. 1304 PointerTypeLoc PtrToFunctionTL = 1305 ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); 1306 // Do the same for the TypeSourceInfo that is used to name the conversion 1307 // operator. 1308 PointerTypeLoc ConvNamePtrToFunctionTL = 1309 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); 1310 1311 // Get the underlying function types that the conversion function will 1312 // be converting to (should match the type of the call operator). 1313 FunctionProtoTypeLoc CallOpConvTL = 1314 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 1315 FunctionProtoTypeLoc CallOpConvNameTL = 1316 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 1317 1318 // Wire up the FunctionProtoTypeLocs with the call operator's parameters. 1319 // These parameter's are essentially used to transform the name and 1320 // the type of the conversion operator. By using the same parameters 1321 // as the call operator's we don't have to fix any back references that 1322 // the trailing return type of the call operator's uses (such as 1323 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) 1324 // - we can simply use the return type of the call operator, and 1325 // everything should work. 1326 SmallVector<ParmVarDecl *, 4> InvokerParams; 1327 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 1328 ParmVarDecl *From = CallOperator->getParamDecl(I); 1329 1330 InvokerParams.push_back(ParmVarDecl::Create( 1331 S.Context, 1332 // Temporarily add to the TU. This is set to the invoker below. 1333 S.Context.getTranslationUnitDecl(), From->getBeginLoc(), 1334 From->getLocation(), From->getIdentifier(), From->getType(), 1335 From->getTypeSourceInfo(), From->getStorageClass(), 1336 /*DefArg=*/nullptr)); 1337 CallOpConvTL.setParam(I, From); 1338 CallOpConvNameTL.setParam(I, From); 1339 } 1340 1341 CXXConversionDecl *Conversion = CXXConversionDecl::Create( 1342 S.Context, Class, Loc, 1343 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI, 1344 /*isInline=*/true, ExplicitSpecifier(), 1345 S.getLangOpts().CPlusPlus17 ? CSK_constexpr : CSK_unspecified, 1346 CallOperator->getBody()->getEndLoc()); 1347 Conversion->setAccess(AS_public); 1348 Conversion->setImplicit(true); 1349 1350 if (Class->isGenericLambda()) { 1351 // Create a template version of the conversion operator, using the template 1352 // parameter list of the function call operator. 1353 FunctionTemplateDecl *TemplateCallOperator = 1354 CallOperator->getDescribedFunctionTemplate(); 1355 FunctionTemplateDecl *ConversionTemplate = 1356 FunctionTemplateDecl::Create(S.Context, Class, 1357 Loc, ConversionName, 1358 TemplateCallOperator->getTemplateParameters(), 1359 Conversion); 1360 ConversionTemplate->setAccess(AS_public); 1361 ConversionTemplate->setImplicit(true); 1362 Conversion->setDescribedFunctionTemplate(ConversionTemplate); 1363 Class->addDecl(ConversionTemplate); 1364 } else 1365 Class->addDecl(Conversion); 1366 // Add a non-static member function that will be the result of 1367 // the conversion with a certain unique ID. 1368 DeclarationName InvokerName = &S.Context.Idents.get( 1369 getLambdaStaticInvokerName()); 1370 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo() 1371 // we should get a prebuilt TrivialTypeSourceInfo from Context 1372 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc 1373 // then rewire the parameters accordingly, by hoisting up the InvokeParams 1374 // loop below and then use its Params to set Invoke->setParams(...) below. 1375 // This would avoid the 'const' qualifier of the calloperator from 1376 // contaminating the type of the invoker, which is currently adjusted 1377 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the 1378 // trailing return type of the invoker would require a visitor to rebuild 1379 // the trailing return type and adjusting all back DeclRefExpr's to refer 1380 // to the new static invoker parameters - not the call operator's. 1381 CXXMethodDecl *Invoke = CXXMethodDecl::Create( 1382 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc), 1383 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static, 1384 /*isInline=*/true, CSK_unspecified, CallOperator->getBody()->getEndLoc()); 1385 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) 1386 InvokerParams[I]->setOwningFunction(Invoke); 1387 Invoke->setParams(InvokerParams); 1388 Invoke->setAccess(AS_private); 1389 Invoke->setImplicit(true); 1390 if (Class->isGenericLambda()) { 1391 FunctionTemplateDecl *TemplateCallOperator = 1392 CallOperator->getDescribedFunctionTemplate(); 1393 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create( 1394 S.Context, Class, Loc, InvokerName, 1395 TemplateCallOperator->getTemplateParameters(), 1396 Invoke); 1397 StaticInvokerTemplate->setAccess(AS_private); 1398 StaticInvokerTemplate->setImplicit(true); 1399 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate); 1400 Class->addDecl(StaticInvokerTemplate); 1401 } else 1402 Class->addDecl(Invoke); 1403 } 1404 1405 /// Add a lambda's conversion to block pointer. 1406 static void addBlockPointerConversion(Sema &S, 1407 SourceRange IntroducerRange, 1408 CXXRecordDecl *Class, 1409 CXXMethodDecl *CallOperator) { 1410 QualType FunctionTy = S.getLambdaConversionFunctionResultType( 1411 CallOperator->getType()->castAs<FunctionProtoType>()); 1412 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 1413 1414 FunctionProtoType::ExtProtoInfo ConversionEPI( 1415 S.Context.getDefaultCallingConvention( 1416 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 1417 ConversionEPI.TypeQuals = Qualifiers(); 1418 ConversionEPI.TypeQuals.addConst(); 1419 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI); 1420 1421 SourceLocation Loc = IntroducerRange.getBegin(); 1422 DeclarationName Name 1423 = S.Context.DeclarationNames.getCXXConversionFunctionName( 1424 S.Context.getCanonicalType(BlockPtrTy)); 1425 DeclarationNameLoc NameLoc; 1426 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); 1427 CXXConversionDecl *Conversion = CXXConversionDecl::Create( 1428 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy, 1429 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 1430 /*isInline=*/true, ExplicitSpecifier(), CSK_unspecified, 1431 CallOperator->getBody()->getEndLoc()); 1432 Conversion->setAccess(AS_public); 1433 Conversion->setImplicit(true); 1434 Class->addDecl(Conversion); 1435 } 1436 1437 ExprResult Sema::BuildCaptureInit(const Capture &Cap, 1438 SourceLocation ImplicitCaptureLoc, 1439 bool IsOpenMPMapping) { 1440 // VLA captures don't have a stored initialization expression. 1441 if (Cap.isVLATypeCapture()) 1442 return ExprResult(); 1443 1444 // An init-capture is initialized directly from its stored initializer. 1445 if (Cap.isInitCapture()) 1446 return Cap.getVariable()->getInit(); 1447 1448 // For anything else, build an initialization expression. For an implicit 1449 // capture, the capture notionally happens at the capture-default, so use 1450 // that location here. 1451 SourceLocation Loc = 1452 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation(); 1453 1454 // C++11 [expr.prim.lambda]p21: 1455 // When the lambda-expression is evaluated, the entities that 1456 // are captured by copy are used to direct-initialize each 1457 // corresponding non-static data member of the resulting closure 1458 // object. (For array members, the array elements are 1459 // direct-initialized in increasing subscript order.) These 1460 // initializations are performed in the (unspecified) order in 1461 // which the non-static data members are declared. 1462 1463 // C++ [expr.prim.lambda]p12: 1464 // An entity captured by a lambda-expression is odr-used (3.2) in 1465 // the scope containing the lambda-expression. 1466 ExprResult Init; 1467 IdentifierInfo *Name = nullptr; 1468 if (Cap.isThisCapture()) { 1469 QualType ThisTy = getCurrentThisType(); 1470 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid()); 1471 if (Cap.isCopyCapture()) 1472 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 1473 else 1474 Init = This; 1475 } else { 1476 assert(Cap.isVariableCapture() && "unknown kind of capture"); 1477 VarDecl *Var = Cap.getVariable(); 1478 Name = Var->getIdentifier(); 1479 Init = BuildDeclarationNameExpr( 1480 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 1481 } 1482 1483 // In OpenMP, the capture kind doesn't actually describe how to capture: 1484 // variables are "mapped" onto the device in a process that does not formally 1485 // make a copy, even for a "copy capture". 1486 if (IsOpenMPMapping) 1487 return Init; 1488 1489 if (Init.isInvalid()) 1490 return ExprError(); 1491 1492 Expr *InitExpr = Init.get(); 1493 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture( 1494 Name, Cap.getCaptureType(), Loc); 1495 InitializationKind InitKind = 1496 InitializationKind::CreateDirect(Loc, Loc, Loc); 1497 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr); 1498 return InitSeq.Perform(*this, Entity, InitKind, InitExpr); 1499 } 1500 1501 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 1502 Scope *CurScope) { 1503 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); 1504 ActOnFinishFunctionBody(LSI.CallOperator, Body); 1505 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); 1506 } 1507 1508 static LambdaCaptureDefault 1509 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) { 1510 switch (ICS) { 1511 case CapturingScopeInfo::ImpCap_None: 1512 return LCD_None; 1513 case CapturingScopeInfo::ImpCap_LambdaByval: 1514 return LCD_ByCopy; 1515 case CapturingScopeInfo::ImpCap_CapturedRegion: 1516 case CapturingScopeInfo::ImpCap_LambdaByref: 1517 return LCD_ByRef; 1518 case CapturingScopeInfo::ImpCap_Block: 1519 llvm_unreachable("block capture in lambda"); 1520 } 1521 llvm_unreachable("Unknown implicit capture style"); 1522 } 1523 1524 bool Sema::CaptureHasSideEffects(const Capture &From) { 1525 if (From.isInitCapture()) { 1526 Expr *Init = From.getVariable()->getInit(); 1527 if (Init && Init->HasSideEffects(Context)) 1528 return true; 1529 } 1530 1531 if (!From.isCopyCapture()) 1532 return false; 1533 1534 const QualType T = From.isThisCapture() 1535 ? getCurrentThisType()->getPointeeType() 1536 : From.getCaptureType(); 1537 1538 if (T.isVolatileQualified()) 1539 return true; 1540 1541 const Type *BaseT = T->getBaseElementTypeUnsafe(); 1542 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl()) 1543 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() || 1544 !RD->hasTrivialDestructor(); 1545 1546 return false; 1547 } 1548 1549 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 1550 const Capture &From) { 1551 if (CaptureHasSideEffects(From)) 1552 return false; 1553 1554 if (From.isVLATypeCapture()) 1555 return false; 1556 1557 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture); 1558 if (From.isThisCapture()) 1559 diag << "'this'"; 1560 else 1561 diag << From.getVariable(); 1562 diag << From.isNonODRUsed(); 1563 diag << FixItHint::CreateRemoval(CaptureRange); 1564 return true; 1565 } 1566 1567 /// Create a field within the lambda class or captured statement record for the 1568 /// given capture. 1569 FieldDecl *Sema::BuildCaptureField(RecordDecl *RD, 1570 const sema::Capture &Capture) { 1571 SourceLocation Loc = Capture.getLocation(); 1572 QualType FieldType = Capture.getCaptureType(); 1573 1574 TypeSourceInfo *TSI = nullptr; 1575 if (Capture.isVariableCapture()) { 1576 auto *Var = Capture.getVariable(); 1577 if (Var->isInitCapture()) 1578 TSI = Capture.getVariable()->getTypeSourceInfo(); 1579 } 1580 1581 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more 1582 // appropriate, at least for an implicit capture. 1583 if (!TSI) 1584 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc); 1585 1586 // Build the non-static data member. 1587 FieldDecl *Field = 1588 FieldDecl::Create(Context, RD, Loc, Loc, nullptr, FieldType, TSI, nullptr, 1589 false, ICIS_NoInit); 1590 // If the variable being captured has an invalid type, mark the class as 1591 // invalid as well. 1592 if (!FieldType->isDependentType()) { 1593 if (RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 1594 RD->setInvalidDecl(); 1595 Field->setInvalidDecl(); 1596 } else { 1597 NamedDecl *Def; 1598 FieldType->isIncompleteType(&Def); 1599 if (Def && Def->isInvalidDecl()) { 1600 RD->setInvalidDecl(); 1601 Field->setInvalidDecl(); 1602 } 1603 } 1604 } 1605 Field->setImplicit(true); 1606 Field->setAccess(AS_private); 1607 RD->addDecl(Field); 1608 1609 if (Capture.isVLATypeCapture()) 1610 Field->setCapturedVLAType(Capture.getCapturedVLAType()); 1611 1612 return Field; 1613 } 1614 1615 ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 1616 LambdaScopeInfo *LSI) { 1617 // Collect information from the lambda scope. 1618 SmallVector<LambdaCapture, 4> Captures; 1619 SmallVector<Expr *, 4> CaptureInits; 1620 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc; 1621 LambdaCaptureDefault CaptureDefault = 1622 mapImplicitCaptureStyle(LSI->ImpCaptureStyle); 1623 CXXRecordDecl *Class; 1624 CXXMethodDecl *CallOperator; 1625 SourceRange IntroducerRange; 1626 bool ExplicitParams; 1627 bool ExplicitResultType; 1628 CleanupInfo LambdaCleanup; 1629 bool ContainsUnexpandedParameterPack; 1630 bool IsGenericLambda; 1631 { 1632 CallOperator = LSI->CallOperator; 1633 Class = LSI->Lambda; 1634 IntroducerRange = LSI->IntroducerRange; 1635 ExplicitParams = LSI->ExplicitParams; 1636 ExplicitResultType = !LSI->HasImplicitReturnType; 1637 LambdaCleanup = LSI->Cleanup; 1638 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; 1639 IsGenericLambda = Class->isGenericLambda(); 1640 1641 CallOperator->setLexicalDeclContext(Class); 1642 Decl *TemplateOrNonTemplateCallOperatorDecl = 1643 CallOperator->getDescribedFunctionTemplate() 1644 ? CallOperator->getDescribedFunctionTemplate() 1645 : cast<Decl>(CallOperator); 1646 1647 // FIXME: Is this really the best choice? Keeping the lexical decl context 1648 // set as CurContext seems more faithful to the source. 1649 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); 1650 1651 PopExpressionEvaluationContext(); 1652 1653 // True if the current capture has a used capture or default before it. 1654 bool CurHasPreviousCapture = CaptureDefault != LCD_None; 1655 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ? 1656 CaptureDefaultLoc : IntroducerRange.getBegin(); 1657 1658 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 1659 const Capture &From = LSI->Captures[I]; 1660 1661 if (From.isInvalid()) 1662 return ExprError(); 1663 1664 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 1665 bool IsImplicit = I >= LSI->NumExplicitCaptures; 1666 SourceLocation ImplicitCaptureLoc = 1667 IsImplicit ? CaptureDefaultLoc : SourceLocation(); 1668 1669 // Use source ranges of explicit captures for fixits where available. 1670 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I]; 1671 1672 // Warn about unused explicit captures. 1673 bool IsCaptureUsed = true; 1674 if (!CurContext->isDependentContext() && !IsImplicit && 1675 !From.isODRUsed()) { 1676 // Initialized captures that are non-ODR used may not be eliminated. 1677 // FIXME: Where did the IsGenericLambda here come from? 1678 bool NonODRUsedInitCapture = 1679 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture(); 1680 if (!NonODRUsedInitCapture) { 1681 bool IsLast = (I + 1) == LSI->NumExplicitCaptures; 1682 SourceRange FixItRange; 1683 if (CaptureRange.isValid()) { 1684 if (!CurHasPreviousCapture && !IsLast) { 1685 // If there are no captures preceding this capture, remove the 1686 // following comma. 1687 FixItRange = SourceRange(CaptureRange.getBegin(), 1688 getLocForEndOfToken(CaptureRange.getEnd())); 1689 } else { 1690 // Otherwise, remove the comma since the last used capture. 1691 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc), 1692 CaptureRange.getEnd()); 1693 } 1694 } 1695 1696 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From); 1697 } 1698 } 1699 1700 if (CaptureRange.isValid()) { 1701 CurHasPreviousCapture |= IsCaptureUsed; 1702 PrevCaptureLoc = CaptureRange.getEnd(); 1703 } 1704 1705 // Map the capture to our AST representation. 1706 LambdaCapture Capture = [&] { 1707 if (From.isThisCapture()) { 1708 // Capturing 'this' implicitly with a default of '[=]' is deprecated, 1709 // because it results in a reference capture. Don't warn prior to 1710 // C++2a; there's nothing that can be done about it before then. 1711 if (getLangOpts().CPlusPlus2a && IsImplicit && 1712 CaptureDefault == LCD_ByCopy) { 1713 Diag(From.getLocation(), diag::warn_deprecated_this_capture); 1714 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture) 1715 << FixItHint::CreateInsertion( 1716 getLocForEndOfToken(CaptureDefaultLoc), ", this"); 1717 } 1718 return LambdaCapture(From.getLocation(), IsImplicit, 1719 From.isCopyCapture() ? LCK_StarThis : LCK_This); 1720 } else if (From.isVLATypeCapture()) { 1721 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType); 1722 } else { 1723 assert(From.isVariableCapture() && "unknown kind of capture"); 1724 VarDecl *Var = From.getVariable(); 1725 LambdaCaptureKind Kind = 1726 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef; 1727 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var, 1728 From.getEllipsisLoc()); 1729 } 1730 }(); 1731 1732 // Form the initializer for the capture field. 1733 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc); 1734 1735 // FIXME: Skip this capture if the capture is not used, the initializer 1736 // has no side-effects, the type of the capture is trivial, and the 1737 // lambda is not externally visible. 1738 1739 // Add a FieldDecl for the capture and form its initializer. 1740 BuildCaptureField(Class, From); 1741 Captures.push_back(Capture); 1742 CaptureInits.push_back(Init.get()); 1743 } 1744 1745 // C++11 [expr.prim.lambda]p6: 1746 // The closure type for a lambda-expression with no lambda-capture 1747 // has a public non-virtual non-explicit const conversion function 1748 // to pointer to function having the same parameter and return 1749 // types as the closure type's function call operator. 1750 if (Captures.empty() && CaptureDefault == LCD_None) 1751 addFunctionPointerConversion(*this, IntroducerRange, Class, 1752 CallOperator); 1753 1754 // Objective-C++: 1755 // The closure type for a lambda-expression has a public non-virtual 1756 // non-explicit const conversion function to a block pointer having the 1757 // same parameter and return types as the closure type's function call 1758 // operator. 1759 // FIXME: Fix generic lambda to block conversions. 1760 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda) 1761 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 1762 1763 // Finalize the lambda class. 1764 SmallVector<Decl*, 4> Fields(Class->fields()); 1765 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 1766 SourceLocation(), ParsedAttributesView()); 1767 CheckCompletedCXXClass(Class); 1768 } 1769 1770 Cleanup.mergeFrom(LambdaCleanup); 1771 1772 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 1773 CaptureDefault, CaptureDefaultLoc, 1774 Captures, 1775 ExplicitParams, ExplicitResultType, 1776 CaptureInits, EndLoc, 1777 ContainsUnexpandedParameterPack); 1778 // If the lambda expression's call operator is not explicitly marked constexpr 1779 // and we are not in a dependent context, analyze the call operator to infer 1780 // its constexpr-ness, suppressing diagnostics while doing so. 1781 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() && 1782 !CallOperator->isConstexpr() && 1783 !isa<CoroutineBodyStmt>(CallOperator->getBody()) && 1784 !Class->getDeclContext()->isDependentContext()) { 1785 CallOperator->setConstexprKind( 1786 CheckConstexprFunctionDefinition(CallOperator, 1787 CheckConstexprKind::CheckValid) 1788 ? CSK_constexpr 1789 : CSK_unspecified); 1790 } 1791 1792 // Emit delayed shadowing warnings now that the full capture list is known. 1793 DiagnoseShadowingLambdaDecls(LSI); 1794 1795 if (!CurContext->isDependentContext()) { 1796 switch (ExprEvalContexts.back().Context) { 1797 // C++11 [expr.prim.lambda]p2: 1798 // A lambda-expression shall not appear in an unevaluated operand 1799 // (Clause 5). 1800 case ExpressionEvaluationContext::Unevaluated: 1801 case ExpressionEvaluationContext::UnevaluatedList: 1802 case ExpressionEvaluationContext::UnevaluatedAbstract: 1803 // C++1y [expr.const]p2: 1804 // A conditional-expression e is a core constant expression unless the 1805 // evaluation of e, following the rules of the abstract machine, would 1806 // evaluate [...] a lambda-expression. 1807 // 1808 // This is technically incorrect, there are some constant evaluated contexts 1809 // where this should be allowed. We should probably fix this when DR1607 is 1810 // ratified, it lays out the exact set of conditions where we shouldn't 1811 // allow a lambda-expression. 1812 case ExpressionEvaluationContext::ConstantEvaluated: 1813 // We don't actually diagnose this case immediately, because we 1814 // could be within a context where we might find out later that 1815 // the expression is potentially evaluated (e.g., for typeid). 1816 ExprEvalContexts.back().Lambdas.push_back(Lambda); 1817 break; 1818 1819 case ExpressionEvaluationContext::DiscardedStatement: 1820 case ExpressionEvaluationContext::PotentiallyEvaluated: 1821 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 1822 break; 1823 } 1824 } 1825 1826 return MaybeBindToTemporary(Lambda); 1827 } 1828 1829 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 1830 SourceLocation ConvLocation, 1831 CXXConversionDecl *Conv, 1832 Expr *Src) { 1833 // Make sure that the lambda call operator is marked used. 1834 CXXRecordDecl *Lambda = Conv->getParent(); 1835 CXXMethodDecl *CallOperator 1836 = cast<CXXMethodDecl>( 1837 Lambda->lookup( 1838 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 1839 CallOperator->setReferenced(); 1840 CallOperator->markUsed(Context); 1841 1842 ExprResult Init = PerformCopyInitialization( 1843 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(), 1844 /*NRVO=*/false), 1845 CurrentLocation, Src); 1846 if (!Init.isInvalid()) 1847 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 1848 1849 if (Init.isInvalid()) 1850 return ExprError(); 1851 1852 // Create the new block to be returned. 1853 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); 1854 1855 // Set the type information. 1856 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); 1857 Block->setIsVariadic(CallOperator->isVariadic()); 1858 Block->setBlockMissingReturnType(false); 1859 1860 // Add parameters. 1861 SmallVector<ParmVarDecl *, 4> BlockParams; 1862 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 1863 ParmVarDecl *From = CallOperator->getParamDecl(I); 1864 BlockParams.push_back(ParmVarDecl::Create( 1865 Context, Block, From->getBeginLoc(), From->getLocation(), 1866 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(), 1867 From->getStorageClass(), 1868 /*DefArg=*/nullptr)); 1869 } 1870 Block->setParams(BlockParams); 1871 1872 Block->setIsConversionFromLambda(true); 1873 1874 // Add capture. The capture uses a fake variable, which doesn't correspond 1875 // to any actual memory location. However, the initializer copy-initializes 1876 // the lambda object. 1877 TypeSourceInfo *CapVarTSI = 1878 Context.getTrivialTypeSourceInfo(Src->getType()); 1879 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, 1880 ConvLocation, nullptr, 1881 Src->getType(), CapVarTSI, 1882 SC_None); 1883 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false, 1884 /*nested=*/false, /*copy=*/Init.get()); 1885 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false); 1886 1887 // Add a fake function body to the block. IR generation is responsible 1888 // for filling in the actual body, which cannot be expressed as an AST. 1889 Block->setBody(new (Context) CompoundStmt(ConvLocation)); 1890 1891 // Create the block literal expression. 1892 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); 1893 ExprCleanupObjects.push_back(Block); 1894 Cleanup.setExprNeedsCleanups(true); 1895 1896 return BuildBlock; 1897 } 1898