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/Analysis/StackLifetime.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstIterator.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/OptimizedStructLayout.h"
34 #include "llvm/Support/circular_raw_ostream.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
38 #include <algorithm>
39 
40 using namespace llvm;
41 
42 // The "coro-suspend-crossing" flag is very noisy. There is another debug type,
43 // "coro-frame", which results in leaner debug spew.
44 #define DEBUG_TYPE "coro-suspend-crossing"
45 
46 static cl::opt<bool> EnableReuseStorageInFrame(
47     "reuse-storage-in-coroutine-frame", cl::Hidden,
48     cl::desc(
49         "Enable the optimization which would reuse the storage in the coroutine \
50          frame for allocas whose liferanges are not overlapped, for testing purposes"),
51     llvm::cl::init(false));
52 
53 enum { SmallVectorThreshold = 32 };
54 
55 // Provides two way mapping between the blocks and numbers.
56 namespace {
57 class BlockToIndexMapping {
58   SmallVector<BasicBlock *, SmallVectorThreshold> V;
59 
60 public:
61   size_t size() const { return V.size(); }
62 
63   BlockToIndexMapping(Function &F) {
64     for (BasicBlock &BB : F)
65       V.push_back(&BB);
66     llvm::sort(V);
67   }
68 
69   size_t blockToIndex(BasicBlock *BB) const {
70     auto *I = llvm::lower_bound(V, BB);
71     assert(I != V.end() && *I == BB && "BasicBlockNumberng: Unknown block");
72     return I - V.begin();
73   }
74 
75   BasicBlock *indexToBlock(unsigned Index) const { return V[Index]; }
76 };
77 } // end anonymous namespace
78 
79 // The SuspendCrossingInfo maintains data that allows to answer a question
80 // whether given two BasicBlocks A and B there is a path from A to B that
81 // passes through a suspend point.
82 //
83 // For every basic block 'i' it maintains a BlockData that consists of:
84 //   Consumes:  a bit vector which contains a set of indices of blocks that can
85 //              reach block 'i'
86 //   Kills: a bit vector which contains a set of indices of blocks that can
87 //          reach block 'i', but one of the path will cross a suspend point
88 //   Suspend: a boolean indicating whether block 'i' contains a suspend point.
89 //   End: a boolean indicating whether block 'i' contains a coro.end intrinsic.
90 //
91 namespace {
92 struct SuspendCrossingInfo {
93   BlockToIndexMapping Mapping;
94 
95   struct BlockData {
96     BitVector Consumes;
97     BitVector Kills;
98     bool Suspend = false;
99     bool End = false;
100   };
101   SmallVector<BlockData, SmallVectorThreshold> Block;
102 
103   iterator_range<succ_iterator> successors(BlockData const &BD) const {
104     BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]);
105     return llvm::successors(BB);
106   }
107 
108   BlockData &getBlockData(BasicBlock *BB) {
109     return Block[Mapping.blockToIndex(BB)];
110   }
111 
112   void dump() const;
113   void dump(StringRef Label, BitVector const &BV) const;
114 
115   SuspendCrossingInfo(Function &F, coro::Shape &Shape);
116 
117   bool hasPathCrossingSuspendPoint(BasicBlock *DefBB, BasicBlock *UseBB) const {
118     size_t const DefIndex = Mapping.blockToIndex(DefBB);
119     size_t const UseIndex = Mapping.blockToIndex(UseBB);
120 
121     bool const Result = Block[UseIndex].Kills[DefIndex];
122     LLVM_DEBUG(dbgs() << UseBB->getName() << " => " << DefBB->getName()
123                       << " answer is " << Result << "\n");
124     return Result;
125   }
126 
127   bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const {
128     auto *I = cast<Instruction>(U);
129 
130     // We rewrote PHINodes, so that only the ones with exactly one incoming
131     // value need to be analyzed.
132     if (auto *PN = dyn_cast<PHINode>(I))
133       if (PN->getNumIncomingValues() > 1)
134         return false;
135 
136     BasicBlock *UseBB = I->getParent();
137 
138     // As a special case, treat uses by an llvm.coro.suspend.retcon or an
139     // llvm.coro.suspend.async as if they were uses in the suspend's single
140     // predecessor: the uses conceptually occur before the suspend.
141     if (isa<CoroSuspendRetconInst>(I) || isa<CoroSuspendAsyncInst>(I)) {
142       UseBB = UseBB->getSinglePredecessor();
143       assert(UseBB && "should have split coro.suspend into its own block");
144     }
145 
146     return hasPathCrossingSuspendPoint(DefBB, UseBB);
147   }
148 
149   bool isDefinitionAcrossSuspend(Argument &A, User *U) const {
150     return isDefinitionAcrossSuspend(&A.getParent()->getEntryBlock(), U);
151   }
152 
153   bool isDefinitionAcrossSuspend(Instruction &I, User *U) const {
154     auto *DefBB = I.getParent();
155 
156     // As a special case, treat values produced by an llvm.coro.suspend.*
157     // as if they were defined in the single successor: the uses
158     // conceptually occur after the suspend.
159     if (isa<AnyCoroSuspendInst>(I)) {
160       DefBB = DefBB->getSingleSuccessor();
161       assert(DefBB && "should have split coro.suspend into its own block");
162     }
163 
164     return isDefinitionAcrossSuspend(DefBB, U);
165   }
166 };
167 } // end anonymous namespace
168 
169 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump(StringRef Label,
171                                                 BitVector const &BV) const {
172   dbgs() << Label << ":";
173   for (size_t I = 0, N = BV.size(); I < N; ++I)
174     if (BV[I])
175       dbgs() << " " << Mapping.indexToBlock(I)->getName();
176   dbgs() << "\n";
177 }
178 
179 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump() const {
180   for (size_t I = 0, N = Block.size(); I < N; ++I) {
181     BasicBlock *const B = Mapping.indexToBlock(I);
182     dbgs() << B->getName() << ":\n";
183     dump("   Consumes", Block[I].Consumes);
184     dump("      Kills", Block[I].Kills);
185   }
186   dbgs() << "\n";
187 }
188 #endif
189 
190 SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape)
191     : Mapping(F) {
192   const size_t N = Mapping.size();
193   Block.resize(N);
194 
195   // Initialize every block so that it consumes itself
196   for (size_t I = 0; I < N; ++I) {
197     auto &B = Block[I];
198     B.Consumes.resize(N);
199     B.Kills.resize(N);
200     B.Consumes.set(I);
201   }
202 
203   // Mark all CoroEnd Blocks. We do not propagate Kills beyond coro.ends as
204   // the code beyond coro.end is reachable during initial invocation of the
205   // coroutine.
206   for (auto *CE : Shape.CoroEnds)
207     getBlockData(CE->getParent()).End = true;
208 
209   // Mark all suspend blocks and indicate that they kill everything they
210   // consume. Note, that crossing coro.save also requires a spill, as any code
211   // between coro.save and coro.suspend may resume the coroutine and all of the
212   // state needs to be saved by that time.
213   auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) {
214     BasicBlock *SuspendBlock = BarrierInst->getParent();
215     auto &B = getBlockData(SuspendBlock);
216     B.Suspend = true;
217     B.Kills |= B.Consumes;
218   };
219   for (auto *CSI : Shape.CoroSuspends) {
220     markSuspendBlock(CSI);
221     if (auto *Save = CSI->getCoroSave())
222       markSuspendBlock(Save);
223   }
224 
225   // Iterate propagating consumes and kills until they stop changing.
226   int Iteration = 0;
227   (void)Iteration;
228 
229   bool Changed;
230   do {
231     LLVM_DEBUG(dbgs() << "iteration " << ++Iteration);
232     LLVM_DEBUG(dbgs() << "==============\n");
233 
234     Changed = false;
235     for (size_t I = 0; I < N; ++I) {
236       auto &B = Block[I];
237       for (BasicBlock *SI : successors(B)) {
238 
239         auto SuccNo = Mapping.blockToIndex(SI);
240 
241         // Saved Consumes and Kills bitsets so that it is easy to see
242         // if anything changed after propagation.
243         auto &S = Block[SuccNo];
244         auto SavedConsumes = S.Consumes;
245         auto SavedKills = S.Kills;
246 
247         // Propagate Kills and Consumes from block B into its successor S.
248         S.Consumes |= B.Consumes;
249         S.Kills |= B.Kills;
250 
251         // If block B is a suspend block, it should propagate kills into the
252         // its successor for every block B consumes.
253         if (B.Suspend) {
254           S.Kills |= B.Consumes;
255         }
256         if (S.Suspend) {
257           // If block S is a suspend block, it should kill all of the blocks it
258           // consumes.
259           S.Kills |= S.Consumes;
260         } else if (S.End) {
261           // If block S is an end block, it should not propagate kills as the
262           // blocks following coro.end() are reached during initial invocation
263           // of the coroutine while all the data are still available on the
264           // stack or in the registers.
265           S.Kills.reset();
266         } else {
267           // This is reached when S block it not Suspend nor coro.end and it
268           // need to make sure that it is not in the kill set.
269           S.Kills.reset(SuccNo);
270         }
271 
272         // See if anything changed.
273         Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes);
274 
275         if (S.Kills != SavedKills) {
276           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI->getName()
277                             << "\n");
278           LLVM_DEBUG(dump("S.Kills", S.Kills));
279           LLVM_DEBUG(dump("SavedKills", SavedKills));
280         }
281         if (S.Consumes != SavedConsumes) {
282           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI << "\n");
283           LLVM_DEBUG(dump("S.Consume", S.Consumes));
284           LLVM_DEBUG(dump("SavedCons", SavedConsumes));
285         }
286       }
287     }
288   } while (Changed);
289   LLVM_DEBUG(dump());
290 }
291 
292 #undef DEBUG_TYPE // "coro-suspend-crossing"
293 #define DEBUG_TYPE "coro-frame"
294 
295 namespace {
296 class FrameTypeBuilder;
297 // Mapping from the to-be-spilled value to all the users that need reload.
298 using SpillInfo = SmallMapVector<Value *, SmallVector<Instruction *, 2>, 8>;
299 struct AllocaInfo {
300   AllocaInst *Alloca;
301   DenseMap<Instruction *, llvm::Optional<APInt>> Aliases;
302   bool MayWriteBeforeCoroBegin;
303   AllocaInfo(AllocaInst *Alloca,
304              DenseMap<Instruction *, llvm::Optional<APInt>> Aliases,
305              bool MayWriteBeforeCoroBegin)
306       : Alloca(Alloca), Aliases(std::move(Aliases)),
307         MayWriteBeforeCoroBegin(MayWriteBeforeCoroBegin) {}
308 };
309 struct FrameDataInfo {
310   // All the values (that are not allocas) that needs to be spilled to the
311   // frame.
312   SpillInfo Spills;
313   // Allocas contains all values defined as allocas that need to live in the
314   // frame.
315   SmallVector<AllocaInfo, 8> Allocas;
316 
317   SmallVector<Value *, 8> getAllDefs() const {
318     SmallVector<Value *, 8> Defs;
319     for (const auto &P : Spills)
320       Defs.push_back(P.first);
321     for (const auto &A : Allocas)
322       Defs.push_back(A.Alloca);
323     return Defs;
324   }
325 
326   uint32_t getFieldIndex(Value *V) const {
327     auto Itr = FieldIndexMap.find(V);
328     assert(Itr != FieldIndexMap.end() &&
329            "Value does not have a frame field index");
330     return Itr->second;
331   }
332 
333   void setFieldIndex(Value *V, uint32_t Index) {
334     assert((LayoutIndexUpdateStarted || FieldIndexMap.count(V) == 0) &&
335            "Cannot set the index for the same field twice.");
336     FieldIndexMap[V] = Index;
337   }
338 
339   // Remap the index of every field in the frame, using the final layout index.
340   void updateLayoutIndex(FrameTypeBuilder &B);
341 
342 private:
343   // LayoutIndexUpdateStarted is used to avoid updating the index of any field
344   // twice by mistake.
345   bool LayoutIndexUpdateStarted = false;
346   // Map from values to their slot indexes on the frame. They will be first set
347   // with their original insertion field index. After the frame is built, their
348   // indexes will be updated into the final layout index.
349   DenseMap<Value *, uint32_t> FieldIndexMap;
350 };
351 } // namespace
352 
353 #ifndef NDEBUG
354 static void dumpSpills(StringRef Title, const SpillInfo &Spills) {
355   dbgs() << "------------- " << Title << "--------------\n";
356   for (const auto &E : Spills) {
357     E.first->dump();
358     dbgs() << "   user: ";
359     for (auto *I : E.second)
360       I->dump();
361   }
362 }
363 
364 static void dumpAllocas(const SmallVectorImpl<AllocaInfo> &Allocas) {
365   dbgs() << "------------- Allocas --------------\n";
366   for (const auto &A : Allocas) {
367     A.Alloca->dump();
368   }
369 }
370 #endif
371 
372 namespace {
373 using FieldIDType = size_t;
374 // We cannot rely solely on natural alignment of a type when building a
375 // coroutine frame and if the alignment specified on the Alloca instruction
376 // differs from the natural alignment of the alloca type we will need to insert
377 // padding.
378 class FrameTypeBuilder {
379 private:
380   struct Field {
381     uint64_t Size;
382     uint64_t Offset;
383     Type *Ty;
384     FieldIDType LayoutFieldIndex;
385     Align Alignment;
386     Align TyAlignment;
387   };
388 
389   const DataLayout &DL;
390   LLVMContext &Context;
391   uint64_t StructSize = 0;
392   Align StructAlign;
393   bool IsFinished = false;
394 
395   SmallVector<Field, 8> Fields;
396   DenseMap<Value*, unsigned> FieldIndexByKey;
397 
398 public:
399   FrameTypeBuilder(LLVMContext &Context, DataLayout const &DL)
400       : DL(DL), Context(Context) {}
401 
402   /// Add a field to this structure for the storage of an `alloca`
403   /// instruction.
404   LLVM_NODISCARD FieldIDType addFieldForAlloca(AllocaInst *AI,
405                                                bool IsHeader = false) {
406     Type *Ty = AI->getAllocatedType();
407 
408     // Make an array type if this is a static array allocation.
409     if (AI->isArrayAllocation()) {
410       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
411         Ty = ArrayType::get(Ty, CI->getValue().getZExtValue());
412       else
413         report_fatal_error("Coroutines cannot handle non static allocas yet");
414     }
415 
416     return addField(Ty, AI->getAlign(), IsHeader);
417   }
418 
419   /// We want to put the allocas whose lifetime-ranges are not overlapped
420   /// into one slot of coroutine frame.
421   /// Consider the example at:https://bugs.llvm.org/show_bug.cgi?id=45566
422   ///
423   ///     cppcoro::task<void> alternative_paths(bool cond) {
424   ///         if (cond) {
425   ///             big_structure a;
426   ///             process(a);
427   ///             co_await something();
428   ///         } else {
429   ///             big_structure b;
430   ///             process2(b);
431   ///             co_await something();
432   ///         }
433   ///     }
434   ///
435   /// We want to put variable a and variable b in the same slot to
436   /// reduce the size of coroutine frame.
437   ///
438   /// This function use StackLifetime algorithm to partition the AllocaInsts in
439   /// Spills to non-overlapped sets in order to put Alloca in the same
440   /// non-overlapped set into the same slot in the Coroutine Frame. Then add
441   /// field for the allocas in the same non-overlapped set by using the largest
442   /// type as the field type.
443   ///
444   /// Side Effects: Because We sort the allocas, the order of allocas in the
445   /// frame may be different with the order in the source code.
446   void addFieldForAllocas(const Function &F, FrameDataInfo &FrameData,
447                           coro::Shape &Shape);
448 
449   /// Add a field to this structure.
450   LLVM_NODISCARD FieldIDType addField(Type *Ty, MaybeAlign FieldAlignment,
451                                       bool IsHeader = false) {
452     assert(!IsFinished && "adding fields to a finished builder");
453     assert(Ty && "must provide a type for a field");
454 
455     // The field size is always the alloc size of the type.
456     uint64_t FieldSize = DL.getTypeAllocSize(Ty);
457 
458     // The field alignment might not be the type alignment, but we need
459     // to remember the type alignment anyway to build the type.
460     Align TyAlignment = DL.getABITypeAlign(Ty);
461     if (!FieldAlignment) FieldAlignment = TyAlignment;
462 
463     // Lay out header fields immediately.
464     uint64_t Offset;
465     if (IsHeader) {
466       Offset = alignTo(StructSize, FieldAlignment);
467       StructSize = Offset + FieldSize;
468 
469     // Everything else has a flexible offset.
470     } else {
471       Offset = OptimizedStructLayoutField::FlexibleOffset;
472     }
473 
474     Fields.push_back({FieldSize, Offset, Ty, 0, *FieldAlignment, TyAlignment});
475     return Fields.size() - 1;
476   }
477 
478   /// Finish the layout and set the body on the given type.
479   void finish(StructType *Ty);
480 
481   uint64_t getStructSize() const {
482     assert(IsFinished && "not yet finished!");
483     return StructSize;
484   }
485 
486   Align getStructAlign() const {
487     assert(IsFinished && "not yet finished!");
488     return StructAlign;
489   }
490 
491   FieldIDType getLayoutFieldIndex(FieldIDType Id) const {
492     assert(IsFinished && "not yet finished!");
493     return Fields[Id].LayoutFieldIndex;
494   }
495 };
496 } // namespace
497 
498 void FrameDataInfo::updateLayoutIndex(FrameTypeBuilder &B) {
499   auto Updater = [&](Value *I) {
500     setFieldIndex(I, B.getLayoutFieldIndex(getFieldIndex(I)));
501   };
502   LayoutIndexUpdateStarted = true;
503   for (auto &S : Spills)
504     Updater(S.first);
505   for (const auto &A : Allocas)
506     Updater(A.Alloca);
507   LayoutIndexUpdateStarted = false;
508 }
509 
510 void FrameTypeBuilder::addFieldForAllocas(const Function &F,
511                                           FrameDataInfo &FrameData,
512                                           coro::Shape &Shape) {
513   DenseMap<AllocaInst *, unsigned int> AllocaIndex;
514   using AllocaSetType = SmallVector<AllocaInst *, 4>;
515   SmallVector<AllocaSetType, 4> NonOverlapedAllocas;
516 
517   // We need to add field for allocas at the end of this function. However, this
518   // function has multiple exits, so we use this helper to avoid redundant code.
519   struct RTTIHelper {
520     std::function<void()> func;
521     RTTIHelper(std::function<void()> &&func) : func(func) {}
522     ~RTTIHelper() { func(); }
523   } Helper([&]() {
524     for (auto AllocaList : NonOverlapedAllocas) {
525       auto *LargestAI = *AllocaList.begin();
526       FieldIDType Id = addFieldForAlloca(LargestAI);
527       for (auto *Alloca : AllocaList)
528         FrameData.setFieldIndex(Alloca, Id);
529     }
530   });
531 
532   if (!Shape.ReuseFrameSlot && !EnableReuseStorageInFrame) {
533     for (const auto &A : FrameData.Allocas) {
534       AllocaInst *Alloca = A.Alloca;
535       AllocaIndex[Alloca] = NonOverlapedAllocas.size();
536       NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
537     }
538     return;
539   }
540 
541   // Because there are pathes from the lifetime.start to coro.end
542   // for each alloca, the liferanges for every alloca is overlaped
543   // in the blocks who contain coro.end and the successor blocks.
544   // So we choose to skip there blocks when we calculates the liferange
545   // for each alloca. It should be reasonable since there shouldn't be uses
546   // in these blocks and the coroutine frame shouldn't be used outside the
547   // coroutine body.
548   //
549   // Note that the user of coro.suspend may not be SwitchInst. However, this
550   // case seems too complex to handle. And it is harmless to skip these
551   // patterns since it just prevend putting the allocas to live in the same
552   // slot.
553   DenseMap<SwitchInst *, BasicBlock *> DefaultSuspendDest;
554   for (auto CoroSuspendInst : Shape.CoroSuspends) {
555     for (auto U : CoroSuspendInst->users()) {
556       if (auto *ConstSWI = dyn_cast<SwitchInst>(U)) {
557         auto *SWI = const_cast<SwitchInst *>(ConstSWI);
558         DefaultSuspendDest[SWI] = SWI->getDefaultDest();
559         SWI->setDefaultDest(SWI->getSuccessor(1));
560       }
561     }
562   }
563 
564   auto ExtractAllocas = [&]() {
565     AllocaSetType Allocas;
566     Allocas.reserve(FrameData.Allocas.size());
567     for (const auto &A : FrameData.Allocas)
568       Allocas.push_back(A.Alloca);
569     return Allocas;
570   };
571   StackLifetime StackLifetimeAnalyzer(F, ExtractAllocas(),
572                                       StackLifetime::LivenessType::May);
573   StackLifetimeAnalyzer.run();
574   auto IsAllocaInferenre = [&](const AllocaInst *AI1, const AllocaInst *AI2) {
575     return StackLifetimeAnalyzer.getLiveRange(AI1).overlaps(
576         StackLifetimeAnalyzer.getLiveRange(AI2));
577   };
578   auto GetAllocaSize = [&](const AllocaInfo &A) {
579     Optional<TypeSize> RetSize = A.Alloca->getAllocationSizeInBits(DL);
580     assert(RetSize && "Variable Length Arrays (VLA) are not supported.\n");
581     assert(!RetSize->isScalable() && "Scalable vectors are not yet supported");
582     return RetSize->getFixedSize();
583   };
584   // Put larger allocas in the front. So the larger allocas have higher
585   // priority to merge, which can save more space potentially. Also each
586   // AllocaSet would be ordered. So we can get the largest Alloca in one
587   // AllocaSet easily.
588   sort(FrameData.Allocas, [&](const auto &Iter1, const auto &Iter2) {
589     return GetAllocaSize(Iter1) > GetAllocaSize(Iter2);
590   });
591   for (const auto &A : FrameData.Allocas) {
592     AllocaInst *Alloca = A.Alloca;
593     bool Merged = false;
594     // Try to find if the Alloca is not inferenced with any existing
595     // NonOverlappedAllocaSet. If it is true, insert the alloca to that
596     // NonOverlappedAllocaSet.
597     for (auto &AllocaSet : NonOverlapedAllocas) {
598       assert(!AllocaSet.empty() && "Processing Alloca Set is not empty.\n");
599       bool NoInference = none_of(AllocaSet, [&](auto Iter) {
600         return IsAllocaInferenre(Alloca, Iter);
601       });
602       // If the alignment of A is multiple of the alignment of B, the address
603       // of A should satisfy the requirement for aligning for B.
604       //
605       // There may be other more fine-grained strategies to handle the alignment
606       // infomation during the merging process. But it seems hard to handle
607       // these strategies and benefit little.
608       bool Alignable = [&]() -> bool {
609         auto *LargestAlloca = *AllocaSet.begin();
610         return LargestAlloca->getAlign().value() % Alloca->getAlign().value() ==
611                0;
612       }();
613       bool CouldMerge = NoInference && Alignable;
614       if (!CouldMerge)
615         continue;
616       AllocaIndex[Alloca] = AllocaIndex[*AllocaSet.begin()];
617       AllocaSet.push_back(Alloca);
618       Merged = true;
619       break;
620     }
621     if (!Merged) {
622       AllocaIndex[Alloca] = NonOverlapedAllocas.size();
623       NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
624     }
625   }
626   // Recover the default target destination for each Switch statement
627   // reserved.
628   for (auto SwitchAndDefaultDest : DefaultSuspendDest) {
629     SwitchInst *SWI = SwitchAndDefaultDest.first;
630     BasicBlock *DestBB = SwitchAndDefaultDest.second;
631     SWI->setDefaultDest(DestBB);
632   }
633   // This Debug Info could tell us which allocas are merged into one slot.
634   LLVM_DEBUG(for (auto &AllocaSet
635                   : NonOverlapedAllocas) {
636     if (AllocaSet.size() > 1) {
637       dbgs() << "In Function:" << F.getName() << "\n";
638       dbgs() << "Find Union Set "
639              << "\n";
640       dbgs() << "\tAllocas are \n";
641       for (auto Alloca : AllocaSet)
642         dbgs() << "\t\t" << *Alloca << "\n";
643     }
644   });
645 }
646 
647 void FrameTypeBuilder::finish(StructType *Ty) {
648   assert(!IsFinished && "already finished!");
649 
650   // Prepare the optimal-layout field array.
651   // The Id in the layout field is a pointer to our Field for it.
652   SmallVector<OptimizedStructLayoutField, 8> LayoutFields;
653   LayoutFields.reserve(Fields.size());
654   for (auto &Field : Fields) {
655     LayoutFields.emplace_back(&Field, Field.Size, Field.Alignment,
656                               Field.Offset);
657   }
658 
659   // Perform layout.
660   auto SizeAndAlign = performOptimizedStructLayout(LayoutFields);
661   StructSize = SizeAndAlign.first;
662   StructAlign = SizeAndAlign.second;
663 
664   auto getField = [](const OptimizedStructLayoutField &LayoutField) -> Field & {
665     return *static_cast<Field *>(const_cast<void*>(LayoutField.Id));
666   };
667 
668   // We need to produce a packed struct type if there's a field whose
669   // assigned offset isn't a multiple of its natural type alignment.
670   bool Packed = [&] {
671     for (auto &LayoutField : LayoutFields) {
672       auto &F = getField(LayoutField);
673       if (!isAligned(F.TyAlignment, LayoutField.Offset))
674         return true;
675     }
676     return false;
677   }();
678 
679   // Build the struct body.
680   SmallVector<Type*, 16> FieldTypes;
681   FieldTypes.reserve(LayoutFields.size() * 3 / 2);
682   uint64_t LastOffset = 0;
683   for (auto &LayoutField : LayoutFields) {
684     auto &F = getField(LayoutField);
685 
686     auto Offset = LayoutField.Offset;
687 
688     // Add a padding field if there's a padding gap and we're either
689     // building a packed struct or the padding gap is more than we'd
690     // get from aligning to the field type's natural alignment.
691     assert(Offset >= LastOffset);
692     if (Offset != LastOffset) {
693       if (Packed || alignTo(LastOffset, F.TyAlignment) != Offset)
694         FieldTypes.push_back(ArrayType::get(Type::getInt8Ty(Context),
695                                             Offset - LastOffset));
696     }
697 
698     F.Offset = Offset;
699     F.LayoutFieldIndex = FieldTypes.size();
700 
701     FieldTypes.push_back(F.Ty);
702     LastOffset = Offset + F.Size;
703   }
704 
705   Ty->setBody(FieldTypes, Packed);
706 
707 #ifndef NDEBUG
708   // Check that the IR layout matches the offsets we expect.
709   auto Layout = DL.getStructLayout(Ty);
710   for (auto &F : Fields) {
711     assert(Ty->getElementType(F.LayoutFieldIndex) == F.Ty);
712     assert(Layout->getElementOffset(F.LayoutFieldIndex) == F.Offset);
713   }
714 #endif
715 
716   IsFinished = true;
717 }
718 
719 // Build a struct that will keep state for an active coroutine.
720 //   struct f.frame {
721 //     ResumeFnTy ResumeFnAddr;
722 //     ResumeFnTy DestroyFnAddr;
723 //     int ResumeIndex;
724 //     ... promise (if present) ...
725 //     ... spills ...
726 //   };
727 static StructType *buildFrameType(Function &F, coro::Shape &Shape,
728                                   FrameDataInfo &FrameData) {
729   LLVMContext &C = F.getContext();
730   const DataLayout &DL = F.getParent()->getDataLayout();
731   StructType *FrameTy = [&] {
732     SmallString<32> Name(F.getName());
733     Name.append(".Frame");
734     return StructType::create(C, Name);
735   }();
736 
737   FrameTypeBuilder B(C, DL);
738 
739   AllocaInst *PromiseAlloca = Shape.getPromiseAlloca();
740   Optional<FieldIDType> SwitchIndexFieldId;
741 
742   if (Shape.ABI == coro::ABI::Switch) {
743     auto *FramePtrTy = FrameTy->getPointerTo();
744     auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy,
745                                    /*IsVarArg=*/false);
746     auto *FnPtrTy = FnTy->getPointerTo();
747 
748     // Add header fields for the resume and destroy functions.
749     // We can rely on these being perfectly packed.
750     (void)B.addField(FnPtrTy, None, /*header*/ true);
751     (void)B.addField(FnPtrTy, None, /*header*/ true);
752 
753     // PromiseAlloca field needs to be explicitly added here because it's
754     // a header field with a fixed offset based on its alignment. Hence it
755     // needs special handling and cannot be added to FrameData.Allocas.
756     if (PromiseAlloca)
757       FrameData.setFieldIndex(
758           PromiseAlloca, B.addFieldForAlloca(PromiseAlloca, /*header*/ true));
759 
760     // Add a field to store the suspend index.  This doesn't need to
761     // be in the header.
762     unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size()));
763     Type *IndexType = Type::getIntNTy(C, IndexBits);
764 
765     SwitchIndexFieldId = B.addField(IndexType, None);
766   } else {
767     assert(PromiseAlloca == nullptr && "lowering doesn't support promises");
768   }
769 
770   // Because multiple allocas may own the same field slot,
771   // we add allocas to field here.
772   B.addFieldForAllocas(F, FrameData, Shape);
773   // Add PromiseAlloca to Allocas list so that
774   // 1. updateLayoutIndex could update its index after
775   // `performOptimizedStructLayout`
776   // 2. it is processed in insertSpills.
777   if (Shape.ABI == coro::ABI::Switch && PromiseAlloca)
778     // We assume that the promise alloca won't be modified before
779     // CoroBegin and no alias will be create before CoroBegin.
780     FrameData.Allocas.emplace_back(
781         PromiseAlloca, DenseMap<Instruction *, llvm::Optional<APInt>>{}, false);
782   // Create an entry for every spilled value.
783   for (auto &S : FrameData.Spills) {
784     FieldIDType Id = B.addField(S.first->getType(), None);
785     FrameData.setFieldIndex(S.first, Id);
786   }
787 
788   B.finish(FrameTy);
789   FrameData.updateLayoutIndex(B);
790   Shape.FrameAlign = B.getStructAlign();
791   Shape.FrameSize = B.getStructSize();
792 
793   switch (Shape.ABI) {
794   case coro::ABI::Switch:
795     // In the switch ABI, remember the switch-index field.
796     Shape.SwitchLowering.IndexField =
797         B.getLayoutFieldIndex(*SwitchIndexFieldId);
798 
799     // Also round the frame size up to a multiple of its alignment, as is
800     // generally expected in C/C++.
801     Shape.FrameSize = alignTo(Shape.FrameSize, Shape.FrameAlign);
802     break;
803 
804   // In the retcon ABI, remember whether the frame is inline in the storage.
805   case coro::ABI::Retcon:
806   case coro::ABI::RetconOnce: {
807     auto Id = Shape.getRetconCoroId();
808     Shape.RetconLowering.IsFrameInlineInStorage
809       = (B.getStructSize() <= Id->getStorageSize() &&
810          B.getStructAlign() <= Id->getStorageAlignment());
811     break;
812   }
813   case coro::ABI::Async: {
814     Shape.AsyncLowering.FrameOffset =
815         alignTo(Shape.AsyncLowering.ContextHeaderSize, Shape.FrameAlign);
816     // Also make the final context size a multiple of the context alignment to
817     // make allocation easier for allocators.
818     Shape.AsyncLowering.ContextSize =
819         alignTo(Shape.AsyncLowering.FrameOffset + Shape.FrameSize,
820                 Shape.AsyncLowering.getContextAlignment());
821     if (Shape.AsyncLowering.getContextAlignment() < Shape.FrameAlign) {
822       report_fatal_error(
823           "The alignment requirment of frame variables cannot be higher than "
824           "the alignment of the async function context");
825     }
826     break;
827   }
828   }
829 
830   return FrameTy;
831 }
832 
833 // We use a pointer use visitor to track how an alloca is being used.
834 // The goal is to be able to answer the following three questions:
835 // 1. Should this alloca be allocated on the frame instead.
836 // 2. Could the content of the alloca be modified prior to CoroBegn, which would
837 // require copying the data from alloca to the frame after CoroBegin.
838 // 3. Is there any alias created for this alloca prior to CoroBegin, but used
839 // after CoroBegin. In that case, we will need to recreate the alias after
840 // CoroBegin based off the frame. To answer question 1, we track two things:
841 //   a. List of all BasicBlocks that use this alloca or any of the aliases of
842 //   the alloca. In the end, we check if there exists any two basic blocks that
843 //   cross suspension points. If so, this alloca must be put on the frame. b.
844 //   Whether the alloca or any alias of the alloca is escaped at some point,
845 //   either by storing the address somewhere, or the address is used in a
846 //   function call that might capture. If it's ever escaped, this alloca must be
847 //   put on the frame conservatively.
848 // To answer quetion 2, we track through the variable MayWriteBeforeCoroBegin.
849 // Whenever a potential write happens, either through a store instruction, a
850 // function call or any of the memory intrinsics, we check whether this
851 // instruction is prior to CoroBegin. To answer question 3, we track the offsets
852 // of all aliases created for the alloca prior to CoroBegin but used after
853 // CoroBegin. llvm::Optional is used to be able to represent the case when the
854 // offset is unknown (e.g. when you have a PHINode that takes in different
855 // offset values). We cannot handle unknown offsets and will assert. This is the
856 // potential issue left out. An ideal solution would likely require a
857 // significant redesign.
858 namespace {
859 struct AllocaUseVisitor : PtrUseVisitor<AllocaUseVisitor> {
860   using Base = PtrUseVisitor<AllocaUseVisitor>;
861   AllocaUseVisitor(const DataLayout &DL, const DominatorTree &DT,
862                    const CoroBeginInst &CB, const SuspendCrossingInfo &Checker)
863       : PtrUseVisitor(DL), DT(DT), CoroBegin(CB), Checker(Checker) {}
864 
865   void visit(Instruction &I) {
866     UserBBs.insert(I.getParent());
867     Base::visit(I);
868     // If the pointer is escaped prior to CoroBegin, we have to assume it would
869     // be written into before CoroBegin as well.
870     if (PI.isEscaped() && !DT.dominates(&CoroBegin, PI.getEscapingInst())) {
871       MayWriteBeforeCoroBegin = true;
872     }
873   }
874   // We need to provide this overload as PtrUseVisitor uses a pointer based
875   // visiting function.
876   void visit(Instruction *I) { return visit(*I); }
877 
878   void visitPHINode(PHINode &I) {
879     enqueueUsers(I);
880     handleAlias(I);
881   }
882 
883   void visitSelectInst(SelectInst &I) {
884     enqueueUsers(I);
885     handleAlias(I);
886   }
887 
888   void visitStoreInst(StoreInst &SI) {
889     // Regardless whether the alias of the alloca is the value operand or the
890     // pointer operand, we need to assume the alloca is been written.
891     handleMayWrite(SI);
892 
893     if (SI.getValueOperand() != U->get())
894       return;
895 
896     // We are storing the pointer into a memory location, potentially escaping.
897     // As an optimization, we try to detect simple cases where it doesn't
898     // actually escape, for example:
899     //   %ptr = alloca ..
900     //   %addr = alloca ..
901     //   store %ptr, %addr
902     //   %x = load %addr
903     //   ..
904     // If %addr is only used by loading from it, we could simply treat %x as
905     // another alias of %ptr, and not considering %ptr being escaped.
906     auto IsSimpleStoreThenLoad = [&]() {
907       auto *AI = dyn_cast<AllocaInst>(SI.getPointerOperand());
908       // If the memory location we are storing to is not an alloca, it
909       // could be an alias of some other memory locations, which is difficult
910       // to analyze.
911       if (!AI)
912         return false;
913       // StoreAliases contains aliases of the memory location stored into.
914       SmallVector<Instruction *, 4> StoreAliases = {AI};
915       while (!StoreAliases.empty()) {
916         Instruction *I = StoreAliases.pop_back_val();
917         for (User *U : I->users()) {
918           // If we are loading from the memory location, we are creating an
919           // alias of the original pointer.
920           if (auto *LI = dyn_cast<LoadInst>(U)) {
921             enqueueUsers(*LI);
922             handleAlias(*LI);
923             continue;
924           }
925           // If we are overriding the memory location, the pointer certainly
926           // won't escape.
927           if (auto *S = dyn_cast<StoreInst>(U))
928             if (S->getPointerOperand() == I)
929               continue;
930           if (auto *II = dyn_cast<IntrinsicInst>(U))
931             if (II->isLifetimeStartOrEnd())
932               continue;
933           // BitCastInst creats aliases of the memory location being stored
934           // into.
935           if (auto *BI = dyn_cast<BitCastInst>(U)) {
936             StoreAliases.push_back(BI);
937             continue;
938           }
939           return false;
940         }
941       }
942 
943       return true;
944     };
945 
946     if (!IsSimpleStoreThenLoad())
947       PI.setEscaped(&SI);
948   }
949 
950   // All mem intrinsics modify the data.
951   void visitMemIntrinsic(MemIntrinsic &MI) { handleMayWrite(MI); }
952 
953   void visitBitCastInst(BitCastInst &BC) {
954     Base::visitBitCastInst(BC);
955     handleAlias(BC);
956   }
957 
958   void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
959     Base::visitAddrSpaceCastInst(ASC);
960     handleAlias(ASC);
961   }
962 
963   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
964     // The base visitor will adjust Offset accordingly.
965     Base::visitGetElementPtrInst(GEPI);
966     handleAlias(GEPI);
967   }
968 
969   void visitCallBase(CallBase &CB) {
970     for (unsigned Op = 0, OpCount = CB.getNumArgOperands(); Op < OpCount; ++Op)
971       if (U->get() == CB.getArgOperand(Op) && !CB.doesNotCapture(Op))
972         PI.setEscaped(&CB);
973     handleMayWrite(CB);
974   }
975 
976   bool getShouldLiveOnFrame() const {
977     if (!ShouldLiveOnFrame)
978       ShouldLiveOnFrame = computeShouldLiveOnFrame();
979     return ShouldLiveOnFrame.getValue();
980   }
981 
982   bool getMayWriteBeforeCoroBegin() const { return MayWriteBeforeCoroBegin; }
983 
984   DenseMap<Instruction *, llvm::Optional<APInt>> getAliasesCopy() const {
985     assert(getShouldLiveOnFrame() && "This method should only be called if the "
986                                      "alloca needs to live on the frame.");
987     for (const auto &P : AliasOffetMap)
988       if (!P.second)
989         report_fatal_error("Unable to handle an alias with unknown offset "
990                            "created before CoroBegin.");
991     return AliasOffetMap;
992   }
993 
994 private:
995   const DominatorTree &DT;
996   const CoroBeginInst &CoroBegin;
997   const SuspendCrossingInfo &Checker;
998   // All alias to the original AllocaInst, created before CoroBegin and used
999   // after CoroBegin. Each entry contains the instruction and the offset in the
1000   // original Alloca. They need to be recreated after CoroBegin off the frame.
1001   DenseMap<Instruction *, llvm::Optional<APInt>> AliasOffetMap{};
1002   SmallPtrSet<BasicBlock *, 2> UserBBs{};
1003   bool MayWriteBeforeCoroBegin{false};
1004 
1005   mutable llvm::Optional<bool> ShouldLiveOnFrame{};
1006 
1007   bool computeShouldLiveOnFrame() const {
1008     if (PI.isEscaped())
1009       return true;
1010 
1011     for (auto *BB1 : UserBBs)
1012       for (auto *BB2 : UserBBs)
1013         if (Checker.hasPathCrossingSuspendPoint(BB1, BB2))
1014           return true;
1015 
1016     return false;
1017   }
1018 
1019   void handleMayWrite(const Instruction &I) {
1020     if (!DT.dominates(&CoroBegin, &I))
1021       MayWriteBeforeCoroBegin = true;
1022   }
1023 
1024   bool usedAfterCoroBegin(Instruction &I) {
1025     for (auto &U : I.uses())
1026       if (DT.dominates(&CoroBegin, U))
1027         return true;
1028     return false;
1029   }
1030 
1031   void handleAlias(Instruction &I) {
1032     // We track all aliases created prior to CoroBegin but used after.
1033     // These aliases may need to be recreated after CoroBegin if the alloca
1034     // need to live on the frame.
1035     if (DT.dominates(&CoroBegin, &I) || !usedAfterCoroBegin(I))
1036       return;
1037 
1038     if (!IsOffsetKnown) {
1039       AliasOffetMap[&I].reset();
1040     } else {
1041       auto Itr = AliasOffetMap.find(&I);
1042       if (Itr == AliasOffetMap.end()) {
1043         AliasOffetMap[&I] = Offset;
1044       } else if (Itr->second.hasValue() && Itr->second.getValue() != Offset) {
1045         // If we have seen two different possible values for this alias, we set
1046         // it to empty.
1047         AliasOffetMap[&I].reset();
1048       }
1049     }
1050   }
1051 };
1052 } // namespace
1053 
1054 // We need to make room to insert a spill after initial PHIs, but before
1055 // catchswitch instruction. Placing it before violates the requirement that
1056 // catchswitch, like all other EHPads must be the first nonPHI in a block.
1057 //
1058 // Split away catchswitch into a separate block and insert in its place:
1059 //
1060 //   cleanuppad <InsertPt> cleanupret.
1061 //
1062 // cleanupret instruction will act as an insert point for the spill.
1063 static Instruction *splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch) {
1064   BasicBlock *CurrentBlock = CatchSwitch->getParent();
1065   BasicBlock *NewBlock = CurrentBlock->splitBasicBlock(CatchSwitch);
1066   CurrentBlock->getTerminator()->eraseFromParent();
1067 
1068   auto *CleanupPad =
1069       CleanupPadInst::Create(CatchSwitch->getParentPad(), {}, "", CurrentBlock);
1070   auto *CleanupRet =
1071       CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock);
1072   return CleanupRet;
1073 }
1074 
1075 // Replace all alloca and SSA values that are accessed across suspend points
1076 // with GetElementPointer from coroutine frame + loads and stores. Create an
1077 // AllocaSpillBB that will become the new entry block for the resume parts of
1078 // the coroutine:
1079 //
1080 //    %hdl = coro.begin(...)
1081 //    whatever
1082 //
1083 // becomes:
1084 //
1085 //    %hdl = coro.begin(...)
1086 //    %FramePtr = bitcast i8* hdl to %f.frame*
1087 //    br label %AllocaSpillBB
1088 //
1089 //  AllocaSpillBB:
1090 //    ; geps corresponding to allocas that were moved to coroutine frame
1091 //    br label PostSpill
1092 //
1093 //  PostSpill:
1094 //    whatever
1095 //
1096 //
1097 static Instruction *insertSpills(const FrameDataInfo &FrameData,
1098                                  coro::Shape &Shape) {
1099   auto *CB = Shape.CoroBegin;
1100   LLVMContext &C = CB->getContext();
1101   IRBuilder<> Builder(CB->getNextNode());
1102   StructType *FrameTy = Shape.FrameTy;
1103   PointerType *FramePtrTy = FrameTy->getPointerTo();
1104   auto *FramePtr =
1105       cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy, "FramePtr"));
1106   DominatorTree DT(*CB->getFunction());
1107   SmallDenseMap<llvm::Value *, llvm::AllocaInst *, 4> DbgPtrAllocaCache;
1108 
1109   // Create a GEP with the given index into the coroutine frame for the original
1110   // value Orig. Appends an extra 0 index for array-allocas, preserving the
1111   // original type.
1112   auto GetFramePointer = [&](Value *Orig) -> Value * {
1113     FieldIDType Index = FrameData.getFieldIndex(Orig);
1114     SmallVector<Value *, 3> Indices = {
1115         ConstantInt::get(Type::getInt32Ty(C), 0),
1116         ConstantInt::get(Type::getInt32Ty(C), Index),
1117     };
1118 
1119     if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
1120       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
1121         auto Count = CI->getValue().getZExtValue();
1122         if (Count > 1) {
1123           Indices.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
1124         }
1125       } else {
1126         report_fatal_error("Coroutines cannot handle non static allocas yet");
1127       }
1128     }
1129 
1130     auto GEP = cast<GetElementPtrInst>(
1131         Builder.CreateInBoundsGEP(FrameTy, FramePtr, Indices));
1132     if (isa<AllocaInst>(Orig)) {
1133       // If the type of GEP is not equal to the type of AllocaInst, it implies
1134       // that the AllocaInst may be reused in the Frame slot of other
1135       // AllocaInst. So We cast GEP to the AllocaInst here to re-use
1136       // the Frame storage.
1137       //
1138       // Note: If we change the strategy dealing with alignment, we need to refine
1139       // this casting.
1140       if (GEP->getResultElementType() != Orig->getType())
1141         return Builder.CreateBitCast(GEP, Orig->getType(),
1142                                      Orig->getName() + Twine(".cast"));
1143     }
1144     return GEP;
1145   };
1146 
1147   for (auto const &E : FrameData.Spills) {
1148     Value *Def = E.first;
1149     // Create a store instruction storing the value into the
1150     // coroutine frame.
1151     Instruction *InsertPt = nullptr;
1152     if (auto *Arg = dyn_cast<Argument>(Def)) {
1153       // For arguments, we will place the store instruction right after
1154       // the coroutine frame pointer instruction, i.e. bitcast of
1155       // coro.begin from i8* to %f.frame*.
1156       InsertPt = FramePtr->getNextNode();
1157 
1158       // If we're spilling an Argument, make sure we clear 'nocapture'
1159       // from the coroutine function.
1160       Arg->getParent()->removeParamAttr(Arg->getArgNo(), Attribute::NoCapture);
1161 
1162     } else if (auto *CSI = dyn_cast<AnyCoroSuspendInst>(Def)) {
1163       // Don't spill immediately after a suspend; splitting assumes
1164       // that the suspend will be followed by a branch.
1165       InsertPt = CSI->getParent()->getSingleSuccessor()->getFirstNonPHI();
1166     } else {
1167       auto *I = cast<Instruction>(Def);
1168       if (!DT.dominates(CB, I)) {
1169         // If it is not dominated by CoroBegin, then spill should be
1170         // inserted immediately after CoroFrame is computed.
1171         InsertPt = FramePtr->getNextNode();
1172       } else if (auto *II = dyn_cast<InvokeInst>(I)) {
1173         // If we are spilling the result of the invoke instruction, split
1174         // the normal edge and insert the spill in the new block.
1175         auto *NewBB = SplitEdge(II->getParent(), II->getNormalDest());
1176         InsertPt = NewBB->getTerminator();
1177       } else if (isa<PHINode>(I)) {
1178         // Skip the PHINodes and EH pads instructions.
1179         BasicBlock *DefBlock = I->getParent();
1180         if (auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->getTerminator()))
1181           InsertPt = splitBeforeCatchSwitch(CSI);
1182         else
1183           InsertPt = &*DefBlock->getFirstInsertionPt();
1184       } else {
1185         assert(!I->isTerminator() && "unexpected terminator");
1186         // For all other values, the spill is placed immediately after
1187         // the definition.
1188         InsertPt = I->getNextNode();
1189       }
1190     }
1191 
1192     auto Index = FrameData.getFieldIndex(Def);
1193     Builder.SetInsertPoint(InsertPt);
1194     auto *G = Builder.CreateConstInBoundsGEP2_32(
1195         FrameTy, FramePtr, 0, Index, Def->getName() + Twine(".spill.addr"));
1196     Builder.CreateStore(Def, G);
1197 
1198     BasicBlock *CurrentBlock = nullptr;
1199     Value *CurrentReload = nullptr;
1200     for (auto *U : E.second) {
1201       // If we have not seen the use block, create a load instruction to reload
1202       // the spilled value from the coroutine frame. Populates the Value pointer
1203       // reference provided with the frame GEP.
1204       if (CurrentBlock != U->getParent()) {
1205         CurrentBlock = U->getParent();
1206         Builder.SetInsertPoint(&*CurrentBlock->getFirstInsertionPt());
1207 
1208         auto *GEP = GetFramePointer(E.first);
1209         GEP->setName(E.first->getName() + Twine(".reload.addr"));
1210         CurrentReload = Builder.CreateLoad(
1211             FrameTy->getElementType(FrameData.getFieldIndex(E.first)), GEP,
1212             E.first->getName() + Twine(".reload"));
1213 
1214         TinyPtrVector<DbgDeclareInst *> DIs = FindDbgDeclareUses(Def);
1215         for (DbgDeclareInst *DDI : DIs) {
1216           bool AllowUnresolved = false;
1217           // This dbg.declare is preserved for all coro-split function
1218           // fragments. It will be unreachable in the main function, and
1219           // processed by coro::salvageDebugInfo() by CoroCloner.
1220           DIBuilder(*CurrentBlock->getParent()->getParent(), AllowUnresolved)
1221               .insertDeclare(CurrentReload, DDI->getVariable(),
1222                              DDI->getExpression(), DDI->getDebugLoc(),
1223                              &*Builder.GetInsertPoint());
1224           // This dbg.declare is for the main function entry point.  It
1225           // will be deleted in all coro-split functions.
1226           coro::salvageDebugInfo(DbgPtrAllocaCache, DDI);
1227         }
1228       }
1229 
1230       // If we have a single edge PHINode, remove it and replace it with a
1231       // reload from the coroutine frame. (We already took care of multi edge
1232       // PHINodes by rewriting them in the rewritePHIs function).
1233       if (auto *PN = dyn_cast<PHINode>(U)) {
1234         assert(PN->getNumIncomingValues() == 1 &&
1235                "unexpected number of incoming "
1236                "values in the PHINode");
1237         PN->replaceAllUsesWith(CurrentReload);
1238         PN->eraseFromParent();
1239         continue;
1240       }
1241 
1242       // Replace all uses of CurrentValue in the current instruction with
1243       // reload.
1244       U->replaceUsesOfWith(Def, CurrentReload);
1245     }
1246   }
1247 
1248   BasicBlock *FramePtrBB = FramePtr->getParent();
1249 
1250   auto SpillBlock =
1251       FramePtrBB->splitBasicBlock(FramePtr->getNextNode(), "AllocaSpillBB");
1252   SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill");
1253   Shape.AllocaSpillBlock = SpillBlock;
1254 
1255   // retcon and retcon.once lowering assumes all uses have been sunk.
1256   if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
1257       Shape.ABI == coro::ABI::Async) {
1258     // If we found any allocas, replace all of their remaining uses with Geps.
1259     Builder.SetInsertPoint(&SpillBlock->front());
1260     for (const auto &P : FrameData.Allocas) {
1261       AllocaInst *Alloca = P.Alloca;
1262       auto *G = GetFramePointer(Alloca);
1263 
1264       // We are not using ReplaceInstWithInst(P.first, cast<Instruction>(G))
1265       // here, as we are changing location of the instruction.
1266       G->takeName(Alloca);
1267       Alloca->replaceAllUsesWith(G);
1268       Alloca->eraseFromParent();
1269     }
1270     return FramePtr;
1271   }
1272 
1273   // If we found any alloca, replace all of their remaining uses with GEP
1274   // instructions. Because new dbg.declare have been created for these alloca,
1275   // we also delete the original dbg.declare and replace other uses with undef.
1276   // Note: We cannot replace the alloca with GEP instructions indiscriminately,
1277   // as some of the uses may not be dominated by CoroBegin.
1278   Builder.SetInsertPoint(&Shape.AllocaSpillBlock->front());
1279   SmallVector<Instruction *, 4> UsersToUpdate;
1280   for (const auto &A : FrameData.Allocas) {
1281     AllocaInst *Alloca = A.Alloca;
1282     UsersToUpdate.clear();
1283     for (User *U : Alloca->users()) {
1284       auto *I = cast<Instruction>(U);
1285       if (DT.dominates(CB, I))
1286         UsersToUpdate.push_back(I);
1287     }
1288     if (UsersToUpdate.empty())
1289       continue;
1290     auto *G = GetFramePointer(Alloca);
1291     G->setName(Alloca->getName() + Twine(".reload.addr"));
1292 
1293     SmallPtrSet<BasicBlock *, 4> SeenDbgBBs;
1294     TinyPtrVector<DbgDeclareInst *> DIs = FindDbgDeclareUses(Alloca);
1295     if (!DIs.empty())
1296       DIBuilder(*Alloca->getModule(),
1297                 /*AllowUnresolved*/ false)
1298           .insertDeclare(G, DIs.front()->getVariable(),
1299                          DIs.front()->getExpression(),
1300                          DIs.front()->getDebugLoc(), DIs.front());
1301     for (auto *DI : FindDbgDeclareUses(Alloca))
1302       DI->eraseFromParent();
1303     replaceDbgUsesWithUndef(Alloca);
1304 
1305     for (Instruction *I : UsersToUpdate)
1306       I->replaceUsesOfWith(Alloca, G);
1307   }
1308   Builder.SetInsertPoint(FramePtr->getNextNode());
1309   for (const auto &A : FrameData.Allocas) {
1310     AllocaInst *Alloca = A.Alloca;
1311     if (A.MayWriteBeforeCoroBegin) {
1312       // isEscaped really means potentially modified before CoroBegin.
1313       if (Alloca->isArrayAllocation())
1314         report_fatal_error(
1315             "Coroutines cannot handle copying of array allocas yet");
1316 
1317       auto *G = GetFramePointer(Alloca);
1318       auto *Value = Builder.CreateLoad(Alloca->getAllocatedType(), Alloca);
1319       Builder.CreateStore(Value, G);
1320     }
1321     // For each alias to Alloca created before CoroBegin but used after
1322     // CoroBegin, we recreate them after CoroBegin by appplying the offset
1323     // to the pointer in the frame.
1324     for (const auto &Alias : A.Aliases) {
1325       auto *FramePtr = GetFramePointer(Alloca);
1326       auto *FramePtrRaw =
1327           Builder.CreateBitCast(FramePtr, Type::getInt8PtrTy(C));
1328       auto *AliasPtr = Builder.CreateGEP(
1329           FramePtrRaw,
1330           ConstantInt::get(Type::getInt64Ty(C), Alias.second.getValue()));
1331       auto *AliasPtrTyped =
1332           Builder.CreateBitCast(AliasPtr, Alias.first->getType());
1333       Alias.first->replaceUsesWithIf(
1334           AliasPtrTyped, [&](Use &U) { return DT.dominates(CB, U); });
1335     }
1336   }
1337   return FramePtr;
1338 }
1339 
1340 // Sets the unwind edge of an instruction to a particular successor.
1341 static void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
1342   if (auto *II = dyn_cast<InvokeInst>(TI))
1343     II->setUnwindDest(Succ);
1344   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
1345     CS->setUnwindDest(Succ);
1346   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
1347     CR->setUnwindDest(Succ);
1348   else
1349     llvm_unreachable("unexpected terminator instruction");
1350 }
1351 
1352 // Replaces all uses of OldPred with the NewPred block in all PHINodes in a
1353 // block.
1354 static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
1355                            BasicBlock *NewPred, PHINode *Until = nullptr) {
1356   unsigned BBIdx = 0;
1357   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
1358     PHINode *PN = cast<PHINode>(I);
1359 
1360     // We manually update the LandingPadReplacement PHINode and it is the last
1361     // PHI Node. So, if we find it, we are done.
1362     if (Until == PN)
1363       break;
1364 
1365     // Reuse the previous value of BBIdx if it lines up.  In cases where we
1366     // have multiple phi nodes with *lots* of predecessors, this is a speed
1367     // win because we don't have to scan the PHI looking for TIBB.  This
1368     // happens because the BB list of PHI nodes are usually in the same
1369     // order.
1370     if (PN->getIncomingBlock(BBIdx) != OldPred)
1371       BBIdx = PN->getBasicBlockIndex(OldPred);
1372 
1373     assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!");
1374     PN->setIncomingBlock(BBIdx, NewPred);
1375   }
1376 }
1377 
1378 // Uses SplitEdge unless the successor block is an EHPad, in which case do EH
1379 // specific handling.
1380 static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
1381                                     LandingPadInst *OriginalPad,
1382                                     PHINode *LandingPadReplacement) {
1383   auto *PadInst = Succ->getFirstNonPHI();
1384   if (!LandingPadReplacement && !PadInst->isEHPad())
1385     return SplitEdge(BB, Succ);
1386 
1387   auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ);
1388   setUnwindEdgeTo(BB->getTerminator(), NewBB);
1389   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
1390 
1391   if (LandingPadReplacement) {
1392     auto *NewLP = OriginalPad->clone();
1393     auto *Terminator = BranchInst::Create(Succ, NewBB);
1394     NewLP->insertBefore(Terminator);
1395     LandingPadReplacement->addIncoming(NewLP, NewBB);
1396     return NewBB;
1397   }
1398   Value *ParentPad = nullptr;
1399   if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
1400     ParentPad = FuncletPad->getParentPad();
1401   else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
1402     ParentPad = CatchSwitch->getParentPad();
1403   else
1404     llvm_unreachable("handling for other EHPads not implemented yet");
1405 
1406   auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB);
1407   CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
1408   return NewBB;
1409 }
1410 
1411 // Moves the values in the PHIs in SuccBB that correspong to PredBB into a new
1412 // PHI in InsertedBB.
1413 static void movePHIValuesToInsertedBlock(BasicBlock *SuccBB,
1414                                          BasicBlock *InsertedBB,
1415                                          BasicBlock *PredBB,
1416                                          PHINode *UntilPHI = nullptr) {
1417   auto *PN = cast<PHINode>(&SuccBB->front());
1418   do {
1419     int Index = PN->getBasicBlockIndex(InsertedBB);
1420     Value *V = PN->getIncomingValue(Index);
1421     PHINode *InputV = PHINode::Create(
1422         V->getType(), 1, V->getName() + Twine(".") + SuccBB->getName(),
1423         &InsertedBB->front());
1424     InputV->addIncoming(V, PredBB);
1425     PN->setIncomingValue(Index, InputV);
1426     PN = dyn_cast<PHINode>(PN->getNextNode());
1427   } while (PN != UntilPHI);
1428 }
1429 
1430 // Rewrites the PHI Nodes in a cleanuppad.
1431 static void rewritePHIsForCleanupPad(BasicBlock *CleanupPadBB,
1432                                      CleanupPadInst *CleanupPad) {
1433   // For every incoming edge to a CleanupPad we will create a new block holding
1434   // all incoming values in single-value PHI nodes. We will then create another
1435   // block to act as a dispather (as all unwind edges for related EH blocks
1436   // must be the same).
1437   //
1438   // cleanuppad:
1439   //    %2 = phi i32[%0, %catchswitch], [%1, %catch.1]
1440   //    %3 = cleanuppad within none []
1441   //
1442   // It will create:
1443   //
1444   // cleanuppad.corodispatch
1445   //    %2 = phi i8[0, %catchswitch], [1, %catch.1]
1446   //    %3 = cleanuppad within none []
1447   //    switch i8 % 2, label %unreachable
1448   //            [i8 0, label %cleanuppad.from.catchswitch
1449   //             i8 1, label %cleanuppad.from.catch.1]
1450   // cleanuppad.from.catchswitch:
1451   //    %4 = phi i32 [%0, %catchswitch]
1452   //    br %label cleanuppad
1453   // cleanuppad.from.catch.1:
1454   //    %6 = phi i32 [%1, %catch.1]
1455   //    br %label cleanuppad
1456   // cleanuppad:
1457   //    %8 = phi i32 [%4, %cleanuppad.from.catchswitch],
1458   //                 [%6, %cleanuppad.from.catch.1]
1459 
1460   // Unreachable BB, in case switching on an invalid value in the dispatcher.
1461   auto *UnreachBB = BasicBlock::Create(
1462       CleanupPadBB->getContext(), "unreachable", CleanupPadBB->getParent());
1463   IRBuilder<> Builder(UnreachBB);
1464   Builder.CreateUnreachable();
1465 
1466   // Create a new cleanuppad which will be the dispatcher.
1467   auto *NewCleanupPadBB =
1468       BasicBlock::Create(CleanupPadBB->getContext(),
1469                          CleanupPadBB->getName() + Twine(".corodispatch"),
1470                          CleanupPadBB->getParent(), CleanupPadBB);
1471   Builder.SetInsertPoint(NewCleanupPadBB);
1472   auto *SwitchType = Builder.getInt8Ty();
1473   auto *SetDispatchValuePN =
1474       Builder.CreatePHI(SwitchType, pred_size(CleanupPadBB));
1475   CleanupPad->removeFromParent();
1476   CleanupPad->insertAfter(SetDispatchValuePN);
1477   auto *SwitchOnDispatch = Builder.CreateSwitch(SetDispatchValuePN, UnreachBB,
1478                                                 pred_size(CleanupPadBB));
1479 
1480   int SwitchIndex = 0;
1481   SmallVector<BasicBlock *, 8> Preds(predecessors(CleanupPadBB));
1482   for (BasicBlock *Pred : Preds) {
1483     // Create a new cleanuppad and move the PHI values to there.
1484     auto *CaseBB = BasicBlock::Create(CleanupPadBB->getContext(),
1485                                       CleanupPadBB->getName() +
1486                                           Twine(".from.") + Pred->getName(),
1487                                       CleanupPadBB->getParent(), CleanupPadBB);
1488     updatePhiNodes(CleanupPadBB, Pred, CaseBB);
1489     CaseBB->setName(CleanupPadBB->getName() + Twine(".from.") +
1490                     Pred->getName());
1491     Builder.SetInsertPoint(CaseBB);
1492     Builder.CreateBr(CleanupPadBB);
1493     movePHIValuesToInsertedBlock(CleanupPadBB, CaseBB, NewCleanupPadBB);
1494 
1495     // Update this Pred to the new unwind point.
1496     setUnwindEdgeTo(Pred->getTerminator(), NewCleanupPadBB);
1497 
1498     // Setup the switch in the dispatcher.
1499     auto *SwitchConstant = ConstantInt::get(SwitchType, SwitchIndex);
1500     SetDispatchValuePN->addIncoming(SwitchConstant, Pred);
1501     SwitchOnDispatch->addCase(SwitchConstant, CaseBB);
1502     SwitchIndex++;
1503   }
1504 }
1505 
1506 static void rewritePHIs(BasicBlock &BB) {
1507   // For every incoming edge we will create a block holding all
1508   // incoming values in a single PHI nodes.
1509   //
1510   // loop:
1511   //    %n.val = phi i32[%n, %entry], [%inc, %loop]
1512   //
1513   // It will create:
1514   //
1515   // loop.from.entry:
1516   //    %n.loop.pre = phi i32 [%n, %entry]
1517   //    br %label loop
1518   // loop.from.loop:
1519   //    %inc.loop.pre = phi i32 [%inc, %loop]
1520   //    br %label loop
1521   //
1522   // After this rewrite, further analysis will ignore any phi nodes with more
1523   // than one incoming edge.
1524 
1525   // TODO: Simplify PHINodes in the basic block to remove duplicate
1526   // predecessors.
1527 
1528   // Special case for CleanupPad: all EH blocks must have the same unwind edge
1529   // so we need to create an additional "dispatcher" block.
1530   if (auto *CleanupPad =
1531           dyn_cast_or_null<CleanupPadInst>(BB.getFirstNonPHI())) {
1532     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
1533     for (BasicBlock *Pred : Preds) {
1534       if (CatchSwitchInst *CS =
1535               dyn_cast<CatchSwitchInst>(Pred->getTerminator())) {
1536         // CleanupPad with a CatchSwitch predecessor: therefore this is an
1537         // unwind destination that needs to be handle specially.
1538         assert(CS->getUnwindDest() == &BB);
1539         (void)CS;
1540         rewritePHIsForCleanupPad(&BB, CleanupPad);
1541         return;
1542       }
1543     }
1544   }
1545 
1546   LandingPadInst *LandingPad = nullptr;
1547   PHINode *ReplPHI = nullptr;
1548   if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) {
1549     // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
1550     // We replace the original landing pad with a PHINode that will collect the
1551     // results from all of them.
1552     ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad);
1553     ReplPHI->takeName(LandingPad);
1554     LandingPad->replaceAllUsesWith(ReplPHI);
1555     // We will erase the original landing pad at the end of this function after
1556     // ehAwareSplitEdge cloned it in the transition blocks.
1557   }
1558 
1559   SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
1560   for (BasicBlock *Pred : Preds) {
1561     auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI);
1562     IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName());
1563 
1564     // Stop the moving of values at ReplPHI, as this is either null or the PHI
1565     // that replaced the landing pad.
1566     movePHIValuesToInsertedBlock(&BB, IncomingBB, Pred, ReplPHI);
1567   }
1568 
1569   if (LandingPad) {
1570     // Calls to ehAwareSplitEdge function cloned the original lading pad.
1571     // No longer need it.
1572     LandingPad->eraseFromParent();
1573   }
1574 }
1575 
1576 static void rewritePHIs(Function &F) {
1577   SmallVector<BasicBlock *, 8> WorkList;
1578 
1579   for (BasicBlock &BB : F)
1580     if (auto *PN = dyn_cast<PHINode>(&BB.front()))
1581       if (PN->getNumIncomingValues() > 1)
1582         WorkList.push_back(&BB);
1583 
1584   for (BasicBlock *BB : WorkList)
1585     rewritePHIs(*BB);
1586 }
1587 
1588 // Check for instructions that we can recreate on resume as opposed to spill
1589 // the result into a coroutine frame.
1590 static bool materializable(Instruction &V) {
1591   return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) ||
1592          isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V);
1593 }
1594 
1595 // Check for structural coroutine intrinsics that should not be spilled into
1596 // the coroutine frame.
1597 static bool isCoroutineStructureIntrinsic(Instruction &I) {
1598   return isa<CoroIdInst>(&I) || isa<CoroSaveInst>(&I) ||
1599          isa<CoroSuspendInst>(&I);
1600 }
1601 
1602 // For every use of the value that is across suspend point, recreate that value
1603 // after a suspend point.
1604 static void rewriteMaterializableInstructions(IRBuilder<> &IRB,
1605                                               const SpillInfo &Spills) {
1606   for (const auto &E : Spills) {
1607     Value *Def = E.first;
1608     BasicBlock *CurrentBlock = nullptr;
1609     Instruction *CurrentMaterialization = nullptr;
1610     for (Instruction *U : E.second) {
1611       // If we have not seen this block, materialize the value.
1612       if (CurrentBlock != U->getParent()) {
1613         CurrentBlock = U->getParent();
1614         CurrentMaterialization = cast<Instruction>(Def)->clone();
1615         CurrentMaterialization->setName(Def->getName());
1616         CurrentMaterialization->insertBefore(
1617             &*CurrentBlock->getFirstInsertionPt());
1618       }
1619       if (auto *PN = dyn_cast<PHINode>(U)) {
1620         assert(PN->getNumIncomingValues() == 1 &&
1621                "unexpected number of incoming "
1622                "values in the PHINode");
1623         PN->replaceAllUsesWith(CurrentMaterialization);
1624         PN->eraseFromParent();
1625         continue;
1626       }
1627       // Replace all uses of Def in the current instruction with the
1628       // CurrentMaterialization for the block.
1629       U->replaceUsesOfWith(Def, CurrentMaterialization);
1630     }
1631   }
1632 }
1633 
1634 // Splits the block at a particular instruction unless it is the first
1635 // instruction in the block with a single predecessor.
1636 static BasicBlock *splitBlockIfNotFirst(Instruction *I, const Twine &Name) {
1637   auto *BB = I->getParent();
1638   if (&BB->front() == I) {
1639     if (BB->getSinglePredecessor()) {
1640       BB->setName(Name);
1641       return BB;
1642     }
1643   }
1644   return BB->splitBasicBlock(I, Name);
1645 }
1646 
1647 // Split above and below a particular instruction so that it
1648 // will be all alone by itself in a block.
1649 static void splitAround(Instruction *I, const Twine &Name) {
1650   splitBlockIfNotFirst(I, Name);
1651   splitBlockIfNotFirst(I->getNextNode(), "After" + Name);
1652 }
1653 
1654 static bool isSuspendBlock(BasicBlock *BB) {
1655   return isa<AnyCoroSuspendInst>(BB->front());
1656 }
1657 
1658 typedef SmallPtrSet<BasicBlock*, 8> VisitedBlocksSet;
1659 
1660 /// Does control flow starting at the given block ever reach a suspend
1661 /// instruction before reaching a block in VisitedOrFreeBBs?
1662 static bool isSuspendReachableFrom(BasicBlock *From,
1663                                    VisitedBlocksSet &VisitedOrFreeBBs) {
1664   // Eagerly try to add this block to the visited set.  If it's already
1665   // there, stop recursing; this path doesn't reach a suspend before
1666   // either looping or reaching a freeing block.
1667   if (!VisitedOrFreeBBs.insert(From).second)
1668     return false;
1669 
1670   // We assume that we'll already have split suspends into their own blocks.
1671   if (isSuspendBlock(From))
1672     return true;
1673 
1674   // Recurse on the successors.
1675   for (auto Succ : successors(From)) {
1676     if (isSuspendReachableFrom(Succ, VisitedOrFreeBBs))
1677       return true;
1678   }
1679 
1680   return false;
1681 }
1682 
1683 /// Is the given alloca "local", i.e. bounded in lifetime to not cross a
1684 /// suspend point?
1685 static bool isLocalAlloca(CoroAllocaAllocInst *AI) {
1686   // Seed the visited set with all the basic blocks containing a free
1687   // so that we won't pass them up.
1688   VisitedBlocksSet VisitedOrFreeBBs;
1689   for (auto User : AI->users()) {
1690     if (auto FI = dyn_cast<CoroAllocaFreeInst>(User))
1691       VisitedOrFreeBBs.insert(FI->getParent());
1692   }
1693 
1694   return !isSuspendReachableFrom(AI->getParent(), VisitedOrFreeBBs);
1695 }
1696 
1697 /// After we split the coroutine, will the given basic block be along
1698 /// an obvious exit path for the resumption function?
1699 static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB,
1700                                               unsigned depth = 3) {
1701   // If we've bottomed out our depth count, stop searching and assume
1702   // that the path might loop back.
1703   if (depth == 0) return false;
1704 
1705   // If this is a suspend block, we're about to exit the resumption function.
1706   if (isSuspendBlock(BB)) return true;
1707 
1708   // Recurse into the successors.
1709   for (auto Succ : successors(BB)) {
1710     if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1))
1711       return false;
1712   }
1713 
1714   // If none of the successors leads back in a loop, we're on an exit/abort.
1715   return true;
1716 }
1717 
1718 static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI) {
1719   // Look for a free that isn't sufficiently obviously followed by
1720   // either a suspend or a termination, i.e. something that will leave
1721   // the coro resumption frame.
1722   for (auto U : AI->users()) {
1723     auto FI = dyn_cast<CoroAllocaFreeInst>(U);
1724     if (!FI) continue;
1725 
1726     if (!willLeaveFunctionImmediatelyAfter(FI->getParent()))
1727       return true;
1728   }
1729 
1730   // If we never found one, we don't need a stack save.
1731   return false;
1732 }
1733 
1734 /// Turn each of the given local allocas into a normal (dynamic) alloca
1735 /// instruction.
1736 static void lowerLocalAllocas(ArrayRef<CoroAllocaAllocInst*> LocalAllocas,
1737                               SmallVectorImpl<Instruction*> &DeadInsts) {
1738   for (auto AI : LocalAllocas) {
1739     auto M = AI->getModule();
1740     IRBuilder<> Builder(AI);
1741 
1742     // Save the stack depth.  Try to avoid doing this if the stackrestore
1743     // is going to immediately precede a return or something.
1744     Value *StackSave = nullptr;
1745     if (localAllocaNeedsStackSave(AI))
1746       StackSave = Builder.CreateCall(
1747                             Intrinsic::getDeclaration(M, Intrinsic::stacksave));
1748 
1749     // Allocate memory.
1750     auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize());
1751     Alloca->setAlignment(Align(AI->getAlignment()));
1752 
1753     for (auto U : AI->users()) {
1754       // Replace gets with the allocation.
1755       if (isa<CoroAllocaGetInst>(U)) {
1756         U->replaceAllUsesWith(Alloca);
1757 
1758       // Replace frees with stackrestores.  This is safe because
1759       // alloca.alloc is required to obey a stack discipline, although we
1760       // don't enforce that structurally.
1761       } else {
1762         auto FI = cast<CoroAllocaFreeInst>(U);
1763         if (StackSave) {
1764           Builder.SetInsertPoint(FI);
1765           Builder.CreateCall(
1766                     Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
1767                              StackSave);
1768         }
1769       }
1770       DeadInsts.push_back(cast<Instruction>(U));
1771     }
1772 
1773     DeadInsts.push_back(AI);
1774   }
1775 }
1776 
1777 /// Turn the given coro.alloca.alloc call into a dynamic allocation.
1778 /// This happens during the all-instructions iteration, so it must not
1779 /// delete the call.
1780 static Instruction *lowerNonLocalAlloca(CoroAllocaAllocInst *AI,
1781                                         coro::Shape &Shape,
1782                                    SmallVectorImpl<Instruction*> &DeadInsts) {
1783   IRBuilder<> Builder(AI);
1784   auto Alloc = Shape.emitAlloc(Builder, AI->getSize(), nullptr);
1785 
1786   for (User *U : AI->users()) {
1787     if (isa<CoroAllocaGetInst>(U)) {
1788       U->replaceAllUsesWith(Alloc);
1789     } else {
1790       auto FI = cast<CoroAllocaFreeInst>(U);
1791       Builder.SetInsertPoint(FI);
1792       Shape.emitDealloc(Builder, Alloc, nullptr);
1793     }
1794     DeadInsts.push_back(cast<Instruction>(U));
1795   }
1796 
1797   // Push this on last so that it gets deleted after all the others.
1798   DeadInsts.push_back(AI);
1799 
1800   // Return the new allocation value so that we can check for needed spills.
1801   return cast<Instruction>(Alloc);
1802 }
1803 
1804 /// Get the current swifterror value.
1805 static Value *emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy,
1806                                      coro::Shape &Shape) {
1807   // Make a fake function pointer as a sort of intrinsic.
1808   auto FnTy = FunctionType::get(ValueTy, {}, false);
1809   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1810 
1811   auto Call = Builder.CreateCall(FnTy, Fn, {});
1812   Shape.SwiftErrorOps.push_back(Call);
1813 
1814   return Call;
1815 }
1816 
1817 /// Set the given value as the current swifterror value.
1818 ///
1819 /// Returns a slot that can be used as a swifterror slot.
1820 static Value *emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V,
1821                                      coro::Shape &Shape) {
1822   // Make a fake function pointer as a sort of intrinsic.
1823   auto FnTy = FunctionType::get(V->getType()->getPointerTo(),
1824                                 {V->getType()}, false);
1825   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1826 
1827   auto Call = Builder.CreateCall(FnTy, Fn, { V });
1828   Shape.SwiftErrorOps.push_back(Call);
1829 
1830   return Call;
1831 }
1832 
1833 /// Set the swifterror value from the given alloca before a call,
1834 /// then put in back in the alloca afterwards.
1835 ///
1836 /// Returns an address that will stand in for the swifterror slot
1837 /// until splitting.
1838 static Value *emitSetAndGetSwiftErrorValueAround(Instruction *Call,
1839                                                  AllocaInst *Alloca,
1840                                                  coro::Shape &Shape) {
1841   auto ValueTy = Alloca->getAllocatedType();
1842   IRBuilder<> Builder(Call);
1843 
1844   // Load the current value from the alloca and set it as the
1845   // swifterror value.
1846   auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca);
1847   auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape);
1848 
1849   // Move to after the call.  Since swifterror only has a guaranteed
1850   // value on normal exits, we can ignore implicit and explicit unwind
1851   // edges.
1852   if (isa<CallInst>(Call)) {
1853     Builder.SetInsertPoint(Call->getNextNode());
1854   } else {
1855     auto Invoke = cast<InvokeInst>(Call);
1856     Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg());
1857   }
1858 
1859   // Get the current swifterror value and store it to the alloca.
1860   auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape);
1861   Builder.CreateStore(ValueAfterCall, Alloca);
1862 
1863   return Addr;
1864 }
1865 
1866 /// Eliminate a formerly-swifterror alloca by inserting the get/set
1867 /// intrinsics and attempting to MemToReg the alloca away.
1868 static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca,
1869                                       coro::Shape &Shape) {
1870   for (auto UI = Alloca->use_begin(), UE = Alloca->use_end(); UI != UE; ) {
1871     // We're likely changing the use list, so use a mutation-safe
1872     // iteration pattern.
1873     auto &Use = *UI;
1874     ++UI;
1875 
1876     // swifterror values can only be used in very specific ways.
1877     // We take advantage of that here.
1878     auto User = Use.getUser();
1879     if (isa<LoadInst>(User) || isa<StoreInst>(User))
1880       continue;
1881 
1882     assert(isa<CallInst>(User) || isa<InvokeInst>(User));
1883     auto Call = cast<Instruction>(User);
1884 
1885     auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape);
1886 
1887     // Use the returned slot address as the call argument.
1888     Use.set(Addr);
1889   }
1890 
1891   // All the uses should be loads and stores now.
1892   assert(isAllocaPromotable(Alloca));
1893 }
1894 
1895 /// "Eliminate" a swifterror argument by reducing it to the alloca case
1896 /// and then loading and storing in the prologue and epilog.
1897 ///
1898 /// The argument keeps the swifterror flag.
1899 static void eliminateSwiftErrorArgument(Function &F, Argument &Arg,
1900                                         coro::Shape &Shape,
1901                              SmallVectorImpl<AllocaInst*> &AllocasToPromote) {
1902   IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
1903 
1904   auto ArgTy = cast<PointerType>(Arg.getType());
1905   auto ValueTy = ArgTy->getElementType();
1906 
1907   // Reduce to the alloca case:
1908 
1909   // Create an alloca and replace all uses of the arg with it.
1910   auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace());
1911   Arg.replaceAllUsesWith(Alloca);
1912 
1913   // Set an initial value in the alloca.  swifterror is always null on entry.
1914   auto InitialValue = Constant::getNullValue(ValueTy);
1915   Builder.CreateStore(InitialValue, Alloca);
1916 
1917   // Find all the suspends in the function and save and restore around them.
1918   for (auto Suspend : Shape.CoroSuspends) {
1919     (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape);
1920   }
1921 
1922   // Find all the coro.ends in the function and restore the error value.
1923   for (auto End : Shape.CoroEnds) {
1924     Builder.SetInsertPoint(End);
1925     auto FinalValue = Builder.CreateLoad(ValueTy, Alloca);
1926     (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape);
1927   }
1928 
1929   // Now we can use the alloca logic.
1930   AllocasToPromote.push_back(Alloca);
1931   eliminateSwiftErrorAlloca(F, Alloca, Shape);
1932 }
1933 
1934 /// Eliminate all problematic uses of swifterror arguments and allocas
1935 /// from the function.  We'll fix them up later when splitting the function.
1936 static void eliminateSwiftError(Function &F, coro::Shape &Shape) {
1937   SmallVector<AllocaInst*, 4> AllocasToPromote;
1938 
1939   // Look for a swifterror argument.
1940   for (auto &Arg : F.args()) {
1941     if (!Arg.hasSwiftErrorAttr()) continue;
1942 
1943     eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote);
1944     break;
1945   }
1946 
1947   // Look for swifterror allocas.
1948   for (auto &Inst : F.getEntryBlock()) {
1949     auto Alloca = dyn_cast<AllocaInst>(&Inst);
1950     if (!Alloca || !Alloca->isSwiftError()) continue;
1951 
1952     // Clear the swifterror flag.
1953     Alloca->setSwiftError(false);
1954 
1955     AllocasToPromote.push_back(Alloca);
1956     eliminateSwiftErrorAlloca(F, Alloca, Shape);
1957   }
1958 
1959   // If we have any allocas to promote, compute a dominator tree and
1960   // promote them en masse.
1961   if (!AllocasToPromote.empty()) {
1962     DominatorTree DT(F);
1963     PromoteMemToReg(AllocasToPromote, DT);
1964   }
1965 }
1966 
1967 /// retcon and retcon.once conventions assume that all spill uses can be sunk
1968 /// after the coro.begin intrinsic.
1969 static void sinkSpillUsesAfterCoroBegin(Function &F,
1970                                         const FrameDataInfo &FrameData,
1971                                         CoroBeginInst *CoroBegin) {
1972   DominatorTree Dom(F);
1973 
1974   SmallSetVector<Instruction *, 32> ToMove;
1975   SmallVector<Instruction *, 32> Worklist;
1976 
1977   // Collect all users that precede coro.begin.
1978   for (auto *Def : FrameData.getAllDefs()) {
1979     for (User *U : Def->users()) {
1980       auto Inst = cast<Instruction>(U);
1981       if (Inst->getParent() != CoroBegin->getParent() ||
1982           Dom.dominates(CoroBegin, Inst))
1983         continue;
1984       if (ToMove.insert(Inst))
1985         Worklist.push_back(Inst);
1986     }
1987   }
1988   // Recursively collect users before coro.begin.
1989   while (!Worklist.empty()) {
1990     auto *Def = Worklist.pop_back_val();
1991     for (User *U : Def->users()) {
1992       auto Inst = cast<Instruction>(U);
1993       if (Dom.dominates(CoroBegin, Inst))
1994         continue;
1995       if (ToMove.insert(Inst))
1996         Worklist.push_back(Inst);
1997     }
1998   }
1999 
2000   // Sort by dominance.
2001   SmallVector<Instruction *, 64> InsertionList(ToMove.begin(), ToMove.end());
2002   llvm::sort(InsertionList, [&Dom](Instruction *A, Instruction *B) -> bool {
2003     // If a dominates b it should preceed (<) b.
2004     return Dom.dominates(A, B);
2005   });
2006 
2007   Instruction *InsertPt = CoroBegin->getNextNode();
2008   for (Instruction *Inst : InsertionList)
2009     Inst->moveBefore(InsertPt);
2010 }
2011 
2012 /// For each local variable that all of its user are only used inside one of
2013 /// suspended region, we sink their lifetime.start markers to the place where
2014 /// after the suspend block. Doing so minimizes the lifetime of each variable,
2015 /// hence minimizing the amount of data we end up putting on the frame.
2016 static void sinkLifetimeStartMarkers(Function &F, coro::Shape &Shape,
2017                                      SuspendCrossingInfo &Checker) {
2018   DominatorTree DT(F);
2019 
2020   // Collect all possible basic blocks which may dominate all uses of allocas.
2021   SmallPtrSet<BasicBlock *, 4> DomSet;
2022   DomSet.insert(&F.getEntryBlock());
2023   for (auto *CSI : Shape.CoroSuspends) {
2024     BasicBlock *SuspendBlock = CSI->getParent();
2025     assert(isSuspendBlock(SuspendBlock) && SuspendBlock->getSingleSuccessor() &&
2026            "should have split coro.suspend into its own block");
2027     DomSet.insert(SuspendBlock->getSingleSuccessor());
2028   }
2029 
2030   for (Instruction &I : instructions(F)) {
2031     AllocaInst* AI = dyn_cast<AllocaInst>(&I);
2032     if (!AI)
2033       continue;
2034 
2035     for (BasicBlock *DomBB : DomSet) {
2036       bool Valid = true;
2037       SmallVector<Instruction *, 1> Lifetimes;
2038 
2039       auto isLifetimeStart = [](Instruction* I) {
2040         if (auto* II = dyn_cast<IntrinsicInst>(I))
2041           return II->getIntrinsicID() == Intrinsic::lifetime_start;
2042         return false;
2043       };
2044 
2045       auto collectLifetimeStart = [&](Instruction *U, AllocaInst *AI) {
2046         if (isLifetimeStart(U)) {
2047           Lifetimes.push_back(U);
2048           return true;
2049         }
2050         if (!U->hasOneUse() || U->stripPointerCasts() != AI)
2051           return false;
2052         if (isLifetimeStart(U->user_back())) {
2053           Lifetimes.push_back(U->user_back());
2054           return true;
2055         }
2056         return false;
2057       };
2058 
2059       for (User *U : AI->users()) {
2060         Instruction *UI = cast<Instruction>(U);
2061         // For all users except lifetime.start markers, if they are all
2062         // dominated by one of the basic blocks and do not cross
2063         // suspend points as well, then there is no need to spill the
2064         // instruction.
2065         if (!DT.dominates(DomBB, UI->getParent()) ||
2066             Checker.isDefinitionAcrossSuspend(DomBB, UI)) {
2067           // Skip lifetime.start, GEP and bitcast used by lifetime.start
2068           // markers.
2069           if (collectLifetimeStart(UI, AI))
2070             continue;
2071           Valid = false;
2072           break;
2073         }
2074       }
2075       // Sink lifetime.start markers to dominate block when they are
2076       // only used outside the region.
2077       if (Valid && Lifetimes.size() != 0) {
2078         // May be AI itself, when the type of AI is i8*
2079         auto *NewBitCast = [&](AllocaInst *AI) -> Value* {
2080           if (isa<AllocaInst>(Lifetimes[0]->getOperand(1)))
2081             return AI;
2082           auto *Int8PtrTy = Type::getInt8PtrTy(F.getContext());
2083           return CastInst::Create(Instruction::BitCast, AI, Int8PtrTy, "",
2084                                   DomBB->getTerminator());
2085         }(AI);
2086 
2087         auto *NewLifetime = Lifetimes[0]->clone();
2088         NewLifetime->replaceUsesOfWith(NewLifetime->getOperand(1), NewBitCast);
2089         NewLifetime->insertBefore(DomBB->getTerminator());
2090 
2091         // All the outsided lifetime.start markers are no longer necessary.
2092         for (Instruction *S : Lifetimes)
2093           S->eraseFromParent();
2094 
2095         break;
2096       }
2097     }
2098   }
2099 }
2100 
2101 static void collectFrameAllocas(Function &F, coro::Shape &Shape,
2102                                 const SuspendCrossingInfo &Checker,
2103                                 SmallVectorImpl<AllocaInfo> &Allocas) {
2104   // Collect lifetime.start info for each alloca.
2105   using LifetimeStart = SmallPtrSet<Instruction *, 2>;
2106   llvm::DenseMap<AllocaInst *, std::unique_ptr<LifetimeStart>> LifetimeMap;
2107   for (Instruction &I : instructions(F)) {
2108     auto *II = dyn_cast<IntrinsicInst>(&I);
2109     if (!II || II->getIntrinsicID() != Intrinsic::lifetime_start)
2110       continue;
2111 
2112     if (auto *OpInst = dyn_cast<Instruction>(II->getOperand(1))) {
2113       if (auto *AI = dyn_cast<AllocaInst>(OpInst->stripPointerCasts())) {
2114 
2115         if (LifetimeMap.find(AI) == LifetimeMap.end())
2116           LifetimeMap[AI] = std::make_unique<LifetimeStart>();
2117         LifetimeMap[AI]->insert(isa<AllocaInst>(OpInst) ? II : OpInst);
2118       }
2119     }
2120   }
2121 
2122   for (Instruction &I : instructions(F)) {
2123     auto *AI = dyn_cast<AllocaInst>(&I);
2124     if (!AI)
2125       continue;
2126     // The PromiseAlloca will be specially handled since it needs to be in a
2127     // fixed position in the frame.
2128     if (AI == Shape.SwitchLowering.PromiseAlloca) {
2129       continue;
2130     }
2131     bool ShouldLiveOnFrame = false;
2132     auto Iter = LifetimeMap.find(AI);
2133     if (Iter != LifetimeMap.end()) {
2134       // Check against lifetime.start if the instruction has the info.
2135       for (User *U : I.users()) {
2136         for (auto *S : *Iter->second)
2137           if ((ShouldLiveOnFrame = Checker.isDefinitionAcrossSuspend(*S, U)))
2138             break;
2139         if (ShouldLiveOnFrame)
2140           break;
2141       }
2142       if (!ShouldLiveOnFrame)
2143         continue;
2144     }
2145     // At this point, either ShouldLiveOnFrame is true or we didn't have
2146     // lifetime information. We will need to rely on more precise pointer
2147     // tracking.
2148     DominatorTree DT(F);
2149     AllocaUseVisitor Visitor{F.getParent()->getDataLayout(), DT,
2150                              *Shape.CoroBegin, Checker};
2151     Visitor.visitPtr(*AI);
2152     if (!Visitor.getShouldLiveOnFrame())
2153       continue;
2154     Allocas.emplace_back(AI, Visitor.getAliasesCopy(),
2155                          Visitor.getMayWriteBeforeCoroBegin());
2156   }
2157 }
2158 
2159 void coro::salvageDebugInfo(
2160     SmallDenseMap<llvm::Value *, llvm::AllocaInst *, 4> &DbgPtrAllocaCache,
2161     DbgDeclareInst *DDI) {
2162   Function *F = DDI->getFunction();
2163   IRBuilder<> Builder(F->getContext());
2164   auto InsertPt = F->getEntryBlock().getFirstInsertionPt();
2165   while (isa<IntrinsicInst>(InsertPt))
2166     ++InsertPt;
2167   Builder.SetInsertPoint(&F->getEntryBlock(), InsertPt);
2168   DIExpression *Expr = DDI->getExpression();
2169   // Follow the pointer arithmetic all the way to the incoming
2170   // function argument and convert into a DIExpression.
2171   bool OutermostLoad = true;
2172   Value *Storage = DDI->getAddress();
2173   while (Storage) {
2174     if (auto *LdInst = dyn_cast<LoadInst>(Storage)) {
2175       Storage = LdInst->getOperand(0);
2176       // FIXME: This is a heuristic that works around the fact that
2177       // LLVM IR debug intrinsics cannot yet distinguish between
2178       // memory and value locations: Because a dbg.declare(alloca) is
2179       // implicitly a memory location no DW_OP_deref operation for the
2180       // last direct load from an alloca is necessary.  This condition
2181       // effectively drops the *last* DW_OP_deref in the expression.
2182       if (!OutermostLoad)
2183         Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2184       OutermostLoad = false;
2185     } else if (auto *StInst = dyn_cast<StoreInst>(Storage)) {
2186       Storage = StInst->getOperand(0);
2187     } else if (auto *GEPInst = dyn_cast<GetElementPtrInst>(Storage)) {
2188       Expr = llvm::salvageDebugInfoImpl(*GEPInst, Expr,
2189                                         /*WithStackValue=*/false);
2190       Storage = GEPInst->getOperand(0);
2191     } else if (auto *BCInst = dyn_cast<llvm::BitCastInst>(Storage))
2192       Storage = BCInst->getOperand(0);
2193     else
2194       break;
2195   }
2196   // Store a pointer to the coroutine frame object in an alloca so it
2197   // is available throughout the function when producing unoptimized
2198   // code. Extending the lifetime this way is correct because the
2199   // variable has been declared by a dbg.declare intrinsic.
2200   if (auto Arg = dyn_cast_or_null<llvm::Argument>(Storage)) {
2201     auto &Cached = DbgPtrAllocaCache[Storage];
2202     if (!Cached) {
2203       Cached = Builder.CreateAlloca(Storage->getType(), 0, nullptr,
2204                                     Arg->getName() + ".debug");
2205       Builder.CreateStore(Storage, Cached);
2206     }
2207     Storage = Cached;
2208     // FIXME: LLVM lacks nuanced semantics to differentiate between
2209     // memory and direct locations at the IR level. The backend will
2210     // turn a dbg.declare(alloca, ..., DIExpression()) into a memory
2211     // location. Thus, if there are deref and offset operations in the
2212     // expression, we need to add a DW_OP_deref at the *start* of the
2213     // expression to first load the contents of the alloca before
2214     // adjusting it with the expression.
2215     if (Expr && Expr->isComplex())
2216       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2217   }
2218   auto &VMContext = DDI->getFunction()->getContext();
2219   DDI->setOperand(
2220       0, MetadataAsValue::get(VMContext, ValueAsMetadata::get(Storage)));
2221   DDI->setOperand(2, MetadataAsValue::get(VMContext, Expr));
2222   if (auto *InsertPt = dyn_cast_or_null<Instruction>(Storage))
2223     DDI->moveAfter(InsertPt);
2224 }
2225 
2226 void coro::buildCoroutineFrame(Function &F, Shape &Shape) {
2227   eliminateSwiftError(F, Shape);
2228 
2229   if (Shape.ABI == coro::ABI::Switch &&
2230       Shape.SwitchLowering.PromiseAlloca) {
2231     Shape.getSwitchCoroId()->clearPromise();
2232   }
2233 
2234   // Make sure that all coro.save, coro.suspend and the fallthrough coro.end
2235   // intrinsics are in their own blocks to simplify the logic of building up
2236   // SuspendCrossing data.
2237   for (auto *CSI : Shape.CoroSuspends) {
2238     if (auto *Save = CSI->getCoroSave())
2239       splitAround(Save, "CoroSave");
2240     splitAround(CSI, "CoroSuspend");
2241   }
2242 
2243   // Put CoroEnds into their own blocks.
2244   for (AnyCoroEndInst *CE : Shape.CoroEnds) {
2245     splitAround(CE, "CoroEnd");
2246 
2247     // Emit the musttail call function in a new block before the CoroEnd.
2248     // We do this here so that the right suspend crossing info is computed for
2249     // the uses of the musttail call function call. (Arguments to the coro.end
2250     // instructions would be ignored)
2251     if (auto *AsyncEnd = dyn_cast<CoroAsyncEndInst>(CE)) {
2252       auto *MustTailCallFn = AsyncEnd->getMustTailCallFunction();
2253       if (!MustTailCallFn)
2254         continue;
2255       IRBuilder<> Builder(AsyncEnd);
2256       SmallVector<Value *, 8> Args(AsyncEnd->args());
2257       auto Arguments = ArrayRef<Value *>(Args).drop_front(3);
2258       auto *Call = createMustTailCall(AsyncEnd->getDebugLoc(), MustTailCallFn,
2259                                       Arguments, Builder);
2260       splitAround(Call, "MustTailCall.Before.CoroEnd");
2261     }
2262   }
2263 
2264   // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will
2265   // never has its definition separated from the PHI by the suspend point.
2266   rewritePHIs(F);
2267 
2268   // Build suspend crossing info.
2269   SuspendCrossingInfo Checker(F, Shape);
2270 
2271   IRBuilder<> Builder(F.getContext());
2272   FrameDataInfo FrameData;
2273   SmallVector<CoroAllocaAllocInst*, 4> LocalAllocas;
2274   SmallVector<Instruction*, 4> DeadInstructions;
2275 
2276   {
2277     SpillInfo Spills;
2278     for (int Repeat = 0; Repeat < 4; ++Repeat) {
2279       // See if there are materializable instructions across suspend points.
2280       for (Instruction &I : instructions(F))
2281         if (materializable(I))
2282           for (User *U : I.users())
2283             if (Checker.isDefinitionAcrossSuspend(I, U))
2284               Spills[&I].push_back(cast<Instruction>(U));
2285 
2286       if (Spills.empty())
2287         break;
2288 
2289       // Rewrite materializable instructions to be materialized at the use
2290       // point.
2291       LLVM_DEBUG(dumpSpills("Materializations", Spills));
2292       rewriteMaterializableInstructions(Builder, Spills);
2293       Spills.clear();
2294     }
2295   }
2296 
2297   sinkLifetimeStartMarkers(F, Shape, Checker);
2298   collectFrameAllocas(F, Shape, Checker, FrameData.Allocas);
2299   LLVM_DEBUG(dumpAllocas(FrameData.Allocas));
2300 
2301   // Collect the spills for arguments and other not-materializable values.
2302   for (Argument &A : F.args())
2303     for (User *U : A.users())
2304       if (Checker.isDefinitionAcrossSuspend(A, U))
2305         FrameData.Spills[&A].push_back(cast<Instruction>(U));
2306 
2307   for (Instruction &I : instructions(F)) {
2308     // Values returned from coroutine structure intrinsics should not be part
2309     // of the Coroutine Frame.
2310     if (isCoroutineStructureIntrinsic(I) || &I == Shape.CoroBegin)
2311       continue;
2312 
2313     // The Coroutine Promise always included into coroutine frame, no need to
2314     // check for suspend crossing.
2315     if (Shape.ABI == coro::ABI::Switch &&
2316         Shape.SwitchLowering.PromiseAlloca == &I)
2317       continue;
2318 
2319     // Handle alloca.alloc specially here.
2320     if (auto AI = dyn_cast<CoroAllocaAllocInst>(&I)) {
2321       // Check whether the alloca's lifetime is bounded by suspend points.
2322       if (isLocalAlloca(AI)) {
2323         LocalAllocas.push_back(AI);
2324         continue;
2325       }
2326 
2327       // If not, do a quick rewrite of the alloca and then add spills of
2328       // the rewritten value.  The rewrite doesn't invalidate anything in
2329       // Spills because the other alloca intrinsics have no other operands
2330       // besides AI, and it doesn't invalidate the iteration because we delay
2331       // erasing AI.
2332       auto Alloc = lowerNonLocalAlloca(AI, Shape, DeadInstructions);
2333 
2334       for (User *U : Alloc->users()) {
2335         if (Checker.isDefinitionAcrossSuspend(*Alloc, U))
2336           FrameData.Spills[Alloc].push_back(cast<Instruction>(U));
2337       }
2338       continue;
2339     }
2340 
2341     // Ignore alloca.get; we process this as part of coro.alloca.alloc.
2342     if (isa<CoroAllocaGetInst>(I))
2343       continue;
2344 
2345     if (isa<AllocaInst>(I))
2346       continue;
2347 
2348     for (User *U : I.users())
2349       if (Checker.isDefinitionAcrossSuspend(I, U)) {
2350         // We cannot spill a token.
2351         if (I.getType()->isTokenTy())
2352           report_fatal_error(
2353               "token definition is separated from the use by a suspend point");
2354         FrameData.Spills[&I].push_back(cast<Instruction>(U));
2355       }
2356   }
2357   LLVM_DEBUG(dumpSpills("Spills", FrameData.Spills));
2358   if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
2359       Shape.ABI == coro::ABI::Async)
2360     sinkSpillUsesAfterCoroBegin(F, FrameData, Shape.CoroBegin);
2361   Shape.FrameTy = buildFrameType(F, Shape, FrameData);
2362   Shape.FramePtr = insertSpills(FrameData, Shape);
2363   lowerLocalAllocas(LocalAllocas, DeadInstructions);
2364 
2365   for (auto I : DeadInstructions)
2366     I->eraseFromParent();
2367 }
2368