1 //===- CoroFrame.cpp - Builds and manipulates coroutine frame -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // This file contains classes used to discover if for a particular value 10 // there from sue to definition that crosses a suspend block. 11 // 12 // Using the information discovered we form a Coroutine Frame structure to 13 // contain those values. All uses of those values are replaced with appropriate 14 // GEP + load from the coroutine frame. At the point of the definition we spill 15 // the value into the coroutine frame. 16 // 17 // TODO: pack values tightly using liveness info. 18 //===----------------------------------------------------------------------===// 19 20 #include "CoroInternal.h" 21 #include "llvm/ADT/BitVector.h" 22 #include "llvm/Analysis/Utils/Local.h" 23 #include "llvm/IR/CFG.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/InstIterator.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/MathExtras.h" 29 #include "llvm/Support/circular_raw_ostream.h" 30 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 31 32 using namespace llvm; 33 34 // The "coro-suspend-crossing" flag is very noisy. There is another debug type, 35 // "coro-frame", which results in leaner debug spew. 36 #define DEBUG_TYPE "coro-suspend-crossing" 37 38 enum { SmallVectorThreshold = 32 }; 39 40 // Provides two way mapping between the blocks and numbers. 41 namespace { 42 class BlockToIndexMapping { 43 SmallVector<BasicBlock *, SmallVectorThreshold> V; 44 45 public: 46 size_t size() const { return V.size(); } 47 48 BlockToIndexMapping(Function &F) { 49 for (BasicBlock &BB : F) 50 V.push_back(&BB); 51 std::sort(V.begin(), V.end()); 52 } 53 54 size_t blockToIndex(BasicBlock *BB) const { 55 auto *I = std::lower_bound(V.begin(), V.end(), BB); 56 assert(I != V.end() && *I == BB && "BasicBlockNumberng: Unknown block"); 57 return I - V.begin(); 58 } 59 60 BasicBlock *indexToBlock(unsigned Index) const { return V[Index]; } 61 }; 62 } // end anonymous namespace 63 64 // The SuspendCrossingInfo maintains data that allows to answer a question 65 // whether given two BasicBlocks A and B there is a path from A to B that 66 // passes through a suspend point. 67 // 68 // For every basic block 'i' it maintains a BlockData that consists of: 69 // Consumes: a bit vector which contains a set of indices of blocks that can 70 // reach block 'i' 71 // Kills: a bit vector which contains a set of indices of blocks that can 72 // reach block 'i', but one of the path will cross a suspend point 73 // Suspend: a boolean indicating whether block 'i' contains a suspend point. 74 // End: a boolean indicating whether block 'i' contains a coro.end intrinsic. 75 // 76 namespace { 77 struct SuspendCrossingInfo { 78 BlockToIndexMapping Mapping; 79 80 struct BlockData { 81 BitVector Consumes; 82 BitVector Kills; 83 bool Suspend = false; 84 bool End = false; 85 }; 86 SmallVector<BlockData, SmallVectorThreshold> Block; 87 88 iterator_range<succ_iterator> successors(BlockData const &BD) const { 89 BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]); 90 return llvm::successors(BB); 91 } 92 93 BlockData &getBlockData(BasicBlock *BB) { 94 return Block[Mapping.blockToIndex(BB)]; 95 } 96 97 void dump() const; 98 void dump(StringRef Label, BitVector const &BV) const; 99 100 SuspendCrossingInfo(Function &F, coro::Shape &Shape); 101 102 bool hasPathCrossingSuspendPoint(BasicBlock *DefBB, BasicBlock *UseBB) const { 103 size_t const DefIndex = Mapping.blockToIndex(DefBB); 104 size_t const UseIndex = Mapping.blockToIndex(UseBB); 105 106 assert(Block[UseIndex].Consumes[DefIndex] && "use must consume def"); 107 bool const Result = Block[UseIndex].Kills[DefIndex]; 108 DEBUG(dbgs() << UseBB->getName() << " => " << DefBB->getName() 109 << " answer is " << Result << "\n"); 110 return Result; 111 } 112 113 bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const { 114 auto *I = cast<Instruction>(U); 115 116 // We rewrote PHINodes, so that only the ones with exactly one incoming 117 // value need to be analyzed. 118 if (auto *PN = dyn_cast<PHINode>(I)) 119 if (PN->getNumIncomingValues() > 1) 120 return false; 121 122 BasicBlock *UseBB = I->getParent(); 123 return hasPathCrossingSuspendPoint(DefBB, UseBB); 124 } 125 126 bool isDefinitionAcrossSuspend(Argument &A, User *U) const { 127 return isDefinitionAcrossSuspend(&A.getParent()->getEntryBlock(), U); 128 } 129 130 bool isDefinitionAcrossSuspend(Instruction &I, User *U) const { 131 return isDefinitionAcrossSuspend(I.getParent(), U); 132 } 133 }; 134 } // end anonymous namespace 135 136 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 137 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump(StringRef Label, 138 BitVector const &BV) const { 139 dbgs() << Label << ":"; 140 for (size_t I = 0, N = BV.size(); I < N; ++I) 141 if (BV[I]) 142 dbgs() << " " << Mapping.indexToBlock(I)->getName(); 143 dbgs() << "\n"; 144 } 145 146 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump() const { 147 for (size_t I = 0, N = Block.size(); I < N; ++I) { 148 BasicBlock *const B = Mapping.indexToBlock(I); 149 dbgs() << B->getName() << ":\n"; 150 dump(" Consumes", Block[I].Consumes); 151 dump(" Kills", Block[I].Kills); 152 } 153 dbgs() << "\n"; 154 } 155 #endif 156 157 SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape) 158 : Mapping(F) { 159 const size_t N = Mapping.size(); 160 Block.resize(N); 161 162 // Initialize every block so that it consumes itself 163 for (size_t I = 0; I < N; ++I) { 164 auto &B = Block[I]; 165 B.Consumes.resize(N); 166 B.Kills.resize(N); 167 B.Consumes.set(I); 168 } 169 170 // Mark all CoroEnd Blocks. We do not propagate Kills beyond coro.ends as 171 // the code beyond coro.end is reachable during initial invocation of the 172 // coroutine. 173 for (auto *CE : Shape.CoroEnds) 174 getBlockData(CE->getParent()).End = true; 175 176 // Mark all suspend blocks and indicate that they kill everything they 177 // consume. Note, that crossing coro.save also requires a spill, as any code 178 // between coro.save and coro.suspend may resume the coroutine and all of the 179 // state needs to be saved by that time. 180 auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) { 181 BasicBlock *SuspendBlock = BarrierInst->getParent(); 182 auto &B = getBlockData(SuspendBlock); 183 B.Suspend = true; 184 B.Kills |= B.Consumes; 185 }; 186 for (CoroSuspendInst *CSI : Shape.CoroSuspends) { 187 markSuspendBlock(CSI); 188 markSuspendBlock(CSI->getCoroSave()); 189 } 190 191 // Iterate propagating consumes and kills until they stop changing. 192 int Iteration = 0; 193 (void)Iteration; 194 195 bool Changed; 196 do { 197 DEBUG(dbgs() << "iteration " << ++Iteration); 198 DEBUG(dbgs() << "==============\n"); 199 200 Changed = false; 201 for (size_t I = 0; I < N; ++I) { 202 auto &B = Block[I]; 203 for (BasicBlock *SI : successors(B)) { 204 205 auto SuccNo = Mapping.blockToIndex(SI); 206 207 // Saved Consumes and Kills bitsets so that it is easy to see 208 // if anything changed after propagation. 209 auto &S = Block[SuccNo]; 210 auto SavedConsumes = S.Consumes; 211 auto SavedKills = S.Kills; 212 213 // Propagate Kills and Consumes from block B into its successor S. 214 S.Consumes |= B.Consumes; 215 S.Kills |= B.Kills; 216 217 // If block B is a suspend block, it should propagate kills into the 218 // its successor for every block B consumes. 219 if (B.Suspend) { 220 S.Kills |= B.Consumes; 221 } 222 if (S.Suspend) { 223 // If block S is a suspend block, it should kill all of the blocks it 224 // consumes. 225 S.Kills |= S.Consumes; 226 } else if (S.End) { 227 // If block S is an end block, it should not propagate kills as the 228 // blocks following coro.end() are reached during initial invocation 229 // of the coroutine while all the data are still available on the 230 // stack or in the registers. 231 S.Kills.reset(); 232 } else { 233 // This is reached when S block it not Suspend nor coro.end and it 234 // need to make sure that it is not in the kill set. 235 S.Kills.reset(SuccNo); 236 } 237 238 // See if anything changed. 239 Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes); 240 241 if (S.Kills != SavedKills) { 242 DEBUG(dbgs() << "\nblock " << I << " follower " << SI->getName() 243 << "\n"); 244 DEBUG(dump("S.Kills", S.Kills)); 245 DEBUG(dump("SavedKills", SavedKills)); 246 } 247 if (S.Consumes != SavedConsumes) { 248 DEBUG(dbgs() << "\nblock " << I << " follower " << SI << "\n"); 249 DEBUG(dump("S.Consume", S.Consumes)); 250 DEBUG(dump("SavedCons", SavedConsumes)); 251 } 252 } 253 } 254 } while (Changed); 255 DEBUG(dump()); 256 } 257 258 #undef DEBUG_TYPE // "coro-suspend-crossing" 259 #define DEBUG_TYPE "coro-frame" 260 261 // We build up the list of spills for every case where a use is separated 262 // from the definition by a suspend point. 263 264 namespace { 265 class Spill { 266 Value *Def = nullptr; 267 Instruction *User = nullptr; 268 unsigned FieldNo = 0; 269 270 public: 271 Spill(Value *Def, llvm::User *U) : Def(Def), User(cast<Instruction>(U)) {} 272 273 Value *def() const { return Def; } 274 Instruction *user() const { return User; } 275 BasicBlock *userBlock() const { return User->getParent(); } 276 277 // Note that field index is stored in the first SpillEntry for a particular 278 // definition. Subsequent mentions of a defintion do not have fieldNo 279 // assigned. This works out fine as the users of Spills capture the info about 280 // the definition the first time they encounter it. Consider refactoring 281 // SpillInfo into two arrays to normalize the spill representation. 282 unsigned fieldIndex() const { 283 assert(FieldNo && "Accessing unassigned field"); 284 return FieldNo; 285 } 286 void setFieldIndex(unsigned FieldNumber) { 287 assert(!FieldNo && "Reassigning field number"); 288 FieldNo = FieldNumber; 289 } 290 }; 291 } // namespace 292 293 // Note that there may be more than one record with the same value of Def in 294 // the SpillInfo vector. 295 using SpillInfo = SmallVector<Spill, 8>; 296 297 #ifndef NDEBUG 298 static void dump(StringRef Title, SpillInfo const &Spills) { 299 dbgs() << "------------- " << Title << "--------------\n"; 300 Value *CurrentValue = nullptr; 301 for (auto const &E : Spills) { 302 if (CurrentValue != E.def()) { 303 CurrentValue = E.def(); 304 CurrentValue->dump(); 305 } 306 dbgs() << " user: "; 307 E.user()->dump(); 308 } 309 } 310 #endif 311 312 namespace { 313 // We cannot rely solely on natural alignment of a type when building a 314 // coroutine frame and if the alignment specified on the Alloca instruction 315 // differs from the natural alignment of the alloca type we will need to insert 316 // padding. 317 struct PaddingCalculator { 318 const DataLayout &DL; 319 LLVMContext &Context; 320 unsigned StructSize = 0; 321 322 PaddingCalculator(LLVMContext &Context, DataLayout const &DL) 323 : DL(DL), Context(Context) {} 324 325 // Replicate the logic from IR/DataLayout.cpp to match field offset 326 // computation for LLVM structs. 327 void addType(Type *Ty) { 328 unsigned TyAlign = DL.getABITypeAlignment(Ty); 329 if ((StructSize & (TyAlign - 1)) != 0) 330 StructSize = alignTo(StructSize, TyAlign); 331 332 StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item. 333 } 334 335 void addTypes(SmallVectorImpl<Type *> const &Types) { 336 for (auto *Ty : Types) 337 addType(Ty); 338 } 339 340 unsigned computePadding(Type *Ty, unsigned ForcedAlignment) { 341 unsigned TyAlign = DL.getABITypeAlignment(Ty); 342 auto Natural = alignTo(StructSize, TyAlign); 343 auto Forced = alignTo(StructSize, ForcedAlignment); 344 345 // Return how many bytes of padding we need to insert. 346 if (Natural != Forced) 347 return std::max(Natural, Forced) - StructSize; 348 349 // Rely on natural alignment. 350 return 0; 351 } 352 353 // If padding required, return the padding field type to insert. 354 ArrayType *getPaddingType(Type *Ty, unsigned ForcedAlignment) { 355 if (auto Padding = computePadding(Ty, ForcedAlignment)) 356 return ArrayType::get(Type::getInt8Ty(Context), Padding); 357 358 return nullptr; 359 } 360 }; 361 } // namespace 362 363 // Build a struct that will keep state for an active coroutine. 364 // struct f.frame { 365 // ResumeFnTy ResumeFnAddr; 366 // ResumeFnTy DestroyFnAddr; 367 // int ResumeIndex; 368 // ... promise (if present) ... 369 // ... spills ... 370 // }; 371 static StructType *buildFrameType(Function &F, coro::Shape &Shape, 372 SpillInfo &Spills) { 373 LLVMContext &C = F.getContext(); 374 const DataLayout &DL = F.getParent()->getDataLayout(); 375 PaddingCalculator Padder(C, DL); 376 SmallString<32> Name(F.getName()); 377 Name.append(".Frame"); 378 StructType *FrameTy = StructType::create(C, Name); 379 auto *FramePtrTy = FrameTy->getPointerTo(); 380 auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy, 381 /*IsVarArgs=*/false); 382 auto *FnPtrTy = FnTy->getPointerTo(); 383 384 // Figure out how wide should be an integer type storing the suspend index. 385 unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size())); 386 Type *PromiseType = Shape.PromiseAlloca 387 ? Shape.PromiseAlloca->getType()->getElementType() 388 : Type::getInt1Ty(C); 389 SmallVector<Type *, 8> Types{FnPtrTy, FnPtrTy, PromiseType, 390 Type::getIntNTy(C, IndexBits)}; 391 Value *CurrentDef = nullptr; 392 393 Padder.addTypes(Types); 394 395 // Create an entry for every spilled value. 396 for (auto &S : Spills) { 397 if (CurrentDef == S.def()) 398 continue; 399 400 CurrentDef = S.def(); 401 // PromiseAlloca was already added to Types array earlier. 402 if (CurrentDef == Shape.PromiseAlloca) 403 continue; 404 405 Type *Ty = nullptr; 406 if (auto *AI = dyn_cast<AllocaInst>(CurrentDef)) { 407 Ty = AI->getAllocatedType(); 408 if (unsigned AllocaAlignment = AI->getAlignment()) { 409 // If alignment is specified in alloca, see if we need to insert extra 410 // padding. 411 if (auto PaddingTy = Padder.getPaddingType(Ty, AllocaAlignment)) { 412 Types.push_back(PaddingTy); 413 Padder.addType(PaddingTy); 414 } 415 } 416 } else { 417 Ty = CurrentDef->getType(); 418 } 419 S.setFieldIndex(Types.size()); 420 Types.push_back(Ty); 421 Padder.addType(Ty); 422 } 423 FrameTy->setBody(Types); 424 425 return FrameTy; 426 } 427 428 // We need to make room to insert a spill after initial PHIs, but before 429 // catchswitch instruction. Placing it before violates the requirement that 430 // catchswitch, like all other EHPads must be the first nonPHI in a block. 431 // 432 // Split away catchswitch into a separate block and insert in its place: 433 // 434 // cleanuppad <InsertPt> cleanupret. 435 // 436 // cleanupret instruction will act as an insert point for the spill. 437 static Instruction *splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch) { 438 BasicBlock *CurrentBlock = CatchSwitch->getParent(); 439 BasicBlock *NewBlock = CurrentBlock->splitBasicBlock(CatchSwitch); 440 CurrentBlock->getTerminator()->eraseFromParent(); 441 442 auto *CleanupPad = 443 CleanupPadInst::Create(CatchSwitch->getParentPad(), {}, "", CurrentBlock); 444 auto *CleanupRet = 445 CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock); 446 return CleanupRet; 447 } 448 449 // Replace all alloca and SSA values that are accessed across suspend points 450 // with GetElementPointer from coroutine frame + loads and stores. Create an 451 // AllocaSpillBB that will become the new entry block for the resume parts of 452 // the coroutine: 453 // 454 // %hdl = coro.begin(...) 455 // whatever 456 // 457 // becomes: 458 // 459 // %hdl = coro.begin(...) 460 // %FramePtr = bitcast i8* hdl to %f.frame* 461 // br label %AllocaSpillBB 462 // 463 // AllocaSpillBB: 464 // ; geps corresponding to allocas that were moved to coroutine frame 465 // br label PostSpill 466 // 467 // PostSpill: 468 // whatever 469 // 470 // 471 static Instruction *insertSpills(SpillInfo &Spills, coro::Shape &Shape) { 472 auto *CB = Shape.CoroBegin; 473 IRBuilder<> Builder(CB->getNextNode()); 474 PointerType *FramePtrTy = Shape.FrameTy->getPointerTo(); 475 auto *FramePtr = 476 cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy, "FramePtr")); 477 Type *FrameTy = FramePtrTy->getElementType(); 478 479 Value *CurrentValue = nullptr; 480 BasicBlock *CurrentBlock = nullptr; 481 Value *CurrentReload = nullptr; 482 unsigned Index = 0; // Proper field number will be read from field definition. 483 484 // We need to keep track of any allocas that need "spilling" 485 // since they will live in the coroutine frame now, all access to them 486 // need to be changed, not just the access across suspend points 487 // we remember allocas and their indices to be handled once we processed 488 // all the spills. 489 SmallVector<std::pair<AllocaInst *, unsigned>, 4> Allocas; 490 // Promise alloca (if present) has a fixed field number (Shape::PromiseField) 491 if (Shape.PromiseAlloca) 492 Allocas.emplace_back(Shape.PromiseAlloca, coro::Shape::PromiseField); 493 494 // Create a load instruction to reload the spilled value from the coroutine 495 // frame. 496 auto CreateReload = [&](Instruction *InsertBefore) { 497 assert(Index && "accessing unassigned field number"); 498 Builder.SetInsertPoint(InsertBefore); 499 auto *G = Builder.CreateConstInBoundsGEP2_32(FrameTy, FramePtr, 0, Index, 500 CurrentValue->getName() + 501 Twine(".reload.addr")); 502 return isa<AllocaInst>(CurrentValue) 503 ? G 504 : Builder.CreateLoad(G, 505 CurrentValue->getName() + Twine(".reload")); 506 }; 507 508 for (auto const &E : Spills) { 509 // If we have not seen the value, generate a spill. 510 if (CurrentValue != E.def()) { 511 CurrentValue = E.def(); 512 CurrentBlock = nullptr; 513 CurrentReload = nullptr; 514 515 Index = E.fieldIndex(); 516 517 if (auto *AI = dyn_cast<AllocaInst>(CurrentValue)) { 518 // Spilled AllocaInst will be replaced with GEP from the coroutine frame 519 // there is no spill required. 520 Allocas.emplace_back(AI, Index); 521 if (!AI->isStaticAlloca()) 522 report_fatal_error("Coroutines cannot handle non static allocas yet"); 523 } else { 524 // Otherwise, create a store instruction storing the value into the 525 // coroutine frame. 526 527 Instruction *InsertPt = nullptr; 528 if (isa<Argument>(CurrentValue)) { 529 // For arguments, we will place the store instruction right after 530 // the coroutine frame pointer instruction, i.e. bitcast of 531 // coro.begin from i8* to %f.frame*. 532 InsertPt = FramePtr->getNextNode(); 533 } else if (auto *II = dyn_cast<InvokeInst>(CurrentValue)) { 534 // If we are spilling the result of the invoke instruction, split the 535 // normal edge and insert the spill in the new block. 536 auto NewBB = SplitEdge(II->getParent(), II->getNormalDest()); 537 InsertPt = NewBB->getTerminator(); 538 } else if (dyn_cast<PHINode>(CurrentValue)) { 539 // Skip the PHINodes and EH pads instructions. 540 BasicBlock *DefBlock = cast<Instruction>(E.def())->getParent(); 541 if (auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->getTerminator())) 542 InsertPt = splitBeforeCatchSwitch(CSI); 543 else 544 InsertPt = &*DefBlock->getFirstInsertionPt(); 545 } else { 546 // For all other values, the spill is placed immediately after 547 // the definition. 548 assert(!isa<TerminatorInst>(E.def()) && "unexpected terminator"); 549 InsertPt = cast<Instruction>(E.def())->getNextNode(); 550 } 551 552 Builder.SetInsertPoint(InsertPt); 553 auto *G = Builder.CreateConstInBoundsGEP2_32( 554 FrameTy, FramePtr, 0, Index, 555 CurrentValue->getName() + Twine(".spill.addr")); 556 Builder.CreateStore(CurrentValue, G); 557 } 558 } 559 560 // If we have not seen the use block, generate a reload in it. 561 if (CurrentBlock != E.userBlock()) { 562 CurrentBlock = E.userBlock(); 563 CurrentReload = CreateReload(&*CurrentBlock->getFirstInsertionPt()); 564 } 565 566 // If we have a single edge PHINode, remove it and replace it with a reload 567 // from the coroutine frame. (We already took care of multi edge PHINodes 568 // by rewriting them in the rewritePHIs function). 569 if (auto *PN = dyn_cast<PHINode>(E.user())) { 570 assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming " 571 "values in the PHINode"); 572 PN->replaceAllUsesWith(CurrentReload); 573 PN->eraseFromParent(); 574 continue; 575 } 576 577 // Replace all uses of CurrentValue in the current instruction with reload. 578 E.user()->replaceUsesOfWith(CurrentValue, CurrentReload); 579 } 580 581 BasicBlock *FramePtrBB = FramePtr->getParent(); 582 Shape.AllocaSpillBlock = 583 FramePtrBB->splitBasicBlock(FramePtr->getNextNode(), "AllocaSpillBB"); 584 Shape.AllocaSpillBlock->splitBasicBlock(&Shape.AllocaSpillBlock->front(), 585 "PostSpill"); 586 587 Builder.SetInsertPoint(&Shape.AllocaSpillBlock->front()); 588 // If we found any allocas, replace all of their remaining uses with Geps. 589 for (auto &P : Allocas) { 590 auto *G = 591 Builder.CreateConstInBoundsGEP2_32(FrameTy, FramePtr, 0, P.second); 592 // We are not using ReplaceInstWithInst(P.first, cast<Instruction>(G)) here, 593 // as we are changing location of the instruction. 594 G->takeName(P.first); 595 P.first->replaceAllUsesWith(G); 596 P.first->eraseFromParent(); 597 } 598 return FramePtr; 599 } 600 601 // Sets the unwind edge of an instruction to a particular successor. 602 static void setUnwindEdgeTo(TerminatorInst *TI, BasicBlock *Succ) { 603 if (auto *II = dyn_cast<InvokeInst>(TI)) 604 II->setUnwindDest(Succ); 605 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI)) 606 CS->setUnwindDest(Succ); 607 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI)) 608 CR->setUnwindDest(Succ); 609 else 610 llvm_unreachable("unexpected terminator instruction"); 611 } 612 613 // Replaces all uses of OldPred with the NewPred block in all PHINodes in a 614 // block. 615 static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, 616 BasicBlock *NewPred, 617 PHINode *LandingPadReplacement) { 618 unsigned BBIdx = 0; 619 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) { 620 PHINode *PN = cast<PHINode>(I); 621 622 // We manually update the LandingPadReplacement PHINode and it is the last 623 // PHI Node. So, if we find it, we are done. 624 if (LandingPadReplacement == PN) 625 break; 626 627 // Reuse the previous value of BBIdx if it lines up. In cases where we 628 // have multiple phi nodes with *lots* of predecessors, this is a speed 629 // win because we don't have to scan the PHI looking for TIBB. This 630 // happens because the BB list of PHI nodes are usually in the same 631 // order. 632 if (PN->getIncomingBlock(BBIdx) != OldPred) 633 BBIdx = PN->getBasicBlockIndex(OldPred); 634 635 assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!"); 636 PN->setIncomingBlock(BBIdx, NewPred); 637 } 638 } 639 640 // Uses SplitEdge unless the successor block is an EHPad, in which case do EH 641 // specific handling. 642 static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, 643 LandingPadInst *OriginalPad, 644 PHINode *LandingPadReplacement) { 645 auto *PadInst = Succ->getFirstNonPHI(); 646 if (!LandingPadReplacement && !PadInst->isEHPad()) 647 return SplitEdge(BB, Succ); 648 649 auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ); 650 setUnwindEdgeTo(BB->getTerminator(), NewBB); 651 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement); 652 653 if (LandingPadReplacement) { 654 auto *NewLP = OriginalPad->clone(); 655 auto *Terminator = BranchInst::Create(Succ, NewBB); 656 NewLP->insertBefore(Terminator); 657 LandingPadReplacement->addIncoming(NewLP, NewBB); 658 return NewBB; 659 } 660 Value *ParentPad = nullptr; 661 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst)) 662 ParentPad = FuncletPad->getParentPad(); 663 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst)) 664 ParentPad = CatchSwitch->getParentPad(); 665 else 666 llvm_unreachable("handling for other EHPads not implemented yet"); 667 668 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB); 669 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB); 670 return NewBB; 671 } 672 673 static void rewritePHIs(BasicBlock &BB) { 674 // For every incoming edge we will create a block holding all 675 // incoming values in a single PHI nodes. 676 // 677 // loop: 678 // %n.val = phi i32[%n, %entry], [%inc, %loop] 679 // 680 // It will create: 681 // 682 // loop.from.entry: 683 // %n.loop.pre = phi i32 [%n, %entry] 684 // br %label loop 685 // loop.from.loop: 686 // %inc.loop.pre = phi i32 [%inc, %loop] 687 // br %label loop 688 // 689 // After this rewrite, further analysis will ignore any phi nodes with more 690 // than one incoming edge. 691 692 // TODO: Simplify PHINodes in the basic block to remove duplicate 693 // predecessors. 694 695 LandingPadInst *LandingPad = nullptr; 696 PHINode *ReplPHI = nullptr; 697 if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) { 698 // ehAwareSplitEdge will clone the LandingPad in all the edge blocks. 699 // We replace the original landing pad with a PHINode that will collect the 700 // results from all of them. 701 ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad); 702 ReplPHI->takeName(LandingPad); 703 LandingPad->replaceAllUsesWith(ReplPHI); 704 // We will erase the original landing pad at the end of this function after 705 // ehAwareSplitEdge cloned it in the transition blocks. 706 } 707 708 SmallVector<BasicBlock *, 8> Preds(pred_begin(&BB), pred_end(&BB)); 709 for (BasicBlock *Pred : Preds) { 710 auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI); 711 IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName()); 712 auto *PN = cast<PHINode>(&BB.front()); 713 do { 714 int Index = PN->getBasicBlockIndex(IncomingBB); 715 Value *V = PN->getIncomingValue(Index); 716 PHINode *InputV = PHINode::Create( 717 V->getType(), 1, V->getName() + Twine(".") + BB.getName(), 718 &IncomingBB->front()); 719 InputV->addIncoming(V, Pred); 720 PN->setIncomingValue(Index, InputV); 721 PN = dyn_cast<PHINode>(PN->getNextNode()); 722 } while (PN != ReplPHI); // ReplPHI is either null or the PHI that replaced 723 // the landing pad. 724 } 725 726 if (LandingPad) { 727 // Calls to ehAwareSplitEdge function cloned the original lading pad. 728 // No longer need it. 729 LandingPad->eraseFromParent(); 730 } 731 } 732 733 static void rewritePHIs(Function &F) { 734 SmallVector<BasicBlock *, 8> WorkList; 735 736 for (BasicBlock &BB : F) 737 if (auto *PN = dyn_cast<PHINode>(&BB.front())) 738 if (PN->getNumIncomingValues() > 1) 739 WorkList.push_back(&BB); 740 741 for (BasicBlock *BB : WorkList) 742 rewritePHIs(*BB); 743 } 744 745 // Check for instructions that we can recreate on resume as opposed to spill 746 // the result into a coroutine frame. 747 static bool materializable(Instruction &V) { 748 return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) || 749 isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V); 750 } 751 752 // Check for structural coroutine intrinsics that should not be spilled into 753 // the coroutine frame. 754 static bool isCoroutineStructureIntrinsic(Instruction &I) { 755 return isa<CoroIdInst>(&I) || isa<CoroSaveInst>(&I) || 756 isa<CoroSuspendInst>(&I); 757 } 758 759 // For every use of the value that is across suspend point, recreate that value 760 // after a suspend point. 761 static void rewriteMaterializableInstructions(IRBuilder<> &IRB, 762 SpillInfo const &Spills) { 763 BasicBlock *CurrentBlock = nullptr; 764 Instruction *CurrentMaterialization = nullptr; 765 Instruction *CurrentDef = nullptr; 766 767 for (auto const &E : Spills) { 768 // If it is a new definition, update CurrentXXX variables. 769 if (CurrentDef != E.def()) { 770 CurrentDef = cast<Instruction>(E.def()); 771 CurrentBlock = nullptr; 772 CurrentMaterialization = nullptr; 773 } 774 775 // If we have not seen this block, materialize the value. 776 if (CurrentBlock != E.userBlock()) { 777 CurrentBlock = E.userBlock(); 778 CurrentMaterialization = cast<Instruction>(CurrentDef)->clone(); 779 CurrentMaterialization->setName(CurrentDef->getName()); 780 CurrentMaterialization->insertBefore( 781 &*CurrentBlock->getFirstInsertionPt()); 782 } 783 784 if (auto *PN = dyn_cast<PHINode>(E.user())) { 785 assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming " 786 "values in the PHINode"); 787 PN->replaceAllUsesWith(CurrentMaterialization); 788 PN->eraseFromParent(); 789 continue; 790 } 791 792 // Replace all uses of CurrentDef in the current instruction with the 793 // CurrentMaterialization for the block. 794 E.user()->replaceUsesOfWith(CurrentDef, CurrentMaterialization); 795 } 796 } 797 798 // Move early uses of spilled variable after CoroBegin. 799 // For example, if a parameter had address taken, we may end up with the code 800 // like: 801 // define @f(i32 %n) { 802 // %n.addr = alloca i32 803 // store %n, %n.addr 804 // ... 805 // call @coro.begin 806 // we need to move the store after coro.begin 807 static void moveSpillUsesAfterCoroBegin(Function &F, SpillInfo const &Spills, 808 CoroBeginInst *CoroBegin) { 809 DominatorTree DT(F); 810 SmallVector<Instruction *, 8> NeedsMoving; 811 812 Value *CurrentValue = nullptr; 813 814 for (auto const &E : Spills) { 815 if (CurrentValue == E.def()) 816 continue; 817 818 CurrentValue = E.def(); 819 820 for (User *U : CurrentValue->users()) { 821 Instruction *I = cast<Instruction>(U); 822 if (!DT.dominates(CoroBegin, I)) { 823 DEBUG(dbgs() << "will move: " << *I << "\n"); 824 825 // TODO: Make this more robust. Currently if we run into a situation 826 // where simple instruction move won't work we panic and 827 // report_fatal_error. 828 for (User *UI : I->users()) { 829 if (!DT.dominates(CoroBegin, cast<Instruction>(UI))) 830 report_fatal_error("cannot move instruction since its users are not" 831 " dominated by CoroBegin"); 832 } 833 834 NeedsMoving.push_back(I); 835 } 836 } 837 } 838 839 Instruction *InsertPt = CoroBegin->getNextNode(); 840 for (Instruction *I : NeedsMoving) 841 I->moveBefore(InsertPt); 842 } 843 844 // Splits the block at a particular instruction unless it is the first 845 // instruction in the block with a single predecessor. 846 static BasicBlock *splitBlockIfNotFirst(Instruction *I, const Twine &Name) { 847 auto *BB = I->getParent(); 848 if (&BB->front() == I) { 849 if (BB->getSinglePredecessor()) { 850 BB->setName(Name); 851 return BB; 852 } 853 } 854 return BB->splitBasicBlock(I, Name); 855 } 856 857 // Split above and below a particular instruction so that it 858 // will be all alone by itself in a block. 859 static void splitAround(Instruction *I, const Twine &Name) { 860 splitBlockIfNotFirst(I, Name); 861 splitBlockIfNotFirst(I->getNextNode(), "After" + Name); 862 } 863 864 void coro::buildCoroutineFrame(Function &F, Shape &Shape) { 865 // Lower coro.dbg.declare to coro.dbg.value, since we are going to rewrite 866 // access to local variables. 867 LowerDbgDeclare(F); 868 869 Shape.PromiseAlloca = Shape.CoroBegin->getId()->getPromise(); 870 if (Shape.PromiseAlloca) { 871 Shape.CoroBegin->getId()->clearPromise(); 872 } 873 874 // Make sure that all coro.save, coro.suspend and the fallthrough coro.end 875 // intrinsics are in their own blocks to simplify the logic of building up 876 // SuspendCrossing data. 877 for (CoroSuspendInst *CSI : Shape.CoroSuspends) { 878 splitAround(CSI->getCoroSave(), "CoroSave"); 879 splitAround(CSI, "CoroSuspend"); 880 } 881 882 // Put CoroEnds into their own blocks. 883 for (CoroEndInst *CE : Shape.CoroEnds) 884 splitAround(CE, "CoroEnd"); 885 886 // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will 887 // never has its definition separated from the PHI by the suspend point. 888 rewritePHIs(F); 889 890 // Build suspend crossing info. 891 SuspendCrossingInfo Checker(F, Shape); 892 893 IRBuilder<> Builder(F.getContext()); 894 SpillInfo Spills; 895 896 for (int Repeat = 0; Repeat < 4; ++Repeat) { 897 // See if there are materializable instructions across suspend points. 898 for (Instruction &I : instructions(F)) 899 if (materializable(I)) 900 for (User *U : I.users()) 901 if (Checker.isDefinitionAcrossSuspend(I, U)) 902 Spills.emplace_back(&I, U); 903 904 if (Spills.empty()) 905 break; 906 907 // Rewrite materializable instructions to be materialized at the use point. 908 DEBUG(dump("Materializations", Spills)); 909 rewriteMaterializableInstructions(Builder, Spills); 910 Spills.clear(); 911 } 912 913 // Collect the spills for arguments and other not-materializable values. 914 for (Argument &A : F.args()) 915 for (User *U : A.users()) 916 if (Checker.isDefinitionAcrossSuspend(A, U)) 917 Spills.emplace_back(&A, U); 918 919 for (Instruction &I : instructions(F)) { 920 // Values returned from coroutine structure intrinsics should not be part 921 // of the Coroutine Frame. 922 if (isCoroutineStructureIntrinsic(I) || &I == Shape.CoroBegin) 923 continue; 924 // The Coroutine Promise always included into coroutine frame, no need to 925 // check for suspend crossing. 926 if (Shape.PromiseAlloca == &I) 927 continue; 928 929 for (User *U : I.users()) 930 if (Checker.isDefinitionAcrossSuspend(I, U)) { 931 // We cannot spill a token. 932 if (I.getType()->isTokenTy()) 933 report_fatal_error( 934 "token definition is separated from the use by a suspend point"); 935 Spills.emplace_back(&I, U); 936 } 937 } 938 DEBUG(dump("Spills", Spills)); 939 moveSpillUsesAfterCoroBegin(F, Spills, Shape.CoroBegin); 940 Shape.FrameTy = buildFrameType(F, Shape, Spills); 941 Shape.FramePtr = insertSpills(Spills, Shape); 942 } 943