1 //===- CoroFrame.cpp - Builds and manipulates coroutine frame -------------===//
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 file contains classes used to discover if for a particular value
9 // there from sue to definition that crosses a suspend block.
10 //
11 // Using the information discovered we form a Coroutine Frame structure to
12 // contain those values. All uses of those values are replaced with appropriate
13 // GEP + load from the coroutine frame. At the point of the definition we spill
14 // the value into the coroutine frame.
15 //
16 // TODO: pack values tightly using liveness info.
17 //===----------------------------------------------------------------------===//
18 
19 #include "CoroInternal.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Analysis/PtrUseVisitor.h"
23 #include "llvm/Config/llvm-config.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/DIBuilder.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/circular_raw_ostream.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
35 #include <algorithm>
36 
37 using namespace llvm;
38 
39 // The "coro-suspend-crossing" flag is very noisy. There is another debug type,
40 // "coro-frame", which results in leaner debug spew.
41 #define DEBUG_TYPE "coro-suspend-crossing"
42 
43 enum { SmallVectorThreshold = 32 };
44 
45 // Provides two way mapping between the blocks and numbers.
46 namespace {
47 class BlockToIndexMapping {
48   SmallVector<BasicBlock *, SmallVectorThreshold> V;
49 
50 public:
51   size_t size() const { return V.size(); }
52 
53   BlockToIndexMapping(Function &F) {
54     for (BasicBlock &BB : F)
55       V.push_back(&BB);
56     llvm::sort(V);
57   }
58 
59   size_t blockToIndex(BasicBlock *BB) const {
60     auto *I = llvm::lower_bound(V, BB);
61     assert(I != V.end() && *I == BB && "BasicBlockNumberng: Unknown block");
62     return I - V.begin();
63   }
64 
65   BasicBlock *indexToBlock(unsigned Index) const { return V[Index]; }
66 };
67 } // end anonymous namespace
68 
69 // The SuspendCrossingInfo maintains data that allows to answer a question
70 // whether given two BasicBlocks A and B there is a path from A to B that
71 // passes through a suspend point.
72 //
73 // For every basic block 'i' it maintains a BlockData that consists of:
74 //   Consumes:  a bit vector which contains a set of indices of blocks that can
75 //              reach block 'i'
76 //   Kills: a bit vector which contains a set of indices of blocks that can
77 //          reach block 'i', but one of the path will cross a suspend point
78 //   Suspend: a boolean indicating whether block 'i' contains a suspend point.
79 //   End: a boolean indicating whether block 'i' contains a coro.end intrinsic.
80 //
81 namespace {
82 struct SuspendCrossingInfo {
83   BlockToIndexMapping Mapping;
84 
85   struct BlockData {
86     BitVector Consumes;
87     BitVector Kills;
88     bool Suspend = false;
89     bool End = false;
90   };
91   SmallVector<BlockData, SmallVectorThreshold> Block;
92 
93   iterator_range<succ_iterator> successors(BlockData const &BD) const {
94     BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]);
95     return llvm::successors(BB);
96   }
97 
98   BlockData &getBlockData(BasicBlock *BB) {
99     return Block[Mapping.blockToIndex(BB)];
100   }
101 
102   void dump() const;
103   void dump(StringRef Label, BitVector const &BV) const;
104 
105   SuspendCrossingInfo(Function &F, coro::Shape &Shape);
106 
107   bool hasPathCrossingSuspendPoint(BasicBlock *DefBB, BasicBlock *UseBB) const {
108     size_t const DefIndex = Mapping.blockToIndex(DefBB);
109     size_t const UseIndex = Mapping.blockToIndex(UseBB);
110 
111     bool const Result = Block[UseIndex].Kills[DefIndex];
112     LLVM_DEBUG(dbgs() << UseBB->getName() << " => " << DefBB->getName()
113                       << " answer is " << Result << "\n");
114     return Result;
115   }
116 
117   bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const {
118     auto *I = cast<Instruction>(U);
119 
120     // We rewrote PHINodes, so that only the ones with exactly one incoming
121     // value need to be analyzed.
122     if (auto *PN = dyn_cast<PHINode>(I))
123       if (PN->getNumIncomingValues() > 1)
124         return false;
125 
126     BasicBlock *UseBB = I->getParent();
127 
128     // As a special case, treat uses by an llvm.coro.suspend.retcon
129     // as if they were uses in the suspend's single predecessor: the
130     // uses conceptually occur before the suspend.
131     if (isa<CoroSuspendRetconInst>(I)) {
132       UseBB = UseBB->getSinglePredecessor();
133       assert(UseBB && "should have split coro.suspend into its own block");
134     }
135 
136     return hasPathCrossingSuspendPoint(DefBB, UseBB);
137   }
138 
139   bool isDefinitionAcrossSuspend(Argument &A, User *U) const {
140     return isDefinitionAcrossSuspend(&A.getParent()->getEntryBlock(), U);
141   }
142 
143   bool isDefinitionAcrossSuspend(Instruction &I, User *U) const {
144     auto *DefBB = I.getParent();
145 
146     // As a special case, treat values produced by an llvm.coro.suspend.*
147     // as if they were defined in the single successor: the uses
148     // conceptually occur after the suspend.
149     if (isa<AnyCoroSuspendInst>(I)) {
150       DefBB = DefBB->getSingleSuccessor();
151       assert(DefBB && "should have split coro.suspend into its own block");
152     }
153 
154     return isDefinitionAcrossSuspend(DefBB, U);
155   }
156 };
157 } // end anonymous namespace
158 
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump(StringRef Label,
161                                                 BitVector const &BV) const {
162   dbgs() << Label << ":";
163   for (size_t I = 0, N = BV.size(); I < N; ++I)
164     if (BV[I])
165       dbgs() << " " << Mapping.indexToBlock(I)->getName();
166   dbgs() << "\n";
167 }
168 
169 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump() const {
170   for (size_t I = 0, N = Block.size(); I < N; ++I) {
171     BasicBlock *const B = Mapping.indexToBlock(I);
172     dbgs() << B->getName() << ":\n";
173     dump("   Consumes", Block[I].Consumes);
174     dump("      Kills", Block[I].Kills);
175   }
176   dbgs() << "\n";
177 }
178 #endif
179 
180 SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape)
181     : Mapping(F) {
182   const size_t N = Mapping.size();
183   Block.resize(N);
184 
185   // Initialize every block so that it consumes itself
186   for (size_t I = 0; I < N; ++I) {
187     auto &B = Block[I];
188     B.Consumes.resize(N);
189     B.Kills.resize(N);
190     B.Consumes.set(I);
191   }
192 
193   // Mark all CoroEnd Blocks. We do not propagate Kills beyond coro.ends as
194   // the code beyond coro.end is reachable during initial invocation of the
195   // coroutine.
196   for (auto *CE : Shape.CoroEnds)
197     getBlockData(CE->getParent()).End = true;
198 
199   // Mark all suspend blocks and indicate that they kill everything they
200   // consume. Note, that crossing coro.save also requires a spill, as any code
201   // between coro.save and coro.suspend may resume the coroutine and all of the
202   // state needs to be saved by that time.
203   auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) {
204     BasicBlock *SuspendBlock = BarrierInst->getParent();
205     auto &B = getBlockData(SuspendBlock);
206     B.Suspend = true;
207     B.Kills |= B.Consumes;
208   };
209   for (auto *CSI : Shape.CoroSuspends) {
210     markSuspendBlock(CSI);
211     if (auto *Save = CSI->getCoroSave())
212       markSuspendBlock(Save);
213   }
214 
215   // Iterate propagating consumes and kills until they stop changing.
216   int Iteration = 0;
217   (void)Iteration;
218 
219   bool Changed;
220   do {
221     LLVM_DEBUG(dbgs() << "iteration " << ++Iteration);
222     LLVM_DEBUG(dbgs() << "==============\n");
223 
224     Changed = false;
225     for (size_t I = 0; I < N; ++I) {
226       auto &B = Block[I];
227       for (BasicBlock *SI : successors(B)) {
228 
229         auto SuccNo = Mapping.blockToIndex(SI);
230 
231         // Saved Consumes and Kills bitsets so that it is easy to see
232         // if anything changed after propagation.
233         auto &S = Block[SuccNo];
234         auto SavedConsumes = S.Consumes;
235         auto SavedKills = S.Kills;
236 
237         // Propagate Kills and Consumes from block B into its successor S.
238         S.Consumes |= B.Consumes;
239         S.Kills |= B.Kills;
240 
241         // If block B is a suspend block, it should propagate kills into the
242         // its successor for every block B consumes.
243         if (B.Suspend) {
244           S.Kills |= B.Consumes;
245         }
246         if (S.Suspend) {
247           // If block S is a suspend block, it should kill all of the blocks it
248           // consumes.
249           S.Kills |= S.Consumes;
250         } else if (S.End) {
251           // If block S is an end block, it should not propagate kills as the
252           // blocks following coro.end() are reached during initial invocation
253           // of the coroutine while all the data are still available on the
254           // stack or in the registers.
255           S.Kills.reset();
256         } else {
257           // This is reached when S block it not Suspend nor coro.end and it
258           // need to make sure that it is not in the kill set.
259           S.Kills.reset(SuccNo);
260         }
261 
262         // See if anything changed.
263         Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes);
264 
265         if (S.Kills != SavedKills) {
266           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI->getName()
267                             << "\n");
268           LLVM_DEBUG(dump("S.Kills", S.Kills));
269           LLVM_DEBUG(dump("SavedKills", SavedKills));
270         }
271         if (S.Consumes != SavedConsumes) {
272           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI << "\n");
273           LLVM_DEBUG(dump("S.Consume", S.Consumes));
274           LLVM_DEBUG(dump("SavedCons", SavedConsumes));
275         }
276       }
277     }
278   } while (Changed);
279   LLVM_DEBUG(dump());
280 }
281 
282 #undef DEBUG_TYPE // "coro-suspend-crossing"
283 #define DEBUG_TYPE "coro-frame"
284 
285 // We build up the list of spills for every case where a use is separated
286 // from the definition by a suspend point.
287 
288 static const unsigned InvalidFieldIndex = ~0U;
289 
290 namespace {
291 class Spill {
292   Value *Def = nullptr;
293   Instruction *User = nullptr;
294   unsigned FieldNo = InvalidFieldIndex;
295 
296 public:
297   Spill(Value *Def, llvm::User *U) : Def(Def), User(cast<Instruction>(U)) {}
298 
299   Value *def() const { return Def; }
300   Instruction *user() const { return User; }
301   BasicBlock *userBlock() const { return User->getParent(); }
302 
303   // Note that field index is stored in the first SpillEntry for a particular
304   // definition. Subsequent mentions of a defintion do not have fieldNo
305   // assigned. This works out fine as the users of Spills capture the info about
306   // the definition the first time they encounter it. Consider refactoring
307   // SpillInfo into two arrays to normalize the spill representation.
308   unsigned fieldIndex() const {
309     assert(FieldNo != InvalidFieldIndex && "Accessing unassigned field");
310     return FieldNo;
311   }
312   void setFieldIndex(unsigned FieldNumber) {
313     assert(FieldNo == InvalidFieldIndex && "Reassigning field number");
314     FieldNo = FieldNumber;
315   }
316 };
317 } // namespace
318 
319 // Note that there may be more than one record with the same value of Def in
320 // the SpillInfo vector.
321 using SpillInfo = SmallVector<Spill, 8>;
322 
323 #ifndef NDEBUG
324 static void dump(StringRef Title, SpillInfo const &Spills) {
325   dbgs() << "------------- " << Title << "--------------\n";
326   Value *CurrentValue = nullptr;
327   for (auto const &E : Spills) {
328     if (CurrentValue != E.def()) {
329       CurrentValue = E.def();
330       CurrentValue->dump();
331     }
332     dbgs() << "   user: ";
333     E.user()->dump();
334   }
335 }
336 #endif
337 
338 namespace {
339 // We cannot rely solely on natural alignment of a type when building a
340 // coroutine frame and if the alignment specified on the Alloca instruction
341 // differs from the natural alignment of the alloca type we will need to insert
342 // padding.
343 struct PaddingCalculator {
344   const DataLayout &DL;
345   LLVMContext &Context;
346   unsigned StructSize = 0;
347 
348   PaddingCalculator(LLVMContext &Context, DataLayout const &DL)
349       : DL(DL), Context(Context) {}
350 
351   // Replicate the logic from IR/DataLayout.cpp to match field offset
352   // computation for LLVM structs.
353   void addType(Type *Ty) {
354     unsigned TyAlign = DL.getABITypeAlignment(Ty);
355     if ((StructSize & (TyAlign - 1)) != 0)
356       StructSize = alignTo(StructSize, TyAlign);
357 
358     StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item.
359   }
360 
361   void addTypes(SmallVectorImpl<Type *> const &Types) {
362     for (auto *Ty : Types)
363       addType(Ty);
364   }
365 
366   unsigned computePadding(Type *Ty, unsigned ForcedAlignment) {
367     unsigned TyAlign = DL.getABITypeAlignment(Ty);
368     auto Natural = alignTo(StructSize, TyAlign);
369     auto Forced = alignTo(StructSize, ForcedAlignment);
370 
371     // Return how many bytes of padding we need to insert.
372     if (Natural != Forced)
373       return std::max(Natural, Forced) - StructSize;
374 
375     // Rely on natural alignment.
376     return 0;
377   }
378 
379   // If padding required, return the padding field type to insert.
380   ArrayType *getPaddingType(Type *Ty, unsigned ForcedAlignment) {
381     if (auto Padding = computePadding(Ty, ForcedAlignment))
382       return ArrayType::get(Type::getInt8Ty(Context), Padding);
383 
384     return nullptr;
385   }
386 };
387 } // namespace
388 
389 // Build a struct that will keep state for an active coroutine.
390 //   struct f.frame {
391 //     ResumeFnTy ResumeFnAddr;
392 //     ResumeFnTy DestroyFnAddr;
393 //     int ResumeIndex;
394 //     ... promise (if present) ...
395 //     ... spills ...
396 //   };
397 static StructType *buildFrameType(Function &F, coro::Shape &Shape,
398                                   SpillInfo &Spills) {
399   LLVMContext &C = F.getContext();
400   const DataLayout &DL = F.getParent()->getDataLayout();
401   PaddingCalculator Padder(C, DL);
402   SmallString<32> Name(F.getName());
403   Name.append(".Frame");
404   StructType *FrameTy = StructType::create(C, Name);
405   SmallVector<Type *, 8> Types;
406 
407   AllocaInst *PromiseAlloca = Shape.getPromiseAlloca();
408 
409   if (Shape.ABI == coro::ABI::Switch) {
410     auto *FramePtrTy = FrameTy->getPointerTo();
411     auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy,
412                                    /*IsVarArg=*/false);
413     auto *FnPtrTy = FnTy->getPointerTo();
414 
415     // Figure out how wide should be an integer type storing the suspend index.
416     unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size()));
417     Type *PromiseType = PromiseAlloca
418                             ? PromiseAlloca->getType()->getElementType()
419                             : Type::getInt1Ty(C);
420     Type *IndexType = Type::getIntNTy(C, IndexBits);
421     Types.push_back(FnPtrTy);
422     Types.push_back(FnPtrTy);
423     Types.push_back(PromiseType);
424     Types.push_back(IndexType);
425   } else {
426     assert(PromiseAlloca == nullptr && "lowering doesn't support promises");
427   }
428 
429   Value *CurrentDef = nullptr;
430 
431   Padder.addTypes(Types);
432 
433   // Create an entry for every spilled value.
434   for (auto &S : Spills) {
435     if (CurrentDef == S.def())
436       continue;
437 
438     CurrentDef = S.def();
439     // PromiseAlloca was already added to Types array earlier.
440     if (CurrentDef == PromiseAlloca)
441       continue;
442 
443     uint64_t Count = 1;
444     Type *Ty = nullptr;
445     if (auto *AI = dyn_cast<AllocaInst>(CurrentDef)) {
446       Ty = AI->getAllocatedType();
447       if (unsigned AllocaAlignment = AI->getAlignment()) {
448         // If alignment is specified in alloca, see if we need to insert extra
449         // padding.
450         if (auto PaddingTy = Padder.getPaddingType(Ty, AllocaAlignment)) {
451           Types.push_back(PaddingTy);
452           Padder.addType(PaddingTy);
453         }
454       }
455       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
456         Count = CI->getValue().getZExtValue();
457       else
458         report_fatal_error("Coroutines cannot handle non static allocas yet");
459     } else {
460       Ty = CurrentDef->getType();
461     }
462     S.setFieldIndex(Types.size());
463     if (Count == 1)
464       Types.push_back(Ty);
465     else
466       Types.push_back(ArrayType::get(Ty, Count));
467     Padder.addType(Ty);
468   }
469   FrameTy->setBody(Types);
470 
471   switch (Shape.ABI) {
472   case coro::ABI::Switch:
473     break;
474 
475   // Remember whether the frame is inline in the storage.
476   case coro::ABI::Retcon:
477   case coro::ABI::RetconOnce: {
478     auto &Layout = F.getParent()->getDataLayout();
479     auto Id = Shape.getRetconCoroId();
480     Shape.RetconLowering.IsFrameInlineInStorage
481       = (Layout.getTypeAllocSize(FrameTy) <= Id->getStorageSize() &&
482          Layout.getABITypeAlignment(FrameTy) <= Id->getStorageAlignment());
483     break;
484   }
485   }
486 
487   return FrameTy;
488 }
489 
490 // We use a pointer use visitor to discover if there are any writes into an
491 // alloca that dominates CoroBegin. If that is the case, insertSpills will copy
492 // the value from the alloca into the coroutine frame spill slot corresponding
493 // to that alloca.
494 namespace {
495 struct AllocaUseVisitor : PtrUseVisitor<AllocaUseVisitor> {
496   using Base = PtrUseVisitor<AllocaUseVisitor>;
497   AllocaUseVisitor(const DataLayout &DL, const DominatorTree &DT,
498                    const CoroBeginInst &CB)
499       : PtrUseVisitor(DL), DT(DT), CoroBegin(CB) {}
500 
501   // We are only interested in uses that dominate coro.begin.
502   void visit(Instruction &I) {
503     if (DT.dominates(&I, &CoroBegin))
504       Base::visit(I);
505   }
506   // We need to provide this overload as PtrUseVisitor uses a pointer based
507   // visiting function.
508   void visit(Instruction *I) { return visit(*I); }
509 
510   void visitLoadInst(LoadInst &) {} // Good. Nothing to do.
511 
512   // If the use is an operand, the pointer escaped and anything can write into
513   // that memory. If the use is the pointer, we are definitely writing into the
514   // alloca and therefore we need to copy.
515   void visitStoreInst(StoreInst &SI) { PI.setAborted(&SI); }
516 
517   // Any other instruction that is not filtered out by PtrUseVisitor, will
518   // result in the copy.
519   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
520 
521 private:
522   const DominatorTree &DT;
523   const CoroBeginInst &CoroBegin;
524 };
525 } // namespace
526 static bool mightWriteIntoAllocaPtr(AllocaInst &A, const DominatorTree &DT,
527                                     const CoroBeginInst &CB) {
528   const DataLayout &DL = A.getModule()->getDataLayout();
529   AllocaUseVisitor Visitor(DL, DT, CB);
530   auto PtrI = Visitor.visitPtr(A);
531   if (PtrI.isEscaped() || PtrI.isAborted()) {
532     auto *PointerEscapingInstr = PtrI.getEscapingInst()
533                                      ? PtrI.getEscapingInst()
534                                      : PtrI.getAbortingInst();
535     if (PointerEscapingInstr) {
536       LLVM_DEBUG(
537           dbgs() << "AllocaInst copy was triggered by instruction: "
538                  << *PointerEscapingInstr << "\n");
539     }
540     return true;
541   }
542   return false;
543 }
544 
545 // We need to make room to insert a spill after initial PHIs, but before
546 // catchswitch instruction. Placing it before violates the requirement that
547 // catchswitch, like all other EHPads must be the first nonPHI in a block.
548 //
549 // Split away catchswitch into a separate block and insert in its place:
550 //
551 //   cleanuppad <InsertPt> cleanupret.
552 //
553 // cleanupret instruction will act as an insert point for the spill.
554 static Instruction *splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch) {
555   BasicBlock *CurrentBlock = CatchSwitch->getParent();
556   BasicBlock *NewBlock = CurrentBlock->splitBasicBlock(CatchSwitch);
557   CurrentBlock->getTerminator()->eraseFromParent();
558 
559   auto *CleanupPad =
560       CleanupPadInst::Create(CatchSwitch->getParentPad(), {}, "", CurrentBlock);
561   auto *CleanupRet =
562       CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock);
563   return CleanupRet;
564 }
565 
566 // Replace all alloca and SSA values that are accessed across suspend points
567 // with GetElementPointer from coroutine frame + loads and stores. Create an
568 // AllocaSpillBB that will become the new entry block for the resume parts of
569 // the coroutine:
570 //
571 //    %hdl = coro.begin(...)
572 //    whatever
573 //
574 // becomes:
575 //
576 //    %hdl = coro.begin(...)
577 //    %FramePtr = bitcast i8* hdl to %f.frame*
578 //    br label %AllocaSpillBB
579 //
580 //  AllocaSpillBB:
581 //    ; geps corresponding to allocas that were moved to coroutine frame
582 //    br label PostSpill
583 //
584 //  PostSpill:
585 //    whatever
586 //
587 //
588 static Instruction *insertSpills(const SpillInfo &Spills, coro::Shape &Shape) {
589   auto *CB = Shape.CoroBegin;
590   LLVMContext &C = CB->getContext();
591   IRBuilder<> Builder(CB->getNextNode());
592   StructType *FrameTy = Shape.FrameTy;
593   PointerType *FramePtrTy = FrameTy->getPointerTo();
594   auto *FramePtr =
595       cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy, "FramePtr"));
596   DominatorTree DT(*CB->getFunction());
597 
598   Value *CurrentValue = nullptr;
599   BasicBlock *CurrentBlock = nullptr;
600   Value *CurrentReload = nullptr;
601 
602   // Proper field number will be read from field definition.
603   unsigned Index = InvalidFieldIndex;
604 
605   // We need to keep track of any allocas that need "spilling"
606   // since they will live in the coroutine frame now, all access to them
607   // need to be changed, not just the access across suspend points
608   // we remember allocas and their indices to be handled once we processed
609   // all the spills.
610   SmallVector<std::pair<AllocaInst *, unsigned>, 4> Allocas;
611   // Promise alloca (if present) has a fixed field number.
612   if (auto *PromiseAlloca = Shape.getPromiseAlloca()) {
613     assert(Shape.ABI == coro::ABI::Switch);
614     Allocas.emplace_back(PromiseAlloca, coro::Shape::SwitchFieldIndex::Promise);
615   }
616 
617   // Create a GEP with the given index into the coroutine frame for the original
618   // value Orig. Appends an extra 0 index for array-allocas, preserving the
619   // original type.
620   auto GetFramePointer = [&](uint32_t Index, Value *Orig) -> Value * {
621     SmallVector<Value *, 3> Indices = {
622         ConstantInt::get(Type::getInt32Ty(C), 0),
623         ConstantInt::get(Type::getInt32Ty(C), Index),
624     };
625 
626     if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
627       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
628         auto Count = CI->getValue().getZExtValue();
629         if (Count > 1) {
630           Indices.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
631         }
632       } else {
633         report_fatal_error("Coroutines cannot handle non static allocas yet");
634       }
635     }
636 
637     return Builder.CreateInBoundsGEP(FrameTy, FramePtr, Indices);
638   };
639 
640   // Create a load instruction to reload the spilled value from the coroutine
641   // frame. Populates the Value pointer reference provided with the frame GEP.
642   auto CreateReload = [&](Instruction *InsertBefore, Value *&G) {
643     assert(Index != InvalidFieldIndex && "accessing unassigned field number");
644     Builder.SetInsertPoint(InsertBefore);
645 
646     G = GetFramePointer(Index, CurrentValue);
647     G->setName(CurrentValue->getName() + Twine(".reload.addr"));
648 
649     return isa<AllocaInst>(CurrentValue)
650                ? G
651                : Builder.CreateLoad(FrameTy->getElementType(Index), G,
652                                     CurrentValue->getName() + Twine(".reload"));
653   };
654 
655   Value *GEP = nullptr, *CurrentGEP = nullptr;
656   for (auto const &E : Spills) {
657     // If we have not seen the value, generate a spill.
658     if (CurrentValue != E.def()) {
659       CurrentValue = E.def();
660       CurrentBlock = nullptr;
661       CurrentReload = nullptr;
662 
663       Index = E.fieldIndex();
664 
665       if (auto *AI = dyn_cast<AllocaInst>(CurrentValue)) {
666         // Spilled AllocaInst will be replaced with GEP from the coroutine frame
667         // there is no spill required.
668         Allocas.emplace_back(AI, Index);
669         if (!AI->isStaticAlloca())
670           report_fatal_error("Coroutines cannot handle non static allocas yet");
671       } else {
672         // Otherwise, create a store instruction storing the value into the
673         // coroutine frame.
674 
675         Instruction *InsertPt = nullptr;
676         if (auto Arg = dyn_cast<Argument>(CurrentValue)) {
677           // For arguments, we will place the store instruction right after
678           // the coroutine frame pointer instruction, i.e. bitcast of
679           // coro.begin from i8* to %f.frame*.
680           InsertPt = FramePtr->getNextNode();
681 
682           // If we're spilling an Argument, make sure we clear 'nocapture'
683           // from the coroutine function.
684           Arg->getParent()->removeParamAttr(Arg->getArgNo(),
685                                             Attribute::NoCapture);
686 
687         } else if (auto *II = dyn_cast<InvokeInst>(CurrentValue)) {
688           // If we are spilling the result of the invoke instruction, split the
689           // normal edge and insert the spill in the new block.
690           auto NewBB = SplitEdge(II->getParent(), II->getNormalDest());
691           InsertPt = NewBB->getTerminator();
692         } else if (isa<PHINode>(CurrentValue)) {
693           // Skip the PHINodes and EH pads instructions.
694           BasicBlock *DefBlock = cast<Instruction>(E.def())->getParent();
695           if (auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->getTerminator()))
696             InsertPt = splitBeforeCatchSwitch(CSI);
697           else
698             InsertPt = &*DefBlock->getFirstInsertionPt();
699         } else if (auto CSI = dyn_cast<AnyCoroSuspendInst>(CurrentValue)) {
700           // Don't spill immediately after a suspend; splitting assumes
701           // that the suspend will be followed by a branch.
702           InsertPt = CSI->getParent()->getSingleSuccessor()->getFirstNonPHI();
703         } else {
704           auto *I = cast<Instruction>(E.def());
705           assert(!I->isTerminator() && "unexpected terminator");
706           // For all other values, the spill is placed immediately after
707           // the definition.
708           if (DT.dominates(CB, I)) {
709             InsertPt = I->getNextNode();
710           } else {
711             // Unless, it is not dominated by CoroBegin, then it will be
712             // inserted immediately after CoroFrame is computed.
713             InsertPt = FramePtr->getNextNode();
714           }
715         }
716 
717         Builder.SetInsertPoint(InsertPt);
718         auto *G = Builder.CreateConstInBoundsGEP2_32(
719             FrameTy, FramePtr, 0, Index,
720             CurrentValue->getName() + Twine(".spill.addr"));
721         Builder.CreateStore(CurrentValue, G);
722       }
723     }
724 
725     // If we have not seen the use block, generate a reload in it.
726     if (CurrentBlock != E.userBlock()) {
727       CurrentBlock = E.userBlock();
728       CurrentReload = CreateReload(&*CurrentBlock->getFirstInsertionPt(), GEP);
729     }
730 
731     // If we have a single edge PHINode, remove it and replace it with a reload
732     // from the coroutine frame. (We already took care of multi edge PHINodes
733     // by rewriting them in the rewritePHIs function).
734     if (auto *PN = dyn_cast<PHINode>(E.user())) {
735       assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming "
736                                                 "values in the PHINode");
737       PN->replaceAllUsesWith(CurrentReload);
738       PN->eraseFromParent();
739       continue;
740     }
741 
742     // If we have not seen this GEP instruction, migrate any dbg.declare from
743     // the alloca to it.
744     if (CurrentGEP != GEP) {
745       CurrentGEP = GEP;
746       TinyPtrVector<DbgDeclareInst *> DIs = FindDbgDeclareUses(CurrentValue);
747       if (!DIs.empty())
748         DIBuilder(*CurrentBlock->getParent()->getParent(),
749                   /*AllowUnresolved*/ false)
750             .insertDeclare(CurrentGEP, DIs.front()->getVariable(),
751                            DIs.front()->getExpression(),
752                            DIs.front()->getDebugLoc(), DIs.front());
753     }
754 
755     // Replace all uses of CurrentValue in the current instruction with reload.
756     E.user()->replaceUsesOfWith(CurrentValue, CurrentReload);
757   }
758 
759   BasicBlock *FramePtrBB = FramePtr->getParent();
760 
761   auto SpillBlock =
762     FramePtrBB->splitBasicBlock(FramePtr->getNextNode(), "AllocaSpillBB");
763   SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill");
764   Shape.AllocaSpillBlock = SpillBlock;
765   // If we found any alloca, replace all of their remaining uses with GEP
766   // instructions. Because new dbg.declare have been created for these alloca,
767   // we also delete the original dbg.declare and replace other uses with undef.
768   // Note: We cannot replace the alloca with GEP instructions indiscriminately,
769   // as some of the uses may not be dominated by CoroBegin.
770   bool MightNeedToCopy = false;
771   Builder.SetInsertPoint(&Shape.AllocaSpillBlock->front());
772   SmallVector<Instruction *, 4> UsersToUpdate;
773   for (auto &P : Allocas) {
774     AllocaInst *const A = P.first;
775 
776     for (auto *DI : FindDbgDeclareUses(A))
777       DI->eraseFromParent();
778     replaceDbgUsesWithUndef(A);
779 
780     UsersToUpdate.clear();
781     for (User *U : A->users()) {
782       auto *I = cast<Instruction>(U);
783       if (DT.dominates(CB, I))
784         UsersToUpdate.push_back(I);
785       else
786         MightNeedToCopy = true;
787     }
788     if (!UsersToUpdate.empty()) {
789       auto *G = GetFramePointer(P.second, A);
790       G->takeName(A);
791       for (Instruction *I : UsersToUpdate)
792         I->replaceUsesOfWith(A, G);
793     }
794   }
795   // If we discovered such uses not dominated by CoroBegin, see if any of them
796   // preceed coro begin and have instructions that can modify the
797   // value of the alloca and therefore would require a copying the value into
798   // the spill slot in the coroutine frame.
799   if (MightNeedToCopy) {
800     Builder.SetInsertPoint(FramePtr->getNextNode());
801 
802     for (auto &P : Allocas) {
803       AllocaInst *const A = P.first;
804       if (mightWriteIntoAllocaPtr(*A, DT, *CB)) {
805         if (A->isArrayAllocation())
806           report_fatal_error(
807               "Coroutines cannot handle copying of array allocas yet");
808 
809         auto *G = GetFramePointer(P.second, A);
810         auto *Value = Builder.CreateLoad(A->getAllocatedType(), A);
811         Builder.CreateStore(Value, G);
812       }
813     }
814   }
815   return FramePtr;
816 }
817 
818 // Sets the unwind edge of an instruction to a particular successor.
819 static void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
820   if (auto *II = dyn_cast<InvokeInst>(TI))
821     II->setUnwindDest(Succ);
822   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
823     CS->setUnwindDest(Succ);
824   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
825     CR->setUnwindDest(Succ);
826   else
827     llvm_unreachable("unexpected terminator instruction");
828 }
829 
830 // Replaces all uses of OldPred with the NewPred block in all PHINodes in a
831 // block.
832 static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
833                            BasicBlock *NewPred,
834                            PHINode *LandingPadReplacement) {
835   unsigned BBIdx = 0;
836   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
837     PHINode *PN = cast<PHINode>(I);
838 
839     // We manually update the LandingPadReplacement PHINode and it is the last
840     // PHI Node. So, if we find it, we are done.
841     if (LandingPadReplacement == PN)
842       break;
843 
844     // Reuse the previous value of BBIdx if it lines up.  In cases where we
845     // have multiple phi nodes with *lots* of predecessors, this is a speed
846     // win because we don't have to scan the PHI looking for TIBB.  This
847     // happens because the BB list of PHI nodes are usually in the same
848     // order.
849     if (PN->getIncomingBlock(BBIdx) != OldPred)
850       BBIdx = PN->getBasicBlockIndex(OldPred);
851 
852     assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!");
853     PN->setIncomingBlock(BBIdx, NewPred);
854   }
855 }
856 
857 // Uses SplitEdge unless the successor block is an EHPad, in which case do EH
858 // specific handling.
859 static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
860                                     LandingPadInst *OriginalPad,
861                                     PHINode *LandingPadReplacement) {
862   auto *PadInst = Succ->getFirstNonPHI();
863   if (!LandingPadReplacement && !PadInst->isEHPad())
864     return SplitEdge(BB, Succ);
865 
866   auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ);
867   setUnwindEdgeTo(BB->getTerminator(), NewBB);
868   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
869 
870   if (LandingPadReplacement) {
871     auto *NewLP = OriginalPad->clone();
872     auto *Terminator = BranchInst::Create(Succ, NewBB);
873     NewLP->insertBefore(Terminator);
874     LandingPadReplacement->addIncoming(NewLP, NewBB);
875     return NewBB;
876   }
877   Value *ParentPad = nullptr;
878   if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
879     ParentPad = FuncletPad->getParentPad();
880   else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
881     ParentPad = CatchSwitch->getParentPad();
882   else
883     llvm_unreachable("handling for other EHPads not implemented yet");
884 
885   auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB);
886   CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
887   return NewBB;
888 }
889 
890 static void rewritePHIs(BasicBlock &BB) {
891   // For every incoming edge we will create a block holding all
892   // incoming values in a single PHI nodes.
893   //
894   // loop:
895   //    %n.val = phi i32[%n, %entry], [%inc, %loop]
896   //
897   // It will create:
898   //
899   // loop.from.entry:
900   //    %n.loop.pre = phi i32 [%n, %entry]
901   //    br %label loop
902   // loop.from.loop:
903   //    %inc.loop.pre = phi i32 [%inc, %loop]
904   //    br %label loop
905   //
906   // After this rewrite, further analysis will ignore any phi nodes with more
907   // than one incoming edge.
908 
909   // TODO: Simplify PHINodes in the basic block to remove duplicate
910   // predecessors.
911 
912   LandingPadInst *LandingPad = nullptr;
913   PHINode *ReplPHI = nullptr;
914   if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) {
915     // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
916     // We replace the original landing pad with a PHINode that will collect the
917     // results from all of them.
918     ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad);
919     ReplPHI->takeName(LandingPad);
920     LandingPad->replaceAllUsesWith(ReplPHI);
921     // We will erase the original landing pad at the end of this function after
922     // ehAwareSplitEdge cloned it in the transition blocks.
923   }
924 
925   SmallVector<BasicBlock *, 8> Preds(pred_begin(&BB), pred_end(&BB));
926   for (BasicBlock *Pred : Preds) {
927     auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI);
928     IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName());
929     auto *PN = cast<PHINode>(&BB.front());
930     do {
931       int Index = PN->getBasicBlockIndex(IncomingBB);
932       Value *V = PN->getIncomingValue(Index);
933       PHINode *InputV = PHINode::Create(
934           V->getType(), 1, V->getName() + Twine(".") + BB.getName(),
935           &IncomingBB->front());
936       InputV->addIncoming(V, Pred);
937       PN->setIncomingValue(Index, InputV);
938       PN = dyn_cast<PHINode>(PN->getNextNode());
939     } while (PN != ReplPHI); // ReplPHI is either null or the PHI that replaced
940                              // the landing pad.
941   }
942 
943   if (LandingPad) {
944     // Calls to ehAwareSplitEdge function cloned the original lading pad.
945     // No longer need it.
946     LandingPad->eraseFromParent();
947   }
948 }
949 
950 static void rewritePHIs(Function &F) {
951   SmallVector<BasicBlock *, 8> WorkList;
952 
953   for (BasicBlock &BB : F)
954     if (auto *PN = dyn_cast<PHINode>(&BB.front()))
955       if (PN->getNumIncomingValues() > 1)
956         WorkList.push_back(&BB);
957 
958   for (BasicBlock *BB : WorkList)
959     rewritePHIs(*BB);
960 }
961 
962 // Check for instructions that we can recreate on resume as opposed to spill
963 // the result into a coroutine frame.
964 static bool materializable(Instruction &V) {
965   return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) ||
966          isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V);
967 }
968 
969 // Check for structural coroutine intrinsics that should not be spilled into
970 // the coroutine frame.
971 static bool isCoroutineStructureIntrinsic(Instruction &I) {
972   return isa<CoroIdInst>(&I) || isa<CoroSaveInst>(&I) ||
973          isa<CoroSuspendInst>(&I);
974 }
975 
976 // For every use of the value that is across suspend point, recreate that value
977 // after a suspend point.
978 static void rewriteMaterializableInstructions(IRBuilder<> &IRB,
979                                               SpillInfo const &Spills) {
980   BasicBlock *CurrentBlock = nullptr;
981   Instruction *CurrentMaterialization = nullptr;
982   Instruction *CurrentDef = nullptr;
983 
984   for (auto const &E : Spills) {
985     // If it is a new definition, update CurrentXXX variables.
986     if (CurrentDef != E.def()) {
987       CurrentDef = cast<Instruction>(E.def());
988       CurrentBlock = nullptr;
989       CurrentMaterialization = nullptr;
990     }
991 
992     // If we have not seen this block, materialize the value.
993     if (CurrentBlock != E.userBlock()) {
994       CurrentBlock = E.userBlock();
995       CurrentMaterialization = cast<Instruction>(CurrentDef)->clone();
996       CurrentMaterialization->setName(CurrentDef->getName());
997       CurrentMaterialization->insertBefore(
998           &*CurrentBlock->getFirstInsertionPt());
999     }
1000 
1001     if (auto *PN = dyn_cast<PHINode>(E.user())) {
1002       assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming "
1003                                                 "values in the PHINode");
1004       PN->replaceAllUsesWith(CurrentMaterialization);
1005       PN->eraseFromParent();
1006       continue;
1007     }
1008 
1009     // Replace all uses of CurrentDef in the current instruction with the
1010     // CurrentMaterialization for the block.
1011     E.user()->replaceUsesOfWith(CurrentDef, CurrentMaterialization);
1012   }
1013 }
1014 
1015 // Splits the block at a particular instruction unless it is the first
1016 // instruction in the block with a single predecessor.
1017 static BasicBlock *splitBlockIfNotFirst(Instruction *I, const Twine &Name) {
1018   auto *BB = I->getParent();
1019   if (&BB->front() == I) {
1020     if (BB->getSinglePredecessor()) {
1021       BB->setName(Name);
1022       return BB;
1023     }
1024   }
1025   return BB->splitBasicBlock(I, Name);
1026 }
1027 
1028 // Split above and below a particular instruction so that it
1029 // will be all alone by itself in a block.
1030 static void splitAround(Instruction *I, const Twine &Name) {
1031   splitBlockIfNotFirst(I, Name);
1032   splitBlockIfNotFirst(I->getNextNode(), "After" + Name);
1033 }
1034 
1035 static bool isSuspendBlock(BasicBlock *BB) {
1036   return isa<AnyCoroSuspendInst>(BB->front());
1037 }
1038 
1039 typedef SmallPtrSet<BasicBlock*, 8> VisitedBlocksSet;
1040 
1041 /// Does control flow starting at the given block ever reach a suspend
1042 /// instruction before reaching a block in VisitedOrFreeBBs?
1043 static bool isSuspendReachableFrom(BasicBlock *From,
1044                                    VisitedBlocksSet &VisitedOrFreeBBs) {
1045   // Eagerly try to add this block to the visited set.  If it's already
1046   // there, stop recursing; this path doesn't reach a suspend before
1047   // either looping or reaching a freeing block.
1048   if (!VisitedOrFreeBBs.insert(From).second)
1049     return false;
1050 
1051   // We assume that we'll already have split suspends into their own blocks.
1052   if (isSuspendBlock(From))
1053     return true;
1054 
1055   // Recurse on the successors.
1056   for (auto Succ : successors(From)) {
1057     if (isSuspendReachableFrom(Succ, VisitedOrFreeBBs))
1058       return true;
1059   }
1060 
1061   return false;
1062 }
1063 
1064 /// Is the given alloca "local", i.e. bounded in lifetime to not cross a
1065 /// suspend point?
1066 static bool isLocalAlloca(CoroAllocaAllocInst *AI) {
1067   // Seed the visited set with all the basic blocks containing a free
1068   // so that we won't pass them up.
1069   VisitedBlocksSet VisitedOrFreeBBs;
1070   for (auto User : AI->users()) {
1071     if (auto FI = dyn_cast<CoroAllocaFreeInst>(User))
1072       VisitedOrFreeBBs.insert(FI->getParent());
1073   }
1074 
1075   return !isSuspendReachableFrom(AI->getParent(), VisitedOrFreeBBs);
1076 }
1077 
1078 /// After we split the coroutine, will the given basic block be along
1079 /// an obvious exit path for the resumption function?
1080 static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB,
1081                                               unsigned depth = 3) {
1082   // If we've bottomed out our depth count, stop searching and assume
1083   // that the path might loop back.
1084   if (depth == 0) return false;
1085 
1086   // If this is a suspend block, we're about to exit the resumption function.
1087   if (isSuspendBlock(BB)) return true;
1088 
1089   // Recurse into the successors.
1090   for (auto Succ : successors(BB)) {
1091     if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1))
1092       return false;
1093   }
1094 
1095   // If none of the successors leads back in a loop, we're on an exit/abort.
1096   return true;
1097 }
1098 
1099 static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI) {
1100   // Look for a free that isn't sufficiently obviously followed by
1101   // either a suspend or a termination, i.e. something that will leave
1102   // the coro resumption frame.
1103   for (auto U : AI->users()) {
1104     auto FI = dyn_cast<CoroAllocaFreeInst>(U);
1105     if (!FI) continue;
1106 
1107     if (!willLeaveFunctionImmediatelyAfter(FI->getParent()))
1108       return true;
1109   }
1110 
1111   // If we never found one, we don't need a stack save.
1112   return false;
1113 }
1114 
1115 /// Turn each of the given local allocas into a normal (dynamic) alloca
1116 /// instruction.
1117 static void lowerLocalAllocas(ArrayRef<CoroAllocaAllocInst*> LocalAllocas,
1118                               SmallVectorImpl<Instruction*> &DeadInsts) {
1119   for (auto AI : LocalAllocas) {
1120     auto M = AI->getModule();
1121     IRBuilder<> Builder(AI);
1122 
1123     // Save the stack depth.  Try to avoid doing this if the stackrestore
1124     // is going to immediately precede a return or something.
1125     Value *StackSave = nullptr;
1126     if (localAllocaNeedsStackSave(AI))
1127       StackSave = Builder.CreateCall(
1128                             Intrinsic::getDeclaration(M, Intrinsic::stacksave));
1129 
1130     // Allocate memory.
1131     auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize());
1132     Alloca->setAlignment(MaybeAlign(AI->getAlignment()));
1133 
1134     for (auto U : AI->users()) {
1135       // Replace gets with the allocation.
1136       if (isa<CoroAllocaGetInst>(U)) {
1137         U->replaceAllUsesWith(Alloca);
1138 
1139       // Replace frees with stackrestores.  This is safe because
1140       // alloca.alloc is required to obey a stack discipline, although we
1141       // don't enforce that structurally.
1142       } else {
1143         auto FI = cast<CoroAllocaFreeInst>(U);
1144         if (StackSave) {
1145           Builder.SetInsertPoint(FI);
1146           Builder.CreateCall(
1147                     Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
1148                              StackSave);
1149         }
1150       }
1151       DeadInsts.push_back(cast<Instruction>(U));
1152     }
1153 
1154     DeadInsts.push_back(AI);
1155   }
1156 }
1157 
1158 /// Turn the given coro.alloca.alloc call into a dynamic allocation.
1159 /// This happens during the all-instructions iteration, so it must not
1160 /// delete the call.
1161 static Instruction *lowerNonLocalAlloca(CoroAllocaAllocInst *AI,
1162                                         coro::Shape &Shape,
1163                                    SmallVectorImpl<Instruction*> &DeadInsts) {
1164   IRBuilder<> Builder(AI);
1165   auto Alloc = Shape.emitAlloc(Builder, AI->getSize(), nullptr);
1166 
1167   for (User *U : AI->users()) {
1168     if (isa<CoroAllocaGetInst>(U)) {
1169       U->replaceAllUsesWith(Alloc);
1170     } else {
1171       auto FI = cast<CoroAllocaFreeInst>(U);
1172       Builder.SetInsertPoint(FI);
1173       Shape.emitDealloc(Builder, Alloc, nullptr);
1174     }
1175     DeadInsts.push_back(cast<Instruction>(U));
1176   }
1177 
1178   // Push this on last so that it gets deleted after all the others.
1179   DeadInsts.push_back(AI);
1180 
1181   // Return the new allocation value so that we can check for needed spills.
1182   return cast<Instruction>(Alloc);
1183 }
1184 
1185 /// Get the current swifterror value.
1186 static Value *emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy,
1187                                      coro::Shape &Shape) {
1188   // Make a fake function pointer as a sort of intrinsic.
1189   auto FnTy = FunctionType::get(ValueTy, {}, false);
1190   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1191 
1192   auto Call = Builder.CreateCall(FnTy, Fn, {});
1193   Shape.SwiftErrorOps.push_back(Call);
1194 
1195   return Call;
1196 }
1197 
1198 /// Set the given value as the current swifterror value.
1199 ///
1200 /// Returns a slot that can be used as a swifterror slot.
1201 static Value *emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V,
1202                                      coro::Shape &Shape) {
1203   // Make a fake function pointer as a sort of intrinsic.
1204   auto FnTy = FunctionType::get(V->getType()->getPointerTo(),
1205                                 {V->getType()}, false);
1206   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1207 
1208   auto Call = Builder.CreateCall(FnTy, Fn, { V });
1209   Shape.SwiftErrorOps.push_back(Call);
1210 
1211   return Call;
1212 }
1213 
1214 /// Set the swifterror value from the given alloca before a call,
1215 /// then put in back in the alloca afterwards.
1216 ///
1217 /// Returns an address that will stand in for the swifterror slot
1218 /// until splitting.
1219 static Value *emitSetAndGetSwiftErrorValueAround(Instruction *Call,
1220                                                  AllocaInst *Alloca,
1221                                                  coro::Shape &Shape) {
1222   auto ValueTy = Alloca->getAllocatedType();
1223   IRBuilder<> Builder(Call);
1224 
1225   // Load the current value from the alloca and set it as the
1226   // swifterror value.
1227   auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca);
1228   auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape);
1229 
1230   // Move to after the call.  Since swifterror only has a guaranteed
1231   // value on normal exits, we can ignore implicit and explicit unwind
1232   // edges.
1233   if (isa<CallInst>(Call)) {
1234     Builder.SetInsertPoint(Call->getNextNode());
1235   } else {
1236     auto Invoke = cast<InvokeInst>(Call);
1237     Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg());
1238   }
1239 
1240   // Get the current swifterror value and store it to the alloca.
1241   auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape);
1242   Builder.CreateStore(ValueAfterCall, Alloca);
1243 
1244   return Addr;
1245 }
1246 
1247 /// Eliminate a formerly-swifterror alloca by inserting the get/set
1248 /// intrinsics and attempting to MemToReg the alloca away.
1249 static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca,
1250                                       coro::Shape &Shape) {
1251   for (auto UI = Alloca->use_begin(), UE = Alloca->use_end(); UI != UE; ) {
1252     // We're likely changing the use list, so use a mutation-safe
1253     // iteration pattern.
1254     auto &Use = *UI;
1255     ++UI;
1256 
1257     // swifterror values can only be used in very specific ways.
1258     // We take advantage of that here.
1259     auto User = Use.getUser();
1260     if (isa<LoadInst>(User) || isa<StoreInst>(User))
1261       continue;
1262 
1263     assert(isa<CallInst>(User) || isa<InvokeInst>(User));
1264     auto Call = cast<Instruction>(User);
1265 
1266     auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape);
1267 
1268     // Use the returned slot address as the call argument.
1269     Use.set(Addr);
1270   }
1271 
1272   // All the uses should be loads and stores now.
1273   assert(isAllocaPromotable(Alloca));
1274 }
1275 
1276 /// "Eliminate" a swifterror argument by reducing it to the alloca case
1277 /// and then loading and storing in the prologue and epilog.
1278 ///
1279 /// The argument keeps the swifterror flag.
1280 static void eliminateSwiftErrorArgument(Function &F, Argument &Arg,
1281                                         coro::Shape &Shape,
1282                              SmallVectorImpl<AllocaInst*> &AllocasToPromote) {
1283   IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
1284 
1285   auto ArgTy = cast<PointerType>(Arg.getType());
1286   auto ValueTy = ArgTy->getElementType();
1287 
1288   // Reduce to the alloca case:
1289 
1290   // Create an alloca and replace all uses of the arg with it.
1291   auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace());
1292   Arg.replaceAllUsesWith(Alloca);
1293 
1294   // Set an initial value in the alloca.  swifterror is always null on entry.
1295   auto InitialValue = Constant::getNullValue(ValueTy);
1296   Builder.CreateStore(InitialValue, Alloca);
1297 
1298   // Find all the suspends in the function and save and restore around them.
1299   for (auto Suspend : Shape.CoroSuspends) {
1300     (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape);
1301   }
1302 
1303   // Find all the coro.ends in the function and restore the error value.
1304   for (auto End : Shape.CoroEnds) {
1305     Builder.SetInsertPoint(End);
1306     auto FinalValue = Builder.CreateLoad(ValueTy, Alloca);
1307     (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape);
1308   }
1309 
1310   // Now we can use the alloca logic.
1311   AllocasToPromote.push_back(Alloca);
1312   eliminateSwiftErrorAlloca(F, Alloca, Shape);
1313 }
1314 
1315 /// Eliminate all problematic uses of swifterror arguments and allocas
1316 /// from the function.  We'll fix them up later when splitting the function.
1317 static void eliminateSwiftError(Function &F, coro::Shape &Shape) {
1318   SmallVector<AllocaInst*, 4> AllocasToPromote;
1319 
1320   // Look for a swifterror argument.
1321   for (auto &Arg : F.args()) {
1322     if (!Arg.hasSwiftErrorAttr()) continue;
1323 
1324     eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote);
1325     break;
1326   }
1327 
1328   // Look for swifterror allocas.
1329   for (auto &Inst : F.getEntryBlock()) {
1330     auto Alloca = dyn_cast<AllocaInst>(&Inst);
1331     if (!Alloca || !Alloca->isSwiftError()) continue;
1332 
1333     // Clear the swifterror flag.
1334     Alloca->setSwiftError(false);
1335 
1336     AllocasToPromote.push_back(Alloca);
1337     eliminateSwiftErrorAlloca(F, Alloca, Shape);
1338   }
1339 
1340   // If we have any allocas to promote, compute a dominator tree and
1341   // promote them en masse.
1342   if (!AllocasToPromote.empty()) {
1343     DominatorTree DT(F);
1344     PromoteMemToReg(AllocasToPromote, DT);
1345   }
1346 }
1347 
1348 void coro::buildCoroutineFrame(Function &F, Shape &Shape) {
1349   eliminateSwiftError(F, Shape);
1350 
1351   if (Shape.ABI == coro::ABI::Switch &&
1352       Shape.SwitchLowering.PromiseAlloca) {
1353     Shape.getSwitchCoroId()->clearPromise();
1354   }
1355 
1356   // Make sure that all coro.save, coro.suspend and the fallthrough coro.end
1357   // intrinsics are in their own blocks to simplify the logic of building up
1358   // SuspendCrossing data.
1359   for (auto *CSI : Shape.CoroSuspends) {
1360     if (auto *Save = CSI->getCoroSave())
1361       splitAround(Save, "CoroSave");
1362     splitAround(CSI, "CoroSuspend");
1363   }
1364 
1365   // Put CoroEnds into their own blocks.
1366   for (CoroEndInst *CE : Shape.CoroEnds)
1367     splitAround(CE, "CoroEnd");
1368 
1369   // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will
1370   // never has its definition separated from the PHI by the suspend point.
1371   rewritePHIs(F);
1372 
1373   // Build suspend crossing info.
1374   SuspendCrossingInfo Checker(F, Shape);
1375 
1376   IRBuilder<> Builder(F.getContext());
1377   SpillInfo Spills;
1378   SmallVector<CoroAllocaAllocInst*, 4> LocalAllocas;
1379   SmallVector<Instruction*, 4> DeadInstructions;
1380 
1381   for (int Repeat = 0; Repeat < 4; ++Repeat) {
1382     // See if there are materializable instructions across suspend points.
1383     for (Instruction &I : instructions(F))
1384       if (materializable(I))
1385         for (User *U : I.users())
1386           if (Checker.isDefinitionAcrossSuspend(I, U))
1387             Spills.emplace_back(&I, U);
1388 
1389     if (Spills.empty())
1390       break;
1391 
1392     // Rewrite materializable instructions to be materialized at the use point.
1393     LLVM_DEBUG(dump("Materializations", Spills));
1394     rewriteMaterializableInstructions(Builder, Spills);
1395     Spills.clear();
1396   }
1397 
1398   // Collect lifetime.start info for each alloca.
1399   using LifetimeStart = SmallPtrSet<Instruction *, 2>;
1400   llvm::DenseMap<Instruction *, std::unique_ptr<LifetimeStart>> LifetimeMap;
1401   for (Instruction &I : instructions(F)) {
1402     auto *II = dyn_cast<IntrinsicInst>(&I);
1403     if (!II || II->getIntrinsicID() != Intrinsic::lifetime_start)
1404       continue;
1405 
1406     if (auto *OpInst = dyn_cast<BitCastInst>(I.getOperand(1)))
1407       if (auto *AI = dyn_cast<AllocaInst>(OpInst->getOperand(0))) {
1408 
1409         if (LifetimeMap.find(AI) == LifetimeMap.end())
1410           LifetimeMap[AI] = std::make_unique<LifetimeStart>();
1411 
1412         LifetimeMap[AI]->insert(OpInst);
1413       }
1414   }
1415 
1416   // Collect the spills for arguments and other not-materializable values.
1417   for (Argument &A : F.args())
1418     for (User *U : A.users())
1419       if (Checker.isDefinitionAcrossSuspend(A, U))
1420         Spills.emplace_back(&A, U);
1421 
1422   for (Instruction &I : instructions(F)) {
1423     // Values returned from coroutine structure intrinsics should not be part
1424     // of the Coroutine Frame.
1425     if (isCoroutineStructureIntrinsic(I) || &I == Shape.CoroBegin)
1426       continue;
1427 
1428     // The Coroutine Promise always included into coroutine frame, no need to
1429     // check for suspend crossing.
1430     if (Shape.ABI == coro::ABI::Switch &&
1431         Shape.SwitchLowering.PromiseAlloca == &I)
1432       continue;
1433 
1434     // Handle alloca.alloc specially here.
1435     if (auto AI = dyn_cast<CoroAllocaAllocInst>(&I)) {
1436       // Check whether the alloca's lifetime is bounded by suspend points.
1437       if (isLocalAlloca(AI)) {
1438         LocalAllocas.push_back(AI);
1439         continue;
1440       }
1441 
1442       // If not, do a quick rewrite of the alloca and then add spills of
1443       // the rewritten value.  The rewrite doesn't invalidate anything in
1444       // Spills because the other alloca intrinsics have no other operands
1445       // besides AI, and it doesn't invalidate the iteration because we delay
1446       // erasing AI.
1447       auto Alloc = lowerNonLocalAlloca(AI, Shape, DeadInstructions);
1448 
1449       for (User *U : Alloc->users()) {
1450         if (Checker.isDefinitionAcrossSuspend(*Alloc, U))
1451           Spills.emplace_back(Alloc, U);
1452       }
1453       continue;
1454     }
1455 
1456     // Ignore alloca.get; we process this as part of coro.alloca.alloc.
1457     if (isa<CoroAllocaGetInst>(I)) {
1458       continue;
1459     }
1460 
1461     auto Iter = LifetimeMap.find(&I);
1462     for (User *U : I.users()) {
1463       bool NeedSpill = false;
1464 
1465       // Check against lifetime.start if the instruction has the info.
1466       if (Iter != LifetimeMap.end())
1467         for (auto *S : *Iter->second) {
1468           if ((NeedSpill = Checker.isDefinitionAcrossSuspend(*S, U)))
1469             break;
1470         }
1471       else
1472         NeedSpill = Checker.isDefinitionAcrossSuspend(I, U);
1473 
1474       if (NeedSpill) {
1475         // We cannot spill a token.
1476         if (I.getType()->isTokenTy())
1477           report_fatal_error(
1478               "token definition is separated from the use by a suspend point");
1479         Spills.emplace_back(&I, U);
1480       }
1481     }
1482   }
1483   LLVM_DEBUG(dump("Spills", Spills));
1484   Shape.FrameTy = buildFrameType(F, Shape, Spills);
1485   Shape.FramePtr = insertSpills(Spills, Shape);
1486   lowerLocalAllocas(LocalAllocas, DeadInstructions);
1487 
1488   for (auto I : DeadInstructions)
1489     I->eraseFromParent();
1490 }
1491