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