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 "CoroInstr.h" 22 #include "CoroInternal.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Twine.h" 28 #include "llvm/Analysis/CallGraph.h" 29 #include "llvm/Analysis/CallGraphSCCPass.h" 30 #include "llvm/IR/Argument.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CFG.h" 34 #include "llvm/IR/CallSite.h" 35 #include "llvm/IR/CallingConv.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DataLayout.h" 38 #include "llvm/IR/DerivedTypes.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/GlobalVariable.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/IR/InstIterator.h" 44 #include "llvm/IR/InstrTypes.h" 45 #include "llvm/IR/Instruction.h" 46 #include "llvm/IR/Instructions.h" 47 #include "llvm/IR/IntrinsicInst.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/LegacyPassManager.h" 50 #include "llvm/IR/Module.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/IR/Verifier.h" 54 #include "llvm/InitializePasses.h" 55 #include "llvm/Pass.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/PrettyStackTrace.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Scalar.h" 61 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 62 #include "llvm/Transforms/Utils/Cloning.h" 63 #include "llvm/Transforms/Utils/Local.h" 64 #include "llvm/Transforms/Utils/ValueMapper.h" 65 #include <cassert> 66 #include <cstddef> 67 #include <cstdint> 68 #include <initializer_list> 69 #include <iterator> 70 71 using namespace llvm; 72 73 #define DEBUG_TYPE "coro-split" 74 75 namespace { 76 77 /// A little helper class for building 78 class CoroCloner { 79 public: 80 enum class Kind { 81 /// The shared resume function for a switch lowering. 82 SwitchResume, 83 84 /// The shared unwind function for a switch lowering. 85 SwitchUnwind, 86 87 /// The shared cleanup function for a switch lowering. 88 SwitchCleanup, 89 90 /// An individual continuation function. 91 Continuation, 92 }; 93 private: 94 Function &OrigF; 95 Function *NewF; 96 const Twine &Suffix; 97 coro::Shape &Shape; 98 Kind FKind; 99 ValueToValueMapTy VMap; 100 IRBuilder<> Builder; 101 Value *NewFramePtr = nullptr; 102 Value *SwiftErrorSlot = nullptr; 103 104 /// The active suspend instruction; meaningful only for continuation ABIs. 105 AnyCoroSuspendInst *ActiveSuspend = nullptr; 106 107 public: 108 /// Create a cloner for a switch lowering. 109 CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, 110 Kind FKind) 111 : OrigF(OrigF), NewF(nullptr), Suffix(Suffix), Shape(Shape), 112 FKind(FKind), Builder(OrigF.getContext()) { 113 assert(Shape.ABI == coro::ABI::Switch); 114 } 115 116 /// Create a cloner for a continuation lowering. 117 CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, 118 Function *NewF, AnyCoroSuspendInst *ActiveSuspend) 119 : OrigF(OrigF), NewF(NewF), Suffix(Suffix), Shape(Shape), 120 FKind(Kind::Continuation), Builder(OrigF.getContext()), 121 ActiveSuspend(ActiveSuspend) { 122 assert(Shape.ABI == coro::ABI::Retcon || 123 Shape.ABI == coro::ABI::RetconOnce); 124 assert(NewF && "need existing function for continuation"); 125 assert(ActiveSuspend && "need active suspend point for continuation"); 126 } 127 128 Function *getFunction() const { 129 assert(NewF != nullptr && "declaration not yet set"); 130 return NewF; 131 } 132 133 void create(); 134 135 private: 136 bool isSwitchDestroyFunction() { 137 switch (FKind) { 138 case Kind::Continuation: 139 case Kind::SwitchResume: 140 return false; 141 case Kind::SwitchUnwind: 142 case Kind::SwitchCleanup: 143 return true; 144 } 145 llvm_unreachable("Unknown CoroCloner::Kind enum"); 146 } 147 148 void createDeclaration(); 149 void replaceEntryBlock(); 150 Value *deriveNewFramePointer(); 151 void replaceRetconSuspendUses(); 152 void replaceCoroSuspends(); 153 void replaceCoroEnds(); 154 void replaceSwiftErrorOps(); 155 void handleFinalSuspend(); 156 void maybeFreeContinuationStorage(); 157 }; 158 159 } // end anonymous namespace 160 161 static void maybeFreeRetconStorage(IRBuilder<> &Builder, coro::Shape &Shape, 162 Value *FramePtr, CallGraph *CG) { 163 assert(Shape.ABI == coro::ABI::Retcon || 164 Shape.ABI == coro::ABI::RetconOnce); 165 if (Shape.RetconLowering.IsFrameInlineInStorage) 166 return; 167 168 Shape.emitDealloc(Builder, FramePtr, CG); 169 } 170 171 /// Replace a non-unwind call to llvm.coro.end. 172 static void replaceFallthroughCoroEnd(CoroEndInst *End, coro::Shape &Shape, 173 Value *FramePtr, bool InResume, 174 CallGraph *CG) { 175 // Start inserting right before the coro.end. 176 IRBuilder<> Builder(End); 177 178 // Create the return instruction. 179 switch (Shape.ABI) { 180 // The cloned functions in switch-lowering always return void. 181 case coro::ABI::Switch: 182 // coro.end doesn't immediately end the coroutine in the main function 183 // in this lowering, because we need to deallocate the coroutine. 184 if (!InResume) 185 return; 186 Builder.CreateRetVoid(); 187 break; 188 189 // In unique continuation lowering, the continuations always return void. 190 // But we may have implicitly allocated storage. 191 case coro::ABI::RetconOnce: 192 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 193 Builder.CreateRetVoid(); 194 break; 195 196 // In non-unique continuation lowering, we signal completion by returning 197 // a null continuation. 198 case coro::ABI::Retcon: { 199 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 200 auto RetTy = Shape.getResumeFunctionType()->getReturnType(); 201 auto RetStructTy = dyn_cast<StructType>(RetTy); 202 PointerType *ContinuationTy = 203 cast<PointerType>(RetStructTy ? RetStructTy->getElementType(0) : RetTy); 204 205 Value *ReturnValue = ConstantPointerNull::get(ContinuationTy); 206 if (RetStructTy) { 207 ReturnValue = Builder.CreateInsertValue(UndefValue::get(RetStructTy), 208 ReturnValue, 0); 209 } 210 Builder.CreateRet(ReturnValue); 211 break; 212 } 213 } 214 215 // Remove the rest of the block, by splitting it into an unreachable block. 216 auto *BB = End->getParent(); 217 BB->splitBasicBlock(End); 218 BB->getTerminator()->eraseFromParent(); 219 } 220 221 /// Replace an unwind call to llvm.coro.end. 222 static void replaceUnwindCoroEnd(CoroEndInst *End, coro::Shape &Shape, 223 Value *FramePtr, bool InResume, CallGraph *CG){ 224 IRBuilder<> Builder(End); 225 226 switch (Shape.ABI) { 227 // In switch-lowering, this does nothing in the main function. 228 case coro::ABI::Switch: 229 if (!InResume) 230 return; 231 break; 232 233 // In continuation-lowering, this frees the continuation storage. 234 case coro::ABI::Retcon: 235 case coro::ABI::RetconOnce: 236 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 237 break; 238 } 239 240 // If coro.end has an associated bundle, add cleanupret instruction. 241 if (auto Bundle = End->getOperandBundle(LLVMContext::OB_funclet)) { 242 auto *FromPad = cast<CleanupPadInst>(Bundle->Inputs[0]); 243 auto *CleanupRet = Builder.CreateCleanupRet(FromPad, nullptr); 244 End->getParent()->splitBasicBlock(End); 245 CleanupRet->getParent()->getTerminator()->eraseFromParent(); 246 } 247 } 248 249 static void replaceCoroEnd(CoroEndInst *End, coro::Shape &Shape, 250 Value *FramePtr, bool InResume, CallGraph *CG) { 251 if (End->isUnwind()) 252 replaceUnwindCoroEnd(End, Shape, FramePtr, InResume, CG); 253 else 254 replaceFallthroughCoroEnd(End, Shape, FramePtr, InResume, CG); 255 256 auto &Context = End->getContext(); 257 End->replaceAllUsesWith(InResume ? ConstantInt::getTrue(Context) 258 : ConstantInt::getFalse(Context)); 259 End->eraseFromParent(); 260 } 261 262 // Create an entry block for a resume function with a switch that will jump to 263 // suspend points. 264 static void createResumeEntryBlock(Function &F, coro::Shape &Shape) { 265 assert(Shape.ABI == coro::ABI::Switch); 266 LLVMContext &C = F.getContext(); 267 268 // resume.entry: 269 // %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0, 270 // i32 2 271 // % index = load i32, i32* %index.addr 272 // switch i32 %index, label %unreachable [ 273 // i32 0, label %resume.0 274 // i32 1, label %resume.1 275 // ... 276 // ] 277 278 auto *NewEntry = BasicBlock::Create(C, "resume.entry", &F); 279 auto *UnreachBB = BasicBlock::Create(C, "unreachable", &F); 280 281 IRBuilder<> Builder(NewEntry); 282 auto *FramePtr = Shape.FramePtr; 283 auto *FrameTy = Shape.FrameTy; 284 auto *GepIndex = Builder.CreateStructGEP( 285 FrameTy, FramePtr, coro::Shape::SwitchFieldIndex::Index, "index.addr"); 286 auto *Index = Builder.CreateLoad(Shape.getIndexType(), GepIndex, "index"); 287 auto *Switch = 288 Builder.CreateSwitch(Index, UnreachBB, Shape.CoroSuspends.size()); 289 Shape.SwitchLowering.ResumeSwitch = Switch; 290 291 size_t SuspendIndex = 0; 292 for (auto *AnyS : Shape.CoroSuspends) { 293 auto *S = cast<CoroSuspendInst>(AnyS); 294 ConstantInt *IndexVal = Shape.getIndex(SuspendIndex); 295 296 // Replace CoroSave with a store to Index: 297 // %index.addr = getelementptr %f.frame... (index field number) 298 // store i32 0, i32* %index.addr1 299 auto *Save = S->getCoroSave(); 300 Builder.SetInsertPoint(Save); 301 if (S->isFinal()) { 302 // Final suspend point is represented by storing zero in ResumeFnAddr. 303 auto *GepIndex = Builder.CreateStructGEP(FrameTy, FramePtr, 304 coro::Shape::SwitchFieldIndex::Resume, 305 "ResumeFn.addr"); 306 auto *NullPtr = ConstantPointerNull::get(cast<PointerType>( 307 cast<PointerType>(GepIndex->getType())->getElementType())); 308 Builder.CreateStore(NullPtr, GepIndex); 309 } else { 310 auto *GepIndex = Builder.CreateStructGEP( 311 FrameTy, FramePtr, coro::Shape::SwitchFieldIndex::Index, "index.addr"); 312 Builder.CreateStore(IndexVal, GepIndex); 313 } 314 Save->replaceAllUsesWith(ConstantTokenNone::get(C)); 315 Save->eraseFromParent(); 316 317 // Split block before and after coro.suspend and add a jump from an entry 318 // switch: 319 // 320 // whateverBB: 321 // whatever 322 // %0 = call i8 @llvm.coro.suspend(token none, i1 false) 323 // switch i8 %0, label %suspend[i8 0, label %resume 324 // i8 1, label %cleanup] 325 // becomes: 326 // 327 // whateverBB: 328 // whatever 329 // br label %resume.0.landing 330 // 331 // resume.0: ; <--- jump from the switch in the resume.entry 332 // %0 = tail call i8 @llvm.coro.suspend(token none, i1 false) 333 // br label %resume.0.landing 334 // 335 // resume.0.landing: 336 // %1 = phi i8[-1, %whateverBB], [%0, %resume.0] 337 // switch i8 % 1, label %suspend [i8 0, label %resume 338 // i8 1, label %cleanup] 339 340 auto *SuspendBB = S->getParent(); 341 auto *ResumeBB = 342 SuspendBB->splitBasicBlock(S, "resume." + Twine(SuspendIndex)); 343 auto *LandingBB = ResumeBB->splitBasicBlock( 344 S->getNextNode(), ResumeBB->getName() + Twine(".landing")); 345 Switch->addCase(IndexVal, ResumeBB); 346 347 cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB); 348 auto *PN = PHINode::Create(Builder.getInt8Ty(), 2, "", &LandingBB->front()); 349 S->replaceAllUsesWith(PN); 350 PN->addIncoming(Builder.getInt8(-1), SuspendBB); 351 PN->addIncoming(S, ResumeBB); 352 353 ++SuspendIndex; 354 } 355 356 Builder.SetInsertPoint(UnreachBB); 357 Builder.CreateUnreachable(); 358 359 Shape.SwitchLowering.ResumeEntryBlock = NewEntry; 360 } 361 362 363 // Rewrite final suspend point handling. We do not use suspend index to 364 // represent the final suspend point. Instead we zero-out ResumeFnAddr in the 365 // coroutine frame, since it is undefined behavior to resume a coroutine 366 // suspended at the final suspend point. Thus, in the resume function, we can 367 // simply remove the last case (when coro::Shape is built, the final suspend 368 // point (if present) is always the last element of CoroSuspends array). 369 // In the destroy function, we add a code sequence to check if ResumeFnAddress 370 // is Null, and if so, jump to the appropriate label to handle cleanup from the 371 // final suspend point. 372 void CoroCloner::handleFinalSuspend() { 373 assert(Shape.ABI == coro::ABI::Switch && 374 Shape.SwitchLowering.HasFinalSuspend); 375 auto *Switch = cast<SwitchInst>(VMap[Shape.SwitchLowering.ResumeSwitch]); 376 auto FinalCaseIt = std::prev(Switch->case_end()); 377 BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor(); 378 Switch->removeCase(FinalCaseIt); 379 if (isSwitchDestroyFunction()) { 380 BasicBlock *OldSwitchBB = Switch->getParent(); 381 auto *NewSwitchBB = OldSwitchBB->splitBasicBlock(Switch, "Switch"); 382 Builder.SetInsertPoint(OldSwitchBB->getTerminator()); 383 auto *GepIndex = Builder.CreateStructGEP(Shape.FrameTy, NewFramePtr, 384 coro::Shape::SwitchFieldIndex::Resume, 385 "ResumeFn.addr"); 386 auto *Load = Builder.CreateLoad(Shape.getSwitchResumePointerType(), 387 GepIndex); 388 auto *Cond = Builder.CreateIsNull(Load); 389 Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB); 390 OldSwitchBB->getTerminator()->eraseFromParent(); 391 } 392 } 393 394 static Function *createCloneDeclaration(Function &OrigF, coro::Shape &Shape, 395 const Twine &Suffix, 396 Module::iterator InsertBefore) { 397 Module *M = OrigF.getParent(); 398 auto *FnTy = Shape.getResumeFunctionType(); 399 400 Function *NewF = 401 Function::Create(FnTy, GlobalValue::LinkageTypes::InternalLinkage, 402 OrigF.getName() + Suffix); 403 NewF->addParamAttr(0, Attribute::NonNull); 404 NewF->addParamAttr(0, Attribute::NoAlias); 405 406 M->getFunctionList().insert(InsertBefore, NewF); 407 408 return NewF; 409 } 410 411 /// Replace uses of the active llvm.coro.suspend.retcon call with the 412 /// arguments to the continuation function. 413 /// 414 /// This assumes that the builder has a meaningful insertion point. 415 void CoroCloner::replaceRetconSuspendUses() { 416 assert(Shape.ABI == coro::ABI::Retcon || 417 Shape.ABI == coro::ABI::RetconOnce); 418 419 auto NewS = VMap[ActiveSuspend]; 420 if (NewS->use_empty()) return; 421 422 // Copy out all the continuation arguments after the buffer pointer into 423 // an easily-indexed data structure for convenience. 424 SmallVector<Value*, 8> Args; 425 for (auto I = std::next(NewF->arg_begin()), E = NewF->arg_end(); I != E; ++I) 426 Args.push_back(&*I); 427 428 // If the suspend returns a single scalar value, we can just do a simple 429 // replacement. 430 if (!isa<StructType>(NewS->getType())) { 431 assert(Args.size() == 1); 432 NewS->replaceAllUsesWith(Args.front()); 433 return; 434 } 435 436 // Try to peephole extracts of an aggregate return. 437 for (auto UI = NewS->use_begin(), UE = NewS->use_end(); UI != UE; ) { 438 auto EVI = dyn_cast<ExtractValueInst>((UI++)->getUser()); 439 if (!EVI || EVI->getNumIndices() != 1) 440 continue; 441 442 EVI->replaceAllUsesWith(Args[EVI->getIndices().front()]); 443 EVI->eraseFromParent(); 444 } 445 446 // If we have no remaining uses, we're done. 447 if (NewS->use_empty()) return; 448 449 // Otherwise, we need to create an aggregate. 450 Value *Agg = UndefValue::get(NewS->getType()); 451 for (size_t I = 0, E = Args.size(); I != E; ++I) 452 Agg = Builder.CreateInsertValue(Agg, Args[I], I); 453 454 NewS->replaceAllUsesWith(Agg); 455 } 456 457 void CoroCloner::replaceCoroSuspends() { 458 Value *SuspendResult; 459 460 switch (Shape.ABI) { 461 // In switch lowering, replace coro.suspend with the appropriate value 462 // for the type of function we're extracting. 463 // Replacing coro.suspend with (0) will result in control flow proceeding to 464 // a resume label associated with a suspend point, replacing it with (1) will 465 // result in control flow proceeding to a cleanup label associated with this 466 // suspend point. 467 case coro::ABI::Switch: 468 SuspendResult = Builder.getInt8(isSwitchDestroyFunction() ? 1 : 0); 469 break; 470 471 // In returned-continuation lowering, the arguments from earlier 472 // continuations are theoretically arbitrary, and they should have been 473 // spilled. 474 case coro::ABI::RetconOnce: 475 case coro::ABI::Retcon: 476 return; 477 } 478 479 for (AnyCoroSuspendInst *CS : Shape.CoroSuspends) { 480 // The active suspend was handled earlier. 481 if (CS == ActiveSuspend) continue; 482 483 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[CS]); 484 MappedCS->replaceAllUsesWith(SuspendResult); 485 MappedCS->eraseFromParent(); 486 } 487 } 488 489 void CoroCloner::replaceCoroEnds() { 490 for (CoroEndInst *CE : Shape.CoroEnds) { 491 // We use a null call graph because there's no call graph node for 492 // the cloned function yet. We'll just be rebuilding that later. 493 auto NewCE = cast<CoroEndInst>(VMap[CE]); 494 replaceCoroEnd(NewCE, Shape, NewFramePtr, /*in resume*/ true, nullptr); 495 } 496 } 497 498 static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape, 499 ValueToValueMapTy *VMap) { 500 Value *CachedSlot = nullptr; 501 auto getSwiftErrorSlot = [&](Type *ValueTy) -> Value * { 502 if (CachedSlot) { 503 assert(CachedSlot->getType()->getPointerElementType() == ValueTy && 504 "multiple swifterror slots in function with different types"); 505 return CachedSlot; 506 } 507 508 // Check if the function has a swifterror argument. 509 for (auto &Arg : F.args()) { 510 if (Arg.isSwiftError()) { 511 CachedSlot = &Arg; 512 assert(Arg.getType()->getPointerElementType() == ValueTy && 513 "swifterror argument does not have expected type"); 514 return &Arg; 515 } 516 } 517 518 // Create a swifterror alloca. 519 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg()); 520 auto Alloca = Builder.CreateAlloca(ValueTy); 521 Alloca->setSwiftError(true); 522 523 CachedSlot = Alloca; 524 return Alloca; 525 }; 526 527 for (CallInst *Op : Shape.SwiftErrorOps) { 528 auto MappedOp = VMap ? cast<CallInst>((*VMap)[Op]) : Op; 529 IRBuilder<> Builder(MappedOp); 530 531 // If there are no arguments, this is a 'get' operation. 532 Value *MappedResult; 533 if (Op->getNumArgOperands() == 0) { 534 auto ValueTy = Op->getType(); 535 auto Slot = getSwiftErrorSlot(ValueTy); 536 MappedResult = Builder.CreateLoad(ValueTy, Slot); 537 } else { 538 assert(Op->getNumArgOperands() == 1); 539 auto Value = MappedOp->getArgOperand(0); 540 auto ValueTy = Value->getType(); 541 auto Slot = getSwiftErrorSlot(ValueTy); 542 Builder.CreateStore(Value, Slot); 543 MappedResult = Slot; 544 } 545 546 MappedOp->replaceAllUsesWith(MappedResult); 547 MappedOp->eraseFromParent(); 548 } 549 550 // If we're updating the original function, we've invalidated SwiftErrorOps. 551 if (VMap == nullptr) { 552 Shape.SwiftErrorOps.clear(); 553 } 554 } 555 556 void CoroCloner::replaceSwiftErrorOps() { 557 ::replaceSwiftErrorOps(*NewF, Shape, &VMap); 558 } 559 560 void CoroCloner::replaceEntryBlock() { 561 // In the original function, the AllocaSpillBlock is a block immediately 562 // following the allocation of the frame object which defines GEPs for 563 // all the allocas that have been moved into the frame, and it ends by 564 // branching to the original beginning of the coroutine. Make this 565 // the entry block of the cloned function. 566 auto *Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]); 567 Entry->setName("entry" + Suffix); 568 Entry->moveBefore(&NewF->getEntryBlock()); 569 Entry->getTerminator()->eraseFromParent(); 570 571 // Clear all predecessors of the new entry block. There should be 572 // exactly one predecessor, which we created when splitting out 573 // AllocaSpillBlock to begin with. 574 assert(Entry->hasOneUse()); 575 auto BranchToEntry = cast<BranchInst>(Entry->user_back()); 576 assert(BranchToEntry->isUnconditional()); 577 Builder.SetInsertPoint(BranchToEntry); 578 Builder.CreateUnreachable(); 579 BranchToEntry->eraseFromParent(); 580 581 // TODO: move any allocas into Entry that weren't moved into the frame. 582 // (Currently we move all allocas into the frame.) 583 584 // Branch from the entry to the appropriate place. 585 Builder.SetInsertPoint(Entry); 586 switch (Shape.ABI) { 587 case coro::ABI::Switch: { 588 // In switch-lowering, we built a resume-entry block in the original 589 // function. Make the entry block branch to this. 590 auto *SwitchBB = 591 cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]); 592 Builder.CreateBr(SwitchBB); 593 break; 594 } 595 596 case coro::ABI::Retcon: 597 case coro::ABI::RetconOnce: { 598 // In continuation ABIs, we want to branch to immediately after the 599 // active suspend point. Earlier phases will have put the suspend in its 600 // own basic block, so just thread our jump directly to its successor. 601 auto MappedCS = cast<CoroSuspendRetconInst>(VMap[ActiveSuspend]); 602 auto Branch = cast<BranchInst>(MappedCS->getNextNode()); 603 assert(Branch->isUnconditional()); 604 Builder.CreateBr(Branch->getSuccessor(0)); 605 break; 606 } 607 } 608 } 609 610 /// Derive the value of the new frame pointer. 611 Value *CoroCloner::deriveNewFramePointer() { 612 // Builder should be inserting to the front of the new entry block. 613 614 switch (Shape.ABI) { 615 // In switch-lowering, the argument is the frame pointer. 616 case coro::ABI::Switch: 617 return &*NewF->arg_begin(); 618 619 // In continuation-lowering, the argument is the opaque storage. 620 case coro::ABI::Retcon: 621 case coro::ABI::RetconOnce: { 622 Argument *NewStorage = &*NewF->arg_begin(); 623 auto FramePtrTy = Shape.FrameTy->getPointerTo(); 624 625 // If the storage is inline, just bitcast to the storage to the frame type. 626 if (Shape.RetconLowering.IsFrameInlineInStorage) 627 return Builder.CreateBitCast(NewStorage, FramePtrTy); 628 629 // Otherwise, load the real frame from the opaque storage. 630 auto FramePtrPtr = 631 Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo()); 632 return Builder.CreateLoad(FramePtrPtr); 633 } 634 } 635 llvm_unreachable("bad ABI"); 636 } 637 638 /// Clone the body of the original function into a resume function of 639 /// some sort. 640 void CoroCloner::create() { 641 // Create the new function if we don't already have one. 642 if (!NewF) { 643 NewF = createCloneDeclaration(OrigF, Shape, Suffix, 644 OrigF.getParent()->end()); 645 } 646 647 // Replace all args with undefs. The buildCoroutineFrame algorithm already 648 // rewritten access to the args that occurs after suspend points with loads 649 // and stores to/from the coroutine frame. 650 for (Argument &A : OrigF.args()) 651 VMap[&A] = UndefValue::get(A.getType()); 652 653 SmallVector<ReturnInst *, 4> Returns; 654 655 // Ignore attempts to change certain attributes of the function. 656 // TODO: maybe there should be a way to suppress this during cloning? 657 auto savedVisibility = NewF->getVisibility(); 658 auto savedUnnamedAddr = NewF->getUnnamedAddr(); 659 auto savedDLLStorageClass = NewF->getDLLStorageClass(); 660 661 // NewF's linkage (which CloneFunctionInto does *not* change) might not 662 // be compatible with the visibility of OrigF (which it *does* change), 663 // so protect against that. 664 auto savedLinkage = NewF->getLinkage(); 665 NewF->setLinkage(llvm::GlobalValue::ExternalLinkage); 666 667 CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns); 668 669 NewF->setLinkage(savedLinkage); 670 NewF->setVisibility(savedVisibility); 671 NewF->setUnnamedAddr(savedUnnamedAddr); 672 NewF->setDLLStorageClass(savedDLLStorageClass); 673 674 auto &Context = NewF->getContext(); 675 676 // Replace the attributes of the new function: 677 auto OrigAttrs = NewF->getAttributes(); 678 auto NewAttrs = AttributeList(); 679 680 switch (Shape.ABI) { 681 case coro::ABI::Switch: 682 // Bootstrap attributes by copying function attributes from the 683 // original function. This should include optimization settings and so on. 684 NewAttrs = NewAttrs.addAttributes(Context, AttributeList::FunctionIndex, 685 OrigAttrs.getFnAttributes()); 686 break; 687 688 case coro::ABI::Retcon: 689 case coro::ABI::RetconOnce: 690 // If we have a continuation prototype, just use its attributes, 691 // full-stop. 692 NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes(); 693 break; 694 } 695 696 // Make the frame parameter nonnull and noalias. 697 NewAttrs = NewAttrs.addParamAttribute(Context, 0, Attribute::NonNull); 698 NewAttrs = NewAttrs.addParamAttribute(Context, 0, Attribute::NoAlias); 699 700 switch (Shape.ABI) { 701 // In these ABIs, the cloned functions always return 'void', and the 702 // existing return sites are meaningless. Note that for unique 703 // continuations, this includes the returns associated with suspends; 704 // this is fine because we can't suspend twice. 705 case coro::ABI::Switch: 706 case coro::ABI::RetconOnce: 707 // Remove old returns. 708 for (ReturnInst *Return : Returns) 709 changeToUnreachable(Return, /*UseLLVMTrap=*/false); 710 break; 711 712 // With multi-suspend continuations, we'll already have eliminated the 713 // original returns and inserted returns before all the suspend points, 714 // so we want to leave any returns in place. 715 case coro::ABI::Retcon: 716 break; 717 } 718 719 NewF->setAttributes(NewAttrs); 720 NewF->setCallingConv(Shape.getResumeFunctionCC()); 721 722 // Set up the new entry block. 723 replaceEntryBlock(); 724 725 Builder.SetInsertPoint(&NewF->getEntryBlock().front()); 726 NewFramePtr = deriveNewFramePointer(); 727 728 // Remap frame pointer. 729 Value *OldFramePtr = VMap[Shape.FramePtr]; 730 NewFramePtr->takeName(OldFramePtr); 731 OldFramePtr->replaceAllUsesWith(NewFramePtr); 732 733 // Remap vFrame pointer. 734 auto *NewVFrame = Builder.CreateBitCast( 735 NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame"); 736 Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]); 737 OldVFrame->replaceAllUsesWith(NewVFrame); 738 739 switch (Shape.ABI) { 740 case coro::ABI::Switch: 741 // Rewrite final suspend handling as it is not done via switch (allows to 742 // remove final case from the switch, since it is undefined behavior to 743 // resume the coroutine suspended at the final suspend point. 744 if (Shape.SwitchLowering.HasFinalSuspend) 745 handleFinalSuspend(); 746 break; 747 748 case coro::ABI::Retcon: 749 case coro::ABI::RetconOnce: 750 // Replace uses of the active suspend with the corresponding 751 // continuation-function arguments. 752 assert(ActiveSuspend != nullptr && 753 "no active suspend when lowering a continuation-style coroutine"); 754 replaceRetconSuspendUses(); 755 break; 756 } 757 758 // Handle suspends. 759 replaceCoroSuspends(); 760 761 // Handle swifterror. 762 replaceSwiftErrorOps(); 763 764 // Remove coro.end intrinsics. 765 replaceCoroEnds(); 766 767 // Eliminate coro.free from the clones, replacing it with 'null' in cleanup, 768 // to suppress deallocation code. 769 if (Shape.ABI == coro::ABI::Switch) 770 coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]), 771 /*Elide=*/ FKind == CoroCloner::Kind::SwitchCleanup); 772 } 773 774 // Create a resume clone by cloning the body of the original function, setting 775 // new entry block and replacing coro.suspend an appropriate value to force 776 // resume or cleanup pass for every suspend point. 777 static Function *createClone(Function &F, const Twine &Suffix, 778 coro::Shape &Shape, CoroCloner::Kind FKind) { 779 CoroCloner Cloner(F, Suffix, Shape, FKind); 780 Cloner.create(); 781 return Cloner.getFunction(); 782 } 783 784 /// Remove calls to llvm.coro.end in the original function. 785 static void removeCoroEnds(coro::Shape &Shape, CallGraph *CG) { 786 for (auto End : Shape.CoroEnds) { 787 replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, CG); 788 } 789 } 790 791 static void replaceFrameSize(coro::Shape &Shape) { 792 if (Shape.CoroSizes.empty()) 793 return; 794 795 // In the same function all coro.sizes should have the same result type. 796 auto *SizeIntrin = Shape.CoroSizes.back(); 797 Module *M = SizeIntrin->getModule(); 798 const DataLayout &DL = M->getDataLayout(); 799 auto Size = DL.getTypeAllocSize(Shape.FrameTy); 800 auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size); 801 802 for (CoroSizeInst *CS : Shape.CoroSizes) { 803 CS->replaceAllUsesWith(SizeConstant); 804 CS->eraseFromParent(); 805 } 806 } 807 808 // Create a global constant array containing pointers to functions provided and 809 // set Info parameter of CoroBegin to point at this constant. Example: 810 // 811 // @f.resumers = internal constant [2 x void(%f.frame*)*] 812 // [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy] 813 // define void @f() { 814 // ... 815 // call i8* @llvm.coro.begin(i8* null, i32 0, i8* null, 816 // i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*)) 817 // 818 // Assumes that all the functions have the same signature. 819 static void setCoroInfo(Function &F, coro::Shape &Shape, 820 ArrayRef<Function *> Fns) { 821 // This only works under the switch-lowering ABI because coro elision 822 // only works on the switch-lowering ABI. 823 assert(Shape.ABI == coro::ABI::Switch); 824 825 SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end()); 826 assert(!Args.empty()); 827 Function *Part = *Fns.begin(); 828 Module *M = Part->getParent(); 829 auto *ArrTy = ArrayType::get(Part->getType(), Args.size()); 830 831 auto *ConstVal = ConstantArray::get(ArrTy, Args); 832 auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true, 833 GlobalVariable::PrivateLinkage, ConstVal, 834 F.getName() + Twine(".resumers")); 835 836 // Update coro.begin instruction to refer to this constant. 837 LLVMContext &C = F.getContext(); 838 auto *BC = ConstantExpr::getPointerCast(GV, Type::getInt8PtrTy(C)); 839 Shape.getSwitchCoroId()->setInfo(BC); 840 } 841 842 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame. 843 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn, 844 Function *DestroyFn, Function *CleanupFn) { 845 assert(Shape.ABI == coro::ABI::Switch); 846 847 IRBuilder<> Builder(Shape.FramePtr->getNextNode()); 848 auto *ResumeAddr = Builder.CreateStructGEP( 849 Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Resume, 850 "resume.addr"); 851 Builder.CreateStore(ResumeFn, ResumeAddr); 852 853 Value *DestroyOrCleanupFn = DestroyFn; 854 855 CoroIdInst *CoroId = Shape.getSwitchCoroId(); 856 if (CoroAllocInst *CA = CoroId->getCoroAlloc()) { 857 // If there is a CoroAlloc and it returns false (meaning we elide the 858 // allocation, use CleanupFn instead of DestroyFn). 859 DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn); 860 } 861 862 auto *DestroyAddr = Builder.CreateStructGEP( 863 Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Destroy, 864 "destroy.addr"); 865 Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr); 866 } 867 868 static void postSplitCleanup(Function &F) { 869 removeUnreachableBlocks(F); 870 871 // For now, we do a mandatory verification step because we don't 872 // entirely trust this pass. Note that we don't want to add a verifier 873 // pass to FPM below because it will also verify all the global data. 874 verifyFunction(F); 875 876 legacy::FunctionPassManager FPM(F.getParent()); 877 878 FPM.add(createSCCPPass()); 879 FPM.add(createCFGSimplificationPass()); 880 FPM.add(createEarlyCSEPass()); 881 FPM.add(createCFGSimplificationPass()); 882 883 FPM.doInitialization(); 884 FPM.run(F); 885 FPM.doFinalization(); 886 } 887 888 // Assuming we arrived at the block NewBlock from Prev instruction, store 889 // PHI's incoming values in the ResolvedValues map. 890 static void 891 scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock, 892 DenseMap<Value *, Value *> &ResolvedValues) { 893 auto *PrevBB = Prev->getParent(); 894 for (PHINode &PN : NewBlock->phis()) { 895 auto V = PN.getIncomingValueForBlock(PrevBB); 896 // See if we already resolved it. 897 auto VI = ResolvedValues.find(V); 898 if (VI != ResolvedValues.end()) 899 V = VI->second; 900 // Remember the value. 901 ResolvedValues[&PN] = V; 902 } 903 } 904 905 // Replace a sequence of branches leading to a ret, with a clone of a ret 906 // instruction. Suspend instruction represented by a switch, track the PHI 907 // values and select the correct case successor when possible. 908 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) { 909 DenseMap<Value *, Value *> ResolvedValues; 910 911 Instruction *I = InitialInst; 912 while (I->isTerminator()) { 913 if (isa<ReturnInst>(I)) { 914 if (I != InitialInst) 915 ReplaceInstWithInst(InitialInst, I->clone()); 916 return true; 917 } 918 if (auto *BR = dyn_cast<BranchInst>(I)) { 919 if (BR->isUnconditional()) { 920 BasicBlock *BB = BR->getSuccessor(0); 921 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 922 I = BB->getFirstNonPHIOrDbgOrLifetime(); 923 continue; 924 } 925 } else if (auto *SI = dyn_cast<SwitchInst>(I)) { 926 Value *V = SI->getCondition(); 927 auto it = ResolvedValues.find(V); 928 if (it != ResolvedValues.end()) 929 V = it->second; 930 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) { 931 BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor(); 932 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 933 I = BB->getFirstNonPHIOrDbgOrLifetime(); 934 continue; 935 } 936 } 937 return false; 938 } 939 return false; 940 } 941 942 // Add musttail to any resume instructions that is immediately followed by a 943 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call 944 // for symmetrical coroutine control transfer (C++ Coroutines TS extension). 945 // This transformation is done only in the resume part of the coroutine that has 946 // identical signature and calling convention as the coro.resume call. 947 static void addMustTailToCoroResumes(Function &F) { 948 bool changed = false; 949 950 // Collect potential resume instructions. 951 SmallVector<CallInst *, 4> Resumes; 952 for (auto &I : instructions(F)) 953 if (auto *Call = dyn_cast<CallInst>(&I)) 954 if (auto *CalledValue = Call->getCalledValue()) 955 // CoroEarly pass replaced coro resumes with indirect calls to an 956 // address return by CoroSubFnInst intrinsic. See if it is one of those. 957 if (isa<CoroSubFnInst>(CalledValue->stripPointerCasts())) 958 Resumes.push_back(Call); 959 960 // Set musttail on those that are followed by a ret instruction. 961 for (CallInst *Call : Resumes) 962 if (simplifyTerminatorLeadingToRet(Call->getNextNode())) { 963 Call->setTailCallKind(CallInst::TCK_MustTail); 964 changed = true; 965 } 966 967 if (changed) 968 removeUnreachableBlocks(F); 969 } 970 971 // Coroutine has no suspend points. Remove heap allocation for the coroutine 972 // frame if possible. 973 static void handleNoSuspendCoroutine(coro::Shape &Shape) { 974 auto *CoroBegin = Shape.CoroBegin; 975 auto *CoroId = CoroBegin->getId(); 976 auto *AllocInst = CoroId->getCoroAlloc(); 977 switch (Shape.ABI) { 978 case coro::ABI::Switch: { 979 auto SwitchId = cast<CoroIdInst>(CoroId); 980 coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr); 981 if (AllocInst) { 982 IRBuilder<> Builder(AllocInst); 983 // FIXME: Need to handle overaligned members. 984 auto *Frame = Builder.CreateAlloca(Shape.FrameTy); 985 auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy()); 986 AllocInst->replaceAllUsesWith(Builder.getFalse()); 987 AllocInst->eraseFromParent(); 988 CoroBegin->replaceAllUsesWith(VFrame); 989 } else { 990 CoroBegin->replaceAllUsesWith(CoroBegin->getMem()); 991 } 992 break; 993 } 994 995 case coro::ABI::Retcon: 996 case coro::ABI::RetconOnce: 997 CoroBegin->replaceAllUsesWith(UndefValue::get(CoroBegin->getType())); 998 break; 999 } 1000 1001 CoroBegin->eraseFromParent(); 1002 } 1003 1004 // SimplifySuspendPoint needs to check that there is no calls between 1005 // coro_save and coro_suspend, since any of the calls may potentially resume 1006 // the coroutine and if that is the case we cannot eliminate the suspend point. 1007 static bool hasCallsInBlockBetween(Instruction *From, Instruction *To) { 1008 for (Instruction *I = From; I != To; I = I->getNextNode()) { 1009 // Assume that no intrinsic can resume the coroutine. 1010 if (isa<IntrinsicInst>(I)) 1011 continue; 1012 1013 if (CallSite(I)) 1014 return true; 1015 } 1016 return false; 1017 } 1018 1019 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) { 1020 SmallPtrSet<BasicBlock *, 8> Set; 1021 SmallVector<BasicBlock *, 8> Worklist; 1022 1023 Set.insert(SaveBB); 1024 Worklist.push_back(ResDesBB); 1025 1026 // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr 1027 // returns a token consumed by suspend instruction, all blocks in between 1028 // will have to eventually hit SaveBB when going backwards from ResDesBB. 1029 while (!Worklist.empty()) { 1030 auto *BB = Worklist.pop_back_val(); 1031 Set.insert(BB); 1032 for (auto *Pred : predecessors(BB)) 1033 if (Set.count(Pred) == 0) 1034 Worklist.push_back(Pred); 1035 } 1036 1037 // SaveBB and ResDesBB are checked separately in hasCallsBetween. 1038 Set.erase(SaveBB); 1039 Set.erase(ResDesBB); 1040 1041 for (auto *BB : Set) 1042 if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr)) 1043 return true; 1044 1045 return false; 1046 } 1047 1048 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) { 1049 auto *SaveBB = Save->getParent(); 1050 auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent(); 1051 1052 if (SaveBB == ResumeOrDestroyBB) 1053 return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy); 1054 1055 // Any calls from Save to the end of the block? 1056 if (hasCallsInBlockBetween(Save->getNextNode(), nullptr)) 1057 return true; 1058 1059 // Any calls from begging of the block up to ResumeOrDestroy? 1060 if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(), 1061 ResumeOrDestroy)) 1062 return true; 1063 1064 // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB? 1065 if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB)) 1066 return true; 1067 1068 return false; 1069 } 1070 1071 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the 1072 // suspend point and replace it with nornal control flow. 1073 static bool simplifySuspendPoint(CoroSuspendInst *Suspend, 1074 CoroBeginInst *CoroBegin) { 1075 Instruction *Prev = Suspend->getPrevNode(); 1076 if (!Prev) { 1077 auto *Pred = Suspend->getParent()->getSinglePredecessor(); 1078 if (!Pred) 1079 return false; 1080 Prev = Pred->getTerminator(); 1081 } 1082 1083 CallSite CS{Prev}; 1084 if (!CS) 1085 return false; 1086 1087 auto *CallInstr = CS.getInstruction(); 1088 1089 auto *Callee = CS.getCalledValue()->stripPointerCasts(); 1090 1091 // See if the callsite is for resumption or destruction of the coroutine. 1092 auto *SubFn = dyn_cast<CoroSubFnInst>(Callee); 1093 if (!SubFn) 1094 return false; 1095 1096 // Does not refer to the current coroutine, we cannot do anything with it. 1097 if (SubFn->getFrame() != CoroBegin) 1098 return false; 1099 1100 // See if the transformation is safe. Specifically, see if there are any 1101 // calls in between Save and CallInstr. They can potenitally resume the 1102 // coroutine rendering this optimization unsafe. 1103 auto *Save = Suspend->getCoroSave(); 1104 if (hasCallsBetween(Save, CallInstr)) 1105 return false; 1106 1107 // Replace llvm.coro.suspend with the value that results in resumption over 1108 // the resume or cleanup path. 1109 Suspend->replaceAllUsesWith(SubFn->getRawIndex()); 1110 Suspend->eraseFromParent(); 1111 Save->eraseFromParent(); 1112 1113 // No longer need a call to coro.resume or coro.destroy. 1114 if (auto *Invoke = dyn_cast<InvokeInst>(CallInstr)) { 1115 BranchInst::Create(Invoke->getNormalDest(), Invoke); 1116 } 1117 1118 // Grab the CalledValue from CS before erasing the CallInstr. 1119 auto *CalledValue = CS.getCalledValue(); 1120 CallInstr->eraseFromParent(); 1121 1122 // If no more users remove it. Usually it is a bitcast of SubFn. 1123 if (CalledValue != SubFn && CalledValue->user_empty()) 1124 if (auto *I = dyn_cast<Instruction>(CalledValue)) 1125 I->eraseFromParent(); 1126 1127 // Now we are good to remove SubFn. 1128 if (SubFn->user_empty()) 1129 SubFn->eraseFromParent(); 1130 1131 return true; 1132 } 1133 1134 // Remove suspend points that are simplified. 1135 static void simplifySuspendPoints(coro::Shape &Shape) { 1136 // Currently, the only simplification we do is switch-lowering-specific. 1137 if (Shape.ABI != coro::ABI::Switch) 1138 return; 1139 1140 auto &S = Shape.CoroSuspends; 1141 size_t I = 0, N = S.size(); 1142 if (N == 0) 1143 return; 1144 while (true) { 1145 if (simplifySuspendPoint(cast<CoroSuspendInst>(S[I]), Shape.CoroBegin)) { 1146 if (--N == I) 1147 break; 1148 std::swap(S[I], S[N]); 1149 continue; 1150 } 1151 if (++I == N) 1152 break; 1153 } 1154 S.resize(N); 1155 } 1156 1157 static void splitSwitchCoroutine(Function &F, coro::Shape &Shape, 1158 SmallVectorImpl<Function *> &Clones) { 1159 assert(Shape.ABI == coro::ABI::Switch); 1160 1161 createResumeEntryBlock(F, Shape); 1162 auto ResumeClone = createClone(F, ".resume", Shape, 1163 CoroCloner::Kind::SwitchResume); 1164 auto DestroyClone = createClone(F, ".destroy", Shape, 1165 CoroCloner::Kind::SwitchUnwind); 1166 auto CleanupClone = createClone(F, ".cleanup", Shape, 1167 CoroCloner::Kind::SwitchCleanup); 1168 1169 postSplitCleanup(*ResumeClone); 1170 postSplitCleanup(*DestroyClone); 1171 postSplitCleanup(*CleanupClone); 1172 1173 addMustTailToCoroResumes(*ResumeClone); 1174 1175 // Store addresses resume/destroy/cleanup functions in the coroutine frame. 1176 updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone); 1177 1178 assert(Clones.empty()); 1179 Clones.push_back(ResumeClone); 1180 Clones.push_back(DestroyClone); 1181 Clones.push_back(CleanupClone); 1182 1183 // Create a constant array referring to resume/destroy/clone functions pointed 1184 // by the last argument of @llvm.coro.info, so that CoroElide pass can 1185 // determined correct function to call. 1186 setCoroInfo(F, Shape, Clones); 1187 } 1188 1189 static void splitRetconCoroutine(Function &F, coro::Shape &Shape, 1190 SmallVectorImpl<Function *> &Clones) { 1191 assert(Shape.ABI == coro::ABI::Retcon || 1192 Shape.ABI == coro::ABI::RetconOnce); 1193 assert(Clones.empty()); 1194 1195 // Reset various things that the optimizer might have decided it 1196 // "knows" about the coroutine function due to not seeing a return. 1197 F.removeFnAttr(Attribute::NoReturn); 1198 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 1199 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 1200 1201 // Allocate the frame. 1202 auto *Id = cast<AnyCoroIdRetconInst>(Shape.CoroBegin->getId()); 1203 Value *RawFramePtr; 1204 if (Shape.RetconLowering.IsFrameInlineInStorage) { 1205 RawFramePtr = Id->getStorage(); 1206 } else { 1207 IRBuilder<> Builder(Id); 1208 1209 // Determine the size of the frame. 1210 const DataLayout &DL = F.getParent()->getDataLayout(); 1211 auto Size = DL.getTypeAllocSize(Shape.FrameTy); 1212 1213 // Allocate. We don't need to update the call graph node because we're 1214 // going to recompute it from scratch after splitting. 1215 RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr); 1216 RawFramePtr = 1217 Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType()); 1218 1219 // Stash the allocated frame pointer in the continuation storage. 1220 auto Dest = Builder.CreateBitCast(Id->getStorage(), 1221 RawFramePtr->getType()->getPointerTo()); 1222 Builder.CreateStore(RawFramePtr, Dest); 1223 } 1224 1225 // Map all uses of llvm.coro.begin to the allocated frame pointer. 1226 { 1227 // Make sure we don't invalidate Shape.FramePtr. 1228 TrackingVH<Instruction> Handle(Shape.FramePtr); 1229 Shape.CoroBegin->replaceAllUsesWith(RawFramePtr); 1230 Shape.FramePtr = Handle.getValPtr(); 1231 } 1232 1233 // Create a unique return block. 1234 BasicBlock *ReturnBB = nullptr; 1235 SmallVector<PHINode *, 4> ReturnPHIs; 1236 1237 // Create all the functions in order after the main function. 1238 auto NextF = std::next(F.getIterator()); 1239 1240 // Create a continuation function for each of the suspend points. 1241 Clones.reserve(Shape.CoroSuspends.size()); 1242 for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) { 1243 auto Suspend = cast<CoroSuspendRetconInst>(Shape.CoroSuspends[i]); 1244 1245 // Create the clone declaration. 1246 auto Continuation = 1247 createCloneDeclaration(F, Shape, ".resume." + Twine(i), NextF); 1248 Clones.push_back(Continuation); 1249 1250 // Insert a branch to the unified return block immediately before 1251 // the suspend point. 1252 auto SuspendBB = Suspend->getParent(); 1253 auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend); 1254 auto Branch = cast<BranchInst>(SuspendBB->getTerminator()); 1255 1256 // Create the unified return block. 1257 if (!ReturnBB) { 1258 // Place it before the first suspend. 1259 ReturnBB = BasicBlock::Create(F.getContext(), "coro.return", &F, 1260 NewSuspendBB); 1261 Shape.RetconLowering.ReturnBlock = ReturnBB; 1262 1263 IRBuilder<> Builder(ReturnBB); 1264 1265 // Create PHIs for all the return values. 1266 assert(ReturnPHIs.empty()); 1267 1268 // First, the continuation. 1269 ReturnPHIs.push_back(Builder.CreatePHI(Continuation->getType(), 1270 Shape.CoroSuspends.size())); 1271 1272 // Next, all the directly-yielded values. 1273 for (auto ResultTy : Shape.getRetconResultTypes()) 1274 ReturnPHIs.push_back(Builder.CreatePHI(ResultTy, 1275 Shape.CoroSuspends.size())); 1276 1277 // Build the return value. 1278 auto RetTy = F.getReturnType(); 1279 1280 // Cast the continuation value if necessary. 1281 // We can't rely on the types matching up because that type would 1282 // have to be infinite. 1283 auto CastedContinuationTy = 1284 (ReturnPHIs.size() == 1 ? RetTy : RetTy->getStructElementType(0)); 1285 auto *CastedContinuation = 1286 Builder.CreateBitCast(ReturnPHIs[0], CastedContinuationTy); 1287 1288 Value *RetV; 1289 if (ReturnPHIs.size() == 1) { 1290 RetV = CastedContinuation; 1291 } else { 1292 RetV = UndefValue::get(RetTy); 1293 RetV = Builder.CreateInsertValue(RetV, CastedContinuation, 0); 1294 for (size_t I = 1, E = ReturnPHIs.size(); I != E; ++I) 1295 RetV = Builder.CreateInsertValue(RetV, ReturnPHIs[I], I); 1296 } 1297 1298 Builder.CreateRet(RetV); 1299 } 1300 1301 // Branch to the return block. 1302 Branch->setSuccessor(0, ReturnBB); 1303 ReturnPHIs[0]->addIncoming(Continuation, SuspendBB); 1304 size_t NextPHIIndex = 1; 1305 for (auto &VUse : Suspend->value_operands()) 1306 ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB); 1307 assert(NextPHIIndex == ReturnPHIs.size()); 1308 } 1309 1310 assert(Clones.size() == Shape.CoroSuspends.size()); 1311 for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) { 1312 auto Suspend = Shape.CoroSuspends[i]; 1313 auto Clone = Clones[i]; 1314 1315 CoroCloner(F, "resume." + Twine(i), Shape, Clone, Suspend).create(); 1316 } 1317 } 1318 1319 namespace { 1320 class PrettyStackTraceFunction : public PrettyStackTraceEntry { 1321 Function &F; 1322 public: 1323 PrettyStackTraceFunction(Function &F) : F(F) {} 1324 void print(raw_ostream &OS) const override { 1325 OS << "While splitting coroutine "; 1326 F.printAsOperand(OS, /*print type*/ false, F.getParent()); 1327 OS << "\n"; 1328 } 1329 }; 1330 } 1331 1332 static void splitCoroutine(Function &F, coro::Shape &Shape, 1333 SmallVectorImpl<Function *> &Clones) { 1334 switch (Shape.ABI) { 1335 case coro::ABI::Switch: 1336 return splitSwitchCoroutine(F, Shape, Clones); 1337 case coro::ABI::Retcon: 1338 case coro::ABI::RetconOnce: 1339 return splitRetconCoroutine(F, Shape, Clones); 1340 } 1341 llvm_unreachable("bad ABI kind"); 1342 } 1343 1344 static void splitCoroutine(Function &F, CallGraph &CG, CallGraphSCC &SCC) { 1345 PrettyStackTraceFunction prettyStackTrace(F); 1346 1347 // The suspend-crossing algorithm in buildCoroutineFrame get tripped 1348 // up by uses in unreachable blocks, so remove them as a first pass. 1349 removeUnreachableBlocks(F); 1350 1351 coro::Shape Shape(F); 1352 if (!Shape.CoroBegin) 1353 return; 1354 1355 simplifySuspendPoints(Shape); 1356 buildCoroutineFrame(F, Shape); 1357 replaceFrameSize(Shape); 1358 1359 SmallVector<Function*, 4> Clones; 1360 1361 // If there are no suspend points, no split required, just remove 1362 // the allocation and deallocation blocks, they are not needed. 1363 if (Shape.CoroSuspends.empty()) { 1364 handleNoSuspendCoroutine(Shape); 1365 } else { 1366 splitCoroutine(F, Shape, Clones); 1367 } 1368 1369 // Replace all the swifterror operations in the original function. 1370 // This invalidates SwiftErrorOps in the Shape. 1371 replaceSwiftErrorOps(F, Shape, nullptr); 1372 1373 removeCoroEnds(Shape, &CG); 1374 postSplitCleanup(F); 1375 1376 // Update call graph and add the functions we created to the SCC. 1377 coro::updateCallGraph(F, Clones, CG, SCC); 1378 } 1379 1380 // When we see the coroutine the first time, we insert an indirect call to a 1381 // devirt trigger function and mark the coroutine that it is now ready for 1382 // split. 1383 static void prepareForSplit(Function &F, CallGraph &CG) { 1384 Module &M = *F.getParent(); 1385 LLVMContext &Context = F.getContext(); 1386 #ifndef NDEBUG 1387 Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN); 1388 assert(DevirtFn && "coro.devirt.trigger function not found"); 1389 #endif 1390 1391 F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT); 1392 1393 // Insert an indirect call sequence that will be devirtualized by CoroElide 1394 // pass: 1395 // %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1) 1396 // %1 = bitcast i8* %0 to void(i8*)* 1397 // call void %1(i8* null) 1398 coro::LowererBase Lowerer(M); 1399 Instruction *InsertPt = F.getEntryBlock().getTerminator(); 1400 auto *Null = ConstantPointerNull::get(Type::getInt8PtrTy(Context)); 1401 auto *DevirtFnAddr = 1402 Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt); 1403 FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Context), 1404 {Type::getInt8PtrTy(Context)}, false); 1405 auto *IndirectCall = CallInst::Create(FnTy, DevirtFnAddr, Null, "", InsertPt); 1406 1407 // Update CG graph with an indirect call we just added. 1408 CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode()); 1409 } 1410 1411 // Make sure that there is a devirtualization trigger function that CoroSplit 1412 // pass uses the force restart CGSCC pipeline. If devirt trigger function is not 1413 // found, we will create one and add it to the current SCC. 1414 static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC) { 1415 Module &M = CG.getModule(); 1416 if (M.getFunction(CORO_DEVIRT_TRIGGER_FN)) 1417 return; 1418 1419 LLVMContext &C = M.getContext(); 1420 auto *FnTy = FunctionType::get(Type::getVoidTy(C), Type::getInt8PtrTy(C), 1421 /*isVarArg=*/false); 1422 Function *DevirtFn = 1423 Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage, 1424 CORO_DEVIRT_TRIGGER_FN, &M); 1425 DevirtFn->addFnAttr(Attribute::AlwaysInline); 1426 auto *Entry = BasicBlock::Create(C, "entry", DevirtFn); 1427 ReturnInst::Create(C, Entry); 1428 1429 auto *Node = CG.getOrInsertFunction(DevirtFn); 1430 1431 SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end()); 1432 Nodes.push_back(Node); 1433 SCC.initialize(Nodes); 1434 } 1435 1436 /// Replace a call to llvm.coro.prepare.retcon. 1437 static void replacePrepare(CallInst *Prepare, CallGraph &CG) { 1438 auto CastFn = Prepare->getArgOperand(0); // as an i8* 1439 auto Fn = CastFn->stripPointerCasts(); // as its original type 1440 1441 // Find call graph nodes for the preparation. 1442 CallGraphNode *PrepareUserNode = nullptr, *FnNode = nullptr; 1443 if (auto ConcreteFn = dyn_cast<Function>(Fn)) { 1444 PrepareUserNode = CG[Prepare->getFunction()]; 1445 FnNode = CG[ConcreteFn]; 1446 } 1447 1448 // Attempt to peephole this pattern: 1449 // %0 = bitcast [[TYPE]] @some_function to i8* 1450 // %1 = call @llvm.coro.prepare.retcon(i8* %0) 1451 // %2 = bitcast %1 to [[TYPE]] 1452 // ==> 1453 // %2 = @some_function 1454 for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); 1455 UI != UE; ) { 1456 // Look for bitcasts back to the original function type. 1457 auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser()); 1458 if (!Cast || Cast->getType() != Fn->getType()) continue; 1459 1460 // Check whether the replacement will introduce new direct calls. 1461 // If so, we'll need to update the call graph. 1462 if (PrepareUserNode) { 1463 for (auto &Use : Cast->uses()) { 1464 if (auto *CB = dyn_cast<CallBase>(Use.getUser())) { 1465 if (!CB->isCallee(&Use)) 1466 continue; 1467 PrepareUserNode->removeCallEdgeFor(*CB); 1468 PrepareUserNode->addCalledFunction(CB, FnNode); 1469 } 1470 } 1471 } 1472 1473 // Replace and remove the cast. 1474 Cast->replaceAllUsesWith(Fn); 1475 Cast->eraseFromParent(); 1476 } 1477 1478 // Replace any remaining uses with the function as an i8*. 1479 // This can never directly be a callee, so we don't need to update CG. 1480 Prepare->replaceAllUsesWith(CastFn); 1481 Prepare->eraseFromParent(); 1482 1483 // Kill dead bitcasts. 1484 while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) { 1485 if (!Cast->use_empty()) break; 1486 CastFn = Cast->getOperand(0); 1487 Cast->eraseFromParent(); 1488 } 1489 } 1490 1491 /// Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent 1492 /// IPO from operating on calls to a retcon coroutine before it's been 1493 /// split. This is only safe to do after we've split all retcon 1494 /// coroutines in the module. We can do that this in this pass because 1495 /// this pass does promise to split all retcon coroutines (as opposed to 1496 /// switch coroutines, which are lowered in multiple stages). 1497 static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG) { 1498 bool Changed = false; 1499 for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); 1500 PI != PE; ) { 1501 // Intrinsics can only be used in calls. 1502 auto *Prepare = cast<CallInst>((PI++)->getUser()); 1503 replacePrepare(Prepare, CG); 1504 Changed = true; 1505 } 1506 1507 return Changed; 1508 } 1509 1510 //===----------------------------------------------------------------------===// 1511 // Top Level Driver 1512 //===----------------------------------------------------------------------===// 1513 1514 namespace { 1515 1516 struct CoroSplit : public CallGraphSCCPass { 1517 static char ID; // Pass identification, replacement for typeid 1518 1519 CoroSplit() : CallGraphSCCPass(ID) { 1520 initializeCoroSplitPass(*PassRegistry::getPassRegistry()); 1521 } 1522 1523 bool Run = false; 1524 1525 // A coroutine is identified by the presence of coro.begin intrinsic, if 1526 // we don't have any, this pass has nothing to do. 1527 bool doInitialization(CallGraph &CG) override { 1528 Run = coro::declaresIntrinsics(CG.getModule(), 1529 {"llvm.coro.begin", 1530 "llvm.coro.prepare.retcon"}); 1531 return CallGraphSCCPass::doInitialization(CG); 1532 } 1533 1534 bool runOnSCC(CallGraphSCC &SCC) override { 1535 if (!Run) 1536 return false; 1537 1538 // Check for uses of llvm.coro.prepare.retcon. 1539 auto PrepareFn = 1540 SCC.getCallGraph().getModule().getFunction("llvm.coro.prepare.retcon"); 1541 if (PrepareFn && PrepareFn->use_empty()) 1542 PrepareFn = nullptr; 1543 1544 // Find coroutines for processing. 1545 SmallVector<Function *, 4> Coroutines; 1546 for (CallGraphNode *CGN : SCC) 1547 if (auto *F = CGN->getFunction()) 1548 if (F->hasFnAttribute(CORO_PRESPLIT_ATTR)) 1549 Coroutines.push_back(F); 1550 1551 if (Coroutines.empty() && !PrepareFn) 1552 return false; 1553 1554 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 1555 1556 if (Coroutines.empty()) 1557 return replaceAllPrepares(PrepareFn, CG); 1558 1559 createDevirtTriggerFunc(CG, SCC); 1560 1561 // Split all the coroutines. 1562 for (Function *F : Coroutines) { 1563 Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR); 1564 StringRef Value = Attr.getValueAsString(); 1565 LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName() 1566 << "' state: " << Value << "\n"); 1567 if (Value == UNPREPARED_FOR_SPLIT) { 1568 prepareForSplit(*F, CG); 1569 continue; 1570 } 1571 F->removeFnAttr(CORO_PRESPLIT_ATTR); 1572 splitCoroutine(*F, CG, SCC); 1573 } 1574 1575 if (PrepareFn) 1576 replaceAllPrepares(PrepareFn, CG); 1577 1578 return true; 1579 } 1580 1581 void getAnalysisUsage(AnalysisUsage &AU) const override { 1582 CallGraphSCCPass::getAnalysisUsage(AU); 1583 } 1584 1585 StringRef getPassName() const override { return "Coroutine Splitting"; } 1586 }; 1587 1588 } // end anonymous namespace 1589 1590 char CoroSplit::ID = 0; 1591 1592 INITIALIZE_PASS_BEGIN( 1593 CoroSplit, "coro-split", 1594 "Split coroutine into a set of functions driving its state machine", false, 1595 false) 1596 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 1597 INITIALIZE_PASS_END( 1598 CoroSplit, "coro-split", 1599 "Split coroutine into a set of functions driving its state machine", false, 1600 false) 1601 1602 Pass *llvm::createCoroSplitPass() { return new CoroSplit(); } 1603