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/Analysis/LazyCallGraph.h"
32 #include "llvm/IR/Argument.h"
33 #include "llvm/IR/Attributes.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/CFG.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     /// An async resume function.
96     Async,
97   };
98 
99 private:
100   Function &OrigF;
101   Function *NewF;
102   const Twine &Suffix;
103   coro::Shape &Shape;
104   Kind FKind;
105   ValueToValueMapTy VMap;
106   IRBuilder<> Builder;
107   Value *NewFramePtr = nullptr;
108 
109   /// The active suspend instruction; meaningful only for continuation and async
110   /// ABIs.
111   AnyCoroSuspendInst *ActiveSuspend = nullptr;
112 
113 public:
114   /// Create a cloner for a switch lowering.
115   CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape,
116              Kind FKind)
117     : OrigF(OrigF), NewF(nullptr), Suffix(Suffix), Shape(Shape),
118       FKind(FKind), Builder(OrigF.getContext()) {
119     assert(Shape.ABI == coro::ABI::Switch);
120   }
121 
122   /// Create a cloner for a continuation lowering.
123   CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape,
124              Function *NewF, AnyCoroSuspendInst *ActiveSuspend)
125       : OrigF(OrigF), NewF(NewF), Suffix(Suffix), Shape(Shape),
126         FKind(Shape.ABI == coro::ABI::Async ? Kind::Async : Kind::Continuation),
127         Builder(OrigF.getContext()), ActiveSuspend(ActiveSuspend) {
128     assert(Shape.ABI == coro::ABI::Retcon ||
129            Shape.ABI == coro::ABI::RetconOnce || Shape.ABI == coro::ABI::Async);
130     assert(NewF && "need existing function for continuation");
131     assert(ActiveSuspend && "need active suspend point for continuation");
132   }
133 
134   Function *getFunction() const {
135     assert(NewF != nullptr && "declaration not yet set");
136     return NewF;
137   }
138 
139   void create();
140 
141 private:
142   bool isSwitchDestroyFunction() {
143     switch (FKind) {
144     case Kind::Async:
145     case Kind::Continuation:
146     case Kind::SwitchResume:
147       return false;
148     case Kind::SwitchUnwind:
149     case Kind::SwitchCleanup:
150       return true;
151     }
152     llvm_unreachable("Unknown CoroCloner::Kind enum");
153   }
154 
155   void replaceEntryBlock();
156   Value *deriveNewFramePointer();
157   void replaceRetconOrAsyncSuspendUses();
158   void replaceCoroSuspends();
159   void replaceCoroEnds();
160   void replaceSwiftErrorOps();
161   void salvageDebugInfo();
162   void handleFinalSuspend();
163 };
164 
165 } // end anonymous namespace
166 
167 static void maybeFreeRetconStorage(IRBuilder<> &Builder,
168                                    const coro::Shape &Shape, Value *FramePtr,
169                                    CallGraph *CG) {
170   assert(Shape.ABI == coro::ABI::Retcon ||
171          Shape.ABI == coro::ABI::RetconOnce);
172   if (Shape.RetconLowering.IsFrameInlineInStorage)
173     return;
174 
175   Shape.emitDealloc(Builder, FramePtr, CG);
176 }
177 
178 /// Replace an llvm.coro.end.async.
179 /// Will inline the must tail call function call if there is one.
180 /// \returns true if cleanup of the coro.end block is needed, false otherwise.
181 static bool replaceCoroEndAsync(AnyCoroEndInst *End) {
182   IRBuilder<> Builder(End);
183 
184   auto *EndAsync = dyn_cast<CoroAsyncEndInst>(End);
185   if (!EndAsync) {
186     Builder.CreateRetVoid();
187     return true /*needs cleanup of coro.end block*/;
188   }
189 
190   auto *MustTailCallFunc = EndAsync->getMustTailCallFunction();
191   if (!MustTailCallFunc) {
192     Builder.CreateRetVoid();
193     return true /*needs cleanup of coro.end block*/;
194   }
195 
196   // Move the must tail call from the predecessor block into the end block.
197   auto *CoroEndBlock = End->getParent();
198   auto *MustTailCallFuncBlock = CoroEndBlock->getSinglePredecessor();
199   assert(MustTailCallFuncBlock && "Must have a single predecessor block");
200   auto It = MustTailCallFuncBlock->getTerminator()->getIterator();
201   auto *MustTailCall = cast<CallInst>(&*std::prev(It));
202   CoroEndBlock->getInstList().splice(
203       End->getIterator(), MustTailCallFuncBlock->getInstList(), MustTailCall);
204 
205   // Insert the return instruction.
206   Builder.SetInsertPoint(End);
207   Builder.CreateRetVoid();
208   InlineFunctionInfo FnInfo;
209 
210   // Remove the rest of the block, by splitting it into an unreachable block.
211   auto *BB = End->getParent();
212   BB->splitBasicBlock(End);
213   BB->getTerminator()->eraseFromParent();
214 
215   auto InlineRes = InlineFunction(*MustTailCall, FnInfo);
216   assert(InlineRes.isSuccess() && "Expected inlining to succeed");
217   (void)InlineRes;
218 
219   // We have cleaned up the coro.end block above.
220   return false;
221 }
222 
223 /// Replace a non-unwind call to llvm.coro.end.
224 static void replaceFallthroughCoroEnd(AnyCoroEndInst *End,
225                                       const coro::Shape &Shape, Value *FramePtr,
226                                       bool InResume, CallGraph *CG) {
227   // Start inserting right before the coro.end.
228   IRBuilder<> Builder(End);
229 
230   // Create the return instruction.
231   switch (Shape.ABI) {
232   // The cloned functions in switch-lowering always return void.
233   case coro::ABI::Switch:
234     // coro.end doesn't immediately end the coroutine in the main function
235     // in this lowering, because we need to deallocate the coroutine.
236     if (!InResume)
237       return;
238     Builder.CreateRetVoid();
239     break;
240 
241   // In async lowering this returns.
242   case coro::ABI::Async: {
243     bool CoroEndBlockNeedsCleanup = replaceCoroEndAsync(End);
244     if (!CoroEndBlockNeedsCleanup)
245       return;
246     break;
247   }
248 
249   // In unique continuation lowering, the continuations always return void.
250   // But we may have implicitly allocated storage.
251   case coro::ABI::RetconOnce:
252     maybeFreeRetconStorage(Builder, Shape, FramePtr, CG);
253     Builder.CreateRetVoid();
254     break;
255 
256   // In non-unique continuation lowering, we signal completion by returning
257   // a null continuation.
258   case coro::ABI::Retcon: {
259     maybeFreeRetconStorage(Builder, Shape, FramePtr, CG);
260     auto RetTy = Shape.getResumeFunctionType()->getReturnType();
261     auto RetStructTy = dyn_cast<StructType>(RetTy);
262     PointerType *ContinuationTy =
263       cast<PointerType>(RetStructTy ? RetStructTy->getElementType(0) : RetTy);
264 
265     Value *ReturnValue = ConstantPointerNull::get(ContinuationTy);
266     if (RetStructTy) {
267       ReturnValue = Builder.CreateInsertValue(UndefValue::get(RetStructTy),
268                                               ReturnValue, 0);
269     }
270     Builder.CreateRet(ReturnValue);
271     break;
272   }
273   }
274 
275   // Remove the rest of the block, by splitting it into an unreachable block.
276   auto *BB = End->getParent();
277   BB->splitBasicBlock(End);
278   BB->getTerminator()->eraseFromParent();
279 }
280 
281 /// Replace an unwind call to llvm.coro.end.
282 static void replaceUnwindCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape,
283                                  Value *FramePtr, bool InResume,
284                                  CallGraph *CG) {
285   IRBuilder<> Builder(End);
286 
287   switch (Shape.ABI) {
288   // In switch-lowering, this does nothing in the main function.
289   case coro::ABI::Switch:
290     if (!InResume)
291       return;
292     break;
293   // In async lowering this does nothing.
294   case coro::ABI::Async:
295     break;
296   // In continuation-lowering, this frees the continuation storage.
297   case coro::ABI::Retcon:
298   case coro::ABI::RetconOnce:
299     maybeFreeRetconStorage(Builder, Shape, FramePtr, CG);
300     break;
301   }
302 
303   // If coro.end has an associated bundle, add cleanupret instruction.
304   if (auto Bundle = End->getOperandBundle(LLVMContext::OB_funclet)) {
305     auto *FromPad = cast<CleanupPadInst>(Bundle->Inputs[0]);
306     auto *CleanupRet = Builder.CreateCleanupRet(FromPad, nullptr);
307     End->getParent()->splitBasicBlock(End);
308     CleanupRet->getParent()->getTerminator()->eraseFromParent();
309   }
310 }
311 
312 static void replaceCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape,
313                            Value *FramePtr, bool InResume, CallGraph *CG) {
314   if (End->isUnwind())
315     replaceUnwindCoroEnd(End, Shape, FramePtr, InResume, CG);
316   else
317     replaceFallthroughCoroEnd(End, Shape, FramePtr, InResume, CG);
318 
319   auto &Context = End->getContext();
320   End->replaceAllUsesWith(InResume ? ConstantInt::getTrue(Context)
321                                    : ConstantInt::getFalse(Context));
322   End->eraseFromParent();
323 }
324 
325 // Create an entry block for a resume function with a switch that will jump to
326 // suspend points.
327 static void createResumeEntryBlock(Function &F, coro::Shape &Shape) {
328   assert(Shape.ABI == coro::ABI::Switch);
329   LLVMContext &C = F.getContext();
330 
331   // resume.entry:
332   //  %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0,
333   //  i32 2
334   //  % index = load i32, i32* %index.addr
335   //  switch i32 %index, label %unreachable [
336   //    i32 0, label %resume.0
337   //    i32 1, label %resume.1
338   //    ...
339   //  ]
340 
341   auto *NewEntry = BasicBlock::Create(C, "resume.entry", &F);
342   auto *UnreachBB = BasicBlock::Create(C, "unreachable", &F);
343 
344   IRBuilder<> Builder(NewEntry);
345   auto *FramePtr = Shape.FramePtr;
346   auto *FrameTy = Shape.FrameTy;
347   auto *GepIndex = Builder.CreateStructGEP(
348       FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr");
349   auto *Index = Builder.CreateLoad(Shape.getIndexType(), GepIndex, "index");
350   auto *Switch =
351       Builder.CreateSwitch(Index, UnreachBB, Shape.CoroSuspends.size());
352   Shape.SwitchLowering.ResumeSwitch = Switch;
353 
354   size_t SuspendIndex = 0;
355   for (auto *AnyS : Shape.CoroSuspends) {
356     auto *S = cast<CoroSuspendInst>(AnyS);
357     ConstantInt *IndexVal = Shape.getIndex(SuspendIndex);
358 
359     // Replace CoroSave with a store to Index:
360     //    %index.addr = getelementptr %f.frame... (index field number)
361     //    store i32 0, i32* %index.addr1
362     auto *Save = S->getCoroSave();
363     Builder.SetInsertPoint(Save);
364     if (S->isFinal()) {
365       // Final suspend point is represented by storing zero in ResumeFnAddr.
366       auto *GepIndex = Builder.CreateStructGEP(FrameTy, FramePtr,
367                                  coro::Shape::SwitchFieldIndex::Resume,
368                                   "ResumeFn.addr");
369       auto *NullPtr = ConstantPointerNull::get(cast<PointerType>(
370           cast<PointerType>(GepIndex->getType())->getElementType()));
371       Builder.CreateStore(NullPtr, GepIndex);
372     } else {
373       auto *GepIndex = Builder.CreateStructGEP(
374           FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr");
375       Builder.CreateStore(IndexVal, GepIndex);
376     }
377     Save->replaceAllUsesWith(ConstantTokenNone::get(C));
378     Save->eraseFromParent();
379 
380     // Split block before and after coro.suspend and add a jump from an entry
381     // switch:
382     //
383     //  whateverBB:
384     //    whatever
385     //    %0 = call i8 @llvm.coro.suspend(token none, i1 false)
386     //    switch i8 %0, label %suspend[i8 0, label %resume
387     //                                 i8 1, label %cleanup]
388     // becomes:
389     //
390     //  whateverBB:
391     //     whatever
392     //     br label %resume.0.landing
393     //
394     //  resume.0: ; <--- jump from the switch in the resume.entry
395     //     %0 = tail call i8 @llvm.coro.suspend(token none, i1 false)
396     //     br label %resume.0.landing
397     //
398     //  resume.0.landing:
399     //     %1 = phi i8[-1, %whateverBB], [%0, %resume.0]
400     //     switch i8 % 1, label %suspend [i8 0, label %resume
401     //                                    i8 1, label %cleanup]
402 
403     auto *SuspendBB = S->getParent();
404     auto *ResumeBB =
405         SuspendBB->splitBasicBlock(S, "resume." + Twine(SuspendIndex));
406     auto *LandingBB = ResumeBB->splitBasicBlock(
407         S->getNextNode(), ResumeBB->getName() + Twine(".landing"));
408     Switch->addCase(IndexVal, ResumeBB);
409 
410     cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB);
411     auto *PN = PHINode::Create(Builder.getInt8Ty(), 2, "", &LandingBB->front());
412     S->replaceAllUsesWith(PN);
413     PN->addIncoming(Builder.getInt8(-1), SuspendBB);
414     PN->addIncoming(S, ResumeBB);
415 
416     ++SuspendIndex;
417   }
418 
419   Builder.SetInsertPoint(UnreachBB);
420   Builder.CreateUnreachable();
421 
422   Shape.SwitchLowering.ResumeEntryBlock = NewEntry;
423 }
424 
425 
426 // Rewrite final suspend point handling. We do not use suspend index to
427 // represent the final suspend point. Instead we zero-out ResumeFnAddr in the
428 // coroutine frame, since it is undefined behavior to resume a coroutine
429 // suspended at the final suspend point. Thus, in the resume function, we can
430 // simply remove the last case (when coro::Shape is built, the final suspend
431 // point (if present) is always the last element of CoroSuspends array).
432 // In the destroy function, we add a code sequence to check if ResumeFnAddress
433 // is Null, and if so, jump to the appropriate label to handle cleanup from the
434 // final suspend point.
435 void CoroCloner::handleFinalSuspend() {
436   assert(Shape.ABI == coro::ABI::Switch &&
437          Shape.SwitchLowering.HasFinalSuspend);
438   auto *Switch = cast<SwitchInst>(VMap[Shape.SwitchLowering.ResumeSwitch]);
439   auto FinalCaseIt = std::prev(Switch->case_end());
440   BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor();
441   Switch->removeCase(FinalCaseIt);
442   if (isSwitchDestroyFunction()) {
443     BasicBlock *OldSwitchBB = Switch->getParent();
444     auto *NewSwitchBB = OldSwitchBB->splitBasicBlock(Switch, "Switch");
445     Builder.SetInsertPoint(OldSwitchBB->getTerminator());
446     auto *GepIndex = Builder.CreateStructGEP(Shape.FrameTy, NewFramePtr,
447                                        coro::Shape::SwitchFieldIndex::Resume,
448                                              "ResumeFn.addr");
449     auto *Load = Builder.CreateLoad(Shape.getSwitchResumePointerType(),
450                                     GepIndex);
451     auto *Cond = Builder.CreateIsNull(Load);
452     Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB);
453     OldSwitchBB->getTerminator()->eraseFromParent();
454   }
455 }
456 
457 static FunctionType *
458 getFunctionTypeFromAsyncSuspend(AnyCoroSuspendInst *Suspend) {
459   auto *AsyncSuspend = cast<CoroSuspendAsyncInst>(Suspend);
460   auto *StructTy = cast<StructType>(AsyncSuspend->getType());
461   auto &Context = Suspend->getParent()->getParent()->getContext();
462   auto *VoidTy = Type::getVoidTy(Context);
463   return FunctionType::get(VoidTy, StructTy->elements(), false);
464 }
465 
466 static Function *createCloneDeclaration(Function &OrigF, coro::Shape &Shape,
467                                         const Twine &Suffix,
468                                         Module::iterator InsertBefore,
469                                         AnyCoroSuspendInst *ActiveSuspend) {
470   Module *M = OrigF.getParent();
471   auto *FnTy = (Shape.ABI != coro::ABI::Async)
472                    ? Shape.getResumeFunctionType()
473                    : getFunctionTypeFromAsyncSuspend(ActiveSuspend);
474 
475   Function *NewF =
476       Function::Create(FnTy, GlobalValue::LinkageTypes::InternalLinkage,
477                        OrigF.getName() + Suffix);
478   NewF->addParamAttr(0, Attribute::NonNull);
479 
480   // For the async lowering ABI we can't guarantee that the context argument is
481   // not access via a different pointer not based on the argument.
482   if (Shape.ABI != coro::ABI::Async)
483     NewF->addParamAttr(0, Attribute::NoAlias);
484 
485   M->getFunctionList().insert(InsertBefore, NewF);
486 
487   return NewF;
488 }
489 
490 /// Replace uses of the active llvm.coro.suspend.retcon/async call with the
491 /// arguments to the continuation function.
492 ///
493 /// This assumes that the builder has a meaningful insertion point.
494 void CoroCloner::replaceRetconOrAsyncSuspendUses() {
495   assert(Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
496          Shape.ABI == coro::ABI::Async);
497 
498   auto NewS = VMap[ActiveSuspend];
499   if (NewS->use_empty()) return;
500 
501   // Copy out all the continuation arguments after the buffer pointer into
502   // an easily-indexed data structure for convenience.
503   SmallVector<Value*, 8> Args;
504   // The async ABI includes all arguments -- including the first argument.
505   bool IsAsyncABI = Shape.ABI == coro::ABI::Async;
506   for (auto I = IsAsyncABI ? NewF->arg_begin() : std::next(NewF->arg_begin()),
507             E = NewF->arg_end();
508        I != E; ++I)
509     Args.push_back(&*I);
510 
511   // If the suspend returns a single scalar value, we can just do a simple
512   // replacement.
513   if (!isa<StructType>(NewS->getType())) {
514     assert(Args.size() == 1);
515     NewS->replaceAllUsesWith(Args.front());
516     return;
517   }
518 
519   // Try to peephole extracts of an aggregate return.
520   for (auto UI = NewS->use_begin(), UE = NewS->use_end(); UI != UE; ) {
521     auto EVI = dyn_cast<ExtractValueInst>((UI++)->getUser());
522     if (!EVI || EVI->getNumIndices() != 1)
523       continue;
524 
525     EVI->replaceAllUsesWith(Args[EVI->getIndices().front()]);
526     EVI->eraseFromParent();
527   }
528 
529   // If we have no remaining uses, we're done.
530   if (NewS->use_empty()) return;
531 
532   // Otherwise, we need to create an aggregate.
533   Value *Agg = UndefValue::get(NewS->getType());
534   for (size_t I = 0, E = Args.size(); I != E; ++I)
535     Agg = Builder.CreateInsertValue(Agg, Args[I], I);
536 
537   NewS->replaceAllUsesWith(Agg);
538 }
539 
540 void CoroCloner::replaceCoroSuspends() {
541   Value *SuspendResult;
542 
543   switch (Shape.ABI) {
544   // In switch lowering, replace coro.suspend with the appropriate value
545   // for the type of function we're extracting.
546   // Replacing coro.suspend with (0) will result in control flow proceeding to
547   // a resume label associated with a suspend point, replacing it with (1) will
548   // result in control flow proceeding to a cleanup label associated with this
549   // suspend point.
550   case coro::ABI::Switch:
551     SuspendResult = Builder.getInt8(isSwitchDestroyFunction() ? 1 : 0);
552     break;
553 
554   // In async lowering there are no uses of the result.
555   case coro::ABI::Async:
556     return;
557 
558   // In returned-continuation lowering, the arguments from earlier
559   // continuations are theoretically arbitrary, and they should have been
560   // spilled.
561   case coro::ABI::RetconOnce:
562   case coro::ABI::Retcon:
563     return;
564   }
565 
566   for (AnyCoroSuspendInst *CS : Shape.CoroSuspends) {
567     // The active suspend was handled earlier.
568     if (CS == ActiveSuspend) continue;
569 
570     auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[CS]);
571     MappedCS->replaceAllUsesWith(SuspendResult);
572     MappedCS->eraseFromParent();
573   }
574 }
575 
576 void CoroCloner::replaceCoroEnds() {
577   for (AnyCoroEndInst *CE : Shape.CoroEnds) {
578     // We use a null call graph because there's no call graph node for
579     // the cloned function yet.  We'll just be rebuilding that later.
580     auto *NewCE = cast<AnyCoroEndInst>(VMap[CE]);
581     replaceCoroEnd(NewCE, Shape, NewFramePtr, /*in resume*/ true, nullptr);
582   }
583 }
584 
585 static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape,
586                                  ValueToValueMapTy *VMap) {
587   if (Shape.ABI == coro::ABI::Async && Shape.CoroSuspends.empty())
588     return;
589   Value *CachedSlot = nullptr;
590   auto getSwiftErrorSlot = [&](Type *ValueTy) -> Value * {
591     if (CachedSlot) {
592       assert(CachedSlot->getType()->getPointerElementType() == ValueTy &&
593              "multiple swifterror slots in function with different types");
594       return CachedSlot;
595     }
596 
597     // Check if the function has a swifterror argument.
598     for (auto &Arg : F.args()) {
599       if (Arg.isSwiftError()) {
600         CachedSlot = &Arg;
601         assert(Arg.getType()->getPointerElementType() == ValueTy &&
602                "swifterror argument does not have expected type");
603         return &Arg;
604       }
605     }
606 
607     // Create a swifterror alloca.
608     IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
609     auto Alloca = Builder.CreateAlloca(ValueTy);
610     Alloca->setSwiftError(true);
611 
612     CachedSlot = Alloca;
613     return Alloca;
614   };
615 
616   for (CallInst *Op : Shape.SwiftErrorOps) {
617     auto MappedOp = VMap ? cast<CallInst>((*VMap)[Op]) : Op;
618     IRBuilder<> Builder(MappedOp);
619 
620     // If there are no arguments, this is a 'get' operation.
621     Value *MappedResult;
622     if (Op->getNumArgOperands() == 0) {
623       auto ValueTy = Op->getType();
624       auto Slot = getSwiftErrorSlot(ValueTy);
625       MappedResult = Builder.CreateLoad(ValueTy, Slot);
626     } else {
627       assert(Op->getNumArgOperands() == 1);
628       auto Value = MappedOp->getArgOperand(0);
629       auto ValueTy = Value->getType();
630       auto Slot = getSwiftErrorSlot(ValueTy);
631       Builder.CreateStore(Value, Slot);
632       MappedResult = Slot;
633     }
634 
635     MappedOp->replaceAllUsesWith(MappedResult);
636     MappedOp->eraseFromParent();
637   }
638 
639   // If we're updating the original function, we've invalidated SwiftErrorOps.
640   if (VMap == nullptr) {
641     Shape.SwiftErrorOps.clear();
642   }
643 }
644 
645 void CoroCloner::replaceSwiftErrorOps() {
646   ::replaceSwiftErrorOps(*NewF, Shape, &VMap);
647 }
648 
649 void CoroCloner::salvageDebugInfo() {
650   SmallVector<DbgDeclareInst *, 8> Worklist;
651   SmallDenseMap<llvm::Value *, llvm::AllocaInst *, 4> DbgPtrAllocaCache;
652   for (auto &BB : *NewF)
653     for (auto &I : BB)
654       if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
655         Worklist.push_back(DDI);
656   for (DbgDeclareInst *DDI : Worklist)
657     coro::salvageDebugInfo(DbgPtrAllocaCache, DDI);
658 
659   // Remove all salvaged dbg.declare intrinsics that became
660   // either unreachable or stale due to the CoroSplit transformation.
661   auto IsUnreachableBlock = [&](BasicBlock *BB) {
662     return BB->hasNPredecessors(0) && BB != &NewF->getEntryBlock();
663   };
664   for (DbgDeclareInst *DDI : Worklist) {
665     if (IsUnreachableBlock(DDI->getParent()))
666       DDI->eraseFromParent();
667     else if (dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
668       // Count all non-debuginfo uses in reachable blocks.
669       unsigned Uses = 0;
670       for (auto *User : DDI->getAddress()->users())
671         if (auto *I = dyn_cast<Instruction>(User))
672           if (!isa<AllocaInst>(I) && !IsUnreachableBlock(I->getParent()))
673             ++Uses;
674       if (!Uses)
675         DDI->eraseFromParent();
676     }
677   }
678 }
679 
680 void CoroCloner::replaceEntryBlock() {
681   // In the original function, the AllocaSpillBlock is a block immediately
682   // following the allocation of the frame object which defines GEPs for
683   // all the allocas that have been moved into the frame, and it ends by
684   // branching to the original beginning of the coroutine.  Make this
685   // the entry block of the cloned function.
686   auto *Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]);
687   auto *OldEntry = &NewF->getEntryBlock();
688   Entry->setName("entry" + Suffix);
689   Entry->moveBefore(OldEntry);
690   Entry->getTerminator()->eraseFromParent();
691 
692   // Clear all predecessors of the new entry block.  There should be
693   // exactly one predecessor, which we created when splitting out
694   // AllocaSpillBlock to begin with.
695   assert(Entry->hasOneUse());
696   auto BranchToEntry = cast<BranchInst>(Entry->user_back());
697   assert(BranchToEntry->isUnconditional());
698   Builder.SetInsertPoint(BranchToEntry);
699   Builder.CreateUnreachable();
700   BranchToEntry->eraseFromParent();
701 
702   // Branch from the entry to the appropriate place.
703   Builder.SetInsertPoint(Entry);
704   switch (Shape.ABI) {
705   case coro::ABI::Switch: {
706     // In switch-lowering, we built a resume-entry block in the original
707     // function.  Make the entry block branch to this.
708     auto *SwitchBB =
709       cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]);
710     Builder.CreateBr(SwitchBB);
711     break;
712   }
713   case coro::ABI::Async:
714   case coro::ABI::Retcon:
715   case coro::ABI::RetconOnce: {
716     // In continuation ABIs, we want to branch to immediately after the
717     // active suspend point.  Earlier phases will have put the suspend in its
718     // own basic block, so just thread our jump directly to its successor.
719     assert((Shape.ABI == coro::ABI::Async &&
720             isa<CoroSuspendAsyncInst>(ActiveSuspend)) ||
721            ((Shape.ABI == coro::ABI::Retcon ||
722              Shape.ABI == coro::ABI::RetconOnce) &&
723             isa<CoroSuspendRetconInst>(ActiveSuspend)));
724     auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[ActiveSuspend]);
725     auto Branch = cast<BranchInst>(MappedCS->getNextNode());
726     assert(Branch->isUnconditional());
727     Builder.CreateBr(Branch->getSuccessor(0));
728     break;
729   }
730   }
731 
732   // Any static alloca that's still being used but not reachable from the new
733   // entry needs to be moved to the new entry.
734   Function *F = OldEntry->getParent();
735   DominatorTree DT{*F};
736   for (auto IT = inst_begin(F), End = inst_end(F); IT != End;) {
737     Instruction &I = *IT++;
738     auto *Alloca = dyn_cast<AllocaInst>(&I);
739     if (!Alloca || I.use_empty())
740       continue;
741     if (DT.isReachableFromEntry(I.getParent()) ||
742         !isa<ConstantInt>(Alloca->getArraySize()))
743       continue;
744     I.moveBefore(*Entry, Entry->getFirstInsertionPt());
745   }
746 }
747 
748 /// Derive the value of the new frame pointer.
749 Value *CoroCloner::deriveNewFramePointer() {
750   // Builder should be inserting to the front of the new entry block.
751 
752   switch (Shape.ABI) {
753   // In switch-lowering, the argument is the frame pointer.
754   case coro::ABI::Switch:
755     return &*NewF->arg_begin();
756   // In async-lowering, one of the arguments is an async context as determined
757   // by the `llvm.coro.id.async` intrinsic. We can retrieve the async context of
758   // the resume function from the async context projection function associated
759   // with the active suspend. The frame is located as a tail to the async
760   // context header.
761   case coro::ABI::Async: {
762     auto *ActiveAsyncSuspend = cast<CoroSuspendAsyncInst>(ActiveSuspend);
763     auto *CalleeContext =
764         NewF->getArg(ActiveAsyncSuspend->getStorageArgumentIndex());
765     auto *FramePtrTy = Shape.FrameTy->getPointerTo();
766     auto *ProjectionFunc =
767         ActiveAsyncSuspend->getAsyncContextProjectionFunction();
768     auto DbgLoc =
769         cast<CoroSuspendAsyncInst>(VMap[ActiveSuspend])->getDebugLoc();
770     // Calling i8* (i8*)
771     auto *CallerContext = Builder.CreateCall(
772         cast<FunctionType>(ProjectionFunc->getType()->getPointerElementType()),
773         ProjectionFunc, CalleeContext);
774     CallerContext->setCallingConv(ProjectionFunc->getCallingConv());
775     CallerContext->setDebugLoc(DbgLoc);
776     // The frame is located after the async_context header.
777     auto &Context = Builder.getContext();
778     auto *FramePtrAddr = Builder.CreateConstInBoundsGEP1_32(
779         Type::getInt8Ty(Context), CallerContext,
780         Shape.AsyncLowering.FrameOffset, "async.ctx.frameptr");
781     // Inline the projection function.
782     InlineFunctionInfo InlineInfo;
783     auto InlineRes = InlineFunction(*CallerContext, InlineInfo);
784     assert(InlineRes.isSuccess());
785     (void)InlineRes;
786     return Builder.CreateBitCast(FramePtrAddr, FramePtrTy);
787   }
788   // In continuation-lowering, the argument is the opaque storage.
789   case coro::ABI::Retcon:
790   case coro::ABI::RetconOnce: {
791     Argument *NewStorage = &*NewF->arg_begin();
792     auto FramePtrTy = Shape.FrameTy->getPointerTo();
793 
794     // If the storage is inline, just bitcast to the storage to the frame type.
795     if (Shape.RetconLowering.IsFrameInlineInStorage)
796       return Builder.CreateBitCast(NewStorage, FramePtrTy);
797 
798     // Otherwise, load the real frame from the opaque storage.
799     auto FramePtrPtr =
800       Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo());
801     return Builder.CreateLoad(FramePtrTy, FramePtrPtr);
802   }
803   }
804   llvm_unreachable("bad ABI");
805 }
806 
807 static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context,
808                                  unsigned ParamIndex,
809                                  uint64_t Size, Align Alignment) {
810   AttrBuilder ParamAttrs;
811   ParamAttrs.addAttribute(Attribute::NonNull);
812   ParamAttrs.addAttribute(Attribute::NoAlias);
813   ParamAttrs.addAlignmentAttr(Alignment);
814   ParamAttrs.addDereferenceableAttr(Size);
815   Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
816 }
817 
818 /// Clone the body of the original function into a resume function of
819 /// some sort.
820 void CoroCloner::create() {
821   // Create the new function if we don't already have one.
822   if (!NewF) {
823     NewF = createCloneDeclaration(OrigF, Shape, Suffix,
824                                   OrigF.getParent()->end(), ActiveSuspend);
825   }
826 
827   // Replace all args with undefs. The buildCoroutineFrame algorithm already
828   // rewritten access to the args that occurs after suspend points with loads
829   // and stores to/from the coroutine frame.
830   for (Argument &A : OrigF.args())
831     VMap[&A] = UndefValue::get(A.getType());
832 
833   SmallVector<ReturnInst *, 4> Returns;
834 
835   // Ignore attempts to change certain attributes of the function.
836   // TODO: maybe there should be a way to suppress this during cloning?
837   auto savedVisibility = NewF->getVisibility();
838   auto savedUnnamedAddr = NewF->getUnnamedAddr();
839   auto savedDLLStorageClass = NewF->getDLLStorageClass();
840 
841   // NewF's linkage (which CloneFunctionInto does *not* change) might not
842   // be compatible with the visibility of OrigF (which it *does* change),
843   // so protect against that.
844   auto savedLinkage = NewF->getLinkage();
845   NewF->setLinkage(llvm::GlobalValue::ExternalLinkage);
846 
847   CloneFunctionInto(NewF, &OrigF, VMap,
848                     CloneFunctionChangeType::LocalChangesOnly, Returns);
849 
850   NewF->setLinkage(savedLinkage);
851   NewF->setVisibility(savedVisibility);
852   NewF->setUnnamedAddr(savedUnnamedAddr);
853   NewF->setDLLStorageClass(savedDLLStorageClass);
854 
855   auto &Context = NewF->getContext();
856 
857   // Replace the attributes of the new function:
858   auto OrigAttrs = NewF->getAttributes();
859   auto NewAttrs = AttributeList();
860 
861   switch (Shape.ABI) {
862   case coro::ABI::Switch:
863     // Bootstrap attributes by copying function attributes from the
864     // original function.  This should include optimization settings and so on.
865     NewAttrs = NewAttrs.addAttributes(Context, AttributeList::FunctionIndex,
866                                       OrigAttrs.getFnAttributes());
867 
868     addFramePointerAttrs(NewAttrs, Context, 0,
869                          Shape.FrameSize, Shape.FrameAlign);
870     break;
871   case coro::ABI::Async:
872     break;
873   case coro::ABI::Retcon:
874   case coro::ABI::RetconOnce:
875     // If we have a continuation prototype, just use its attributes,
876     // full-stop.
877     NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes();
878 
879     addFramePointerAttrs(NewAttrs, Context, 0,
880                          Shape.getRetconCoroId()->getStorageSize(),
881                          Shape.getRetconCoroId()->getStorageAlignment());
882     break;
883   }
884 
885   switch (Shape.ABI) {
886   // In these ABIs, the cloned functions always return 'void', and the
887   // existing return sites are meaningless.  Note that for unique
888   // continuations, this includes the returns associated with suspends;
889   // this is fine because we can't suspend twice.
890   case coro::ABI::Switch:
891   case coro::ABI::RetconOnce:
892     // Remove old returns.
893     for (ReturnInst *Return : Returns)
894       changeToUnreachable(Return, /*UseLLVMTrap=*/false);
895     break;
896 
897   // With multi-suspend continuations, we'll already have eliminated the
898   // original returns and inserted returns before all the suspend points,
899   // so we want to leave any returns in place.
900   case coro::ABI::Retcon:
901     break;
902   // Async lowering will insert musttail call functions at all suspend points
903   // followed by a return.
904   // Don't change returns to unreachable because that will trip up the verifier.
905   // These returns should be unreachable from the clone.
906   case coro::ABI::Async:
907     break;
908   }
909 
910   NewF->setAttributes(NewAttrs);
911   NewF->setCallingConv(Shape.getResumeFunctionCC());
912 
913   // Set up the new entry block.
914   replaceEntryBlock();
915 
916   Builder.SetInsertPoint(&NewF->getEntryBlock().front());
917   NewFramePtr = deriveNewFramePointer();
918 
919   // Remap frame pointer.
920   Value *OldFramePtr = VMap[Shape.FramePtr];
921   NewFramePtr->takeName(OldFramePtr);
922   OldFramePtr->replaceAllUsesWith(NewFramePtr);
923 
924   // Remap vFrame pointer.
925   auto *NewVFrame = Builder.CreateBitCast(
926       NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame");
927   Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]);
928   OldVFrame->replaceAllUsesWith(NewVFrame);
929 
930   switch (Shape.ABI) {
931   case coro::ABI::Switch:
932     // Rewrite final suspend handling as it is not done via switch (allows to
933     // remove final case from the switch, since it is undefined behavior to
934     // resume the coroutine suspended at the final suspend point.
935     if (Shape.SwitchLowering.HasFinalSuspend)
936       handleFinalSuspend();
937     break;
938   case coro::ABI::Async:
939   case coro::ABI::Retcon:
940   case coro::ABI::RetconOnce:
941     // Replace uses of the active suspend with the corresponding
942     // continuation-function arguments.
943     assert(ActiveSuspend != nullptr &&
944            "no active suspend when lowering a continuation-style coroutine");
945     replaceRetconOrAsyncSuspendUses();
946     break;
947   }
948 
949   // Handle suspends.
950   replaceCoroSuspends();
951 
952   // Handle swifterror.
953   replaceSwiftErrorOps();
954 
955   // Remove coro.end intrinsics.
956   replaceCoroEnds();
957 
958   // Salvage debug info that points into the coroutine frame.
959   salvageDebugInfo();
960 
961   // Eliminate coro.free from the clones, replacing it with 'null' in cleanup,
962   // to suppress deallocation code.
963   if (Shape.ABI == coro::ABI::Switch)
964     coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]),
965                           /*Elide=*/ FKind == CoroCloner::Kind::SwitchCleanup);
966 }
967 
968 // Create a resume clone by cloning the body of the original function, setting
969 // new entry block and replacing coro.suspend an appropriate value to force
970 // resume or cleanup pass for every suspend point.
971 static Function *createClone(Function &F, const Twine &Suffix,
972                              coro::Shape &Shape, CoroCloner::Kind FKind) {
973   CoroCloner Cloner(F, Suffix, Shape, FKind);
974   Cloner.create();
975   return Cloner.getFunction();
976 }
977 
978 /// Remove calls to llvm.coro.end in the original function.
979 static void removeCoroEnds(const coro::Shape &Shape, CallGraph *CG) {
980   for (auto End : Shape.CoroEnds) {
981     replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, CG);
982   }
983 }
984 
985 static void updateAsyncFuncPointerContextSize(coro::Shape &Shape) {
986   assert(Shape.ABI == coro::ABI::Async);
987 
988   auto *FuncPtrStruct = cast<ConstantStruct>(
989       Shape.AsyncLowering.AsyncFuncPointer->getInitializer());
990   auto *OrigRelativeFunOffset = FuncPtrStruct->getOperand(0);
991   auto *OrigContextSize = FuncPtrStruct->getOperand(1);
992   auto *NewContextSize = ConstantInt::get(OrigContextSize->getType(),
993                                           Shape.AsyncLowering.ContextSize);
994   auto *NewFuncPtrStruct = ConstantStruct::get(
995       FuncPtrStruct->getType(), OrigRelativeFunOffset, NewContextSize);
996 
997   Shape.AsyncLowering.AsyncFuncPointer->setInitializer(NewFuncPtrStruct);
998 }
999 
1000 static void replaceFrameSize(coro::Shape &Shape) {
1001   if (Shape.ABI == coro::ABI::Async)
1002     updateAsyncFuncPointerContextSize(Shape);
1003 
1004   if (Shape.CoroSizes.empty())
1005     return;
1006 
1007   // In the same function all coro.sizes should have the same result type.
1008   auto *SizeIntrin = Shape.CoroSizes.back();
1009   Module *M = SizeIntrin->getModule();
1010   const DataLayout &DL = M->getDataLayout();
1011   auto Size = DL.getTypeAllocSize(Shape.FrameTy);
1012   auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size);
1013 
1014   for (CoroSizeInst *CS : Shape.CoroSizes) {
1015     CS->replaceAllUsesWith(SizeConstant);
1016     CS->eraseFromParent();
1017   }
1018 }
1019 
1020 // Create a global constant array containing pointers to functions provided and
1021 // set Info parameter of CoroBegin to point at this constant. Example:
1022 //
1023 //   @f.resumers = internal constant [2 x void(%f.frame*)*]
1024 //                    [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy]
1025 //   define void @f() {
1026 //     ...
1027 //     call i8* @llvm.coro.begin(i8* null, i32 0, i8* null,
1028 //                    i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*))
1029 //
1030 // Assumes that all the functions have the same signature.
1031 static void setCoroInfo(Function &F, coro::Shape &Shape,
1032                         ArrayRef<Function *> Fns) {
1033   // This only works under the switch-lowering ABI because coro elision
1034   // only works on the switch-lowering ABI.
1035   assert(Shape.ABI == coro::ABI::Switch);
1036 
1037   SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end());
1038   assert(!Args.empty());
1039   Function *Part = *Fns.begin();
1040   Module *M = Part->getParent();
1041   auto *ArrTy = ArrayType::get(Part->getType(), Args.size());
1042 
1043   auto *ConstVal = ConstantArray::get(ArrTy, Args);
1044   auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true,
1045                                 GlobalVariable::PrivateLinkage, ConstVal,
1046                                 F.getName() + Twine(".resumers"));
1047 
1048   // Update coro.begin instruction to refer to this constant.
1049   LLVMContext &C = F.getContext();
1050   auto *BC = ConstantExpr::getPointerCast(GV, Type::getInt8PtrTy(C));
1051   Shape.getSwitchCoroId()->setInfo(BC);
1052 }
1053 
1054 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame.
1055 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn,
1056                             Function *DestroyFn, Function *CleanupFn) {
1057   assert(Shape.ABI == coro::ABI::Switch);
1058 
1059   IRBuilder<> Builder(Shape.FramePtr->getNextNode());
1060   auto *ResumeAddr = Builder.CreateStructGEP(
1061       Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Resume,
1062       "resume.addr");
1063   Builder.CreateStore(ResumeFn, ResumeAddr);
1064 
1065   Value *DestroyOrCleanupFn = DestroyFn;
1066 
1067   CoroIdInst *CoroId = Shape.getSwitchCoroId();
1068   if (CoroAllocInst *CA = CoroId->getCoroAlloc()) {
1069     // If there is a CoroAlloc and it returns false (meaning we elide the
1070     // allocation, use CleanupFn instead of DestroyFn).
1071     DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
1072   }
1073 
1074   auto *DestroyAddr = Builder.CreateStructGEP(
1075       Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Destroy,
1076       "destroy.addr");
1077   Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
1078 }
1079 
1080 static void postSplitCleanup(Function &F) {
1081   removeUnreachableBlocks(F);
1082 
1083   // For now, we do a mandatory verification step because we don't
1084   // entirely trust this pass.  Note that we don't want to add a verifier
1085   // pass to FPM below because it will also verify all the global data.
1086   if (verifyFunction(F, &errs()))
1087     report_fatal_error("Broken function");
1088 
1089   legacy::FunctionPassManager FPM(F.getParent());
1090 
1091   FPM.add(createSCCPPass());
1092   FPM.add(createCFGSimplificationPass());
1093   FPM.add(createEarlyCSEPass());
1094   FPM.add(createCFGSimplificationPass());
1095 
1096   FPM.doInitialization();
1097   FPM.run(F);
1098   FPM.doFinalization();
1099 }
1100 
1101 // Assuming we arrived at the block NewBlock from Prev instruction, store
1102 // PHI's incoming values in the ResolvedValues map.
1103 static void
1104 scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock,
1105                           DenseMap<Value *, Value *> &ResolvedValues) {
1106   auto *PrevBB = Prev->getParent();
1107   for (PHINode &PN : NewBlock->phis()) {
1108     auto V = PN.getIncomingValueForBlock(PrevBB);
1109     // See if we already resolved it.
1110     auto VI = ResolvedValues.find(V);
1111     if (VI != ResolvedValues.end())
1112       V = VI->second;
1113     // Remember the value.
1114     ResolvedValues[&PN] = V;
1115   }
1116 }
1117 
1118 // Replace a sequence of branches leading to a ret, with a clone of a ret
1119 // instruction. Suspend instruction represented by a switch, track the PHI
1120 // values and select the correct case successor when possible.
1121 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) {
1122   DenseMap<Value *, Value *> ResolvedValues;
1123   BasicBlock *UnconditionalSucc = nullptr;
1124 
1125   Instruction *I = InitialInst;
1126   while (I->isTerminator() ||
1127          (isa<CmpInst>(I) && I->getNextNode()->isTerminator())) {
1128     if (isa<ReturnInst>(I)) {
1129       if (I != InitialInst) {
1130         // If InitialInst is an unconditional branch,
1131         // remove PHI values that come from basic block of InitialInst
1132         if (UnconditionalSucc)
1133           UnconditionalSucc->removePredecessor(InitialInst->getParent(), true);
1134         ReplaceInstWithInst(InitialInst, I->clone());
1135       }
1136       return true;
1137     }
1138     if (auto *BR = dyn_cast<BranchInst>(I)) {
1139       if (BR->isUnconditional()) {
1140         BasicBlock *BB = BR->getSuccessor(0);
1141         if (I == InitialInst)
1142           UnconditionalSucc = BB;
1143         scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
1144         I = BB->getFirstNonPHIOrDbgOrLifetime();
1145         continue;
1146       }
1147     } else if (auto *CondCmp = dyn_cast<CmpInst>(I)) {
1148       auto *BR = dyn_cast<BranchInst>(I->getNextNode());
1149       if (BR && BR->isConditional() && CondCmp == BR->getCondition()) {
1150         // If the case number of suspended switch instruction is reduced to
1151         // 1, then it is simplified to CmpInst in llvm::ConstantFoldTerminator.
1152         // And the comparsion looks like : %cond = icmp eq i8 %V, constant.
1153         ConstantInt *CondConst = dyn_cast<ConstantInt>(CondCmp->getOperand(1));
1154         if (CondConst && CondCmp->getPredicate() == CmpInst::ICMP_EQ) {
1155           Value *V = CondCmp->getOperand(0);
1156           auto it = ResolvedValues.find(V);
1157           if (it != ResolvedValues.end())
1158             V = it->second;
1159 
1160           if (ConstantInt *Cond0 = dyn_cast<ConstantInt>(V)) {
1161             BasicBlock *BB = Cond0->equalsInt(CondConst->getZExtValue())
1162                                  ? BR->getSuccessor(0)
1163                                  : BR->getSuccessor(1);
1164             scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
1165             I = BB->getFirstNonPHIOrDbgOrLifetime();
1166             continue;
1167           }
1168         }
1169       }
1170     } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
1171       Value *V = SI->getCondition();
1172       auto it = ResolvedValues.find(V);
1173       if (it != ResolvedValues.end())
1174         V = it->second;
1175       if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1176         BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor();
1177         scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
1178         I = BB->getFirstNonPHIOrDbgOrLifetime();
1179         continue;
1180       }
1181     }
1182     return false;
1183   }
1184   return false;
1185 }
1186 
1187 // Check whether CI obeys the rules of musttail attribute.
1188 static bool shouldBeMustTail(const CallInst &CI, const Function &F) {
1189   if (CI.isInlineAsm())
1190     return false;
1191 
1192   // Match prototypes and calling conventions of resume function.
1193   FunctionType *CalleeTy = CI.getFunctionType();
1194   if (!CalleeTy->getReturnType()->isVoidTy() || (CalleeTy->getNumParams() != 1))
1195     return false;
1196 
1197   Type *CalleeParmTy = CalleeTy->getParamType(0);
1198   if (!CalleeParmTy->isPointerTy() ||
1199       (CalleeParmTy->getPointerAddressSpace() != 0))
1200     return false;
1201 
1202   if (CI.getCallingConv() != F.getCallingConv())
1203     return false;
1204 
1205   // CI should not has any ABI-impacting function attributes.
1206   static const Attribute::AttrKind ABIAttrs[] = {
1207       Attribute::StructRet,    Attribute::ByVal,     Attribute::InAlloca,
1208       Attribute::Preallocated, Attribute::InReg,     Attribute::Returned,
1209       Attribute::SwiftSelf,    Attribute::SwiftError};
1210   AttributeList Attrs = CI.getAttributes();
1211   for (auto AK : ABIAttrs)
1212     if (Attrs.hasParamAttribute(0, AK))
1213       return false;
1214 
1215   return true;
1216 }
1217 
1218 // Add musttail to any resume instructions that is immediately followed by a
1219 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call
1220 // for symmetrical coroutine control transfer (C++ Coroutines TS extension).
1221 // This transformation is done only in the resume part of the coroutine that has
1222 // identical signature and calling convention as the coro.resume call.
1223 static void addMustTailToCoroResumes(Function &F) {
1224   bool changed = false;
1225 
1226   // Collect potential resume instructions.
1227   SmallVector<CallInst *, 4> Resumes;
1228   for (auto &I : instructions(F))
1229     if (auto *Call = dyn_cast<CallInst>(&I))
1230       if (shouldBeMustTail(*Call, F))
1231         Resumes.push_back(Call);
1232 
1233   // Set musttail on those that are followed by a ret instruction.
1234   for (CallInst *Call : Resumes)
1235     if (simplifyTerminatorLeadingToRet(Call->getNextNode())) {
1236       Call->setTailCallKind(CallInst::TCK_MustTail);
1237       changed = true;
1238     }
1239 
1240   if (changed)
1241     removeUnreachableBlocks(F);
1242 }
1243 
1244 // Coroutine has no suspend points. Remove heap allocation for the coroutine
1245 // frame if possible.
1246 static void handleNoSuspendCoroutine(coro::Shape &Shape) {
1247   auto *CoroBegin = Shape.CoroBegin;
1248   auto *CoroId = CoroBegin->getId();
1249   auto *AllocInst = CoroId->getCoroAlloc();
1250   switch (Shape.ABI) {
1251   case coro::ABI::Switch: {
1252     auto SwitchId = cast<CoroIdInst>(CoroId);
1253     coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr);
1254     if (AllocInst) {
1255       IRBuilder<> Builder(AllocInst);
1256       auto *Frame = Builder.CreateAlloca(Shape.FrameTy);
1257       Frame->setAlignment(Shape.FrameAlign);
1258       auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy());
1259       AllocInst->replaceAllUsesWith(Builder.getFalse());
1260       AllocInst->eraseFromParent();
1261       CoroBegin->replaceAllUsesWith(VFrame);
1262     } else {
1263       CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
1264     }
1265     break;
1266   }
1267   case coro::ABI::Async:
1268   case coro::ABI::Retcon:
1269   case coro::ABI::RetconOnce:
1270     CoroBegin->replaceAllUsesWith(UndefValue::get(CoroBegin->getType()));
1271     break;
1272   }
1273 
1274   CoroBegin->eraseFromParent();
1275 }
1276 
1277 // SimplifySuspendPoint needs to check that there is no calls between
1278 // coro_save and coro_suspend, since any of the calls may potentially resume
1279 // the coroutine and if that is the case we cannot eliminate the suspend point.
1280 static bool hasCallsInBlockBetween(Instruction *From, Instruction *To) {
1281   for (Instruction *I = From; I != To; I = I->getNextNode()) {
1282     // Assume that no intrinsic can resume the coroutine.
1283     if (isa<IntrinsicInst>(I))
1284       continue;
1285 
1286     if (isa<CallBase>(I))
1287       return true;
1288   }
1289   return false;
1290 }
1291 
1292 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) {
1293   SmallPtrSet<BasicBlock *, 8> Set;
1294   SmallVector<BasicBlock *, 8> Worklist;
1295 
1296   Set.insert(SaveBB);
1297   Worklist.push_back(ResDesBB);
1298 
1299   // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr
1300   // returns a token consumed by suspend instruction, all blocks in between
1301   // will have to eventually hit SaveBB when going backwards from ResDesBB.
1302   while (!Worklist.empty()) {
1303     auto *BB = Worklist.pop_back_val();
1304     Set.insert(BB);
1305     for (auto *Pred : predecessors(BB))
1306       if (Set.count(Pred) == 0)
1307         Worklist.push_back(Pred);
1308   }
1309 
1310   // SaveBB and ResDesBB are checked separately in hasCallsBetween.
1311   Set.erase(SaveBB);
1312   Set.erase(ResDesBB);
1313 
1314   for (auto *BB : Set)
1315     if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr))
1316       return true;
1317 
1318   return false;
1319 }
1320 
1321 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) {
1322   auto *SaveBB = Save->getParent();
1323   auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent();
1324 
1325   if (SaveBB == ResumeOrDestroyBB)
1326     return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy);
1327 
1328   // Any calls from Save to the end of the block?
1329   if (hasCallsInBlockBetween(Save->getNextNode(), nullptr))
1330     return true;
1331 
1332   // Any calls from begging of the block up to ResumeOrDestroy?
1333   if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(),
1334                              ResumeOrDestroy))
1335     return true;
1336 
1337   // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB?
1338   if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB))
1339     return true;
1340 
1341   return false;
1342 }
1343 
1344 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the
1345 // suspend point and replace it with nornal control flow.
1346 static bool simplifySuspendPoint(CoroSuspendInst *Suspend,
1347                                  CoroBeginInst *CoroBegin) {
1348   Instruction *Prev = Suspend->getPrevNode();
1349   if (!Prev) {
1350     auto *Pred = Suspend->getParent()->getSinglePredecessor();
1351     if (!Pred)
1352       return false;
1353     Prev = Pred->getTerminator();
1354   }
1355 
1356   CallBase *CB = dyn_cast<CallBase>(Prev);
1357   if (!CB)
1358     return false;
1359 
1360   auto *Callee = CB->getCalledOperand()->stripPointerCasts();
1361 
1362   // See if the callsite is for resumption or destruction of the coroutine.
1363   auto *SubFn = dyn_cast<CoroSubFnInst>(Callee);
1364   if (!SubFn)
1365     return false;
1366 
1367   // Does not refer to the current coroutine, we cannot do anything with it.
1368   if (SubFn->getFrame() != CoroBegin)
1369     return false;
1370 
1371   // See if the transformation is safe. Specifically, see if there are any
1372   // calls in between Save and CallInstr. They can potenitally resume the
1373   // coroutine rendering this optimization unsafe.
1374   auto *Save = Suspend->getCoroSave();
1375   if (hasCallsBetween(Save, CB))
1376     return false;
1377 
1378   // Replace llvm.coro.suspend with the value that results in resumption over
1379   // the resume or cleanup path.
1380   Suspend->replaceAllUsesWith(SubFn->getRawIndex());
1381   Suspend->eraseFromParent();
1382   Save->eraseFromParent();
1383 
1384   // No longer need a call to coro.resume or coro.destroy.
1385   if (auto *Invoke = dyn_cast<InvokeInst>(CB)) {
1386     BranchInst::Create(Invoke->getNormalDest(), Invoke);
1387   }
1388 
1389   // Grab the CalledValue from CB before erasing the CallInstr.
1390   auto *CalledValue = CB->getCalledOperand();
1391   CB->eraseFromParent();
1392 
1393   // If no more users remove it. Usually it is a bitcast of SubFn.
1394   if (CalledValue != SubFn && CalledValue->user_empty())
1395     if (auto *I = dyn_cast<Instruction>(CalledValue))
1396       I->eraseFromParent();
1397 
1398   // Now we are good to remove SubFn.
1399   if (SubFn->user_empty())
1400     SubFn->eraseFromParent();
1401 
1402   return true;
1403 }
1404 
1405 // Remove suspend points that are simplified.
1406 static void simplifySuspendPoints(coro::Shape &Shape) {
1407   // Currently, the only simplification we do is switch-lowering-specific.
1408   if (Shape.ABI != coro::ABI::Switch)
1409     return;
1410 
1411   auto &S = Shape.CoroSuspends;
1412   size_t I = 0, N = S.size();
1413   if (N == 0)
1414     return;
1415   while (true) {
1416     auto SI = cast<CoroSuspendInst>(S[I]);
1417     // Leave final.suspend to handleFinalSuspend since it is undefined behavior
1418     // to resume a coroutine suspended at the final suspend point.
1419     if (!SI->isFinal() && simplifySuspendPoint(SI, Shape.CoroBegin)) {
1420       if (--N == I)
1421         break;
1422       std::swap(S[I], S[N]);
1423       continue;
1424     }
1425     if (++I == N)
1426       break;
1427   }
1428   S.resize(N);
1429 }
1430 
1431 static void splitSwitchCoroutine(Function &F, coro::Shape &Shape,
1432                                  SmallVectorImpl<Function *> &Clones) {
1433   assert(Shape.ABI == coro::ABI::Switch);
1434 
1435   createResumeEntryBlock(F, Shape);
1436   auto ResumeClone = createClone(F, ".resume", Shape,
1437                                  CoroCloner::Kind::SwitchResume);
1438   auto DestroyClone = createClone(F, ".destroy", Shape,
1439                                   CoroCloner::Kind::SwitchUnwind);
1440   auto CleanupClone = createClone(F, ".cleanup", Shape,
1441                                   CoroCloner::Kind::SwitchCleanup);
1442 
1443   postSplitCleanup(*ResumeClone);
1444   postSplitCleanup(*DestroyClone);
1445   postSplitCleanup(*CleanupClone);
1446 
1447   addMustTailToCoroResumes(*ResumeClone);
1448 
1449   // Store addresses resume/destroy/cleanup functions in the coroutine frame.
1450   updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone);
1451 
1452   assert(Clones.empty());
1453   Clones.push_back(ResumeClone);
1454   Clones.push_back(DestroyClone);
1455   Clones.push_back(CleanupClone);
1456 
1457   // Create a constant array referring to resume/destroy/clone functions pointed
1458   // by the last argument of @llvm.coro.info, so that CoroElide pass can
1459   // determined correct function to call.
1460   setCoroInfo(F, Shape, Clones);
1461 }
1462 
1463 static void replaceAsyncResumeFunction(CoroSuspendAsyncInst *Suspend,
1464                                        Value *Continuation) {
1465   auto *ResumeIntrinsic = Suspend->getResumeFunction();
1466   auto &Context = Suspend->getParent()->getParent()->getContext();
1467   auto *Int8PtrTy = Type::getInt8PtrTy(Context);
1468 
1469   IRBuilder<> Builder(ResumeIntrinsic);
1470   auto *Val = Builder.CreateBitOrPointerCast(Continuation, Int8PtrTy);
1471   ResumeIntrinsic->replaceAllUsesWith(Val);
1472   ResumeIntrinsic->eraseFromParent();
1473   Suspend->setOperand(CoroSuspendAsyncInst::ResumeFunctionArg,
1474                       UndefValue::get(Int8PtrTy));
1475 }
1476 
1477 /// Coerce the arguments in \p FnArgs according to \p FnTy in \p CallArgs.
1478 static void coerceArguments(IRBuilder<> &Builder, FunctionType *FnTy,
1479                             ArrayRef<Value *> FnArgs,
1480                             SmallVectorImpl<Value *> &CallArgs) {
1481   size_t ArgIdx = 0;
1482   for (auto paramTy : FnTy->params()) {
1483     assert(ArgIdx < FnArgs.size());
1484     if (paramTy != FnArgs[ArgIdx]->getType())
1485       CallArgs.push_back(
1486           Builder.CreateBitOrPointerCast(FnArgs[ArgIdx], paramTy));
1487     else
1488       CallArgs.push_back(FnArgs[ArgIdx]);
1489     ++ArgIdx;
1490   }
1491 }
1492 
1493 CallInst *coro::createMustTailCall(DebugLoc Loc, Function *MustTailCallFn,
1494                                    ArrayRef<Value *> Arguments,
1495                                    IRBuilder<> &Builder) {
1496   auto *FnTy =
1497       cast<FunctionType>(MustTailCallFn->getType()->getPointerElementType());
1498   // Coerce the arguments, llvm optimizations seem to ignore the types in
1499   // vaarg functions and throws away casts in optimized mode.
1500   SmallVector<Value *, 8> CallArgs;
1501   coerceArguments(Builder, FnTy, Arguments, CallArgs);
1502 
1503   auto *TailCall = Builder.CreateCall(FnTy, MustTailCallFn, CallArgs);
1504   TailCall->setTailCallKind(CallInst::TCK_MustTail);
1505   TailCall->setDebugLoc(Loc);
1506   TailCall->setCallingConv(MustTailCallFn->getCallingConv());
1507   return TailCall;
1508 }
1509 
1510 static void splitAsyncCoroutine(Function &F, coro::Shape &Shape,
1511                                 SmallVectorImpl<Function *> &Clones) {
1512   assert(Shape.ABI == coro::ABI::Async);
1513   assert(Clones.empty());
1514   // Reset various things that the optimizer might have decided it
1515   // "knows" about the coroutine function due to not seeing a return.
1516   F.removeFnAttr(Attribute::NoReturn);
1517   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1518   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1519 
1520   auto &Context = F.getContext();
1521   auto *Int8PtrTy = Type::getInt8PtrTy(Context);
1522 
1523   auto *Id = cast<CoroIdAsyncInst>(Shape.CoroBegin->getId());
1524   IRBuilder<> Builder(Id);
1525 
1526   auto *FramePtr = Id->getStorage();
1527   FramePtr = Builder.CreateBitOrPointerCast(FramePtr, Int8PtrTy);
1528   FramePtr = Builder.CreateConstInBoundsGEP1_32(
1529       Type::getInt8Ty(Context), FramePtr, Shape.AsyncLowering.FrameOffset,
1530       "async.ctx.frameptr");
1531 
1532   // Map all uses of llvm.coro.begin to the allocated frame pointer.
1533   {
1534     // Make sure we don't invalidate Shape.FramePtr.
1535     TrackingVH<Instruction> Handle(Shape.FramePtr);
1536     Shape.CoroBegin->replaceAllUsesWith(FramePtr);
1537     Shape.FramePtr = Handle.getValPtr();
1538   }
1539 
1540   // Create all the functions in order after the main function.
1541   auto NextF = std::next(F.getIterator());
1542 
1543   // Create a continuation function for each of the suspend points.
1544   Clones.reserve(Shape.CoroSuspends.size());
1545   for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) {
1546     auto *Suspend = cast<CoroSuspendAsyncInst>(Shape.CoroSuspends[Idx]);
1547 
1548     // Create the clone declaration.
1549     auto *Continuation = createCloneDeclaration(
1550         F, Shape, ".resume." + Twine(Idx), NextF, Suspend);
1551     Clones.push_back(Continuation);
1552 
1553     // Insert a branch to a new return block immediately before the suspend
1554     // point.
1555     auto *SuspendBB = Suspend->getParent();
1556     auto *NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1557     auto *Branch = cast<BranchInst>(SuspendBB->getTerminator());
1558 
1559     // Place it before the first suspend.
1560     auto *ReturnBB =
1561         BasicBlock::Create(F.getContext(), "coro.return", &F, NewSuspendBB);
1562     Branch->setSuccessor(0, ReturnBB);
1563 
1564     IRBuilder<> Builder(ReturnBB);
1565 
1566     // Insert the call to the tail call function and inline it.
1567     auto *Fn = Suspend->getMustTailCallFunction();
1568     SmallVector<Value *, 8> Args(Suspend->args());
1569     auto FnArgs = ArrayRef<Value *>(Args).drop_front(
1570         CoroSuspendAsyncInst::MustTailCallFuncArg + 1);
1571     auto *TailCall =
1572         coro::createMustTailCall(Suspend->getDebugLoc(), Fn, FnArgs, Builder);
1573     Builder.CreateRetVoid();
1574     InlineFunctionInfo FnInfo;
1575     auto InlineRes = InlineFunction(*TailCall, FnInfo);
1576     assert(InlineRes.isSuccess() && "Expected inlining to succeed");
1577     (void)InlineRes;
1578 
1579     // Replace the lvm.coro.async.resume intrisic call.
1580     replaceAsyncResumeFunction(Suspend, Continuation);
1581   }
1582 
1583   assert(Clones.size() == Shape.CoroSuspends.size());
1584   for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) {
1585     auto *Suspend = Shape.CoroSuspends[Idx];
1586     auto *Clone = Clones[Idx];
1587 
1588     CoroCloner(F, "resume." + Twine(Idx), Shape, Clone, Suspend).create();
1589   }
1590 }
1591 
1592 static void splitRetconCoroutine(Function &F, coro::Shape &Shape,
1593                                  SmallVectorImpl<Function *> &Clones) {
1594   assert(Shape.ABI == coro::ABI::Retcon ||
1595          Shape.ABI == coro::ABI::RetconOnce);
1596   assert(Clones.empty());
1597 
1598   // Reset various things that the optimizer might have decided it
1599   // "knows" about the coroutine function due to not seeing a return.
1600   F.removeFnAttr(Attribute::NoReturn);
1601   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1602   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1603 
1604   // Allocate the frame.
1605   auto *Id = cast<AnyCoroIdRetconInst>(Shape.CoroBegin->getId());
1606   Value *RawFramePtr;
1607   if (Shape.RetconLowering.IsFrameInlineInStorage) {
1608     RawFramePtr = Id->getStorage();
1609   } else {
1610     IRBuilder<> Builder(Id);
1611 
1612     // Determine the size of the frame.
1613     const DataLayout &DL = F.getParent()->getDataLayout();
1614     auto Size = DL.getTypeAllocSize(Shape.FrameTy);
1615 
1616     // Allocate.  We don't need to update the call graph node because we're
1617     // going to recompute it from scratch after splitting.
1618     // FIXME: pass the required alignment
1619     RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr);
1620     RawFramePtr =
1621       Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType());
1622 
1623     // Stash the allocated frame pointer in the continuation storage.
1624     auto Dest = Builder.CreateBitCast(Id->getStorage(),
1625                                       RawFramePtr->getType()->getPointerTo());
1626     Builder.CreateStore(RawFramePtr, Dest);
1627   }
1628 
1629   // Map all uses of llvm.coro.begin to the allocated frame pointer.
1630   {
1631     // Make sure we don't invalidate Shape.FramePtr.
1632     TrackingVH<Instruction> Handle(Shape.FramePtr);
1633     Shape.CoroBegin->replaceAllUsesWith(RawFramePtr);
1634     Shape.FramePtr = Handle.getValPtr();
1635   }
1636 
1637   // Create a unique return block.
1638   BasicBlock *ReturnBB = nullptr;
1639   SmallVector<PHINode *, 4> ReturnPHIs;
1640 
1641   // Create all the functions in order after the main function.
1642   auto NextF = std::next(F.getIterator());
1643 
1644   // Create a continuation function for each of the suspend points.
1645   Clones.reserve(Shape.CoroSuspends.size());
1646   for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) {
1647     auto Suspend = cast<CoroSuspendRetconInst>(Shape.CoroSuspends[i]);
1648 
1649     // Create the clone declaration.
1650     auto Continuation =
1651         createCloneDeclaration(F, Shape, ".resume." + Twine(i), NextF, nullptr);
1652     Clones.push_back(Continuation);
1653 
1654     // Insert a branch to the unified return block immediately before
1655     // the suspend point.
1656     auto SuspendBB = Suspend->getParent();
1657     auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1658     auto Branch = cast<BranchInst>(SuspendBB->getTerminator());
1659 
1660     // Create the unified return block.
1661     if (!ReturnBB) {
1662       // Place it before the first suspend.
1663       ReturnBB = BasicBlock::Create(F.getContext(), "coro.return", &F,
1664                                     NewSuspendBB);
1665       Shape.RetconLowering.ReturnBlock = ReturnBB;
1666 
1667       IRBuilder<> Builder(ReturnBB);
1668 
1669       // Create PHIs for all the return values.
1670       assert(ReturnPHIs.empty());
1671 
1672       // First, the continuation.
1673       ReturnPHIs.push_back(Builder.CreatePHI(Continuation->getType(),
1674                                              Shape.CoroSuspends.size()));
1675 
1676       // Next, all the directly-yielded values.
1677       for (auto ResultTy : Shape.getRetconResultTypes())
1678         ReturnPHIs.push_back(Builder.CreatePHI(ResultTy,
1679                                                Shape.CoroSuspends.size()));
1680 
1681       // Build the return value.
1682       auto RetTy = F.getReturnType();
1683 
1684       // Cast the continuation value if necessary.
1685       // We can't rely on the types matching up because that type would
1686       // have to be infinite.
1687       auto CastedContinuationTy =
1688         (ReturnPHIs.size() == 1 ? RetTy : RetTy->getStructElementType(0));
1689       auto *CastedContinuation =
1690         Builder.CreateBitCast(ReturnPHIs[0], CastedContinuationTy);
1691 
1692       Value *RetV;
1693       if (ReturnPHIs.size() == 1) {
1694         RetV = CastedContinuation;
1695       } else {
1696         RetV = UndefValue::get(RetTy);
1697         RetV = Builder.CreateInsertValue(RetV, CastedContinuation, 0);
1698         for (size_t I = 1, E = ReturnPHIs.size(); I != E; ++I)
1699           RetV = Builder.CreateInsertValue(RetV, ReturnPHIs[I], I);
1700       }
1701 
1702       Builder.CreateRet(RetV);
1703     }
1704 
1705     // Branch to the return block.
1706     Branch->setSuccessor(0, ReturnBB);
1707     ReturnPHIs[0]->addIncoming(Continuation, SuspendBB);
1708     size_t NextPHIIndex = 1;
1709     for (auto &VUse : Suspend->value_operands())
1710       ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB);
1711     assert(NextPHIIndex == ReturnPHIs.size());
1712   }
1713 
1714   assert(Clones.size() == Shape.CoroSuspends.size());
1715   for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) {
1716     auto Suspend = Shape.CoroSuspends[i];
1717     auto Clone = Clones[i];
1718 
1719     CoroCloner(F, "resume." + Twine(i), Shape, Clone, Suspend).create();
1720   }
1721 }
1722 
1723 namespace {
1724   class PrettyStackTraceFunction : public PrettyStackTraceEntry {
1725     Function &F;
1726   public:
1727     PrettyStackTraceFunction(Function &F) : F(F) {}
1728     void print(raw_ostream &OS) const override {
1729       OS << "While splitting coroutine ";
1730       F.printAsOperand(OS, /*print type*/ false, F.getParent());
1731       OS << "\n";
1732     }
1733   };
1734 }
1735 
1736 static coro::Shape splitCoroutine(Function &F,
1737                                   SmallVectorImpl<Function *> &Clones,
1738                                   bool ReuseFrameSlot) {
1739   PrettyStackTraceFunction prettyStackTrace(F);
1740 
1741   // The suspend-crossing algorithm in buildCoroutineFrame get tripped
1742   // up by uses in unreachable blocks, so remove them as a first pass.
1743   removeUnreachableBlocks(F);
1744 
1745   coro::Shape Shape(F, ReuseFrameSlot);
1746   if (!Shape.CoroBegin)
1747     return Shape;
1748 
1749   simplifySuspendPoints(Shape);
1750   buildCoroutineFrame(F, Shape);
1751   replaceFrameSize(Shape);
1752 
1753   // If there are no suspend points, no split required, just remove
1754   // the allocation and deallocation blocks, they are not needed.
1755   if (Shape.CoroSuspends.empty()) {
1756     handleNoSuspendCoroutine(Shape);
1757   } else {
1758     switch (Shape.ABI) {
1759     case coro::ABI::Switch:
1760       splitSwitchCoroutine(F, Shape, Clones);
1761       break;
1762     case coro::ABI::Async:
1763       splitAsyncCoroutine(F, Shape, Clones);
1764       break;
1765     case coro::ABI::Retcon:
1766     case coro::ABI::RetconOnce:
1767       splitRetconCoroutine(F, Shape, Clones);
1768       break;
1769     }
1770   }
1771 
1772   // Replace all the swifterror operations in the original function.
1773   // This invalidates SwiftErrorOps in the Shape.
1774   replaceSwiftErrorOps(F, Shape, nullptr);
1775 
1776   return Shape;
1777 }
1778 
1779 static void
1780 updateCallGraphAfterCoroutineSplit(Function &F, const coro::Shape &Shape,
1781                                    const SmallVectorImpl<Function *> &Clones,
1782                                    CallGraph &CG, CallGraphSCC &SCC) {
1783   if (!Shape.CoroBegin)
1784     return;
1785 
1786   removeCoroEnds(Shape, &CG);
1787   postSplitCleanup(F);
1788 
1789   // Update call graph and add the functions we created to the SCC.
1790   coro::updateCallGraph(F, Clones, CG, SCC);
1791 }
1792 
1793 static void updateCallGraphAfterCoroutineSplit(
1794     LazyCallGraph::Node &N, const coro::Shape &Shape,
1795     const SmallVectorImpl<Function *> &Clones, LazyCallGraph::SCC &C,
1796     LazyCallGraph &CG, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1797     FunctionAnalysisManager &FAM) {
1798   if (!Shape.CoroBegin)
1799     return;
1800 
1801   for (llvm::AnyCoroEndInst *End : Shape.CoroEnds) {
1802     auto &Context = End->getContext();
1803     End->replaceAllUsesWith(ConstantInt::getFalse(Context));
1804     End->eraseFromParent();
1805   }
1806 
1807   if (!Clones.empty()) {
1808     switch (Shape.ABI) {
1809     case coro::ABI::Switch:
1810       // Each clone in the Switch lowering is independent of the other clones.
1811       // Let the LazyCallGraph know about each one separately.
1812       for (Function *Clone : Clones)
1813         CG.addSplitFunction(N.getFunction(), *Clone);
1814       break;
1815     case coro::ABI::Async:
1816     case coro::ABI::Retcon:
1817     case coro::ABI::RetconOnce:
1818       // Each clone in the Async/Retcon lowering references of the other clones.
1819       // Let the LazyCallGraph know about all of them at once.
1820       if (!Clones.empty())
1821         CG.addSplitRefRecursiveFunctions(N.getFunction(), Clones);
1822       break;
1823     }
1824 
1825     // Let the CGSCC infra handle the changes to the original function.
1826     updateCGAndAnalysisManagerForCGSCCPass(CG, C, N, AM, UR, FAM);
1827   }
1828 
1829   // Do some cleanup and let the CGSCC infra see if we've cleaned up any edges
1830   // to the split functions.
1831   postSplitCleanup(N.getFunction());
1832   updateCGAndAnalysisManagerForFunctionPass(CG, C, N, AM, UR, FAM);
1833 }
1834 
1835 // When we see the coroutine the first time, we insert an indirect call to a
1836 // devirt trigger function and mark the coroutine that it is now ready for
1837 // split.
1838 // Async lowering uses this after it has split the function to restart the
1839 // pipeline.
1840 static void prepareForSplit(Function &F, CallGraph &CG,
1841                             bool MarkForAsyncRestart = false) {
1842   Module &M = *F.getParent();
1843   LLVMContext &Context = F.getContext();
1844 #ifndef NDEBUG
1845   Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN);
1846   assert(DevirtFn && "coro.devirt.trigger function not found");
1847 #endif
1848 
1849   F.addFnAttr(CORO_PRESPLIT_ATTR, MarkForAsyncRestart
1850                                       ? ASYNC_RESTART_AFTER_SPLIT
1851                                       : PREPARED_FOR_SPLIT);
1852 
1853   // Insert an indirect call sequence that will be devirtualized by CoroElide
1854   // pass:
1855   //    %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1)
1856   //    %1 = bitcast i8* %0 to void(i8*)*
1857   //    call void %1(i8* null)
1858   coro::LowererBase Lowerer(M);
1859   Instruction *InsertPt =
1860       MarkForAsyncRestart ? F.getEntryBlock().getFirstNonPHIOrDbgOrLifetime()
1861                           : F.getEntryBlock().getTerminator();
1862   auto *Null = ConstantPointerNull::get(Type::getInt8PtrTy(Context));
1863   auto *DevirtFnAddr =
1864       Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt);
1865   FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Context),
1866                                          {Type::getInt8PtrTy(Context)}, false);
1867   auto *IndirectCall = CallInst::Create(FnTy, DevirtFnAddr, Null, "", InsertPt);
1868 
1869   // Update CG graph with an indirect call we just added.
1870   CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode());
1871 }
1872 
1873 // Make sure that there is a devirtualization trigger function that the
1874 // coro-split pass uses to force a restart of the CGSCC pipeline. If the devirt
1875 // trigger function is not found, we will create one and add it to the current
1876 // SCC.
1877 static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC) {
1878   Module &M = CG.getModule();
1879   if (M.getFunction(CORO_DEVIRT_TRIGGER_FN))
1880     return;
1881 
1882   LLVMContext &C = M.getContext();
1883   auto *FnTy = FunctionType::get(Type::getVoidTy(C), Type::getInt8PtrTy(C),
1884                                  /*isVarArg=*/false);
1885   Function *DevirtFn =
1886       Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage,
1887                        CORO_DEVIRT_TRIGGER_FN, &M);
1888   DevirtFn->addFnAttr(Attribute::AlwaysInline);
1889   auto *Entry = BasicBlock::Create(C, "entry", DevirtFn);
1890   ReturnInst::Create(C, Entry);
1891 
1892   auto *Node = CG.getOrInsertFunction(DevirtFn);
1893 
1894   SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end());
1895   Nodes.push_back(Node);
1896   SCC.initialize(Nodes);
1897 }
1898 
1899 /// Replace a call to llvm.coro.prepare.retcon.
1900 static void replacePrepare(CallInst *Prepare, LazyCallGraph &CG,
1901                            LazyCallGraph::SCC &C) {
1902   auto CastFn = Prepare->getArgOperand(0); // as an i8*
1903   auto Fn = CastFn->stripPointerCasts();   // as its original type
1904 
1905   // Attempt to peephole this pattern:
1906   //    %0 = bitcast [[TYPE]] @some_function to i8*
1907   //    %1 = call @llvm.coro.prepare.retcon(i8* %0)
1908   //    %2 = bitcast %1 to [[TYPE]]
1909   // ==>
1910   //    %2 = @some_function
1911   for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); UI != UE;) {
1912     // Look for bitcasts back to the original function type.
1913     auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser());
1914     if (!Cast || Cast->getType() != Fn->getType())
1915       continue;
1916 
1917     // Replace and remove the cast.
1918     Cast->replaceAllUsesWith(Fn);
1919     Cast->eraseFromParent();
1920   }
1921 
1922   // Replace any remaining uses with the function as an i8*.
1923   // This can never directly be a callee, so we don't need to update CG.
1924   Prepare->replaceAllUsesWith(CastFn);
1925   Prepare->eraseFromParent();
1926 
1927   // Kill dead bitcasts.
1928   while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
1929     if (!Cast->use_empty())
1930       break;
1931     CastFn = Cast->getOperand(0);
1932     Cast->eraseFromParent();
1933   }
1934 }
1935 /// Replace a call to llvm.coro.prepare.retcon.
1936 static void replacePrepare(CallInst *Prepare, CallGraph &CG) {
1937   auto CastFn = Prepare->getArgOperand(0); // as an i8*
1938   auto Fn = CastFn->stripPointerCasts(); // as its original type
1939 
1940   // Find call graph nodes for the preparation.
1941   CallGraphNode *PrepareUserNode = nullptr, *FnNode = nullptr;
1942   if (auto ConcreteFn = dyn_cast<Function>(Fn)) {
1943     PrepareUserNode = CG[Prepare->getFunction()];
1944     FnNode = CG[ConcreteFn];
1945   }
1946 
1947   // Attempt to peephole this pattern:
1948   //    %0 = bitcast [[TYPE]] @some_function to i8*
1949   //    %1 = call @llvm.coro.prepare.retcon(i8* %0)
1950   //    %2 = bitcast %1 to [[TYPE]]
1951   // ==>
1952   //    %2 = @some_function
1953   for (auto UI = Prepare->use_begin(), UE = Prepare->use_end();
1954          UI != UE; ) {
1955     // Look for bitcasts back to the original function type.
1956     auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser());
1957     if (!Cast || Cast->getType() != Fn->getType()) continue;
1958 
1959     // Check whether the replacement will introduce new direct calls.
1960     // If so, we'll need to update the call graph.
1961     if (PrepareUserNode) {
1962       for (auto &Use : Cast->uses()) {
1963         if (auto *CB = dyn_cast<CallBase>(Use.getUser())) {
1964           if (!CB->isCallee(&Use))
1965             continue;
1966           PrepareUserNode->removeCallEdgeFor(*CB);
1967           PrepareUserNode->addCalledFunction(CB, FnNode);
1968         }
1969       }
1970     }
1971 
1972     // Replace and remove the cast.
1973     Cast->replaceAllUsesWith(Fn);
1974     Cast->eraseFromParent();
1975   }
1976 
1977   // Replace any remaining uses with the function as an i8*.
1978   // This can never directly be a callee, so we don't need to update CG.
1979   Prepare->replaceAllUsesWith(CastFn);
1980   Prepare->eraseFromParent();
1981 
1982   // Kill dead bitcasts.
1983   while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
1984     if (!Cast->use_empty()) break;
1985     CastFn = Cast->getOperand(0);
1986     Cast->eraseFromParent();
1987   }
1988 }
1989 
1990 static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG,
1991                                LazyCallGraph::SCC &C) {
1992   bool Changed = false;
1993   for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); PI != PE;) {
1994     // Intrinsics can only be used in calls.
1995     auto *Prepare = cast<CallInst>((PI++)->getUser());
1996     replacePrepare(Prepare, CG, C);
1997     Changed = true;
1998   }
1999 
2000   return Changed;
2001 }
2002 
2003 /// Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent
2004 /// IPO from operating on calls to a retcon coroutine before it's been
2005 /// split.  This is only safe to do after we've split all retcon
2006 /// coroutines in the module.  We can do that this in this pass because
2007 /// this pass does promise to split all retcon coroutines (as opposed to
2008 /// switch coroutines, which are lowered in multiple stages).
2009 static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG) {
2010   bool Changed = false;
2011   for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end();
2012          PI != PE; ) {
2013     // Intrinsics can only be used in calls.
2014     auto *Prepare = cast<CallInst>((PI++)->getUser());
2015     replacePrepare(Prepare, CG);
2016     Changed = true;
2017   }
2018 
2019   return Changed;
2020 }
2021 
2022 static bool declaresCoroSplitIntrinsics(const Module &M) {
2023   return coro::declaresIntrinsics(M, {"llvm.coro.begin",
2024                                       "llvm.coro.prepare.retcon",
2025                                       "llvm.coro.prepare.async"});
2026 }
2027 
2028 static void addPrepareFunction(const Module &M,
2029                                SmallVectorImpl<Function *> &Fns,
2030                                StringRef Name) {
2031   auto *PrepareFn = M.getFunction(Name);
2032   if (PrepareFn && !PrepareFn->use_empty())
2033     Fns.push_back(PrepareFn);
2034 }
2035 
2036 PreservedAnalyses CoroSplitPass::run(LazyCallGraph::SCC &C,
2037                                      CGSCCAnalysisManager &AM,
2038                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
2039   // NB: One invariant of a valid LazyCallGraph::SCC is that it must contain a
2040   //     non-zero number of nodes, so we assume that here and grab the first
2041   //     node's function's module.
2042   Module &M = *C.begin()->getFunction().getParent();
2043   auto &FAM =
2044       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2045 
2046   if (!declaresCoroSplitIntrinsics(M))
2047     return PreservedAnalyses::all();
2048 
2049   // Check for uses of llvm.coro.prepare.retcon/async.
2050   SmallVector<Function *, 2> PrepareFns;
2051   addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon");
2052   addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async");
2053 
2054   // Find coroutines for processing.
2055   SmallVector<LazyCallGraph::Node *, 4> Coroutines;
2056   for (LazyCallGraph::Node &N : C)
2057     if (N.getFunction().hasFnAttribute(CORO_PRESPLIT_ATTR))
2058       Coroutines.push_back(&N);
2059 
2060   if (Coroutines.empty() && PrepareFns.empty())
2061     return PreservedAnalyses::all();
2062 
2063   if (Coroutines.empty()) {
2064     for (auto *PrepareFn : PrepareFns) {
2065       replaceAllPrepares(PrepareFn, CG, C);
2066     }
2067   }
2068 
2069   // Split all the coroutines.
2070   for (LazyCallGraph::Node *N : Coroutines) {
2071     Function &F = N->getFunction();
2072     Attribute Attr = F.getFnAttribute(CORO_PRESPLIT_ATTR);
2073     StringRef Value = Attr.getValueAsString();
2074     LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F.getName()
2075                       << "' state: " << Value << "\n");
2076     if (Value == UNPREPARED_FOR_SPLIT) {
2077       // Enqueue a second iteration of the CGSCC pipeline on this SCC.
2078       UR.CWorklist.insert(&C);
2079       F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT);
2080       continue;
2081     }
2082     F.removeFnAttr(CORO_PRESPLIT_ATTR);
2083 
2084     SmallVector<Function *, 4> Clones;
2085     const coro::Shape Shape = splitCoroutine(F, Clones, ReuseFrameSlot);
2086     updateCallGraphAfterCoroutineSplit(*N, Shape, Clones, C, CG, AM, UR, FAM);
2087 
2088     if ((Shape.ABI == coro::ABI::Async || Shape.ABI == coro::ABI::Retcon ||
2089          Shape.ABI == coro::ABI::RetconOnce) &&
2090         !Shape.CoroSuspends.empty()) {
2091       // Run the CGSCC pipeline on the newly split functions.
2092       // All clones will be in the same RefSCC, so choose a random clone.
2093       UR.RCWorklist.insert(CG.lookupRefSCC(CG.get(*Clones[0])));
2094     }
2095   }
2096 
2097   if (!PrepareFns.empty()) {
2098     for (auto *PrepareFn : PrepareFns) {
2099       replaceAllPrepares(PrepareFn, CG, C);
2100     }
2101   }
2102 
2103   return PreservedAnalyses::none();
2104 }
2105 
2106 namespace {
2107 
2108 // We present a coroutine to LLVM as an ordinary function with suspension
2109 // points marked up with intrinsics. We let the optimizer party on the coroutine
2110 // as a single function for as long as possible. Shortly before the coroutine is
2111 // eligible to be inlined into its callers, we split up the coroutine into parts
2112 // corresponding to initial, resume and destroy invocations of the coroutine,
2113 // add them to the current SCC and restart the IPO pipeline to optimize the
2114 // coroutine subfunctions we extracted before proceeding to the caller of the
2115 // coroutine.
2116 struct CoroSplitLegacy : public CallGraphSCCPass {
2117   static char ID; // Pass identification, replacement for typeid
2118 
2119   CoroSplitLegacy(bool ReuseFrameSlot = false)
2120       : CallGraphSCCPass(ID), ReuseFrameSlot(ReuseFrameSlot) {
2121     initializeCoroSplitLegacyPass(*PassRegistry::getPassRegistry());
2122   }
2123 
2124   bool Run = false;
2125   bool ReuseFrameSlot;
2126 
2127   // A coroutine is identified by the presence of coro.begin intrinsic, if
2128   // we don't have any, this pass has nothing to do.
2129   bool doInitialization(CallGraph &CG) override {
2130     Run = declaresCoroSplitIntrinsics(CG.getModule());
2131     return CallGraphSCCPass::doInitialization(CG);
2132   }
2133 
2134   bool runOnSCC(CallGraphSCC &SCC) override {
2135     if (!Run)
2136       return false;
2137 
2138     // Check for uses of llvm.coro.prepare.retcon.
2139     SmallVector<Function *, 2> PrepareFns;
2140     auto &M = SCC.getCallGraph().getModule();
2141     addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon");
2142     addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async");
2143 
2144     // Find coroutines for processing.
2145     SmallVector<Function *, 4> Coroutines;
2146     for (CallGraphNode *CGN : SCC)
2147       if (auto *F = CGN->getFunction())
2148         if (F->hasFnAttribute(CORO_PRESPLIT_ATTR))
2149           Coroutines.push_back(F);
2150 
2151     if (Coroutines.empty() && PrepareFns.empty())
2152       return false;
2153 
2154     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
2155 
2156     if (Coroutines.empty()) {
2157       bool Changed = false;
2158       for (auto *PrepareFn : PrepareFns)
2159         Changed |= replaceAllPrepares(PrepareFn, CG);
2160       return Changed;
2161     }
2162 
2163     createDevirtTriggerFunc(CG, SCC);
2164 
2165     // Split all the coroutines.
2166     for (Function *F : Coroutines) {
2167       Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR);
2168       StringRef Value = Attr.getValueAsString();
2169       LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName()
2170                         << "' state: " << Value << "\n");
2171       // Async lowering marks coroutines to trigger a restart of the pipeline
2172       // after it has split them.
2173       if (Value == ASYNC_RESTART_AFTER_SPLIT) {
2174         F->removeFnAttr(CORO_PRESPLIT_ATTR);
2175         continue;
2176       }
2177       if (Value == UNPREPARED_FOR_SPLIT) {
2178         prepareForSplit(*F, CG);
2179         continue;
2180       }
2181       F->removeFnAttr(CORO_PRESPLIT_ATTR);
2182 
2183       SmallVector<Function *, 4> Clones;
2184       const coro::Shape Shape = splitCoroutine(*F, Clones, ReuseFrameSlot);
2185       updateCallGraphAfterCoroutineSplit(*F, Shape, Clones, CG, SCC);
2186       if (Shape.ABI == coro::ABI::Async) {
2187         // Restart SCC passes.
2188         // Mark function for CoroElide pass. It will devirtualize causing a
2189         // restart of the SCC pipeline.
2190         prepareForSplit(*F, CG, true /*MarkForAsyncRestart*/);
2191       }
2192     }
2193 
2194     for (auto *PrepareFn : PrepareFns)
2195       replaceAllPrepares(PrepareFn, CG);
2196 
2197     return true;
2198   }
2199 
2200   void getAnalysisUsage(AnalysisUsage &AU) const override {
2201     CallGraphSCCPass::getAnalysisUsage(AU);
2202   }
2203 
2204   StringRef getPassName() const override { return "Coroutine Splitting"; }
2205 };
2206 
2207 } // end anonymous namespace
2208 
2209 char CoroSplitLegacy::ID = 0;
2210 
2211 INITIALIZE_PASS_BEGIN(
2212     CoroSplitLegacy, "coro-split",
2213     "Split coroutine into a set of functions driving its state machine", false,
2214     false)
2215 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
2216 INITIALIZE_PASS_END(
2217     CoroSplitLegacy, "coro-split",
2218     "Split coroutine into a set of functions driving its state machine", false,
2219     false)
2220 
2221 Pass *llvm::createCoroSplitLegacyPass(bool ReuseFrameSlot) {
2222   return new CoroSplitLegacy(ReuseFrameSlot);
2223 }
2224