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