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