1 //===- CoroCleanup.cpp - Coroutine Cleanup Pass ---------------------------===//
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 
9 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
10 #include "CoroInternal.h"
11 #include "llvm/IR/IRBuilder.h"
12 #include "llvm/IR/InstIterator.h"
13 #include "llvm/IR/LegacyPassManager.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Transforms/Scalar.h"
16 
17 using namespace llvm;
18 
19 #define DEBUG_TYPE "coro-cleanup"
20 
21 namespace {
22 // Created on demand if CoroCleanup pass has work to do.
23 struct Lowerer : coro::LowererBase {
24   IRBuilder<> Builder;
25   Lowerer(Module &M) : LowererBase(M), Builder(Context) {}
26   bool lowerRemainingCoroIntrinsics(Function &F);
27 };
28 }
29 
30 static void simplifyCFG(Function &F) {
31   llvm::legacy::FunctionPassManager FPM(F.getParent());
32   FPM.add(createCFGSimplificationPass());
33 
34   FPM.doInitialization();
35   FPM.run(F);
36   FPM.doFinalization();
37 }
38 
39 static void lowerSubFn(IRBuilder<> &Builder, CoroSubFnInst *SubFn) {
40   Builder.SetInsertPoint(SubFn);
41   Value *FrameRaw = SubFn->getFrame();
42   int Index = SubFn->getIndex();
43 
44   auto *FrameTy = StructType::get(
45       SubFn->getContext(), {Builder.getInt8PtrTy(), Builder.getInt8PtrTy()});
46   PointerType *FramePtrTy = FrameTy->getPointerTo();
47 
48   Builder.SetInsertPoint(SubFn);
49   auto *FramePtr = Builder.CreateBitCast(FrameRaw, FramePtrTy);
50   auto *Gep = Builder.CreateConstInBoundsGEP2_32(FrameTy, FramePtr, 0, Index);
51   auto *Load = Builder.CreateLoad(FrameTy->getElementType(Index), Gep);
52 
53   SubFn->replaceAllUsesWith(Load);
54 }
55 
56 bool Lowerer::lowerRemainingCoroIntrinsics(Function &F) {
57   bool Changed = false;
58 
59   for (auto IB = inst_begin(F), E = inst_end(F); IB != E;) {
60     Instruction &I = *IB++;
61     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
62       switch (II->getIntrinsicID()) {
63       default:
64         continue;
65       case Intrinsic::coro_begin:
66         II->replaceAllUsesWith(II->getArgOperand(1));
67         break;
68       case Intrinsic::coro_free:
69         II->replaceAllUsesWith(II->getArgOperand(1));
70         break;
71       case Intrinsic::coro_alloc:
72         II->replaceAllUsesWith(ConstantInt::getTrue(Context));
73         break;
74       case Intrinsic::coro_id:
75       case Intrinsic::coro_id_retcon:
76       case Intrinsic::coro_id_retcon_once:
77         II->replaceAllUsesWith(ConstantTokenNone::get(Context));
78         break;
79       case Intrinsic::coro_subfn_addr:
80         lowerSubFn(Builder, cast<CoroSubFnInst>(II));
81         break;
82       }
83       II->eraseFromParent();
84       Changed = true;
85     }
86   }
87 
88   if (Changed) {
89     // After replacement were made we can cleanup the function body a little.
90     simplifyCFG(F);
91   }
92 
93   return Changed;
94 }
95 
96 static bool declaresCoroCleanupIntrinsics(const Module &M) {
97   return coro::declaresIntrinsics(M, {"llvm.coro.alloc", "llvm.coro.begin",
98                                       "llvm.coro.subfn.addr", "llvm.coro.free",
99                                       "llvm.coro.id", "llvm.coro.id.retcon",
100                                       "llvm.coro.id.retcon.once"});
101 }
102 
103 PreservedAnalyses CoroCleanupPass::run(Function &F,
104                                        FunctionAnalysisManager &AM) {
105   auto &M = *F.getParent();
106   if (!declaresCoroCleanupIntrinsics(M) ||
107       !Lowerer(M).lowerRemainingCoroIntrinsics(F))
108     return PreservedAnalyses::all();
109 
110   return PreservedAnalyses::none();
111 }
112 
113 namespace {
114 
115 struct CoroCleanupLegacy : FunctionPass {
116   static char ID; // Pass identification, replacement for typeid
117 
118   CoroCleanupLegacy() : FunctionPass(ID) {
119     initializeCoroCleanupLegacyPass(*PassRegistry::getPassRegistry());
120   }
121 
122   std::unique_ptr<Lowerer> L;
123 
124   // This pass has work to do only if we find intrinsics we are going to lower
125   // in the module.
126   bool doInitialization(Module &M) override {
127     if (declaresCoroCleanupIntrinsics(M))
128       L = std::make_unique<Lowerer>(M);
129     return false;
130   }
131 
132   bool runOnFunction(Function &F) override {
133     if (L)
134       return L->lowerRemainingCoroIntrinsics(F);
135     return false;
136   }
137   void getAnalysisUsage(AnalysisUsage &AU) const override {
138     if (!L)
139       AU.setPreservesAll();
140   }
141   StringRef getPassName() const override { return "Coroutine Cleanup"; }
142 };
143 }
144 
145 char CoroCleanupLegacy::ID = 0;
146 INITIALIZE_PASS(CoroCleanupLegacy, "coro-cleanup",
147                 "Lower all coroutine related intrinsics", false, false)
148 
149 Pass *llvm::createCoroCleanupLegacyPass() { return new CoroCleanupLegacy(); }
150