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