1 //===- CoroSplit.cpp - Converts a coroutine into a state machine ----------===// 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 // This pass builds the coroutine frame and outlines resume and destroy parts 9 // of the coroutine into separate functions. 10 // 11 // We present a coroutine to an LLVM as an ordinary function with suspension 12 // points marked up with intrinsics. We let the optimizer party on the coroutine 13 // as a single function for as long as possible. Shortly before the coroutine is 14 // eligible to be inlined into its callers, we split up the coroutine into parts 15 // corresponding to an initial, resume and destroy invocations of the coroutine, 16 // add them to the current SCC and restart the IPO pipeline to optimize the 17 // coroutine subfunctions we extracted before proceeding to the caller of the 18 // coroutine. 19 //===----------------------------------------------------------------------===// 20 21 #include "llvm/Transforms/Coroutines/CoroSplit.h" 22 #include "CoroInstr.h" 23 #include "CoroInternal.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/CallGraph.h" 30 #include "llvm/Analysis/CallGraphSCCPass.h" 31 #include "llvm/Analysis/LazyCallGraph.h" 32 #include "llvm/IR/Argument.h" 33 #include "llvm/IR/Attributes.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/CFG.h" 36 #include "llvm/IR/CallingConv.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/DataLayout.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalValue.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/IRBuilder.h" 44 #include "llvm/IR/InstIterator.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/Instruction.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/LegacyPassManager.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/IR/Type.h" 53 #include "llvm/IR/Value.h" 54 #include "llvm/IR/Verifier.h" 55 #include "llvm/InitializePasses.h" 56 #include "llvm/Pass.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/PrettyStackTrace.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Transforms/Scalar.h" 62 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 63 #include "llvm/Transforms/Utils/CallGraphUpdater.h" 64 #include "llvm/Transforms/Utils/Cloning.h" 65 #include "llvm/Transforms/Utils/Local.h" 66 #include "llvm/Transforms/Utils/ValueMapper.h" 67 #include <cassert> 68 #include <cstddef> 69 #include <cstdint> 70 #include <initializer_list> 71 #include <iterator> 72 73 using namespace llvm; 74 75 #define DEBUG_TYPE "coro-split" 76 77 namespace { 78 79 /// A little helper class for building 80 class CoroCloner { 81 public: 82 enum class Kind { 83 /// The shared resume function for a switch lowering. 84 SwitchResume, 85 86 /// The shared unwind function for a switch lowering. 87 SwitchUnwind, 88 89 /// The shared cleanup function for a switch lowering. 90 SwitchCleanup, 91 92 /// An individual continuation function. 93 Continuation, 94 95 /// An async resume function. 96 Async, 97 }; 98 99 private: 100 Function &OrigF; 101 Function *NewF; 102 const Twine &Suffix; 103 coro::Shape &Shape; 104 Kind FKind; 105 ValueToValueMapTy VMap; 106 IRBuilder<> Builder; 107 Value *NewFramePtr = nullptr; 108 109 /// The active suspend instruction; meaningful only for continuation and async 110 /// ABIs. 111 AnyCoroSuspendInst *ActiveSuspend = nullptr; 112 113 public: 114 /// Create a cloner for a switch lowering. 115 CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, 116 Kind FKind) 117 : OrigF(OrigF), NewF(nullptr), Suffix(Suffix), Shape(Shape), 118 FKind(FKind), Builder(OrigF.getContext()) { 119 assert(Shape.ABI == coro::ABI::Switch); 120 } 121 122 /// Create a cloner for a continuation lowering. 123 CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, 124 Function *NewF, AnyCoroSuspendInst *ActiveSuspend) 125 : OrigF(OrigF), NewF(NewF), Suffix(Suffix), Shape(Shape), 126 FKind(Shape.ABI == coro::ABI::Async ? Kind::Async : Kind::Continuation), 127 Builder(OrigF.getContext()), ActiveSuspend(ActiveSuspend) { 128 assert(Shape.ABI == coro::ABI::Retcon || 129 Shape.ABI == coro::ABI::RetconOnce || Shape.ABI == coro::ABI::Async); 130 assert(NewF && "need existing function for continuation"); 131 assert(ActiveSuspend && "need active suspend point for continuation"); 132 } 133 134 Function *getFunction() const { 135 assert(NewF != nullptr && "declaration not yet set"); 136 return NewF; 137 } 138 139 void create(); 140 141 private: 142 bool isSwitchDestroyFunction() { 143 switch (FKind) { 144 case Kind::Async: 145 case Kind::Continuation: 146 case Kind::SwitchResume: 147 return false; 148 case Kind::SwitchUnwind: 149 case Kind::SwitchCleanup: 150 return true; 151 } 152 llvm_unreachable("Unknown CoroCloner::Kind enum"); 153 } 154 155 void replaceEntryBlock(); 156 Value *deriveNewFramePointer(); 157 void replaceRetconOrAsyncSuspendUses(); 158 void replaceCoroSuspends(); 159 void replaceCoroEnds(); 160 void replaceSwiftErrorOps(); 161 void salvageDebugInfo(); 162 void handleFinalSuspend(); 163 }; 164 165 } // end anonymous namespace 166 167 static void maybeFreeRetconStorage(IRBuilder<> &Builder, 168 const coro::Shape &Shape, Value *FramePtr, 169 CallGraph *CG) { 170 assert(Shape.ABI == coro::ABI::Retcon || 171 Shape.ABI == coro::ABI::RetconOnce); 172 if (Shape.RetconLowering.IsFrameInlineInStorage) 173 return; 174 175 Shape.emitDealloc(Builder, FramePtr, CG); 176 } 177 178 /// Replace an llvm.coro.end.async. 179 /// Will inline the must tail call function call if there is one. 180 /// \returns true if cleanup of the coro.end block is needed, false otherwise. 181 static bool replaceCoroEndAsync(AnyCoroEndInst *End) { 182 IRBuilder<> Builder(End); 183 184 auto *EndAsync = dyn_cast<CoroAsyncEndInst>(End); 185 if (!EndAsync) { 186 Builder.CreateRetVoid(); 187 return true /*needs cleanup of coro.end block*/; 188 } 189 190 auto *MustTailCallFunc = EndAsync->getMustTailCallFunction(); 191 if (!MustTailCallFunc) { 192 Builder.CreateRetVoid(); 193 return true /*needs cleanup of coro.end block*/; 194 } 195 196 // Move the must tail call from the predecessor block into the end block. 197 auto *CoroEndBlock = End->getParent(); 198 auto *MustTailCallFuncBlock = CoroEndBlock->getSinglePredecessor(); 199 assert(MustTailCallFuncBlock && "Must have a single predecessor block"); 200 auto It = MustTailCallFuncBlock->getTerminator()->getIterator(); 201 auto *MustTailCall = cast<CallInst>(&*std::prev(It)); 202 CoroEndBlock->getInstList().splice( 203 End->getIterator(), MustTailCallFuncBlock->getInstList(), MustTailCall); 204 205 // Insert the return instruction. 206 Builder.SetInsertPoint(End); 207 Builder.CreateRetVoid(); 208 InlineFunctionInfo FnInfo; 209 210 // Remove the rest of the block, by splitting it into an unreachable block. 211 auto *BB = End->getParent(); 212 BB->splitBasicBlock(End); 213 BB->getTerminator()->eraseFromParent(); 214 215 auto InlineRes = InlineFunction(*MustTailCall, FnInfo); 216 assert(InlineRes.isSuccess() && "Expected inlining to succeed"); 217 (void)InlineRes; 218 219 // We have cleaned up the coro.end block above. 220 return false; 221 } 222 223 /// Replace a non-unwind call to llvm.coro.end. 224 static void replaceFallthroughCoroEnd(AnyCoroEndInst *End, 225 const coro::Shape &Shape, Value *FramePtr, 226 bool InResume, CallGraph *CG) { 227 // Start inserting right before the coro.end. 228 IRBuilder<> Builder(End); 229 230 // Create the return instruction. 231 switch (Shape.ABI) { 232 // The cloned functions in switch-lowering always return void. 233 case coro::ABI::Switch: 234 // coro.end doesn't immediately end the coroutine in the main function 235 // in this lowering, because we need to deallocate the coroutine. 236 if (!InResume) 237 return; 238 Builder.CreateRetVoid(); 239 break; 240 241 // In async lowering this returns. 242 case coro::ABI::Async: { 243 bool CoroEndBlockNeedsCleanup = replaceCoroEndAsync(End); 244 if (!CoroEndBlockNeedsCleanup) 245 return; 246 break; 247 } 248 249 // In unique continuation lowering, the continuations always return void. 250 // But we may have implicitly allocated storage. 251 case coro::ABI::RetconOnce: 252 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 253 Builder.CreateRetVoid(); 254 break; 255 256 // In non-unique continuation lowering, we signal completion by returning 257 // a null continuation. 258 case coro::ABI::Retcon: { 259 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 260 auto RetTy = Shape.getResumeFunctionType()->getReturnType(); 261 auto RetStructTy = dyn_cast<StructType>(RetTy); 262 PointerType *ContinuationTy = 263 cast<PointerType>(RetStructTy ? RetStructTy->getElementType(0) : RetTy); 264 265 Value *ReturnValue = ConstantPointerNull::get(ContinuationTy); 266 if (RetStructTy) { 267 ReturnValue = Builder.CreateInsertValue(UndefValue::get(RetStructTy), 268 ReturnValue, 0); 269 } 270 Builder.CreateRet(ReturnValue); 271 break; 272 } 273 } 274 275 // Remove the rest of the block, by splitting it into an unreachable block. 276 auto *BB = End->getParent(); 277 BB->splitBasicBlock(End); 278 BB->getTerminator()->eraseFromParent(); 279 } 280 281 /// Replace an unwind call to llvm.coro.end. 282 static void replaceUnwindCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, 283 Value *FramePtr, bool InResume, 284 CallGraph *CG) { 285 IRBuilder<> Builder(End); 286 287 switch (Shape.ABI) { 288 // In switch-lowering, this does nothing in the main function. 289 case coro::ABI::Switch: 290 if (!InResume) 291 return; 292 break; 293 // In async lowering this does nothing. 294 case coro::ABI::Async: 295 break; 296 // In continuation-lowering, this frees the continuation storage. 297 case coro::ABI::Retcon: 298 case coro::ABI::RetconOnce: 299 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 300 break; 301 } 302 303 // If coro.end has an associated bundle, add cleanupret instruction. 304 if (auto Bundle = End->getOperandBundle(LLVMContext::OB_funclet)) { 305 auto *FromPad = cast<CleanupPadInst>(Bundle->Inputs[0]); 306 auto *CleanupRet = Builder.CreateCleanupRet(FromPad, nullptr); 307 End->getParent()->splitBasicBlock(End); 308 CleanupRet->getParent()->getTerminator()->eraseFromParent(); 309 } 310 } 311 312 static void replaceCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, 313 Value *FramePtr, bool InResume, CallGraph *CG) { 314 if (End->isUnwind()) 315 replaceUnwindCoroEnd(End, Shape, FramePtr, InResume, CG); 316 else 317 replaceFallthroughCoroEnd(End, Shape, FramePtr, InResume, CG); 318 319 auto &Context = End->getContext(); 320 End->replaceAllUsesWith(InResume ? ConstantInt::getTrue(Context) 321 : ConstantInt::getFalse(Context)); 322 End->eraseFromParent(); 323 } 324 325 // Create an entry block for a resume function with a switch that will jump to 326 // suspend points. 327 static void createResumeEntryBlock(Function &F, coro::Shape &Shape) { 328 assert(Shape.ABI == coro::ABI::Switch); 329 LLVMContext &C = F.getContext(); 330 331 // resume.entry: 332 // %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0, 333 // i32 2 334 // % index = load i32, i32* %index.addr 335 // switch i32 %index, label %unreachable [ 336 // i32 0, label %resume.0 337 // i32 1, label %resume.1 338 // ... 339 // ] 340 341 auto *NewEntry = BasicBlock::Create(C, "resume.entry", &F); 342 auto *UnreachBB = BasicBlock::Create(C, "unreachable", &F); 343 344 IRBuilder<> Builder(NewEntry); 345 auto *FramePtr = Shape.FramePtr; 346 auto *FrameTy = Shape.FrameTy; 347 auto *GepIndex = Builder.CreateStructGEP( 348 FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr"); 349 auto *Index = Builder.CreateLoad(Shape.getIndexType(), GepIndex, "index"); 350 auto *Switch = 351 Builder.CreateSwitch(Index, UnreachBB, Shape.CoroSuspends.size()); 352 Shape.SwitchLowering.ResumeSwitch = Switch; 353 354 size_t SuspendIndex = 0; 355 for (auto *AnyS : Shape.CoroSuspends) { 356 auto *S = cast<CoroSuspendInst>(AnyS); 357 ConstantInt *IndexVal = Shape.getIndex(SuspendIndex); 358 359 // Replace CoroSave with a store to Index: 360 // %index.addr = getelementptr %f.frame... (index field number) 361 // store i32 0, i32* %index.addr1 362 auto *Save = S->getCoroSave(); 363 Builder.SetInsertPoint(Save); 364 if (S->isFinal()) { 365 // Final suspend point is represented by storing zero in ResumeFnAddr. 366 auto *GepIndex = Builder.CreateStructGEP(FrameTy, FramePtr, 367 coro::Shape::SwitchFieldIndex::Resume, 368 "ResumeFn.addr"); 369 auto *NullPtr = ConstantPointerNull::get(cast<PointerType>( 370 cast<PointerType>(GepIndex->getType())->getElementType())); 371 Builder.CreateStore(NullPtr, GepIndex); 372 } else { 373 auto *GepIndex = Builder.CreateStructGEP( 374 FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr"); 375 Builder.CreateStore(IndexVal, GepIndex); 376 } 377 Save->replaceAllUsesWith(ConstantTokenNone::get(C)); 378 Save->eraseFromParent(); 379 380 // Split block before and after coro.suspend and add a jump from an entry 381 // switch: 382 // 383 // whateverBB: 384 // whatever 385 // %0 = call i8 @llvm.coro.suspend(token none, i1 false) 386 // switch i8 %0, label %suspend[i8 0, label %resume 387 // i8 1, label %cleanup] 388 // becomes: 389 // 390 // whateverBB: 391 // whatever 392 // br label %resume.0.landing 393 // 394 // resume.0: ; <--- jump from the switch in the resume.entry 395 // %0 = tail call i8 @llvm.coro.suspend(token none, i1 false) 396 // br label %resume.0.landing 397 // 398 // resume.0.landing: 399 // %1 = phi i8[-1, %whateverBB], [%0, %resume.0] 400 // switch i8 % 1, label %suspend [i8 0, label %resume 401 // i8 1, label %cleanup] 402 403 auto *SuspendBB = S->getParent(); 404 auto *ResumeBB = 405 SuspendBB->splitBasicBlock(S, "resume." + Twine(SuspendIndex)); 406 auto *LandingBB = ResumeBB->splitBasicBlock( 407 S->getNextNode(), ResumeBB->getName() + Twine(".landing")); 408 Switch->addCase(IndexVal, ResumeBB); 409 410 cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB); 411 auto *PN = PHINode::Create(Builder.getInt8Ty(), 2, "", &LandingBB->front()); 412 S->replaceAllUsesWith(PN); 413 PN->addIncoming(Builder.getInt8(-1), SuspendBB); 414 PN->addIncoming(S, ResumeBB); 415 416 ++SuspendIndex; 417 } 418 419 Builder.SetInsertPoint(UnreachBB); 420 Builder.CreateUnreachable(); 421 422 Shape.SwitchLowering.ResumeEntryBlock = NewEntry; 423 } 424 425 426 // Rewrite final suspend point handling. We do not use suspend index to 427 // represent the final suspend point. Instead we zero-out ResumeFnAddr in the 428 // coroutine frame, since it is undefined behavior to resume a coroutine 429 // suspended at the final suspend point. Thus, in the resume function, we can 430 // simply remove the last case (when coro::Shape is built, the final suspend 431 // point (if present) is always the last element of CoroSuspends array). 432 // In the destroy function, we add a code sequence to check if ResumeFnAddress 433 // is Null, and if so, jump to the appropriate label to handle cleanup from the 434 // final suspend point. 435 void CoroCloner::handleFinalSuspend() { 436 assert(Shape.ABI == coro::ABI::Switch && 437 Shape.SwitchLowering.HasFinalSuspend); 438 auto *Switch = cast<SwitchInst>(VMap[Shape.SwitchLowering.ResumeSwitch]); 439 auto FinalCaseIt = std::prev(Switch->case_end()); 440 BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor(); 441 Switch->removeCase(FinalCaseIt); 442 if (isSwitchDestroyFunction()) { 443 BasicBlock *OldSwitchBB = Switch->getParent(); 444 auto *NewSwitchBB = OldSwitchBB->splitBasicBlock(Switch, "Switch"); 445 Builder.SetInsertPoint(OldSwitchBB->getTerminator()); 446 auto *GepIndex = Builder.CreateStructGEP(Shape.FrameTy, NewFramePtr, 447 coro::Shape::SwitchFieldIndex::Resume, 448 "ResumeFn.addr"); 449 auto *Load = Builder.CreateLoad(Shape.getSwitchResumePointerType(), 450 GepIndex); 451 auto *Cond = Builder.CreateIsNull(Load); 452 Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB); 453 OldSwitchBB->getTerminator()->eraseFromParent(); 454 } 455 } 456 457 static Function *createCloneDeclaration(Function &OrigF, coro::Shape &Shape, 458 const Twine &Suffix, 459 Module::iterator InsertBefore) { 460 Module *M = OrigF.getParent(); 461 auto *FnTy = Shape.getResumeFunctionType(); 462 463 Function *NewF = 464 Function::Create(FnTy, GlobalValue::LinkageTypes::InternalLinkage, 465 OrigF.getName() + Suffix); 466 NewF->addParamAttr(0, Attribute::NonNull); 467 468 // For the async lowering ABI we can't guarantee that the context argument is 469 // not access via a different pointer not based on the argument. 470 if (Shape.ABI != coro::ABI::Async) 471 NewF->addParamAttr(0, Attribute::NoAlias); 472 473 M->getFunctionList().insert(InsertBefore, NewF); 474 475 return NewF; 476 } 477 478 /// Replace uses of the active llvm.coro.suspend.retcon/async call with the 479 /// arguments to the continuation function. 480 /// 481 /// This assumes that the builder has a meaningful insertion point. 482 void CoroCloner::replaceRetconOrAsyncSuspendUses() { 483 assert(Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce || 484 Shape.ABI == coro::ABI::Async); 485 486 auto NewS = VMap[ActiveSuspend]; 487 if (NewS->use_empty()) return; 488 489 // Copy out all the continuation arguments after the buffer pointer into 490 // an easily-indexed data structure for convenience. 491 SmallVector<Value*, 8> Args; 492 // The async ABI includes all arguments -- including the first argument. 493 bool IsAsyncABI = Shape.ABI == coro::ABI::Async; 494 for (auto I = IsAsyncABI ? NewF->arg_begin() : std::next(NewF->arg_begin()), 495 E = NewF->arg_end(); 496 I != E; ++I) 497 Args.push_back(&*I); 498 499 // If the suspend returns a single scalar value, we can just do a simple 500 // replacement. 501 if (!isa<StructType>(NewS->getType())) { 502 assert(Args.size() == 1); 503 NewS->replaceAllUsesWith(Args.front()); 504 return; 505 } 506 507 // Try to peephole extracts of an aggregate return. 508 for (auto UI = NewS->use_begin(), UE = NewS->use_end(); UI != UE; ) { 509 auto EVI = dyn_cast<ExtractValueInst>((UI++)->getUser()); 510 if (!EVI || EVI->getNumIndices() != 1) 511 continue; 512 513 EVI->replaceAllUsesWith(Args[EVI->getIndices().front()]); 514 EVI->eraseFromParent(); 515 } 516 517 // If we have no remaining uses, we're done. 518 if (NewS->use_empty()) return; 519 520 // Otherwise, we need to create an aggregate. 521 Value *Agg = UndefValue::get(NewS->getType()); 522 for (size_t I = 0, E = Args.size(); I != E; ++I) 523 Agg = Builder.CreateInsertValue(Agg, Args[I], I); 524 525 NewS->replaceAllUsesWith(Agg); 526 } 527 528 void CoroCloner::replaceCoroSuspends() { 529 Value *SuspendResult; 530 531 switch (Shape.ABI) { 532 // In switch lowering, replace coro.suspend with the appropriate value 533 // for the type of function we're extracting. 534 // Replacing coro.suspend with (0) will result in control flow proceeding to 535 // a resume label associated with a suspend point, replacing it with (1) will 536 // result in control flow proceeding to a cleanup label associated with this 537 // suspend point. 538 case coro::ABI::Switch: 539 SuspendResult = Builder.getInt8(isSwitchDestroyFunction() ? 1 : 0); 540 break; 541 542 // In async lowering there are no uses of the result. 543 case coro::ABI::Async: 544 return; 545 546 // In returned-continuation lowering, the arguments from earlier 547 // continuations are theoretically arbitrary, and they should have been 548 // spilled. 549 case coro::ABI::RetconOnce: 550 case coro::ABI::Retcon: 551 return; 552 } 553 554 for (AnyCoroSuspendInst *CS : Shape.CoroSuspends) { 555 // The active suspend was handled earlier. 556 if (CS == ActiveSuspend) continue; 557 558 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[CS]); 559 MappedCS->replaceAllUsesWith(SuspendResult); 560 MappedCS->eraseFromParent(); 561 } 562 } 563 564 void CoroCloner::replaceCoroEnds() { 565 for (AnyCoroEndInst *CE : Shape.CoroEnds) { 566 // We use a null call graph because there's no call graph node for 567 // the cloned function yet. We'll just be rebuilding that later. 568 auto *NewCE = cast<AnyCoroEndInst>(VMap[CE]); 569 replaceCoroEnd(NewCE, Shape, NewFramePtr, /*in resume*/ true, nullptr); 570 } 571 } 572 573 static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape, 574 ValueToValueMapTy *VMap) { 575 Value *CachedSlot = nullptr; 576 auto getSwiftErrorSlot = [&](Type *ValueTy) -> Value * { 577 if (CachedSlot) { 578 assert(CachedSlot->getType()->getPointerElementType() == ValueTy && 579 "multiple swifterror slots in function with different types"); 580 return CachedSlot; 581 } 582 583 // Check if the function has a swifterror argument. 584 for (auto &Arg : F.args()) { 585 if (Arg.isSwiftError()) { 586 CachedSlot = &Arg; 587 assert(Arg.getType()->getPointerElementType() == ValueTy && 588 "swifterror argument does not have expected type"); 589 return &Arg; 590 } 591 } 592 593 // Create a swifterror alloca. 594 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg()); 595 auto Alloca = Builder.CreateAlloca(ValueTy); 596 Alloca->setSwiftError(true); 597 598 CachedSlot = Alloca; 599 return Alloca; 600 }; 601 602 for (CallInst *Op : Shape.SwiftErrorOps) { 603 auto MappedOp = VMap ? cast<CallInst>((*VMap)[Op]) : Op; 604 IRBuilder<> Builder(MappedOp); 605 606 // If there are no arguments, this is a 'get' operation. 607 Value *MappedResult; 608 if (Op->getNumArgOperands() == 0) { 609 auto ValueTy = Op->getType(); 610 auto Slot = getSwiftErrorSlot(ValueTy); 611 MappedResult = Builder.CreateLoad(ValueTy, Slot); 612 } else { 613 assert(Op->getNumArgOperands() == 1); 614 auto Value = MappedOp->getArgOperand(0); 615 auto ValueTy = Value->getType(); 616 auto Slot = getSwiftErrorSlot(ValueTy); 617 Builder.CreateStore(Value, Slot); 618 MappedResult = Slot; 619 } 620 621 MappedOp->replaceAllUsesWith(MappedResult); 622 MappedOp->eraseFromParent(); 623 } 624 625 // If we're updating the original function, we've invalidated SwiftErrorOps. 626 if (VMap == nullptr) { 627 Shape.SwiftErrorOps.clear(); 628 } 629 } 630 631 void CoroCloner::replaceSwiftErrorOps() { 632 ::replaceSwiftErrorOps(*NewF, Shape, &VMap); 633 } 634 635 void CoroCloner::salvageDebugInfo() { 636 SmallVector<DbgDeclareInst *, 8> Worklist; 637 SmallDenseMap<llvm::Value *, llvm::AllocaInst *, 4> DbgPtrAllocaCache; 638 for (auto &BB : *NewF) 639 for (auto &I : BB) 640 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I)) 641 Worklist.push_back(DDI); 642 for (DbgDeclareInst *DDI : Worklist) 643 coro::salvageDebugInfo(DbgPtrAllocaCache, DDI); 644 645 // Remove all salvaged dbg.declare intrinsics that became 646 // either unreachable or stale due to the CoroSplit transformation. 647 auto IsUnreachableBlock = [&](BasicBlock *BB) { 648 return BB->hasNPredecessors(0) && BB != &NewF->getEntryBlock(); 649 }; 650 for (DbgDeclareInst *DDI : Worklist) { 651 if (IsUnreachableBlock(DDI->getParent())) 652 DDI->eraseFromParent(); 653 else if (dyn_cast_or_null<AllocaInst>(DDI->getAddress())) { 654 // Count all non-debuginfo uses in reachable blocks. 655 unsigned Uses = 0; 656 for (auto *User : DDI->getAddress()->users()) 657 if (auto *I = dyn_cast<Instruction>(User)) 658 if (!isa<AllocaInst>(I) && !IsUnreachableBlock(I->getParent())) 659 ++Uses; 660 if (!Uses) 661 DDI->eraseFromParent(); 662 } 663 } 664 } 665 666 void CoroCloner::replaceEntryBlock() { 667 // In the original function, the AllocaSpillBlock is a block immediately 668 // following the allocation of the frame object which defines GEPs for 669 // all the allocas that have been moved into the frame, and it ends by 670 // branching to the original beginning of the coroutine. Make this 671 // the entry block of the cloned function. 672 auto *Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]); 673 auto *OldEntry = &NewF->getEntryBlock(); 674 Entry->setName("entry" + Suffix); 675 Entry->moveBefore(OldEntry); 676 Entry->getTerminator()->eraseFromParent(); 677 678 // Clear all predecessors of the new entry block. There should be 679 // exactly one predecessor, which we created when splitting out 680 // AllocaSpillBlock to begin with. 681 assert(Entry->hasOneUse()); 682 auto BranchToEntry = cast<BranchInst>(Entry->user_back()); 683 assert(BranchToEntry->isUnconditional()); 684 Builder.SetInsertPoint(BranchToEntry); 685 Builder.CreateUnreachable(); 686 BranchToEntry->eraseFromParent(); 687 688 // Branch from the entry to the appropriate place. 689 Builder.SetInsertPoint(Entry); 690 switch (Shape.ABI) { 691 case coro::ABI::Switch: { 692 // In switch-lowering, we built a resume-entry block in the original 693 // function. Make the entry block branch to this. 694 auto *SwitchBB = 695 cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]); 696 Builder.CreateBr(SwitchBB); 697 break; 698 } 699 case coro::ABI::Async: 700 case coro::ABI::Retcon: 701 case coro::ABI::RetconOnce: { 702 // In continuation ABIs, we want to branch to immediately after the 703 // active suspend point. Earlier phases will have put the suspend in its 704 // own basic block, so just thread our jump directly to its successor. 705 assert((Shape.ABI == coro::ABI::Async && 706 isa<CoroSuspendAsyncInst>(ActiveSuspend)) || 707 ((Shape.ABI == coro::ABI::Retcon || 708 Shape.ABI == coro::ABI::RetconOnce) && 709 isa<CoroSuspendRetconInst>(ActiveSuspend))); 710 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[ActiveSuspend]); 711 auto Branch = cast<BranchInst>(MappedCS->getNextNode()); 712 assert(Branch->isUnconditional()); 713 Builder.CreateBr(Branch->getSuccessor(0)); 714 break; 715 } 716 } 717 718 // Any alloca that's still being used but not reachable from the new entry 719 // needs to be moved to the new entry. 720 Function *F = OldEntry->getParent(); 721 DominatorTree DT{*F}; 722 for (auto IT = inst_begin(F), End = inst_end(F); IT != End;) { 723 Instruction &I = *IT++; 724 if (!isa<AllocaInst>(&I) || I.use_empty()) 725 continue; 726 if (DT.isReachableFromEntry(I.getParent())) 727 continue; 728 I.moveBefore(*Entry, Entry->getFirstInsertionPt()); 729 } 730 } 731 732 /// Derive the value of the new frame pointer. 733 Value *CoroCloner::deriveNewFramePointer() { 734 // Builder should be inserting to the front of the new entry block. 735 736 switch (Shape.ABI) { 737 // In switch-lowering, the argument is the frame pointer. 738 case coro::ABI::Switch: 739 return &*NewF->arg_begin(); 740 // In async-lowering, one of the arguments is an async context as determined 741 // by the `llvm.coro.id.async` intrinsic. We can retrieve the async context of 742 // the resume function from the async context projection function associated 743 // with the active suspend. The frame is located as a tail to the async 744 // context header. 745 case coro::ABI::Async: { 746 auto *CalleeContext = NewF->getArg(Shape.AsyncLowering.ContextArgNo); 747 auto *FramePtrTy = Shape.FrameTy->getPointerTo(); 748 auto *ProjectionFunc = cast<CoroSuspendAsyncInst>(ActiveSuspend) 749 ->getAsyncContextProjectionFunction(); 750 auto DbgLoc = 751 cast<CoroSuspendAsyncInst>(VMap[ActiveSuspend])->getDebugLoc(); 752 // Calling i8* (i8*) 753 auto *CallerContext = Builder.CreateCall( 754 cast<FunctionType>(ProjectionFunc->getType()->getPointerElementType()), 755 ProjectionFunc, CalleeContext); 756 CallerContext->setCallingConv(ProjectionFunc->getCallingConv()); 757 CallerContext->setDebugLoc(DbgLoc); 758 // The frame is located after the async_context header. 759 auto &Context = Builder.getContext(); 760 auto *FramePtrAddr = Builder.CreateConstInBoundsGEP1_32( 761 Type::getInt8Ty(Context), CallerContext, 762 Shape.AsyncLowering.FrameOffset, "async.ctx.frameptr"); 763 // Inline the projection function. 764 InlineFunctionInfo InlineInfo; 765 auto InlineRes = InlineFunction(*CallerContext, InlineInfo); 766 assert(InlineRes.isSuccess()); 767 (void)InlineRes; 768 return Builder.CreateBitCast(FramePtrAddr, FramePtrTy); 769 } 770 // In continuation-lowering, the argument is the opaque storage. 771 case coro::ABI::Retcon: 772 case coro::ABI::RetconOnce: { 773 Argument *NewStorage = &*NewF->arg_begin(); 774 auto FramePtrTy = Shape.FrameTy->getPointerTo(); 775 776 // If the storage is inline, just bitcast to the storage to the frame type. 777 if (Shape.RetconLowering.IsFrameInlineInStorage) 778 return Builder.CreateBitCast(NewStorage, FramePtrTy); 779 780 // Otherwise, load the real frame from the opaque storage. 781 auto FramePtrPtr = 782 Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo()); 783 return Builder.CreateLoad(FramePtrTy, FramePtrPtr); 784 } 785 } 786 llvm_unreachable("bad ABI"); 787 } 788 789 static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context, 790 unsigned ParamIndex, 791 uint64_t Size, Align Alignment) { 792 AttrBuilder ParamAttrs; 793 ParamAttrs.addAttribute(Attribute::NonNull); 794 ParamAttrs.addAttribute(Attribute::NoAlias); 795 ParamAttrs.addAlignmentAttr(Alignment); 796 ParamAttrs.addDereferenceableAttr(Size); 797 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs); 798 } 799 800 /// Clone the body of the original function into a resume function of 801 /// some sort. 802 void CoroCloner::create() { 803 // Create the new function if we don't already have one. 804 if (!NewF) { 805 NewF = createCloneDeclaration(OrigF, Shape, Suffix, 806 OrigF.getParent()->end()); 807 } 808 809 // Replace all args with undefs. The buildCoroutineFrame algorithm already 810 // rewritten access to the args that occurs after suspend points with loads 811 // and stores to/from the coroutine frame. 812 for (Argument &A : OrigF.args()) 813 VMap[&A] = UndefValue::get(A.getType()); 814 815 SmallVector<ReturnInst *, 4> Returns; 816 817 // Ignore attempts to change certain attributes of the function. 818 // TODO: maybe there should be a way to suppress this during cloning? 819 auto savedVisibility = NewF->getVisibility(); 820 auto savedUnnamedAddr = NewF->getUnnamedAddr(); 821 auto savedDLLStorageClass = NewF->getDLLStorageClass(); 822 823 // NewF's linkage (which CloneFunctionInto does *not* change) might not 824 // be compatible with the visibility of OrigF (which it *does* change), 825 // so protect against that. 826 auto savedLinkage = NewF->getLinkage(); 827 NewF->setLinkage(llvm::GlobalValue::ExternalLinkage); 828 829 CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns); 830 831 NewF->setLinkage(savedLinkage); 832 NewF->setVisibility(savedVisibility); 833 NewF->setUnnamedAddr(savedUnnamedAddr); 834 NewF->setDLLStorageClass(savedDLLStorageClass); 835 836 auto &Context = NewF->getContext(); 837 838 // Replace the attributes of the new function: 839 auto OrigAttrs = NewF->getAttributes(); 840 auto NewAttrs = AttributeList(); 841 842 switch (Shape.ABI) { 843 case coro::ABI::Switch: 844 // Bootstrap attributes by copying function attributes from the 845 // original function. This should include optimization settings and so on. 846 NewAttrs = NewAttrs.addAttributes(Context, AttributeList::FunctionIndex, 847 OrigAttrs.getFnAttributes()); 848 849 addFramePointerAttrs(NewAttrs, Context, 0, 850 Shape.FrameSize, Shape.FrameAlign); 851 break; 852 case coro::ABI::Async: 853 break; 854 case coro::ABI::Retcon: 855 case coro::ABI::RetconOnce: 856 // If we have a continuation prototype, just use its attributes, 857 // full-stop. 858 NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes(); 859 860 addFramePointerAttrs(NewAttrs, Context, 0, 861 Shape.getRetconCoroId()->getStorageSize(), 862 Shape.getRetconCoroId()->getStorageAlignment()); 863 break; 864 } 865 866 switch (Shape.ABI) { 867 // In these ABIs, the cloned functions always return 'void', and the 868 // existing return sites are meaningless. Note that for unique 869 // continuations, this includes the returns associated with suspends; 870 // this is fine because we can't suspend twice. 871 case coro::ABI::Switch: 872 case coro::ABI::RetconOnce: 873 // Remove old returns. 874 for (ReturnInst *Return : Returns) 875 changeToUnreachable(Return, /*UseLLVMTrap=*/false); 876 break; 877 878 // With multi-suspend continuations, we'll already have eliminated the 879 // original returns and inserted returns before all the suspend points, 880 // so we want to leave any returns in place. 881 case coro::ABI::Retcon: 882 break; 883 // Async lowering will insert musttail call functions at all suspend points 884 // followed by a return. 885 // Don't change returns to unreachable because that will trip up the verifier. 886 // These returns should be unreachable from the clone. 887 case coro::ABI::Async: 888 break; 889 } 890 891 NewF->setAttributes(NewAttrs); 892 NewF->setCallingConv(Shape.getResumeFunctionCC()); 893 894 // Set up the new entry block. 895 replaceEntryBlock(); 896 897 Builder.SetInsertPoint(&NewF->getEntryBlock().front()); 898 NewFramePtr = deriveNewFramePointer(); 899 900 // Remap frame pointer. 901 Value *OldFramePtr = VMap[Shape.FramePtr]; 902 NewFramePtr->takeName(OldFramePtr); 903 OldFramePtr->replaceAllUsesWith(NewFramePtr); 904 905 // Remap vFrame pointer. 906 auto *NewVFrame = Builder.CreateBitCast( 907 NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame"); 908 Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]); 909 OldVFrame->replaceAllUsesWith(NewVFrame); 910 911 switch (Shape.ABI) { 912 case coro::ABI::Switch: 913 // Rewrite final suspend handling as it is not done via switch (allows to 914 // remove final case from the switch, since it is undefined behavior to 915 // resume the coroutine suspended at the final suspend point. 916 if (Shape.SwitchLowering.HasFinalSuspend) 917 handleFinalSuspend(); 918 break; 919 case coro::ABI::Async: 920 case coro::ABI::Retcon: 921 case coro::ABI::RetconOnce: 922 // Replace uses of the active suspend with the corresponding 923 // continuation-function arguments. 924 assert(ActiveSuspend != nullptr && 925 "no active suspend when lowering a continuation-style coroutine"); 926 replaceRetconOrAsyncSuspendUses(); 927 break; 928 } 929 930 // Handle suspends. 931 replaceCoroSuspends(); 932 933 // Handle swifterror. 934 replaceSwiftErrorOps(); 935 936 // Remove coro.end intrinsics. 937 replaceCoroEnds(); 938 939 // Salvage debug info that points into the coroutine frame. 940 salvageDebugInfo(); 941 942 // Eliminate coro.free from the clones, replacing it with 'null' in cleanup, 943 // to suppress deallocation code. 944 if (Shape.ABI == coro::ABI::Switch) 945 coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]), 946 /*Elide=*/ FKind == CoroCloner::Kind::SwitchCleanup); 947 } 948 949 // Create a resume clone by cloning the body of the original function, setting 950 // new entry block and replacing coro.suspend an appropriate value to force 951 // resume or cleanup pass for every suspend point. 952 static Function *createClone(Function &F, const Twine &Suffix, 953 coro::Shape &Shape, CoroCloner::Kind FKind) { 954 CoroCloner Cloner(F, Suffix, Shape, FKind); 955 Cloner.create(); 956 return Cloner.getFunction(); 957 } 958 959 /// Remove calls to llvm.coro.end in the original function. 960 static void removeCoroEnds(const coro::Shape &Shape, CallGraph *CG) { 961 for (auto End : Shape.CoroEnds) { 962 replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, CG); 963 } 964 } 965 966 static void updateAsyncFuncPointerContextSize(coro::Shape &Shape) { 967 assert(Shape.ABI == coro::ABI::Async); 968 969 auto *FuncPtrStruct = cast<ConstantStruct>( 970 Shape.AsyncLowering.AsyncFuncPointer->getInitializer()); 971 auto *OrigRelativeFunOffset = FuncPtrStruct->getOperand(0); 972 auto *OrigContextSize = FuncPtrStruct->getOperand(1); 973 auto *NewContextSize = ConstantInt::get(OrigContextSize->getType(), 974 Shape.AsyncLowering.ContextSize); 975 auto *NewFuncPtrStruct = ConstantStruct::get( 976 FuncPtrStruct->getType(), OrigRelativeFunOffset, NewContextSize); 977 978 Shape.AsyncLowering.AsyncFuncPointer->setInitializer(NewFuncPtrStruct); 979 } 980 981 static void replaceFrameSize(coro::Shape &Shape) { 982 if (Shape.ABI == coro::ABI::Async) 983 updateAsyncFuncPointerContextSize(Shape); 984 985 if (Shape.CoroSizes.empty()) 986 return; 987 988 // In the same function all coro.sizes should have the same result type. 989 auto *SizeIntrin = Shape.CoroSizes.back(); 990 Module *M = SizeIntrin->getModule(); 991 const DataLayout &DL = M->getDataLayout(); 992 auto Size = DL.getTypeAllocSize(Shape.FrameTy); 993 auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size); 994 995 for (CoroSizeInst *CS : Shape.CoroSizes) { 996 CS->replaceAllUsesWith(SizeConstant); 997 CS->eraseFromParent(); 998 } 999 } 1000 1001 // Create a global constant array containing pointers to functions provided and 1002 // set Info parameter of CoroBegin to point at this constant. Example: 1003 // 1004 // @f.resumers = internal constant [2 x void(%f.frame*)*] 1005 // [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy] 1006 // define void @f() { 1007 // ... 1008 // call i8* @llvm.coro.begin(i8* null, i32 0, i8* null, 1009 // i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*)) 1010 // 1011 // Assumes that all the functions have the same signature. 1012 static void setCoroInfo(Function &F, coro::Shape &Shape, 1013 ArrayRef<Function *> Fns) { 1014 // This only works under the switch-lowering ABI because coro elision 1015 // only works on the switch-lowering ABI. 1016 assert(Shape.ABI == coro::ABI::Switch); 1017 1018 SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end()); 1019 assert(!Args.empty()); 1020 Function *Part = *Fns.begin(); 1021 Module *M = Part->getParent(); 1022 auto *ArrTy = ArrayType::get(Part->getType(), Args.size()); 1023 1024 auto *ConstVal = ConstantArray::get(ArrTy, Args); 1025 auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true, 1026 GlobalVariable::PrivateLinkage, ConstVal, 1027 F.getName() + Twine(".resumers")); 1028 1029 // Update coro.begin instruction to refer to this constant. 1030 LLVMContext &C = F.getContext(); 1031 auto *BC = ConstantExpr::getPointerCast(GV, Type::getInt8PtrTy(C)); 1032 Shape.getSwitchCoroId()->setInfo(BC); 1033 } 1034 1035 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame. 1036 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn, 1037 Function *DestroyFn, Function *CleanupFn) { 1038 assert(Shape.ABI == coro::ABI::Switch); 1039 1040 IRBuilder<> Builder(Shape.FramePtr->getNextNode()); 1041 auto *ResumeAddr = Builder.CreateStructGEP( 1042 Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Resume, 1043 "resume.addr"); 1044 Builder.CreateStore(ResumeFn, ResumeAddr); 1045 1046 Value *DestroyOrCleanupFn = DestroyFn; 1047 1048 CoroIdInst *CoroId = Shape.getSwitchCoroId(); 1049 if (CoroAllocInst *CA = CoroId->getCoroAlloc()) { 1050 // If there is a CoroAlloc and it returns false (meaning we elide the 1051 // allocation, use CleanupFn instead of DestroyFn). 1052 DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn); 1053 } 1054 1055 auto *DestroyAddr = Builder.CreateStructGEP( 1056 Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Destroy, 1057 "destroy.addr"); 1058 Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr); 1059 } 1060 1061 static void postSplitCleanup(Function &F) { 1062 removeUnreachableBlocks(F); 1063 1064 // For now, we do a mandatory verification step because we don't 1065 // entirely trust this pass. Note that we don't want to add a verifier 1066 // pass to FPM below because it will also verify all the global data. 1067 if (verifyFunction(F, &errs())) 1068 report_fatal_error("Broken function"); 1069 1070 legacy::FunctionPassManager FPM(F.getParent()); 1071 1072 FPM.add(createSCCPPass()); 1073 FPM.add(createCFGSimplificationPass()); 1074 FPM.add(createEarlyCSEPass()); 1075 FPM.add(createCFGSimplificationPass()); 1076 1077 FPM.doInitialization(); 1078 FPM.run(F); 1079 FPM.doFinalization(); 1080 } 1081 1082 // Assuming we arrived at the block NewBlock from Prev instruction, store 1083 // PHI's incoming values in the ResolvedValues map. 1084 static void 1085 scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock, 1086 DenseMap<Value *, Value *> &ResolvedValues) { 1087 auto *PrevBB = Prev->getParent(); 1088 for (PHINode &PN : NewBlock->phis()) { 1089 auto V = PN.getIncomingValueForBlock(PrevBB); 1090 // See if we already resolved it. 1091 auto VI = ResolvedValues.find(V); 1092 if (VI != ResolvedValues.end()) 1093 V = VI->second; 1094 // Remember the value. 1095 ResolvedValues[&PN] = V; 1096 } 1097 } 1098 1099 // Replace a sequence of branches leading to a ret, with a clone of a ret 1100 // instruction. Suspend instruction represented by a switch, track the PHI 1101 // values and select the correct case successor when possible. 1102 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) { 1103 DenseMap<Value *, Value *> ResolvedValues; 1104 BasicBlock *UnconditionalSucc = nullptr; 1105 1106 Instruction *I = InitialInst; 1107 while (I->isTerminator() || 1108 (isa<CmpInst>(I) && I->getNextNode()->isTerminator())) { 1109 if (isa<ReturnInst>(I)) { 1110 if (I != InitialInst) { 1111 // If InitialInst is an unconditional branch, 1112 // remove PHI values that come from basic block of InitialInst 1113 if (UnconditionalSucc) 1114 UnconditionalSucc->removePredecessor(InitialInst->getParent(), true); 1115 ReplaceInstWithInst(InitialInst, I->clone()); 1116 } 1117 return true; 1118 } 1119 if (auto *BR = dyn_cast<BranchInst>(I)) { 1120 if (BR->isUnconditional()) { 1121 BasicBlock *BB = BR->getSuccessor(0); 1122 if (I == InitialInst) 1123 UnconditionalSucc = BB; 1124 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 1125 I = BB->getFirstNonPHIOrDbgOrLifetime(); 1126 continue; 1127 } 1128 } else if (auto *CondCmp = dyn_cast<CmpInst>(I)) { 1129 auto *BR = dyn_cast<BranchInst>(I->getNextNode()); 1130 if (BR && BR->isConditional() && CondCmp == BR->getCondition()) { 1131 // If the case number of suspended switch instruction is reduced to 1132 // 1, then it is simplified to CmpInst in llvm::ConstantFoldTerminator. 1133 // And the comparsion looks like : %cond = icmp eq i8 %V, constant. 1134 ConstantInt *CondConst = dyn_cast<ConstantInt>(CondCmp->getOperand(1)); 1135 if (CondConst && CondCmp->getPredicate() == CmpInst::ICMP_EQ) { 1136 Value *V = CondCmp->getOperand(0); 1137 auto it = ResolvedValues.find(V); 1138 if (it != ResolvedValues.end()) 1139 V = it->second; 1140 1141 if (ConstantInt *Cond0 = dyn_cast<ConstantInt>(V)) { 1142 BasicBlock *BB = Cond0->equalsInt(CondConst->getZExtValue()) 1143 ? BR->getSuccessor(0) 1144 : BR->getSuccessor(1); 1145 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 1146 I = BB->getFirstNonPHIOrDbgOrLifetime(); 1147 continue; 1148 } 1149 } 1150 } 1151 } else if (auto *SI = dyn_cast<SwitchInst>(I)) { 1152 Value *V = SI->getCondition(); 1153 auto it = ResolvedValues.find(V); 1154 if (it != ResolvedValues.end()) 1155 V = it->second; 1156 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) { 1157 BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor(); 1158 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 1159 I = BB->getFirstNonPHIOrDbgOrLifetime(); 1160 continue; 1161 } 1162 } 1163 return false; 1164 } 1165 return false; 1166 } 1167 1168 // Check whether CI obeys the rules of musttail attribute. 1169 static bool shouldBeMustTail(const CallInst &CI, const Function &F) { 1170 if (CI.isInlineAsm()) 1171 return false; 1172 1173 // Match prototypes and calling conventions of resume function. 1174 FunctionType *CalleeTy = CI.getFunctionType(); 1175 if (!CalleeTy->getReturnType()->isVoidTy() || (CalleeTy->getNumParams() != 1)) 1176 return false; 1177 1178 Type *CalleeParmTy = CalleeTy->getParamType(0); 1179 if (!CalleeParmTy->isPointerTy() || 1180 (CalleeParmTy->getPointerAddressSpace() != 0)) 1181 return false; 1182 1183 if (CI.getCallingConv() != F.getCallingConv()) 1184 return false; 1185 1186 // CI should not has any ABI-impacting function attributes. 1187 static const Attribute::AttrKind ABIAttrs[] = { 1188 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 1189 Attribute::Preallocated, Attribute::InReg, Attribute::Returned, 1190 Attribute::SwiftSelf, Attribute::SwiftError}; 1191 AttributeList Attrs = CI.getAttributes(); 1192 for (auto AK : ABIAttrs) 1193 if (Attrs.hasParamAttribute(0, AK)) 1194 return false; 1195 1196 return true; 1197 } 1198 1199 // Add musttail to any resume instructions that is immediately followed by a 1200 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call 1201 // for symmetrical coroutine control transfer (C++ Coroutines TS extension). 1202 // This transformation is done only in the resume part of the coroutine that has 1203 // identical signature and calling convention as the coro.resume call. 1204 static void addMustTailToCoroResumes(Function &F) { 1205 bool changed = false; 1206 1207 // Collect potential resume instructions. 1208 SmallVector<CallInst *, 4> Resumes; 1209 for (auto &I : instructions(F)) 1210 if (auto *Call = dyn_cast<CallInst>(&I)) 1211 if (shouldBeMustTail(*Call, F)) 1212 Resumes.push_back(Call); 1213 1214 // Set musttail on those that are followed by a ret instruction. 1215 for (CallInst *Call : Resumes) 1216 if (simplifyTerminatorLeadingToRet(Call->getNextNode())) { 1217 Call->setTailCallKind(CallInst::TCK_MustTail); 1218 changed = true; 1219 } 1220 1221 if (changed) 1222 removeUnreachableBlocks(F); 1223 } 1224 1225 // Coroutine has no suspend points. Remove heap allocation for the coroutine 1226 // frame if possible. 1227 static void handleNoSuspendCoroutine(coro::Shape &Shape) { 1228 auto *CoroBegin = Shape.CoroBegin; 1229 auto *CoroId = CoroBegin->getId(); 1230 auto *AllocInst = CoroId->getCoroAlloc(); 1231 switch (Shape.ABI) { 1232 case coro::ABI::Switch: { 1233 auto SwitchId = cast<CoroIdInst>(CoroId); 1234 coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr); 1235 if (AllocInst) { 1236 IRBuilder<> Builder(AllocInst); 1237 auto *Frame = Builder.CreateAlloca(Shape.FrameTy); 1238 Frame->setAlignment(Shape.FrameAlign); 1239 auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy()); 1240 AllocInst->replaceAllUsesWith(Builder.getFalse()); 1241 AllocInst->eraseFromParent(); 1242 CoroBegin->replaceAllUsesWith(VFrame); 1243 } else { 1244 CoroBegin->replaceAllUsesWith(CoroBegin->getMem()); 1245 } 1246 break; 1247 } 1248 case coro::ABI::Async: 1249 case coro::ABI::Retcon: 1250 case coro::ABI::RetconOnce: 1251 CoroBegin->replaceAllUsesWith(UndefValue::get(CoroBegin->getType())); 1252 break; 1253 } 1254 1255 CoroBegin->eraseFromParent(); 1256 } 1257 1258 // SimplifySuspendPoint needs to check that there is no calls between 1259 // coro_save and coro_suspend, since any of the calls may potentially resume 1260 // the coroutine and if that is the case we cannot eliminate the suspend point. 1261 static bool hasCallsInBlockBetween(Instruction *From, Instruction *To) { 1262 for (Instruction *I = From; I != To; I = I->getNextNode()) { 1263 // Assume that no intrinsic can resume the coroutine. 1264 if (isa<IntrinsicInst>(I)) 1265 continue; 1266 1267 if (isa<CallBase>(I)) 1268 return true; 1269 } 1270 return false; 1271 } 1272 1273 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) { 1274 SmallPtrSet<BasicBlock *, 8> Set; 1275 SmallVector<BasicBlock *, 8> Worklist; 1276 1277 Set.insert(SaveBB); 1278 Worklist.push_back(ResDesBB); 1279 1280 // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr 1281 // returns a token consumed by suspend instruction, all blocks in between 1282 // will have to eventually hit SaveBB when going backwards from ResDesBB. 1283 while (!Worklist.empty()) { 1284 auto *BB = Worklist.pop_back_val(); 1285 Set.insert(BB); 1286 for (auto *Pred : predecessors(BB)) 1287 if (Set.count(Pred) == 0) 1288 Worklist.push_back(Pred); 1289 } 1290 1291 // SaveBB and ResDesBB are checked separately in hasCallsBetween. 1292 Set.erase(SaveBB); 1293 Set.erase(ResDesBB); 1294 1295 for (auto *BB : Set) 1296 if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr)) 1297 return true; 1298 1299 return false; 1300 } 1301 1302 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) { 1303 auto *SaveBB = Save->getParent(); 1304 auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent(); 1305 1306 if (SaveBB == ResumeOrDestroyBB) 1307 return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy); 1308 1309 // Any calls from Save to the end of the block? 1310 if (hasCallsInBlockBetween(Save->getNextNode(), nullptr)) 1311 return true; 1312 1313 // Any calls from begging of the block up to ResumeOrDestroy? 1314 if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(), 1315 ResumeOrDestroy)) 1316 return true; 1317 1318 // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB? 1319 if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB)) 1320 return true; 1321 1322 return false; 1323 } 1324 1325 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the 1326 // suspend point and replace it with nornal control flow. 1327 static bool simplifySuspendPoint(CoroSuspendInst *Suspend, 1328 CoroBeginInst *CoroBegin) { 1329 Instruction *Prev = Suspend->getPrevNode(); 1330 if (!Prev) { 1331 auto *Pred = Suspend->getParent()->getSinglePredecessor(); 1332 if (!Pred) 1333 return false; 1334 Prev = Pred->getTerminator(); 1335 } 1336 1337 CallBase *CB = dyn_cast<CallBase>(Prev); 1338 if (!CB) 1339 return false; 1340 1341 auto *Callee = CB->getCalledOperand()->stripPointerCasts(); 1342 1343 // See if the callsite is for resumption or destruction of the coroutine. 1344 auto *SubFn = dyn_cast<CoroSubFnInst>(Callee); 1345 if (!SubFn) 1346 return false; 1347 1348 // Does not refer to the current coroutine, we cannot do anything with it. 1349 if (SubFn->getFrame() != CoroBegin) 1350 return false; 1351 1352 // See if the transformation is safe. Specifically, see if there are any 1353 // calls in between Save and CallInstr. They can potenitally resume the 1354 // coroutine rendering this optimization unsafe. 1355 auto *Save = Suspend->getCoroSave(); 1356 if (hasCallsBetween(Save, CB)) 1357 return false; 1358 1359 // Replace llvm.coro.suspend with the value that results in resumption over 1360 // the resume or cleanup path. 1361 Suspend->replaceAllUsesWith(SubFn->getRawIndex()); 1362 Suspend->eraseFromParent(); 1363 Save->eraseFromParent(); 1364 1365 // No longer need a call to coro.resume or coro.destroy. 1366 if (auto *Invoke = dyn_cast<InvokeInst>(CB)) { 1367 BranchInst::Create(Invoke->getNormalDest(), Invoke); 1368 } 1369 1370 // Grab the CalledValue from CB before erasing the CallInstr. 1371 auto *CalledValue = CB->getCalledOperand(); 1372 CB->eraseFromParent(); 1373 1374 // If no more users remove it. Usually it is a bitcast of SubFn. 1375 if (CalledValue != SubFn && CalledValue->user_empty()) 1376 if (auto *I = dyn_cast<Instruction>(CalledValue)) 1377 I->eraseFromParent(); 1378 1379 // Now we are good to remove SubFn. 1380 if (SubFn->user_empty()) 1381 SubFn->eraseFromParent(); 1382 1383 return true; 1384 } 1385 1386 // Remove suspend points that are simplified. 1387 static void simplifySuspendPoints(coro::Shape &Shape) { 1388 // Currently, the only simplification we do is switch-lowering-specific. 1389 if (Shape.ABI != coro::ABI::Switch) 1390 return; 1391 1392 auto &S = Shape.CoroSuspends; 1393 size_t I = 0, N = S.size(); 1394 if (N == 0) 1395 return; 1396 while (true) { 1397 auto SI = cast<CoroSuspendInst>(S[I]); 1398 // Leave final.suspend to handleFinalSuspend since it is undefined behavior 1399 // to resume a coroutine suspended at the final suspend point. 1400 if (!SI->isFinal() && simplifySuspendPoint(SI, Shape.CoroBegin)) { 1401 if (--N == I) 1402 break; 1403 std::swap(S[I], S[N]); 1404 continue; 1405 } 1406 if (++I == N) 1407 break; 1408 } 1409 S.resize(N); 1410 } 1411 1412 static void splitSwitchCoroutine(Function &F, coro::Shape &Shape, 1413 SmallVectorImpl<Function *> &Clones) { 1414 assert(Shape.ABI == coro::ABI::Switch); 1415 1416 createResumeEntryBlock(F, Shape); 1417 auto ResumeClone = createClone(F, ".resume", Shape, 1418 CoroCloner::Kind::SwitchResume); 1419 auto DestroyClone = createClone(F, ".destroy", Shape, 1420 CoroCloner::Kind::SwitchUnwind); 1421 auto CleanupClone = createClone(F, ".cleanup", Shape, 1422 CoroCloner::Kind::SwitchCleanup); 1423 1424 postSplitCleanup(*ResumeClone); 1425 postSplitCleanup(*DestroyClone); 1426 postSplitCleanup(*CleanupClone); 1427 1428 addMustTailToCoroResumes(*ResumeClone); 1429 1430 // Store addresses resume/destroy/cleanup functions in the coroutine frame. 1431 updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone); 1432 1433 assert(Clones.empty()); 1434 Clones.push_back(ResumeClone); 1435 Clones.push_back(DestroyClone); 1436 Clones.push_back(CleanupClone); 1437 1438 // Create a constant array referring to resume/destroy/clone functions pointed 1439 // by the last argument of @llvm.coro.info, so that CoroElide pass can 1440 // determined correct function to call. 1441 setCoroInfo(F, Shape, Clones); 1442 } 1443 1444 static void replaceAsyncResumeFunction(CoroSuspendAsyncInst *Suspend, 1445 Value *Continuation) { 1446 auto *ResumeIntrinsic = Suspend->getResumeFunction(); 1447 auto &Context = Suspend->getParent()->getParent()->getContext(); 1448 auto *Int8PtrTy = Type::getInt8PtrTy(Context); 1449 1450 IRBuilder<> Builder(ResumeIntrinsic); 1451 auto *Val = Builder.CreateBitOrPointerCast(Continuation, Int8PtrTy); 1452 ResumeIntrinsic->replaceAllUsesWith(Val); 1453 ResumeIntrinsic->eraseFromParent(); 1454 Suspend->setOperand(0, UndefValue::get(Int8PtrTy)); 1455 } 1456 1457 /// Coerce the arguments in \p FnArgs according to \p FnTy in \p CallArgs. 1458 static void coerceArguments(IRBuilder<> &Builder, FunctionType *FnTy, 1459 ArrayRef<Value *> FnArgs, 1460 SmallVectorImpl<Value *> &CallArgs) { 1461 size_t ArgIdx = 0; 1462 for (auto paramTy : FnTy->params()) { 1463 assert(ArgIdx < FnArgs.size()); 1464 if (paramTy != FnArgs[ArgIdx]->getType()) 1465 CallArgs.push_back( 1466 Builder.CreateBitOrPointerCast(FnArgs[ArgIdx], paramTy)); 1467 else 1468 CallArgs.push_back(FnArgs[ArgIdx]); 1469 ++ArgIdx; 1470 } 1471 } 1472 1473 CallInst *coro::createMustTailCall(DebugLoc Loc, Function *MustTailCallFn, 1474 ArrayRef<Value *> Arguments, 1475 IRBuilder<> &Builder) { 1476 auto *FnTy = 1477 cast<FunctionType>(MustTailCallFn->getType()->getPointerElementType()); 1478 // Coerce the arguments, llvm optimizations seem to ignore the types in 1479 // vaarg functions and throws away casts in optimized mode. 1480 SmallVector<Value *, 8> CallArgs; 1481 coerceArguments(Builder, FnTy, Arguments, CallArgs); 1482 1483 auto *TailCall = Builder.CreateCall(FnTy, MustTailCallFn, CallArgs); 1484 TailCall->setTailCallKind(CallInst::TCK_MustTail); 1485 TailCall->setDebugLoc(Loc); 1486 TailCall->setCallingConv(MustTailCallFn->getCallingConv()); 1487 return TailCall; 1488 } 1489 1490 static void splitAsyncCoroutine(Function &F, coro::Shape &Shape, 1491 SmallVectorImpl<Function *> &Clones) { 1492 assert(Shape.ABI == coro::ABI::Async); 1493 assert(Clones.empty()); 1494 // Reset various things that the optimizer might have decided it 1495 // "knows" about the coroutine function due to not seeing a return. 1496 F.removeFnAttr(Attribute::NoReturn); 1497 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 1498 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 1499 1500 auto &Context = F.getContext(); 1501 auto *Int8PtrTy = Type::getInt8PtrTy(Context); 1502 1503 auto *Id = cast<CoroIdAsyncInst>(Shape.CoroBegin->getId()); 1504 IRBuilder<> Builder(Id); 1505 1506 auto *FramePtr = Id->getStorage(); 1507 FramePtr = Builder.CreateBitOrPointerCast(FramePtr, Int8PtrTy); 1508 FramePtr = Builder.CreateConstInBoundsGEP1_32( 1509 Type::getInt8Ty(Context), FramePtr, Shape.AsyncLowering.FrameOffset, 1510 "async.ctx.frameptr"); 1511 1512 // Map all uses of llvm.coro.begin to the allocated frame pointer. 1513 { 1514 // Make sure we don't invalidate Shape.FramePtr. 1515 TrackingVH<Instruction> Handle(Shape.FramePtr); 1516 Shape.CoroBegin->replaceAllUsesWith(FramePtr); 1517 Shape.FramePtr = Handle.getValPtr(); 1518 } 1519 1520 // Create all the functions in order after the main function. 1521 auto NextF = std::next(F.getIterator()); 1522 1523 // Create a continuation function for each of the suspend points. 1524 Clones.reserve(Shape.CoroSuspends.size()); 1525 for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) { 1526 auto *Suspend = cast<CoroSuspendAsyncInst>(Shape.CoroSuspends[Idx]); 1527 1528 // Create the clone declaration. 1529 auto *Continuation = 1530 createCloneDeclaration(F, Shape, ".resume." + Twine(Idx), NextF); 1531 Clones.push_back(Continuation); 1532 1533 // Insert a branch to a new return block immediately before the suspend 1534 // point. 1535 auto *SuspendBB = Suspend->getParent(); 1536 auto *NewSuspendBB = SuspendBB->splitBasicBlock(Suspend); 1537 auto *Branch = cast<BranchInst>(SuspendBB->getTerminator()); 1538 1539 // Place it before the first suspend. 1540 auto *ReturnBB = 1541 BasicBlock::Create(F.getContext(), "coro.return", &F, NewSuspendBB); 1542 Branch->setSuccessor(0, ReturnBB); 1543 1544 IRBuilder<> Builder(ReturnBB); 1545 1546 // Insert the call to the tail call function and inline it. 1547 auto *Fn = Suspend->getMustTailCallFunction(); 1548 SmallVector<Value *, 8> Args(Suspend->args()); 1549 auto FnArgs = ArrayRef<Value *>(Args).drop_front(3); 1550 auto *TailCall = 1551 coro::createMustTailCall(Suspend->getDebugLoc(), Fn, FnArgs, Builder); 1552 Builder.CreateRetVoid(); 1553 InlineFunctionInfo FnInfo; 1554 auto InlineRes = InlineFunction(*TailCall, FnInfo); 1555 assert(InlineRes.isSuccess() && "Expected inlining to succeed"); 1556 (void)InlineRes; 1557 1558 // Replace the lvm.coro.async.resume intrisic call. 1559 replaceAsyncResumeFunction(Suspend, Continuation); 1560 } 1561 1562 assert(Clones.size() == Shape.CoroSuspends.size()); 1563 for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) { 1564 auto *Suspend = Shape.CoroSuspends[Idx]; 1565 auto *Clone = Clones[Idx]; 1566 1567 CoroCloner(F, "resume." + Twine(Idx), Shape, Clone, Suspend).create(); 1568 } 1569 } 1570 1571 static void splitRetconCoroutine(Function &F, coro::Shape &Shape, 1572 SmallVectorImpl<Function *> &Clones) { 1573 assert(Shape.ABI == coro::ABI::Retcon || 1574 Shape.ABI == coro::ABI::RetconOnce); 1575 assert(Clones.empty()); 1576 1577 // Reset various things that the optimizer might have decided it 1578 // "knows" about the coroutine function due to not seeing a return. 1579 F.removeFnAttr(Attribute::NoReturn); 1580 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 1581 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 1582 1583 // Allocate the frame. 1584 auto *Id = cast<AnyCoroIdRetconInst>(Shape.CoroBegin->getId()); 1585 Value *RawFramePtr; 1586 if (Shape.RetconLowering.IsFrameInlineInStorage) { 1587 RawFramePtr = Id->getStorage(); 1588 } else { 1589 IRBuilder<> Builder(Id); 1590 1591 // Determine the size of the frame. 1592 const DataLayout &DL = F.getParent()->getDataLayout(); 1593 auto Size = DL.getTypeAllocSize(Shape.FrameTy); 1594 1595 // Allocate. We don't need to update the call graph node because we're 1596 // going to recompute it from scratch after splitting. 1597 // FIXME: pass the required alignment 1598 RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr); 1599 RawFramePtr = 1600 Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType()); 1601 1602 // Stash the allocated frame pointer in the continuation storage. 1603 auto Dest = Builder.CreateBitCast(Id->getStorage(), 1604 RawFramePtr->getType()->getPointerTo()); 1605 Builder.CreateStore(RawFramePtr, Dest); 1606 } 1607 1608 // Map all uses of llvm.coro.begin to the allocated frame pointer. 1609 { 1610 // Make sure we don't invalidate Shape.FramePtr. 1611 TrackingVH<Instruction> Handle(Shape.FramePtr); 1612 Shape.CoroBegin->replaceAllUsesWith(RawFramePtr); 1613 Shape.FramePtr = Handle.getValPtr(); 1614 } 1615 1616 // Create a unique return block. 1617 BasicBlock *ReturnBB = nullptr; 1618 SmallVector<PHINode *, 4> ReturnPHIs; 1619 1620 // Create all the functions in order after the main function. 1621 auto NextF = std::next(F.getIterator()); 1622 1623 // Create a continuation function for each of the suspend points. 1624 Clones.reserve(Shape.CoroSuspends.size()); 1625 for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) { 1626 auto Suspend = cast<CoroSuspendRetconInst>(Shape.CoroSuspends[i]); 1627 1628 // Create the clone declaration. 1629 auto Continuation = 1630 createCloneDeclaration(F, Shape, ".resume." + Twine(i), NextF); 1631 Clones.push_back(Continuation); 1632 1633 // Insert a branch to the unified return block immediately before 1634 // the suspend point. 1635 auto SuspendBB = Suspend->getParent(); 1636 auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend); 1637 auto Branch = cast<BranchInst>(SuspendBB->getTerminator()); 1638 1639 // Create the unified return block. 1640 if (!ReturnBB) { 1641 // Place it before the first suspend. 1642 ReturnBB = BasicBlock::Create(F.getContext(), "coro.return", &F, 1643 NewSuspendBB); 1644 Shape.RetconLowering.ReturnBlock = ReturnBB; 1645 1646 IRBuilder<> Builder(ReturnBB); 1647 1648 // Create PHIs for all the return values. 1649 assert(ReturnPHIs.empty()); 1650 1651 // First, the continuation. 1652 ReturnPHIs.push_back(Builder.CreatePHI(Continuation->getType(), 1653 Shape.CoroSuspends.size())); 1654 1655 // Next, all the directly-yielded values. 1656 for (auto ResultTy : Shape.getRetconResultTypes()) 1657 ReturnPHIs.push_back(Builder.CreatePHI(ResultTy, 1658 Shape.CoroSuspends.size())); 1659 1660 // Build the return value. 1661 auto RetTy = F.getReturnType(); 1662 1663 // Cast the continuation value if necessary. 1664 // We can't rely on the types matching up because that type would 1665 // have to be infinite. 1666 auto CastedContinuationTy = 1667 (ReturnPHIs.size() == 1 ? RetTy : RetTy->getStructElementType(0)); 1668 auto *CastedContinuation = 1669 Builder.CreateBitCast(ReturnPHIs[0], CastedContinuationTy); 1670 1671 Value *RetV; 1672 if (ReturnPHIs.size() == 1) { 1673 RetV = CastedContinuation; 1674 } else { 1675 RetV = UndefValue::get(RetTy); 1676 RetV = Builder.CreateInsertValue(RetV, CastedContinuation, 0); 1677 for (size_t I = 1, E = ReturnPHIs.size(); I != E; ++I) 1678 RetV = Builder.CreateInsertValue(RetV, ReturnPHIs[I], I); 1679 } 1680 1681 Builder.CreateRet(RetV); 1682 } 1683 1684 // Branch to the return block. 1685 Branch->setSuccessor(0, ReturnBB); 1686 ReturnPHIs[0]->addIncoming(Continuation, SuspendBB); 1687 size_t NextPHIIndex = 1; 1688 for (auto &VUse : Suspend->value_operands()) 1689 ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB); 1690 assert(NextPHIIndex == ReturnPHIs.size()); 1691 } 1692 1693 assert(Clones.size() == Shape.CoroSuspends.size()); 1694 for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) { 1695 auto Suspend = Shape.CoroSuspends[i]; 1696 auto Clone = Clones[i]; 1697 1698 CoroCloner(F, "resume." + Twine(i), Shape, Clone, Suspend).create(); 1699 } 1700 } 1701 1702 namespace { 1703 class PrettyStackTraceFunction : public PrettyStackTraceEntry { 1704 Function &F; 1705 public: 1706 PrettyStackTraceFunction(Function &F) : F(F) {} 1707 void print(raw_ostream &OS) const override { 1708 OS << "While splitting coroutine "; 1709 F.printAsOperand(OS, /*print type*/ false, F.getParent()); 1710 OS << "\n"; 1711 } 1712 }; 1713 } 1714 1715 static coro::Shape splitCoroutine(Function &F, 1716 SmallVectorImpl<Function *> &Clones, 1717 bool ReuseFrameSlot) { 1718 PrettyStackTraceFunction prettyStackTrace(F); 1719 1720 // The suspend-crossing algorithm in buildCoroutineFrame get tripped 1721 // up by uses in unreachable blocks, so remove them as a first pass. 1722 removeUnreachableBlocks(F); 1723 1724 coro::Shape Shape(F, ReuseFrameSlot); 1725 if (!Shape.CoroBegin) 1726 return Shape; 1727 1728 simplifySuspendPoints(Shape); 1729 buildCoroutineFrame(F, Shape); 1730 replaceFrameSize(Shape); 1731 1732 // If there are no suspend points, no split required, just remove 1733 // the allocation and deallocation blocks, they are not needed. 1734 if (Shape.CoroSuspends.empty()) { 1735 handleNoSuspendCoroutine(Shape); 1736 } else { 1737 switch (Shape.ABI) { 1738 case coro::ABI::Switch: 1739 splitSwitchCoroutine(F, Shape, Clones); 1740 break; 1741 case coro::ABI::Async: 1742 splitAsyncCoroutine(F, Shape, Clones); 1743 break; 1744 case coro::ABI::Retcon: 1745 case coro::ABI::RetconOnce: 1746 splitRetconCoroutine(F, Shape, Clones); 1747 break; 1748 } 1749 } 1750 1751 // Replace all the swifterror operations in the original function. 1752 // This invalidates SwiftErrorOps in the Shape. 1753 replaceSwiftErrorOps(F, Shape, nullptr); 1754 1755 return Shape; 1756 } 1757 1758 static void 1759 updateCallGraphAfterCoroutineSplit(Function &F, const coro::Shape &Shape, 1760 const SmallVectorImpl<Function *> &Clones, 1761 CallGraph &CG, CallGraphSCC &SCC) { 1762 if (!Shape.CoroBegin) 1763 return; 1764 1765 removeCoroEnds(Shape, &CG); 1766 postSplitCleanup(F); 1767 1768 // Update call graph and add the functions we created to the SCC. 1769 coro::updateCallGraph(F, Clones, CG, SCC); 1770 } 1771 1772 static void updateCallGraphAfterCoroutineSplit( 1773 LazyCallGraph::Node &N, const coro::Shape &Shape, 1774 const SmallVectorImpl<Function *> &Clones, LazyCallGraph::SCC &C, 1775 LazyCallGraph &CG, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, 1776 FunctionAnalysisManager &FAM) { 1777 if (!Shape.CoroBegin) 1778 return; 1779 1780 for (llvm::AnyCoroEndInst *End : Shape.CoroEnds) { 1781 auto &Context = End->getContext(); 1782 End->replaceAllUsesWith(ConstantInt::getFalse(Context)); 1783 End->eraseFromParent(); 1784 } 1785 1786 if (!Clones.empty()) { 1787 switch (Shape.ABI) { 1788 case coro::ABI::Switch: 1789 // Each clone in the Switch lowering is independent of the other clones. 1790 // Let the LazyCallGraph know about each one separately. 1791 for (Function *Clone : Clones) 1792 CG.addSplitFunction(N.getFunction(), *Clone); 1793 break; 1794 case coro::ABI::Async: 1795 case coro::ABI::Retcon: 1796 case coro::ABI::RetconOnce: 1797 // Each clone in the Async/Retcon lowering references of the other clones. 1798 // Let the LazyCallGraph know about all of them at once. 1799 CG.addSplitRefRecursiveFunctions(N.getFunction(), Clones); 1800 break; 1801 } 1802 1803 // Let the CGSCC infra handle the changes to the original function. 1804 updateCGAndAnalysisManagerForCGSCCPass(CG, C, N, AM, UR, FAM); 1805 } 1806 1807 // Do some cleanup and let the CGSCC infra see if we've cleaned up any edges 1808 // to the split functions. 1809 postSplitCleanup(N.getFunction()); 1810 updateCGAndAnalysisManagerForFunctionPass(CG, C, N, AM, UR, FAM); 1811 } 1812 1813 // When we see the coroutine the first time, we insert an indirect call to a 1814 // devirt trigger function and mark the coroutine that it is now ready for 1815 // split. 1816 // Async lowering uses this after it has split the function to restart the 1817 // pipeline. 1818 static void prepareForSplit(Function &F, CallGraph &CG, 1819 bool MarkForAsyncRestart = false) { 1820 Module &M = *F.getParent(); 1821 LLVMContext &Context = F.getContext(); 1822 #ifndef NDEBUG 1823 Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN); 1824 assert(DevirtFn && "coro.devirt.trigger function not found"); 1825 #endif 1826 1827 F.addFnAttr(CORO_PRESPLIT_ATTR, MarkForAsyncRestart 1828 ? ASYNC_RESTART_AFTER_SPLIT 1829 : PREPARED_FOR_SPLIT); 1830 1831 // Insert an indirect call sequence that will be devirtualized by CoroElide 1832 // pass: 1833 // %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1) 1834 // %1 = bitcast i8* %0 to void(i8*)* 1835 // call void %1(i8* null) 1836 coro::LowererBase Lowerer(M); 1837 Instruction *InsertPt = 1838 MarkForAsyncRestart ? F.getEntryBlock().getFirstNonPHIOrDbgOrLifetime() 1839 : F.getEntryBlock().getTerminator(); 1840 auto *Null = ConstantPointerNull::get(Type::getInt8PtrTy(Context)); 1841 auto *DevirtFnAddr = 1842 Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt); 1843 FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Context), 1844 {Type::getInt8PtrTy(Context)}, false); 1845 auto *IndirectCall = CallInst::Create(FnTy, DevirtFnAddr, Null, "", InsertPt); 1846 1847 // Update CG graph with an indirect call we just added. 1848 CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode()); 1849 } 1850 1851 // Make sure that there is a devirtualization trigger function that the 1852 // coro-split pass uses to force a restart of the CGSCC pipeline. If the devirt 1853 // trigger function is not found, we will create one and add it to the current 1854 // SCC. 1855 static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC) { 1856 Module &M = CG.getModule(); 1857 if (M.getFunction(CORO_DEVIRT_TRIGGER_FN)) 1858 return; 1859 1860 LLVMContext &C = M.getContext(); 1861 auto *FnTy = FunctionType::get(Type::getVoidTy(C), Type::getInt8PtrTy(C), 1862 /*isVarArg=*/false); 1863 Function *DevirtFn = 1864 Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage, 1865 CORO_DEVIRT_TRIGGER_FN, &M); 1866 DevirtFn->addFnAttr(Attribute::AlwaysInline); 1867 auto *Entry = BasicBlock::Create(C, "entry", DevirtFn); 1868 ReturnInst::Create(C, Entry); 1869 1870 auto *Node = CG.getOrInsertFunction(DevirtFn); 1871 1872 SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end()); 1873 Nodes.push_back(Node); 1874 SCC.initialize(Nodes); 1875 } 1876 1877 /// Replace a call to llvm.coro.prepare.retcon. 1878 static void replacePrepare(CallInst *Prepare, LazyCallGraph &CG, 1879 LazyCallGraph::SCC &C) { 1880 auto CastFn = Prepare->getArgOperand(0); // as an i8* 1881 auto Fn = CastFn->stripPointerCasts(); // as its original type 1882 1883 // Attempt to peephole this pattern: 1884 // %0 = bitcast [[TYPE]] @some_function to i8* 1885 // %1 = call @llvm.coro.prepare.retcon(i8* %0) 1886 // %2 = bitcast %1 to [[TYPE]] 1887 // ==> 1888 // %2 = @some_function 1889 for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); UI != UE;) { 1890 // Look for bitcasts back to the original function type. 1891 auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser()); 1892 if (!Cast || Cast->getType() != Fn->getType()) 1893 continue; 1894 1895 // Replace and remove the cast. 1896 Cast->replaceAllUsesWith(Fn); 1897 Cast->eraseFromParent(); 1898 } 1899 1900 // Replace any remaining uses with the function as an i8*. 1901 // This can never directly be a callee, so we don't need to update CG. 1902 Prepare->replaceAllUsesWith(CastFn); 1903 Prepare->eraseFromParent(); 1904 1905 // Kill dead bitcasts. 1906 while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) { 1907 if (!Cast->use_empty()) 1908 break; 1909 CastFn = Cast->getOperand(0); 1910 Cast->eraseFromParent(); 1911 } 1912 } 1913 /// Replace a call to llvm.coro.prepare.retcon. 1914 static void replacePrepare(CallInst *Prepare, CallGraph &CG) { 1915 auto CastFn = Prepare->getArgOperand(0); // as an i8* 1916 auto Fn = CastFn->stripPointerCasts(); // as its original type 1917 1918 // Find call graph nodes for the preparation. 1919 CallGraphNode *PrepareUserNode = nullptr, *FnNode = nullptr; 1920 if (auto ConcreteFn = dyn_cast<Function>(Fn)) { 1921 PrepareUserNode = CG[Prepare->getFunction()]; 1922 FnNode = CG[ConcreteFn]; 1923 } 1924 1925 // Attempt to peephole this pattern: 1926 // %0 = bitcast [[TYPE]] @some_function to i8* 1927 // %1 = call @llvm.coro.prepare.retcon(i8* %0) 1928 // %2 = bitcast %1 to [[TYPE]] 1929 // ==> 1930 // %2 = @some_function 1931 for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); 1932 UI != UE; ) { 1933 // Look for bitcasts back to the original function type. 1934 auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser()); 1935 if (!Cast || Cast->getType() != Fn->getType()) continue; 1936 1937 // Check whether the replacement will introduce new direct calls. 1938 // If so, we'll need to update the call graph. 1939 if (PrepareUserNode) { 1940 for (auto &Use : Cast->uses()) { 1941 if (auto *CB = dyn_cast<CallBase>(Use.getUser())) { 1942 if (!CB->isCallee(&Use)) 1943 continue; 1944 PrepareUserNode->removeCallEdgeFor(*CB); 1945 PrepareUserNode->addCalledFunction(CB, FnNode); 1946 } 1947 } 1948 } 1949 1950 // Replace and remove the cast. 1951 Cast->replaceAllUsesWith(Fn); 1952 Cast->eraseFromParent(); 1953 } 1954 1955 // Replace any remaining uses with the function as an i8*. 1956 // This can never directly be a callee, so we don't need to update CG. 1957 Prepare->replaceAllUsesWith(CastFn); 1958 Prepare->eraseFromParent(); 1959 1960 // Kill dead bitcasts. 1961 while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) { 1962 if (!Cast->use_empty()) break; 1963 CastFn = Cast->getOperand(0); 1964 Cast->eraseFromParent(); 1965 } 1966 } 1967 1968 static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG, 1969 LazyCallGraph::SCC &C) { 1970 bool Changed = false; 1971 for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); PI != PE;) { 1972 // Intrinsics can only be used in calls. 1973 auto *Prepare = cast<CallInst>((PI++)->getUser()); 1974 replacePrepare(Prepare, CG, C); 1975 Changed = true; 1976 } 1977 1978 return Changed; 1979 } 1980 1981 /// Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent 1982 /// IPO from operating on calls to a retcon coroutine before it's been 1983 /// split. This is only safe to do after we've split all retcon 1984 /// coroutines in the module. We can do that this in this pass because 1985 /// this pass does promise to split all retcon coroutines (as opposed to 1986 /// switch coroutines, which are lowered in multiple stages). 1987 static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG) { 1988 bool Changed = false; 1989 for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); 1990 PI != PE; ) { 1991 // Intrinsics can only be used in calls. 1992 auto *Prepare = cast<CallInst>((PI++)->getUser()); 1993 replacePrepare(Prepare, CG); 1994 Changed = true; 1995 } 1996 1997 return Changed; 1998 } 1999 2000 static bool declaresCoroSplitIntrinsics(const Module &M) { 2001 return coro::declaresIntrinsics(M, {"llvm.coro.begin", 2002 "llvm.coro.prepare.retcon", 2003 "llvm.coro.prepare.async"}); 2004 } 2005 2006 static void addPrepareFunction(const Module &M, 2007 SmallVectorImpl<Function *> &Fns, 2008 StringRef Name) { 2009 auto *PrepareFn = M.getFunction(Name); 2010 if (PrepareFn && !PrepareFn->use_empty()) 2011 Fns.push_back(PrepareFn); 2012 } 2013 2014 PreservedAnalyses CoroSplitPass::run(LazyCallGraph::SCC &C, 2015 CGSCCAnalysisManager &AM, 2016 LazyCallGraph &CG, CGSCCUpdateResult &UR) { 2017 // NB: One invariant of a valid LazyCallGraph::SCC is that it must contain a 2018 // non-zero number of nodes, so we assume that here and grab the first 2019 // node's function's module. 2020 Module &M = *C.begin()->getFunction().getParent(); 2021 auto &FAM = 2022 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 2023 2024 if (!declaresCoroSplitIntrinsics(M)) 2025 return PreservedAnalyses::all(); 2026 2027 // Check for uses of llvm.coro.prepare.retcon/async. 2028 SmallVector<Function *, 2> PrepareFns; 2029 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon"); 2030 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async"); 2031 2032 // Find coroutines for processing. 2033 SmallVector<LazyCallGraph::Node *, 4> Coroutines; 2034 for (LazyCallGraph::Node &N : C) 2035 if (N.getFunction().hasFnAttribute(CORO_PRESPLIT_ATTR)) 2036 Coroutines.push_back(&N); 2037 2038 if (Coroutines.empty() && PrepareFns.empty()) 2039 return PreservedAnalyses::all(); 2040 2041 if (Coroutines.empty()) { 2042 for (auto *PrepareFn : PrepareFns) { 2043 replaceAllPrepares(PrepareFn, CG, C); 2044 } 2045 } 2046 2047 // Split all the coroutines. 2048 for (LazyCallGraph::Node *N : Coroutines) { 2049 Function &F = N->getFunction(); 2050 Attribute Attr = F.getFnAttribute(CORO_PRESPLIT_ATTR); 2051 StringRef Value = Attr.getValueAsString(); 2052 LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F.getName() 2053 << "' state: " << Value << "\n"); 2054 if (Value == UNPREPARED_FOR_SPLIT) { 2055 // Enqueue a second iteration of the CGSCC pipeline on this SCC. 2056 UR.CWorklist.insert(&C); 2057 F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT); 2058 continue; 2059 } 2060 F.removeFnAttr(CORO_PRESPLIT_ATTR); 2061 2062 SmallVector<Function *, 4> Clones; 2063 const coro::Shape Shape = splitCoroutine(F, Clones, ReuseFrameSlot); 2064 updateCallGraphAfterCoroutineSplit(*N, Shape, Clones, C, CG, AM, UR, FAM); 2065 2066 if ((Shape.ABI == coro::ABI::Async || Shape.ABI == coro::ABI::Retcon || 2067 Shape.ABI == coro::ABI::RetconOnce) && 2068 !Shape.CoroSuspends.empty()) { 2069 // Run the CGSCC pipeline on the newly split functions. 2070 // All clones will be in the same RefSCC, so choose a random clone. 2071 UR.RCWorklist.insert(CG.lookupRefSCC(CG.get(*Clones[0]))); 2072 } 2073 } 2074 2075 if (!PrepareFns.empty()) { 2076 for (auto *PrepareFn : PrepareFns) { 2077 replaceAllPrepares(PrepareFn, CG, C); 2078 } 2079 } 2080 2081 return PreservedAnalyses::none(); 2082 } 2083 2084 namespace { 2085 2086 // We present a coroutine to LLVM as an ordinary function with suspension 2087 // points marked up with intrinsics. We let the optimizer party on the coroutine 2088 // as a single function for as long as possible. Shortly before the coroutine is 2089 // eligible to be inlined into its callers, we split up the coroutine into parts 2090 // corresponding to initial, resume and destroy invocations of the coroutine, 2091 // add them to the current SCC and restart the IPO pipeline to optimize the 2092 // coroutine subfunctions we extracted before proceeding to the caller of the 2093 // coroutine. 2094 struct CoroSplitLegacy : public CallGraphSCCPass { 2095 static char ID; // Pass identification, replacement for typeid 2096 2097 CoroSplitLegacy(bool ReuseFrameSlot = false) 2098 : CallGraphSCCPass(ID), ReuseFrameSlot(ReuseFrameSlot) { 2099 initializeCoroSplitLegacyPass(*PassRegistry::getPassRegistry()); 2100 } 2101 2102 bool Run = false; 2103 bool ReuseFrameSlot; 2104 2105 // A coroutine is identified by the presence of coro.begin intrinsic, if 2106 // we don't have any, this pass has nothing to do. 2107 bool doInitialization(CallGraph &CG) override { 2108 Run = declaresCoroSplitIntrinsics(CG.getModule()); 2109 return CallGraphSCCPass::doInitialization(CG); 2110 } 2111 2112 bool runOnSCC(CallGraphSCC &SCC) override { 2113 if (!Run) 2114 return false; 2115 2116 // Check for uses of llvm.coro.prepare.retcon. 2117 SmallVector<Function *, 2> PrepareFns; 2118 auto &M = SCC.getCallGraph().getModule(); 2119 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon"); 2120 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async"); 2121 2122 // Find coroutines for processing. 2123 SmallVector<Function *, 4> Coroutines; 2124 for (CallGraphNode *CGN : SCC) 2125 if (auto *F = CGN->getFunction()) 2126 if (F->hasFnAttribute(CORO_PRESPLIT_ATTR)) 2127 Coroutines.push_back(F); 2128 2129 if (Coroutines.empty() && PrepareFns.empty()) 2130 return false; 2131 2132 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 2133 2134 if (Coroutines.empty()) { 2135 bool Changed = false; 2136 for (auto *PrepareFn : PrepareFns) 2137 Changed |= replaceAllPrepares(PrepareFn, CG); 2138 return Changed; 2139 } 2140 2141 createDevirtTriggerFunc(CG, SCC); 2142 2143 // Split all the coroutines. 2144 for (Function *F : Coroutines) { 2145 Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR); 2146 StringRef Value = Attr.getValueAsString(); 2147 LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName() 2148 << "' state: " << Value << "\n"); 2149 // Async lowering marks coroutines to trigger a restart of the pipeline 2150 // after it has split them. 2151 if (Value == ASYNC_RESTART_AFTER_SPLIT) { 2152 F->removeFnAttr(CORO_PRESPLIT_ATTR); 2153 continue; 2154 } 2155 if (Value == UNPREPARED_FOR_SPLIT) { 2156 prepareForSplit(*F, CG); 2157 continue; 2158 } 2159 F->removeFnAttr(CORO_PRESPLIT_ATTR); 2160 2161 SmallVector<Function *, 4> Clones; 2162 const coro::Shape Shape = splitCoroutine(*F, Clones, ReuseFrameSlot); 2163 updateCallGraphAfterCoroutineSplit(*F, Shape, Clones, CG, SCC); 2164 if (Shape.ABI == coro::ABI::Async) { 2165 // Restart SCC passes. 2166 // Mark function for CoroElide pass. It will devirtualize causing a 2167 // restart of the SCC pipeline. 2168 prepareForSplit(*F, CG, true /*MarkForAsyncRestart*/); 2169 } 2170 } 2171 2172 for (auto *PrepareFn : PrepareFns) 2173 replaceAllPrepares(PrepareFn, CG); 2174 2175 return true; 2176 } 2177 2178 void getAnalysisUsage(AnalysisUsage &AU) const override { 2179 CallGraphSCCPass::getAnalysisUsage(AU); 2180 } 2181 2182 StringRef getPassName() const override { return "Coroutine Splitting"; } 2183 }; 2184 2185 } // end anonymous namespace 2186 2187 char CoroSplitLegacy::ID = 0; 2188 2189 INITIALIZE_PASS_BEGIN( 2190 CoroSplitLegacy, "coro-split", 2191 "Split coroutine into a set of functions driving its state machine", false, 2192 false) 2193 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 2194 INITIALIZE_PASS_END( 2195 CoroSplitLegacy, "coro-split", 2196 "Split coroutine into a set of functions driving its state machine", false, 2197 false) 2198 2199 Pass *llvm::createCoroSplitLegacyPass(bool ReuseFrameSlot) { 2200 return new CoroSplitLegacy(ReuseFrameSlot); 2201 } 2202