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 *CalleeContext = NewF->getArg(Shape.AsyncLowering.ContextArgNo);
763     auto *FramePtrTy = Shape.FrameTy->getPointerTo();
764     auto *ProjectionFunc = cast<CoroSuspendAsyncInst>(ActiveSuspend)
765                                ->getAsyncContextProjectionFunction();
766     auto DbgLoc =
767         cast<CoroSuspendAsyncInst>(VMap[ActiveSuspend])->getDebugLoc();
768     // Calling i8* (i8*)
769     auto *CallerContext = Builder.CreateCall(
770         cast<FunctionType>(ProjectionFunc->getType()->getPointerElementType()),
771         ProjectionFunc, CalleeContext);
772     CallerContext->setCallingConv(ProjectionFunc->getCallingConv());
773     CallerContext->setDebugLoc(DbgLoc);
774     // The frame is located after the async_context header.
775     auto &Context = Builder.getContext();
776     auto *FramePtrAddr = Builder.CreateConstInBoundsGEP1_32(
777         Type::getInt8Ty(Context), CallerContext,
778         Shape.AsyncLowering.FrameOffset, "async.ctx.frameptr");
779     // Inline the projection function.
780     InlineFunctionInfo InlineInfo;
781     auto InlineRes = InlineFunction(*CallerContext, InlineInfo);
782     assert(InlineRes.isSuccess());
783     (void)InlineRes;
784     return Builder.CreateBitCast(FramePtrAddr, FramePtrTy);
785   }
786   // In continuation-lowering, the argument is the opaque storage.
787   case coro::ABI::Retcon:
788   case coro::ABI::RetconOnce: {
789     Argument *NewStorage = &*NewF->arg_begin();
790     auto FramePtrTy = Shape.FrameTy->getPointerTo();
791 
792     // If the storage is inline, just bitcast to the storage to the frame type.
793     if (Shape.RetconLowering.IsFrameInlineInStorage)
794       return Builder.CreateBitCast(NewStorage, FramePtrTy);
795 
796     // Otherwise, load the real frame from the opaque storage.
797     auto FramePtrPtr =
798       Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo());
799     return Builder.CreateLoad(FramePtrTy, FramePtrPtr);
800   }
801   }
802   llvm_unreachable("bad ABI");
803 }
804 
805 static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context,
806                                  unsigned ParamIndex,
807                                  uint64_t Size, Align Alignment) {
808   AttrBuilder ParamAttrs;
809   ParamAttrs.addAttribute(Attribute::NonNull);
810   ParamAttrs.addAttribute(Attribute::NoAlias);
811   ParamAttrs.addAlignmentAttr(Alignment);
812   ParamAttrs.addDereferenceableAttr(Size);
813   Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
814 }
815 
816 /// Clone the body of the original function into a resume function of
817 /// some sort.
818 void CoroCloner::create() {
819   // Create the new function if we don't already have one.
820   if (!NewF) {
821     NewF = createCloneDeclaration(OrigF, Shape, Suffix,
822                                   OrigF.getParent()->end(), ActiveSuspend);
823   }
824 
825   // Replace all args with undefs. The buildCoroutineFrame algorithm already
826   // rewritten access to the args that occurs after suspend points with loads
827   // and stores to/from the coroutine frame.
828   for (Argument &A : OrigF.args())
829     VMap[&A] = UndefValue::get(A.getType());
830 
831   SmallVector<ReturnInst *, 4> Returns;
832 
833   // Ignore attempts to change certain attributes of the function.
834   // TODO: maybe there should be a way to suppress this during cloning?
835   auto savedVisibility = NewF->getVisibility();
836   auto savedUnnamedAddr = NewF->getUnnamedAddr();
837   auto savedDLLStorageClass = NewF->getDLLStorageClass();
838 
839   // NewF's linkage (which CloneFunctionInto does *not* change) might not
840   // be compatible with the visibility of OrigF (which it *does* change),
841   // so protect against that.
842   auto savedLinkage = NewF->getLinkage();
843   NewF->setLinkage(llvm::GlobalValue::ExternalLinkage);
844 
845   CloneFunctionInto(NewF, &OrigF, VMap,
846                     CloneFunctionChangeType::LocalChangesOnly, Returns);
847 
848   NewF->setLinkage(savedLinkage);
849   NewF->setVisibility(savedVisibility);
850   NewF->setUnnamedAddr(savedUnnamedAddr);
851   NewF->setDLLStorageClass(savedDLLStorageClass);
852 
853   auto &Context = NewF->getContext();
854 
855   // Replace the attributes of the new function:
856   auto OrigAttrs = NewF->getAttributes();
857   auto NewAttrs = AttributeList();
858 
859   switch (Shape.ABI) {
860   case coro::ABI::Switch:
861     // Bootstrap attributes by copying function attributes from the
862     // original function.  This should include optimization settings and so on.
863     NewAttrs = NewAttrs.addAttributes(Context, AttributeList::FunctionIndex,
864                                       OrigAttrs.getFnAttributes());
865 
866     addFramePointerAttrs(NewAttrs, Context, 0,
867                          Shape.FrameSize, Shape.FrameAlign);
868     break;
869   case coro::ABI::Async:
870     break;
871   case coro::ABI::Retcon:
872   case coro::ABI::RetconOnce:
873     // If we have a continuation prototype, just use its attributes,
874     // full-stop.
875     NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes();
876 
877     addFramePointerAttrs(NewAttrs, Context, 0,
878                          Shape.getRetconCoroId()->getStorageSize(),
879                          Shape.getRetconCoroId()->getStorageAlignment());
880     break;
881   }
882 
883   switch (Shape.ABI) {
884   // In these ABIs, the cloned functions always return 'void', and the
885   // existing return sites are meaningless.  Note that for unique
886   // continuations, this includes the returns associated with suspends;
887   // this is fine because we can't suspend twice.
888   case coro::ABI::Switch:
889   case coro::ABI::RetconOnce:
890     // Remove old returns.
891     for (ReturnInst *Return : Returns)
892       changeToUnreachable(Return, /*UseLLVMTrap=*/false);
893     break;
894 
895   // With multi-suspend continuations, we'll already have eliminated the
896   // original returns and inserted returns before all the suspend points,
897   // so we want to leave any returns in place.
898   case coro::ABI::Retcon:
899     break;
900   // Async lowering will insert musttail call functions at all suspend points
901   // followed by a return.
902   // Don't change returns to unreachable because that will trip up the verifier.
903   // These returns should be unreachable from the clone.
904   case coro::ABI::Async:
905     break;
906   }
907 
908   NewF->setAttributes(NewAttrs);
909   NewF->setCallingConv(Shape.getResumeFunctionCC());
910 
911   // Set up the new entry block.
912   replaceEntryBlock();
913 
914   Builder.SetInsertPoint(&NewF->getEntryBlock().front());
915   NewFramePtr = deriveNewFramePointer();
916 
917   // Remap frame pointer.
918   Value *OldFramePtr = VMap[Shape.FramePtr];
919   NewFramePtr->takeName(OldFramePtr);
920   OldFramePtr->replaceAllUsesWith(NewFramePtr);
921 
922   // Remap vFrame pointer.
923   auto *NewVFrame = Builder.CreateBitCast(
924       NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame");
925   Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]);
926   OldVFrame->replaceAllUsesWith(NewVFrame);
927 
928   switch (Shape.ABI) {
929   case coro::ABI::Switch:
930     // Rewrite final suspend handling as it is not done via switch (allows to
931     // remove final case from the switch, since it is undefined behavior to
932     // resume the coroutine suspended at the final suspend point.
933     if (Shape.SwitchLowering.HasFinalSuspend)
934       handleFinalSuspend();
935     break;
936   case coro::ABI::Async:
937   case coro::ABI::Retcon:
938   case coro::ABI::RetconOnce:
939     // Replace uses of the active suspend with the corresponding
940     // continuation-function arguments.
941     assert(ActiveSuspend != nullptr &&
942            "no active suspend when lowering a continuation-style coroutine");
943     replaceRetconOrAsyncSuspendUses();
944     break;
945   }
946 
947   // Handle suspends.
948   replaceCoroSuspends();
949 
950   // Handle swifterror.
951   replaceSwiftErrorOps();
952 
953   // Remove coro.end intrinsics.
954   replaceCoroEnds();
955 
956   // Salvage debug info that points into the coroutine frame.
957   salvageDebugInfo();
958 
959   // Eliminate coro.free from the clones, replacing it with 'null' in cleanup,
960   // to suppress deallocation code.
961   if (Shape.ABI == coro::ABI::Switch)
962     coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]),
963                           /*Elide=*/ FKind == CoroCloner::Kind::SwitchCleanup);
964 }
965 
966 // Create a resume clone by cloning the body of the original function, setting
967 // new entry block and replacing coro.suspend an appropriate value to force
968 // resume or cleanup pass for every suspend point.
969 static Function *createClone(Function &F, const Twine &Suffix,
970                              coro::Shape &Shape, CoroCloner::Kind FKind) {
971   CoroCloner Cloner(F, Suffix, Shape, FKind);
972   Cloner.create();
973   return Cloner.getFunction();
974 }
975 
976 /// Remove calls to llvm.coro.end in the original function.
977 static void removeCoroEnds(const coro::Shape &Shape, CallGraph *CG) {
978   for (auto End : Shape.CoroEnds) {
979     replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, CG);
980   }
981 }
982 
983 static void updateAsyncFuncPointerContextSize(coro::Shape &Shape) {
984   assert(Shape.ABI == coro::ABI::Async);
985 
986   auto *FuncPtrStruct = cast<ConstantStruct>(
987       Shape.AsyncLowering.AsyncFuncPointer->getInitializer());
988   auto *OrigRelativeFunOffset = FuncPtrStruct->getOperand(0);
989   auto *OrigContextSize = FuncPtrStruct->getOperand(1);
990   auto *NewContextSize = ConstantInt::get(OrigContextSize->getType(),
991                                           Shape.AsyncLowering.ContextSize);
992   auto *NewFuncPtrStruct = ConstantStruct::get(
993       FuncPtrStruct->getType(), OrigRelativeFunOffset, NewContextSize);
994 
995   Shape.AsyncLowering.AsyncFuncPointer->setInitializer(NewFuncPtrStruct);
996 }
997 
998 static void replaceFrameSize(coro::Shape &Shape) {
999   if (Shape.ABI == coro::ABI::Async)
1000     updateAsyncFuncPointerContextSize(Shape);
1001 
1002   if (Shape.CoroSizes.empty())
1003     return;
1004 
1005   // In the same function all coro.sizes should have the same result type.
1006   auto *SizeIntrin = Shape.CoroSizes.back();
1007   Module *M = SizeIntrin->getModule();
1008   const DataLayout &DL = M->getDataLayout();
1009   auto Size = DL.getTypeAllocSize(Shape.FrameTy);
1010   auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size);
1011 
1012   for (CoroSizeInst *CS : Shape.CoroSizes) {
1013     CS->replaceAllUsesWith(SizeConstant);
1014     CS->eraseFromParent();
1015   }
1016 }
1017 
1018 // Create a global constant array containing pointers to functions provided and
1019 // set Info parameter of CoroBegin to point at this constant. Example:
1020 //
1021 //   @f.resumers = internal constant [2 x void(%f.frame*)*]
1022 //                    [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy]
1023 //   define void @f() {
1024 //     ...
1025 //     call i8* @llvm.coro.begin(i8* null, i32 0, i8* null,
1026 //                    i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*))
1027 //
1028 // Assumes that all the functions have the same signature.
1029 static void setCoroInfo(Function &F, coro::Shape &Shape,
1030                         ArrayRef<Function *> Fns) {
1031   // This only works under the switch-lowering ABI because coro elision
1032   // only works on the switch-lowering ABI.
1033   assert(Shape.ABI == coro::ABI::Switch);
1034 
1035   SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end());
1036   assert(!Args.empty());
1037   Function *Part = *Fns.begin();
1038   Module *M = Part->getParent();
1039   auto *ArrTy = ArrayType::get(Part->getType(), Args.size());
1040 
1041   auto *ConstVal = ConstantArray::get(ArrTy, Args);
1042   auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true,
1043                                 GlobalVariable::PrivateLinkage, ConstVal,
1044                                 F.getName() + Twine(".resumers"));
1045 
1046   // Update coro.begin instruction to refer to this constant.
1047   LLVMContext &C = F.getContext();
1048   auto *BC = ConstantExpr::getPointerCast(GV, Type::getInt8PtrTy(C));
1049   Shape.getSwitchCoroId()->setInfo(BC);
1050 }
1051 
1052 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame.
1053 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn,
1054                             Function *DestroyFn, Function *CleanupFn) {
1055   assert(Shape.ABI == coro::ABI::Switch);
1056 
1057   IRBuilder<> Builder(Shape.FramePtr->getNextNode());
1058   auto *ResumeAddr = Builder.CreateStructGEP(
1059       Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Resume,
1060       "resume.addr");
1061   Builder.CreateStore(ResumeFn, ResumeAddr);
1062 
1063   Value *DestroyOrCleanupFn = DestroyFn;
1064 
1065   CoroIdInst *CoroId = Shape.getSwitchCoroId();
1066   if (CoroAllocInst *CA = CoroId->getCoroAlloc()) {
1067     // If there is a CoroAlloc and it returns false (meaning we elide the
1068     // allocation, use CleanupFn instead of DestroyFn).
1069     DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
1070   }
1071 
1072   auto *DestroyAddr = Builder.CreateStructGEP(
1073       Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Destroy,
1074       "destroy.addr");
1075   Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
1076 }
1077 
1078 static void postSplitCleanup(Function &F) {
1079   removeUnreachableBlocks(F);
1080 
1081   // For now, we do a mandatory verification step because we don't
1082   // entirely trust this pass.  Note that we don't want to add a verifier
1083   // pass to FPM below because it will also verify all the global data.
1084   if (verifyFunction(F, &errs()))
1085     report_fatal_error("Broken function");
1086 
1087   legacy::FunctionPassManager FPM(F.getParent());
1088 
1089   FPM.add(createSCCPPass());
1090   FPM.add(createCFGSimplificationPass());
1091   FPM.add(createEarlyCSEPass());
1092   FPM.add(createCFGSimplificationPass());
1093 
1094   FPM.doInitialization();
1095   FPM.run(F);
1096   FPM.doFinalization();
1097 }
1098 
1099 // Assuming we arrived at the block NewBlock from Prev instruction, store
1100 // PHI's incoming values in the ResolvedValues map.
1101 static void
1102 scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock,
1103                           DenseMap<Value *, Value *> &ResolvedValues) {
1104   auto *PrevBB = Prev->getParent();
1105   for (PHINode &PN : NewBlock->phis()) {
1106     auto V = PN.getIncomingValueForBlock(PrevBB);
1107     // See if we already resolved it.
1108     auto VI = ResolvedValues.find(V);
1109     if (VI != ResolvedValues.end())
1110       V = VI->second;
1111     // Remember the value.
1112     ResolvedValues[&PN] = V;
1113   }
1114 }
1115 
1116 // Replace a sequence of branches leading to a ret, with a clone of a ret
1117 // instruction. Suspend instruction represented by a switch, track the PHI
1118 // values and select the correct case successor when possible.
1119 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) {
1120   DenseMap<Value *, Value *> ResolvedValues;
1121   BasicBlock *UnconditionalSucc = nullptr;
1122 
1123   Instruction *I = InitialInst;
1124   while (I->isTerminator() ||
1125          (isa<CmpInst>(I) && I->getNextNode()->isTerminator())) {
1126     if (isa<ReturnInst>(I)) {
1127       if (I != InitialInst) {
1128         // If InitialInst is an unconditional branch,
1129         // remove PHI values that come from basic block of InitialInst
1130         if (UnconditionalSucc)
1131           UnconditionalSucc->removePredecessor(InitialInst->getParent(), true);
1132         ReplaceInstWithInst(InitialInst, I->clone());
1133       }
1134       return true;
1135     }
1136     if (auto *BR = dyn_cast<BranchInst>(I)) {
1137       if (BR->isUnconditional()) {
1138         BasicBlock *BB = BR->getSuccessor(0);
1139         if (I == InitialInst)
1140           UnconditionalSucc = BB;
1141         scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
1142         I = BB->getFirstNonPHIOrDbgOrLifetime();
1143         continue;
1144       }
1145     } else if (auto *CondCmp = dyn_cast<CmpInst>(I)) {
1146       auto *BR = dyn_cast<BranchInst>(I->getNextNode());
1147       if (BR && BR->isConditional() && CondCmp == BR->getCondition()) {
1148         // If the case number of suspended switch instruction is reduced to
1149         // 1, then it is simplified to CmpInst in llvm::ConstantFoldTerminator.
1150         // And the comparsion looks like : %cond = icmp eq i8 %V, constant.
1151         ConstantInt *CondConst = dyn_cast<ConstantInt>(CondCmp->getOperand(1));
1152         if (CondConst && CondCmp->getPredicate() == CmpInst::ICMP_EQ) {
1153           Value *V = CondCmp->getOperand(0);
1154           auto it = ResolvedValues.find(V);
1155           if (it != ResolvedValues.end())
1156             V = it->second;
1157 
1158           if (ConstantInt *Cond0 = dyn_cast<ConstantInt>(V)) {
1159             BasicBlock *BB = Cond0->equalsInt(CondConst->getZExtValue())
1160                                  ? BR->getSuccessor(0)
1161                                  : BR->getSuccessor(1);
1162             scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
1163             I = BB->getFirstNonPHIOrDbgOrLifetime();
1164             continue;
1165           }
1166         }
1167       }
1168     } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
1169       Value *V = SI->getCondition();
1170       auto it = ResolvedValues.find(V);
1171       if (it != ResolvedValues.end())
1172         V = it->second;
1173       if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1174         BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor();
1175         scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
1176         I = BB->getFirstNonPHIOrDbgOrLifetime();
1177         continue;
1178       }
1179     }
1180     return false;
1181   }
1182   return false;
1183 }
1184 
1185 // Check whether CI obeys the rules of musttail attribute.
1186 static bool shouldBeMustTail(const CallInst &CI, const Function &F) {
1187   if (CI.isInlineAsm())
1188     return false;
1189 
1190   // Match prototypes and calling conventions of resume function.
1191   FunctionType *CalleeTy = CI.getFunctionType();
1192   if (!CalleeTy->getReturnType()->isVoidTy() || (CalleeTy->getNumParams() != 1))
1193     return false;
1194 
1195   Type *CalleeParmTy = CalleeTy->getParamType(0);
1196   if (!CalleeParmTy->isPointerTy() ||
1197       (CalleeParmTy->getPointerAddressSpace() != 0))
1198     return false;
1199 
1200   if (CI.getCallingConv() != F.getCallingConv())
1201     return false;
1202 
1203   // CI should not has any ABI-impacting function attributes.
1204   static const Attribute::AttrKind ABIAttrs[] = {
1205       Attribute::StructRet,    Attribute::ByVal,     Attribute::InAlloca,
1206       Attribute::Preallocated, Attribute::InReg,     Attribute::Returned,
1207       Attribute::SwiftSelf,    Attribute::SwiftError};
1208   AttributeList Attrs = CI.getAttributes();
1209   for (auto AK : ABIAttrs)
1210     if (Attrs.hasParamAttribute(0, AK))
1211       return false;
1212 
1213   return true;
1214 }
1215 
1216 // Add musttail to any resume instructions that is immediately followed by a
1217 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call
1218 // for symmetrical coroutine control transfer (C++ Coroutines TS extension).
1219 // This transformation is done only in the resume part of the coroutine that has
1220 // identical signature and calling convention as the coro.resume call.
1221 static void addMustTailToCoroResumes(Function &F) {
1222   bool changed = false;
1223 
1224   // Collect potential resume instructions.
1225   SmallVector<CallInst *, 4> Resumes;
1226   for (auto &I : instructions(F))
1227     if (auto *Call = dyn_cast<CallInst>(&I))
1228       if (shouldBeMustTail(*Call, F))
1229         Resumes.push_back(Call);
1230 
1231   // Set musttail on those that are followed by a ret instruction.
1232   for (CallInst *Call : Resumes)
1233     if (simplifyTerminatorLeadingToRet(Call->getNextNode())) {
1234       Call->setTailCallKind(CallInst::TCK_MustTail);
1235       changed = true;
1236     }
1237 
1238   if (changed)
1239     removeUnreachableBlocks(F);
1240 }
1241 
1242 // Coroutine has no suspend points. Remove heap allocation for the coroutine
1243 // frame if possible.
1244 static void handleNoSuspendCoroutine(coro::Shape &Shape) {
1245   auto *CoroBegin = Shape.CoroBegin;
1246   auto *CoroId = CoroBegin->getId();
1247   auto *AllocInst = CoroId->getCoroAlloc();
1248   switch (Shape.ABI) {
1249   case coro::ABI::Switch: {
1250     auto SwitchId = cast<CoroIdInst>(CoroId);
1251     coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr);
1252     if (AllocInst) {
1253       IRBuilder<> Builder(AllocInst);
1254       auto *Frame = Builder.CreateAlloca(Shape.FrameTy);
1255       Frame->setAlignment(Shape.FrameAlign);
1256       auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy());
1257       AllocInst->replaceAllUsesWith(Builder.getFalse());
1258       AllocInst->eraseFromParent();
1259       CoroBegin->replaceAllUsesWith(VFrame);
1260     } else {
1261       CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
1262     }
1263     break;
1264   }
1265   case coro::ABI::Async:
1266   case coro::ABI::Retcon:
1267   case coro::ABI::RetconOnce:
1268     CoroBegin->replaceAllUsesWith(UndefValue::get(CoroBegin->getType()));
1269     break;
1270   }
1271 
1272   CoroBegin->eraseFromParent();
1273 }
1274 
1275 // SimplifySuspendPoint needs to check that there is no calls between
1276 // coro_save and coro_suspend, since any of the calls may potentially resume
1277 // the coroutine and if that is the case we cannot eliminate the suspend point.
1278 static bool hasCallsInBlockBetween(Instruction *From, Instruction *To) {
1279   for (Instruction *I = From; I != To; I = I->getNextNode()) {
1280     // Assume that no intrinsic can resume the coroutine.
1281     if (isa<IntrinsicInst>(I))
1282       continue;
1283 
1284     if (isa<CallBase>(I))
1285       return true;
1286   }
1287   return false;
1288 }
1289 
1290 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) {
1291   SmallPtrSet<BasicBlock *, 8> Set;
1292   SmallVector<BasicBlock *, 8> Worklist;
1293 
1294   Set.insert(SaveBB);
1295   Worklist.push_back(ResDesBB);
1296 
1297   // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr
1298   // returns a token consumed by suspend instruction, all blocks in between
1299   // will have to eventually hit SaveBB when going backwards from ResDesBB.
1300   while (!Worklist.empty()) {
1301     auto *BB = Worklist.pop_back_val();
1302     Set.insert(BB);
1303     for (auto *Pred : predecessors(BB))
1304       if (Set.count(Pred) == 0)
1305         Worklist.push_back(Pred);
1306   }
1307 
1308   // SaveBB and ResDesBB are checked separately in hasCallsBetween.
1309   Set.erase(SaveBB);
1310   Set.erase(ResDesBB);
1311 
1312   for (auto *BB : Set)
1313     if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr))
1314       return true;
1315 
1316   return false;
1317 }
1318 
1319 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) {
1320   auto *SaveBB = Save->getParent();
1321   auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent();
1322 
1323   if (SaveBB == ResumeOrDestroyBB)
1324     return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy);
1325 
1326   // Any calls from Save to the end of the block?
1327   if (hasCallsInBlockBetween(Save->getNextNode(), nullptr))
1328     return true;
1329 
1330   // Any calls from begging of the block up to ResumeOrDestroy?
1331   if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(),
1332                              ResumeOrDestroy))
1333     return true;
1334 
1335   // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB?
1336   if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB))
1337     return true;
1338 
1339   return false;
1340 }
1341 
1342 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the
1343 // suspend point and replace it with nornal control flow.
1344 static bool simplifySuspendPoint(CoroSuspendInst *Suspend,
1345                                  CoroBeginInst *CoroBegin) {
1346   Instruction *Prev = Suspend->getPrevNode();
1347   if (!Prev) {
1348     auto *Pred = Suspend->getParent()->getSinglePredecessor();
1349     if (!Pred)
1350       return false;
1351     Prev = Pred->getTerminator();
1352   }
1353 
1354   CallBase *CB = dyn_cast<CallBase>(Prev);
1355   if (!CB)
1356     return false;
1357 
1358   auto *Callee = CB->getCalledOperand()->stripPointerCasts();
1359 
1360   // See if the callsite is for resumption or destruction of the coroutine.
1361   auto *SubFn = dyn_cast<CoroSubFnInst>(Callee);
1362   if (!SubFn)
1363     return false;
1364 
1365   // Does not refer to the current coroutine, we cannot do anything with it.
1366   if (SubFn->getFrame() != CoroBegin)
1367     return false;
1368 
1369   // See if the transformation is safe. Specifically, see if there are any
1370   // calls in between Save and CallInstr. They can potenitally resume the
1371   // coroutine rendering this optimization unsafe.
1372   auto *Save = Suspend->getCoroSave();
1373   if (hasCallsBetween(Save, CB))
1374     return false;
1375 
1376   // Replace llvm.coro.suspend with the value that results in resumption over
1377   // the resume or cleanup path.
1378   Suspend->replaceAllUsesWith(SubFn->getRawIndex());
1379   Suspend->eraseFromParent();
1380   Save->eraseFromParent();
1381 
1382   // No longer need a call to coro.resume or coro.destroy.
1383   if (auto *Invoke = dyn_cast<InvokeInst>(CB)) {
1384     BranchInst::Create(Invoke->getNormalDest(), Invoke);
1385   }
1386 
1387   // Grab the CalledValue from CB before erasing the CallInstr.
1388   auto *CalledValue = CB->getCalledOperand();
1389   CB->eraseFromParent();
1390 
1391   // If no more users remove it. Usually it is a bitcast of SubFn.
1392   if (CalledValue != SubFn && CalledValue->user_empty())
1393     if (auto *I = dyn_cast<Instruction>(CalledValue))
1394       I->eraseFromParent();
1395 
1396   // Now we are good to remove SubFn.
1397   if (SubFn->user_empty())
1398     SubFn->eraseFromParent();
1399 
1400   return true;
1401 }
1402 
1403 // Remove suspend points that are simplified.
1404 static void simplifySuspendPoints(coro::Shape &Shape) {
1405   // Currently, the only simplification we do is switch-lowering-specific.
1406   if (Shape.ABI != coro::ABI::Switch)
1407     return;
1408 
1409   auto &S = Shape.CoroSuspends;
1410   size_t I = 0, N = S.size();
1411   if (N == 0)
1412     return;
1413   while (true) {
1414     auto SI = cast<CoroSuspendInst>(S[I]);
1415     // Leave final.suspend to handleFinalSuspend since it is undefined behavior
1416     // to resume a coroutine suspended at the final suspend point.
1417     if (!SI->isFinal() && simplifySuspendPoint(SI, Shape.CoroBegin)) {
1418       if (--N == I)
1419         break;
1420       std::swap(S[I], S[N]);
1421       continue;
1422     }
1423     if (++I == N)
1424       break;
1425   }
1426   S.resize(N);
1427 }
1428 
1429 static void splitSwitchCoroutine(Function &F, coro::Shape &Shape,
1430                                  SmallVectorImpl<Function *> &Clones) {
1431   assert(Shape.ABI == coro::ABI::Switch);
1432 
1433   createResumeEntryBlock(F, Shape);
1434   auto ResumeClone = createClone(F, ".resume", Shape,
1435                                  CoroCloner::Kind::SwitchResume);
1436   auto DestroyClone = createClone(F, ".destroy", Shape,
1437                                   CoroCloner::Kind::SwitchUnwind);
1438   auto CleanupClone = createClone(F, ".cleanup", Shape,
1439                                   CoroCloner::Kind::SwitchCleanup);
1440 
1441   postSplitCleanup(*ResumeClone);
1442   postSplitCleanup(*DestroyClone);
1443   postSplitCleanup(*CleanupClone);
1444 
1445   addMustTailToCoroResumes(*ResumeClone);
1446 
1447   // Store addresses resume/destroy/cleanup functions in the coroutine frame.
1448   updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone);
1449 
1450   assert(Clones.empty());
1451   Clones.push_back(ResumeClone);
1452   Clones.push_back(DestroyClone);
1453   Clones.push_back(CleanupClone);
1454 
1455   // Create a constant array referring to resume/destroy/clone functions pointed
1456   // by the last argument of @llvm.coro.info, so that CoroElide pass can
1457   // determined correct function to call.
1458   setCoroInfo(F, Shape, Clones);
1459 }
1460 
1461 static void replaceAsyncResumeFunction(CoroSuspendAsyncInst *Suspend,
1462                                        Value *Continuation) {
1463   auto *ResumeIntrinsic = Suspend->getResumeFunction();
1464   auto &Context = Suspend->getParent()->getParent()->getContext();
1465   auto *Int8PtrTy = Type::getInt8PtrTy(Context);
1466 
1467   IRBuilder<> Builder(ResumeIntrinsic);
1468   auto *Val = Builder.CreateBitOrPointerCast(Continuation, Int8PtrTy);
1469   ResumeIntrinsic->replaceAllUsesWith(Val);
1470   ResumeIntrinsic->eraseFromParent();
1471   Suspend->setOperand(0, UndefValue::get(Int8PtrTy));
1472 }
1473 
1474 /// Coerce the arguments in \p FnArgs according to \p FnTy in \p CallArgs.
1475 static void coerceArguments(IRBuilder<> &Builder, FunctionType *FnTy,
1476                             ArrayRef<Value *> FnArgs,
1477                             SmallVectorImpl<Value *> &CallArgs) {
1478   size_t ArgIdx = 0;
1479   for (auto paramTy : FnTy->params()) {
1480     assert(ArgIdx < FnArgs.size());
1481     if (paramTy != FnArgs[ArgIdx]->getType())
1482       CallArgs.push_back(
1483           Builder.CreateBitOrPointerCast(FnArgs[ArgIdx], paramTy));
1484     else
1485       CallArgs.push_back(FnArgs[ArgIdx]);
1486     ++ArgIdx;
1487   }
1488 }
1489 
1490 CallInst *coro::createMustTailCall(DebugLoc Loc, Function *MustTailCallFn,
1491                                    ArrayRef<Value *> Arguments,
1492                                    IRBuilder<> &Builder) {
1493   auto *FnTy =
1494       cast<FunctionType>(MustTailCallFn->getType()->getPointerElementType());
1495   // Coerce the arguments, llvm optimizations seem to ignore the types in
1496   // vaarg functions and throws away casts in optimized mode.
1497   SmallVector<Value *, 8> CallArgs;
1498   coerceArguments(Builder, FnTy, Arguments, CallArgs);
1499 
1500   auto *TailCall = Builder.CreateCall(FnTy, MustTailCallFn, CallArgs);
1501   TailCall->setTailCallKind(CallInst::TCK_MustTail);
1502   TailCall->setDebugLoc(Loc);
1503   TailCall->setCallingConv(MustTailCallFn->getCallingConv());
1504   return TailCall;
1505 }
1506 
1507 static void splitAsyncCoroutine(Function &F, coro::Shape &Shape,
1508                                 SmallVectorImpl<Function *> &Clones) {
1509   assert(Shape.ABI == coro::ABI::Async);
1510   assert(Clones.empty());
1511   // Reset various things that the optimizer might have decided it
1512   // "knows" about the coroutine function due to not seeing a return.
1513   F.removeFnAttr(Attribute::NoReturn);
1514   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1515   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1516 
1517   auto &Context = F.getContext();
1518   auto *Int8PtrTy = Type::getInt8PtrTy(Context);
1519 
1520   auto *Id = cast<CoroIdAsyncInst>(Shape.CoroBegin->getId());
1521   IRBuilder<> Builder(Id);
1522 
1523   auto *FramePtr = Id->getStorage();
1524   FramePtr = Builder.CreateBitOrPointerCast(FramePtr, Int8PtrTy);
1525   FramePtr = Builder.CreateConstInBoundsGEP1_32(
1526       Type::getInt8Ty(Context), FramePtr, Shape.AsyncLowering.FrameOffset,
1527       "async.ctx.frameptr");
1528 
1529   // Map all uses of llvm.coro.begin to the allocated frame pointer.
1530   {
1531     // Make sure we don't invalidate Shape.FramePtr.
1532     TrackingVH<Instruction> Handle(Shape.FramePtr);
1533     Shape.CoroBegin->replaceAllUsesWith(FramePtr);
1534     Shape.FramePtr = Handle.getValPtr();
1535   }
1536 
1537   // Create all the functions in order after the main function.
1538   auto NextF = std::next(F.getIterator());
1539 
1540   // Create a continuation function for each of the suspend points.
1541   Clones.reserve(Shape.CoroSuspends.size());
1542   for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) {
1543     auto *Suspend = cast<CoroSuspendAsyncInst>(Shape.CoroSuspends[Idx]);
1544 
1545     // Create the clone declaration.
1546     auto *Continuation = createCloneDeclaration(
1547         F, Shape, ".resume." + Twine(Idx), NextF, Suspend);
1548     Clones.push_back(Continuation);
1549 
1550     // Insert a branch to a new return block immediately before the suspend
1551     // point.
1552     auto *SuspendBB = Suspend->getParent();
1553     auto *NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1554     auto *Branch = cast<BranchInst>(SuspendBB->getTerminator());
1555 
1556     // Place it before the first suspend.
1557     auto *ReturnBB =
1558         BasicBlock::Create(F.getContext(), "coro.return", &F, NewSuspendBB);
1559     Branch->setSuccessor(0, ReturnBB);
1560 
1561     IRBuilder<> Builder(ReturnBB);
1562 
1563     // Insert the call to the tail call function and inline it.
1564     auto *Fn = Suspend->getMustTailCallFunction();
1565     SmallVector<Value *, 8> Args(Suspend->args());
1566     auto FnArgs = ArrayRef<Value *>(Args).drop_front(3);
1567     auto *TailCall =
1568         coro::createMustTailCall(Suspend->getDebugLoc(), Fn, FnArgs, Builder);
1569     Builder.CreateRetVoid();
1570     InlineFunctionInfo FnInfo;
1571     auto InlineRes = InlineFunction(*TailCall, FnInfo);
1572     assert(InlineRes.isSuccess() && "Expected inlining to succeed");
1573     (void)InlineRes;
1574 
1575     // Replace the lvm.coro.async.resume intrisic call.
1576     replaceAsyncResumeFunction(Suspend, Continuation);
1577   }
1578 
1579   assert(Clones.size() == Shape.CoroSuspends.size());
1580   for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) {
1581     auto *Suspend = Shape.CoroSuspends[Idx];
1582     auto *Clone = Clones[Idx];
1583 
1584     CoroCloner(F, "resume." + Twine(Idx), Shape, Clone, Suspend).create();
1585   }
1586 }
1587 
1588 static void splitRetconCoroutine(Function &F, coro::Shape &Shape,
1589                                  SmallVectorImpl<Function *> &Clones) {
1590   assert(Shape.ABI == coro::ABI::Retcon ||
1591          Shape.ABI == coro::ABI::RetconOnce);
1592   assert(Clones.empty());
1593 
1594   // Reset various things that the optimizer might have decided it
1595   // "knows" about the coroutine function due to not seeing a return.
1596   F.removeFnAttr(Attribute::NoReturn);
1597   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1598   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1599 
1600   // Allocate the frame.
1601   auto *Id = cast<AnyCoroIdRetconInst>(Shape.CoroBegin->getId());
1602   Value *RawFramePtr;
1603   if (Shape.RetconLowering.IsFrameInlineInStorage) {
1604     RawFramePtr = Id->getStorage();
1605   } else {
1606     IRBuilder<> Builder(Id);
1607 
1608     // Determine the size of the frame.
1609     const DataLayout &DL = F.getParent()->getDataLayout();
1610     auto Size = DL.getTypeAllocSize(Shape.FrameTy);
1611 
1612     // Allocate.  We don't need to update the call graph node because we're
1613     // going to recompute it from scratch after splitting.
1614     // FIXME: pass the required alignment
1615     RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr);
1616     RawFramePtr =
1617       Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType());
1618 
1619     // Stash the allocated frame pointer in the continuation storage.
1620     auto Dest = Builder.CreateBitCast(Id->getStorage(),
1621                                       RawFramePtr->getType()->getPointerTo());
1622     Builder.CreateStore(RawFramePtr, Dest);
1623   }
1624 
1625   // Map all uses of llvm.coro.begin to the allocated frame pointer.
1626   {
1627     // Make sure we don't invalidate Shape.FramePtr.
1628     TrackingVH<Instruction> Handle(Shape.FramePtr);
1629     Shape.CoroBegin->replaceAllUsesWith(RawFramePtr);
1630     Shape.FramePtr = Handle.getValPtr();
1631   }
1632 
1633   // Create a unique return block.
1634   BasicBlock *ReturnBB = nullptr;
1635   SmallVector<PHINode *, 4> ReturnPHIs;
1636 
1637   // Create all the functions in order after the main function.
1638   auto NextF = std::next(F.getIterator());
1639 
1640   // Create a continuation function for each of the suspend points.
1641   Clones.reserve(Shape.CoroSuspends.size());
1642   for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) {
1643     auto Suspend = cast<CoroSuspendRetconInst>(Shape.CoroSuspends[i]);
1644 
1645     // Create the clone declaration.
1646     auto Continuation =
1647         createCloneDeclaration(F, Shape, ".resume." + Twine(i), NextF, nullptr);
1648     Clones.push_back(Continuation);
1649 
1650     // Insert a branch to the unified return block immediately before
1651     // the suspend point.
1652     auto SuspendBB = Suspend->getParent();
1653     auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1654     auto Branch = cast<BranchInst>(SuspendBB->getTerminator());
1655 
1656     // Create the unified return block.
1657     if (!ReturnBB) {
1658       // Place it before the first suspend.
1659       ReturnBB = BasicBlock::Create(F.getContext(), "coro.return", &F,
1660                                     NewSuspendBB);
1661       Shape.RetconLowering.ReturnBlock = ReturnBB;
1662 
1663       IRBuilder<> Builder(ReturnBB);
1664 
1665       // Create PHIs for all the return values.
1666       assert(ReturnPHIs.empty());
1667 
1668       // First, the continuation.
1669       ReturnPHIs.push_back(Builder.CreatePHI(Continuation->getType(),
1670                                              Shape.CoroSuspends.size()));
1671 
1672       // Next, all the directly-yielded values.
1673       for (auto ResultTy : Shape.getRetconResultTypes())
1674         ReturnPHIs.push_back(Builder.CreatePHI(ResultTy,
1675                                                Shape.CoroSuspends.size()));
1676 
1677       // Build the return value.
1678       auto RetTy = F.getReturnType();
1679 
1680       // Cast the continuation value if necessary.
1681       // We can't rely on the types matching up because that type would
1682       // have to be infinite.
1683       auto CastedContinuationTy =
1684         (ReturnPHIs.size() == 1 ? RetTy : RetTy->getStructElementType(0));
1685       auto *CastedContinuation =
1686         Builder.CreateBitCast(ReturnPHIs[0], CastedContinuationTy);
1687 
1688       Value *RetV;
1689       if (ReturnPHIs.size() == 1) {
1690         RetV = CastedContinuation;
1691       } else {
1692         RetV = UndefValue::get(RetTy);
1693         RetV = Builder.CreateInsertValue(RetV, CastedContinuation, 0);
1694         for (size_t I = 1, E = ReturnPHIs.size(); I != E; ++I)
1695           RetV = Builder.CreateInsertValue(RetV, ReturnPHIs[I], I);
1696       }
1697 
1698       Builder.CreateRet(RetV);
1699     }
1700 
1701     // Branch to the return block.
1702     Branch->setSuccessor(0, ReturnBB);
1703     ReturnPHIs[0]->addIncoming(Continuation, SuspendBB);
1704     size_t NextPHIIndex = 1;
1705     for (auto &VUse : Suspend->value_operands())
1706       ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB);
1707     assert(NextPHIIndex == ReturnPHIs.size());
1708   }
1709 
1710   assert(Clones.size() == Shape.CoroSuspends.size());
1711   for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) {
1712     auto Suspend = Shape.CoroSuspends[i];
1713     auto Clone = Clones[i];
1714 
1715     CoroCloner(F, "resume." + Twine(i), Shape, Clone, Suspend).create();
1716   }
1717 }
1718 
1719 namespace {
1720   class PrettyStackTraceFunction : public PrettyStackTraceEntry {
1721     Function &F;
1722   public:
1723     PrettyStackTraceFunction(Function &F) : F(F) {}
1724     void print(raw_ostream &OS) const override {
1725       OS << "While splitting coroutine ";
1726       F.printAsOperand(OS, /*print type*/ false, F.getParent());
1727       OS << "\n";
1728     }
1729   };
1730 }
1731 
1732 static coro::Shape splitCoroutine(Function &F,
1733                                   SmallVectorImpl<Function *> &Clones,
1734                                   bool ReuseFrameSlot) {
1735   PrettyStackTraceFunction prettyStackTrace(F);
1736 
1737   // The suspend-crossing algorithm in buildCoroutineFrame get tripped
1738   // up by uses in unreachable blocks, so remove them as a first pass.
1739   removeUnreachableBlocks(F);
1740 
1741   coro::Shape Shape(F, ReuseFrameSlot);
1742   if (!Shape.CoroBegin)
1743     return Shape;
1744 
1745   simplifySuspendPoints(Shape);
1746   buildCoroutineFrame(F, Shape);
1747   replaceFrameSize(Shape);
1748 
1749   // If there are no suspend points, no split required, just remove
1750   // the allocation and deallocation blocks, they are not needed.
1751   if (Shape.CoroSuspends.empty()) {
1752     handleNoSuspendCoroutine(Shape);
1753   } else {
1754     switch (Shape.ABI) {
1755     case coro::ABI::Switch:
1756       splitSwitchCoroutine(F, Shape, Clones);
1757       break;
1758     case coro::ABI::Async:
1759       splitAsyncCoroutine(F, Shape, Clones);
1760       break;
1761     case coro::ABI::Retcon:
1762     case coro::ABI::RetconOnce:
1763       splitRetconCoroutine(F, Shape, Clones);
1764       break;
1765     }
1766   }
1767 
1768   // Replace all the swifterror operations in the original function.
1769   // This invalidates SwiftErrorOps in the Shape.
1770   replaceSwiftErrorOps(F, Shape, nullptr);
1771 
1772   return Shape;
1773 }
1774 
1775 static void
1776 updateCallGraphAfterCoroutineSplit(Function &F, const coro::Shape &Shape,
1777                                    const SmallVectorImpl<Function *> &Clones,
1778                                    CallGraph &CG, CallGraphSCC &SCC) {
1779   if (!Shape.CoroBegin)
1780     return;
1781 
1782   removeCoroEnds(Shape, &CG);
1783   postSplitCleanup(F);
1784 
1785   // Update call graph and add the functions we created to the SCC.
1786   coro::updateCallGraph(F, Clones, CG, SCC);
1787 }
1788 
1789 static void updateCallGraphAfterCoroutineSplit(
1790     LazyCallGraph::Node &N, const coro::Shape &Shape,
1791     const SmallVectorImpl<Function *> &Clones, LazyCallGraph::SCC &C,
1792     LazyCallGraph &CG, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
1793     FunctionAnalysisManager &FAM) {
1794   if (!Shape.CoroBegin)
1795     return;
1796 
1797   for (llvm::AnyCoroEndInst *End : Shape.CoroEnds) {
1798     auto &Context = End->getContext();
1799     End->replaceAllUsesWith(ConstantInt::getFalse(Context));
1800     End->eraseFromParent();
1801   }
1802 
1803   if (!Clones.empty()) {
1804     switch (Shape.ABI) {
1805     case coro::ABI::Switch:
1806       // Each clone in the Switch lowering is independent of the other clones.
1807       // Let the LazyCallGraph know about each one separately.
1808       for (Function *Clone : Clones)
1809         CG.addSplitFunction(N.getFunction(), *Clone);
1810       break;
1811     case coro::ABI::Async:
1812     case coro::ABI::Retcon:
1813     case coro::ABI::RetconOnce:
1814       // Each clone in the Async/Retcon lowering references of the other clones.
1815       // Let the LazyCallGraph know about all of them at once.
1816       if (!Clones.empty())
1817         CG.addSplitRefRecursiveFunctions(N.getFunction(), Clones);
1818       break;
1819     }
1820 
1821     // Let the CGSCC infra handle the changes to the original function.
1822     updateCGAndAnalysisManagerForCGSCCPass(CG, C, N, AM, UR, FAM);
1823   }
1824 
1825   // Do some cleanup and let the CGSCC infra see if we've cleaned up any edges
1826   // to the split functions.
1827   postSplitCleanup(N.getFunction());
1828   updateCGAndAnalysisManagerForFunctionPass(CG, C, N, AM, UR, FAM);
1829 }
1830 
1831 // When we see the coroutine the first time, we insert an indirect call to a
1832 // devirt trigger function and mark the coroutine that it is now ready for
1833 // split.
1834 // Async lowering uses this after it has split the function to restart the
1835 // pipeline.
1836 static void prepareForSplit(Function &F, CallGraph &CG,
1837                             bool MarkForAsyncRestart = false) {
1838   Module &M = *F.getParent();
1839   LLVMContext &Context = F.getContext();
1840 #ifndef NDEBUG
1841   Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN);
1842   assert(DevirtFn && "coro.devirt.trigger function not found");
1843 #endif
1844 
1845   F.addFnAttr(CORO_PRESPLIT_ATTR, MarkForAsyncRestart
1846                                       ? ASYNC_RESTART_AFTER_SPLIT
1847                                       : PREPARED_FOR_SPLIT);
1848 
1849   // Insert an indirect call sequence that will be devirtualized by CoroElide
1850   // pass:
1851   //    %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1)
1852   //    %1 = bitcast i8* %0 to void(i8*)*
1853   //    call void %1(i8* null)
1854   coro::LowererBase Lowerer(M);
1855   Instruction *InsertPt =
1856       MarkForAsyncRestart ? F.getEntryBlock().getFirstNonPHIOrDbgOrLifetime()
1857                           : F.getEntryBlock().getTerminator();
1858   auto *Null = ConstantPointerNull::get(Type::getInt8PtrTy(Context));
1859   auto *DevirtFnAddr =
1860       Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt);
1861   FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Context),
1862                                          {Type::getInt8PtrTy(Context)}, false);
1863   auto *IndirectCall = CallInst::Create(FnTy, DevirtFnAddr, Null, "", InsertPt);
1864 
1865   // Update CG graph with an indirect call we just added.
1866   CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode());
1867 }
1868 
1869 // Make sure that there is a devirtualization trigger function that the
1870 // coro-split pass uses to force a restart of the CGSCC pipeline. If the devirt
1871 // trigger function is not found, we will create one and add it to the current
1872 // SCC.
1873 static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC) {
1874   Module &M = CG.getModule();
1875   if (M.getFunction(CORO_DEVIRT_TRIGGER_FN))
1876     return;
1877 
1878   LLVMContext &C = M.getContext();
1879   auto *FnTy = FunctionType::get(Type::getVoidTy(C), Type::getInt8PtrTy(C),
1880                                  /*isVarArg=*/false);
1881   Function *DevirtFn =
1882       Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage,
1883                        CORO_DEVIRT_TRIGGER_FN, &M);
1884   DevirtFn->addFnAttr(Attribute::AlwaysInline);
1885   auto *Entry = BasicBlock::Create(C, "entry", DevirtFn);
1886   ReturnInst::Create(C, Entry);
1887 
1888   auto *Node = CG.getOrInsertFunction(DevirtFn);
1889 
1890   SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end());
1891   Nodes.push_back(Node);
1892   SCC.initialize(Nodes);
1893 }
1894 
1895 /// Replace a call to llvm.coro.prepare.retcon.
1896 static void replacePrepare(CallInst *Prepare, LazyCallGraph &CG,
1897                            LazyCallGraph::SCC &C) {
1898   auto CastFn = Prepare->getArgOperand(0); // as an i8*
1899   auto Fn = CastFn->stripPointerCasts();   // as its original type
1900 
1901   // Attempt to peephole this pattern:
1902   //    %0 = bitcast [[TYPE]] @some_function to i8*
1903   //    %1 = call @llvm.coro.prepare.retcon(i8* %0)
1904   //    %2 = bitcast %1 to [[TYPE]]
1905   // ==>
1906   //    %2 = @some_function
1907   for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); UI != UE;) {
1908     // Look for bitcasts back to the original function type.
1909     auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser());
1910     if (!Cast || Cast->getType() != Fn->getType())
1911       continue;
1912 
1913     // Replace and remove the cast.
1914     Cast->replaceAllUsesWith(Fn);
1915     Cast->eraseFromParent();
1916   }
1917 
1918   // Replace any remaining uses with the function as an i8*.
1919   // This can never directly be a callee, so we don't need to update CG.
1920   Prepare->replaceAllUsesWith(CastFn);
1921   Prepare->eraseFromParent();
1922 
1923   // Kill dead bitcasts.
1924   while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
1925     if (!Cast->use_empty())
1926       break;
1927     CastFn = Cast->getOperand(0);
1928     Cast->eraseFromParent();
1929   }
1930 }
1931 /// Replace a call to llvm.coro.prepare.retcon.
1932 static void replacePrepare(CallInst *Prepare, CallGraph &CG) {
1933   auto CastFn = Prepare->getArgOperand(0); // as an i8*
1934   auto Fn = CastFn->stripPointerCasts(); // as its original type
1935 
1936   // Find call graph nodes for the preparation.
1937   CallGraphNode *PrepareUserNode = nullptr, *FnNode = nullptr;
1938   if (auto ConcreteFn = dyn_cast<Function>(Fn)) {
1939     PrepareUserNode = CG[Prepare->getFunction()];
1940     FnNode = CG[ConcreteFn];
1941   }
1942 
1943   // Attempt to peephole this pattern:
1944   //    %0 = bitcast [[TYPE]] @some_function to i8*
1945   //    %1 = call @llvm.coro.prepare.retcon(i8* %0)
1946   //    %2 = bitcast %1 to [[TYPE]]
1947   // ==>
1948   //    %2 = @some_function
1949   for (auto UI = Prepare->use_begin(), UE = Prepare->use_end();
1950          UI != UE; ) {
1951     // Look for bitcasts back to the original function type.
1952     auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser());
1953     if (!Cast || Cast->getType() != Fn->getType()) continue;
1954 
1955     // Check whether the replacement will introduce new direct calls.
1956     // If so, we'll need to update the call graph.
1957     if (PrepareUserNode) {
1958       for (auto &Use : Cast->uses()) {
1959         if (auto *CB = dyn_cast<CallBase>(Use.getUser())) {
1960           if (!CB->isCallee(&Use))
1961             continue;
1962           PrepareUserNode->removeCallEdgeFor(*CB);
1963           PrepareUserNode->addCalledFunction(CB, FnNode);
1964         }
1965       }
1966     }
1967 
1968     // Replace and remove the cast.
1969     Cast->replaceAllUsesWith(Fn);
1970     Cast->eraseFromParent();
1971   }
1972 
1973   // Replace any remaining uses with the function as an i8*.
1974   // This can never directly be a callee, so we don't need to update CG.
1975   Prepare->replaceAllUsesWith(CastFn);
1976   Prepare->eraseFromParent();
1977 
1978   // Kill dead bitcasts.
1979   while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
1980     if (!Cast->use_empty()) break;
1981     CastFn = Cast->getOperand(0);
1982     Cast->eraseFromParent();
1983   }
1984 }
1985 
1986 static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG,
1987                                LazyCallGraph::SCC &C) {
1988   bool Changed = false;
1989   for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); PI != PE;) {
1990     // Intrinsics can only be used in calls.
1991     auto *Prepare = cast<CallInst>((PI++)->getUser());
1992     replacePrepare(Prepare, CG, C);
1993     Changed = true;
1994   }
1995 
1996   return Changed;
1997 }
1998 
1999 /// Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent
2000 /// IPO from operating on calls to a retcon coroutine before it's been
2001 /// split.  This is only safe to do after we've split all retcon
2002 /// coroutines in the module.  We can do that this in this pass because
2003 /// this pass does promise to split all retcon coroutines (as opposed to
2004 /// switch coroutines, which are lowered in multiple stages).
2005 static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG) {
2006   bool Changed = false;
2007   for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end();
2008          PI != PE; ) {
2009     // Intrinsics can only be used in calls.
2010     auto *Prepare = cast<CallInst>((PI++)->getUser());
2011     replacePrepare(Prepare, CG);
2012     Changed = true;
2013   }
2014 
2015   return Changed;
2016 }
2017 
2018 static bool declaresCoroSplitIntrinsics(const Module &M) {
2019   return coro::declaresIntrinsics(M, {"llvm.coro.begin",
2020                                       "llvm.coro.prepare.retcon",
2021                                       "llvm.coro.prepare.async"});
2022 }
2023 
2024 static void addPrepareFunction(const Module &M,
2025                                SmallVectorImpl<Function *> &Fns,
2026                                StringRef Name) {
2027   auto *PrepareFn = M.getFunction(Name);
2028   if (PrepareFn && !PrepareFn->use_empty())
2029     Fns.push_back(PrepareFn);
2030 }
2031 
2032 PreservedAnalyses CoroSplitPass::run(LazyCallGraph::SCC &C,
2033                                      CGSCCAnalysisManager &AM,
2034                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
2035   // NB: One invariant of a valid LazyCallGraph::SCC is that it must contain a
2036   //     non-zero number of nodes, so we assume that here and grab the first
2037   //     node's function's module.
2038   Module &M = *C.begin()->getFunction().getParent();
2039   auto &FAM =
2040       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2041 
2042   if (!declaresCoroSplitIntrinsics(M))
2043     return PreservedAnalyses::all();
2044 
2045   // Check for uses of llvm.coro.prepare.retcon/async.
2046   SmallVector<Function *, 2> PrepareFns;
2047   addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon");
2048   addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async");
2049 
2050   // Find coroutines for processing.
2051   SmallVector<LazyCallGraph::Node *, 4> Coroutines;
2052   for (LazyCallGraph::Node &N : C)
2053     if (N.getFunction().hasFnAttribute(CORO_PRESPLIT_ATTR))
2054       Coroutines.push_back(&N);
2055 
2056   if (Coroutines.empty() && PrepareFns.empty())
2057     return PreservedAnalyses::all();
2058 
2059   if (Coroutines.empty()) {
2060     for (auto *PrepareFn : PrepareFns) {
2061       replaceAllPrepares(PrepareFn, CG, C);
2062     }
2063   }
2064 
2065   // Split all the coroutines.
2066   for (LazyCallGraph::Node *N : Coroutines) {
2067     Function &F = N->getFunction();
2068     Attribute Attr = F.getFnAttribute(CORO_PRESPLIT_ATTR);
2069     StringRef Value = Attr.getValueAsString();
2070     LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F.getName()
2071                       << "' state: " << Value << "\n");
2072     if (Value == UNPREPARED_FOR_SPLIT) {
2073       // Enqueue a second iteration of the CGSCC pipeline on this SCC.
2074       UR.CWorklist.insert(&C);
2075       F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT);
2076       continue;
2077     }
2078     F.removeFnAttr(CORO_PRESPLIT_ATTR);
2079 
2080     SmallVector<Function *, 4> Clones;
2081     const coro::Shape Shape = splitCoroutine(F, Clones, ReuseFrameSlot);
2082     updateCallGraphAfterCoroutineSplit(*N, Shape, Clones, C, CG, AM, UR, FAM);
2083 
2084     if ((Shape.ABI == coro::ABI::Async || Shape.ABI == coro::ABI::Retcon ||
2085          Shape.ABI == coro::ABI::RetconOnce) &&
2086         !Shape.CoroSuspends.empty()) {
2087       // Run the CGSCC pipeline on the newly split functions.
2088       // All clones will be in the same RefSCC, so choose a random clone.
2089       UR.RCWorklist.insert(CG.lookupRefSCC(CG.get(*Clones[0])));
2090     }
2091   }
2092 
2093   if (!PrepareFns.empty()) {
2094     for (auto *PrepareFn : PrepareFns) {
2095       replaceAllPrepares(PrepareFn, CG, C);
2096     }
2097   }
2098 
2099   return PreservedAnalyses::none();
2100 }
2101 
2102 namespace {
2103 
2104 // We present a coroutine to LLVM as an ordinary function with suspension
2105 // points marked up with intrinsics. We let the optimizer party on the coroutine
2106 // as a single function for as long as possible. Shortly before the coroutine is
2107 // eligible to be inlined into its callers, we split up the coroutine into parts
2108 // corresponding to initial, resume and destroy invocations of the coroutine,
2109 // add them to the current SCC and restart the IPO pipeline to optimize the
2110 // coroutine subfunctions we extracted before proceeding to the caller of the
2111 // coroutine.
2112 struct CoroSplitLegacy : public CallGraphSCCPass {
2113   static char ID; // Pass identification, replacement for typeid
2114 
2115   CoroSplitLegacy(bool ReuseFrameSlot = false)
2116       : CallGraphSCCPass(ID), ReuseFrameSlot(ReuseFrameSlot) {
2117     initializeCoroSplitLegacyPass(*PassRegistry::getPassRegistry());
2118   }
2119 
2120   bool Run = false;
2121   bool ReuseFrameSlot;
2122 
2123   // A coroutine is identified by the presence of coro.begin intrinsic, if
2124   // we don't have any, this pass has nothing to do.
2125   bool doInitialization(CallGraph &CG) override {
2126     Run = declaresCoroSplitIntrinsics(CG.getModule());
2127     return CallGraphSCCPass::doInitialization(CG);
2128   }
2129 
2130   bool runOnSCC(CallGraphSCC &SCC) override {
2131     if (!Run)
2132       return false;
2133 
2134     // Check for uses of llvm.coro.prepare.retcon.
2135     SmallVector<Function *, 2> PrepareFns;
2136     auto &M = SCC.getCallGraph().getModule();
2137     addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon");
2138     addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async");
2139 
2140     // Find coroutines for processing.
2141     SmallVector<Function *, 4> Coroutines;
2142     for (CallGraphNode *CGN : SCC)
2143       if (auto *F = CGN->getFunction())
2144         if (F->hasFnAttribute(CORO_PRESPLIT_ATTR))
2145           Coroutines.push_back(F);
2146 
2147     if (Coroutines.empty() && PrepareFns.empty())
2148       return false;
2149 
2150     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
2151 
2152     if (Coroutines.empty()) {
2153       bool Changed = false;
2154       for (auto *PrepareFn : PrepareFns)
2155         Changed |= replaceAllPrepares(PrepareFn, CG);
2156       return Changed;
2157     }
2158 
2159     createDevirtTriggerFunc(CG, SCC);
2160 
2161     // Split all the coroutines.
2162     for (Function *F : Coroutines) {
2163       Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR);
2164       StringRef Value = Attr.getValueAsString();
2165       LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName()
2166                         << "' state: " << Value << "\n");
2167       // Async lowering marks coroutines to trigger a restart of the pipeline
2168       // after it has split them.
2169       if (Value == ASYNC_RESTART_AFTER_SPLIT) {
2170         F->removeFnAttr(CORO_PRESPLIT_ATTR);
2171         continue;
2172       }
2173       if (Value == UNPREPARED_FOR_SPLIT) {
2174         prepareForSplit(*F, CG);
2175         continue;
2176       }
2177       F->removeFnAttr(CORO_PRESPLIT_ATTR);
2178 
2179       SmallVector<Function *, 4> Clones;
2180       const coro::Shape Shape = splitCoroutine(*F, Clones, ReuseFrameSlot);
2181       updateCallGraphAfterCoroutineSplit(*F, Shape, Clones, CG, SCC);
2182       if (Shape.ABI == coro::ABI::Async) {
2183         // Restart SCC passes.
2184         // Mark function for CoroElide pass. It will devirtualize causing a
2185         // restart of the SCC pipeline.
2186         prepareForSplit(*F, CG, true /*MarkForAsyncRestart*/);
2187       }
2188     }
2189 
2190     for (auto *PrepareFn : PrepareFns)
2191       replaceAllPrepares(PrepareFn, CG);
2192 
2193     return true;
2194   }
2195 
2196   void getAnalysisUsage(AnalysisUsage &AU) const override {
2197     CallGraphSCCPass::getAnalysisUsage(AU);
2198   }
2199 
2200   StringRef getPassName() const override { return "Coroutine Splitting"; }
2201 };
2202 
2203 } // end anonymous namespace
2204 
2205 char CoroSplitLegacy::ID = 0;
2206 
2207 INITIALIZE_PASS_BEGIN(
2208     CoroSplitLegacy, "coro-split",
2209     "Split coroutine into a set of functions driving its state machine", false,
2210     false)
2211 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
2212 INITIALIZE_PASS_END(
2213     CoroSplitLegacy, "coro-split",
2214     "Split coroutine into a set of functions driving its state machine", false,
2215     false)
2216 
2217 Pass *llvm::createCoroSplitLegacyPass(bool ReuseFrameSlot) {
2218   return new CoroSplitLegacy(ReuseFrameSlot);
2219 }
2220