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   void lower(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 void Lowerer::lower(Function &F) {
57   bool IsPrivateAndUnprocessed =
58       F.hasFnAttribute(CORO_PRESPLIT_ATTR) && F.hasLocalLinkage();
59 
60   for (Instruction &I : llvm::make_early_inc_range(instructions(F))) {
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_async_resume:
75         II->replaceAllUsesWith(
76             ConstantPointerNull::get(cast<PointerType>(I.getType())));
77         break;
78       case Intrinsic::coro_id:
79       case Intrinsic::coro_id_retcon:
80       case Intrinsic::coro_id_retcon_once:
81       case Intrinsic::coro_id_async:
82         II->replaceAllUsesWith(ConstantTokenNone::get(Context));
83         break;
84       case Intrinsic::coro_subfn_addr:
85         lowerSubFn(Builder, cast<CoroSubFnInst>(II));
86         break;
87       case Intrinsic::coro_end:
88       case Intrinsic::coro_suspend_retcon:
89         if (IsPrivateAndUnprocessed) {
90           II->replaceAllUsesWith(UndefValue::get(II->getType()));
91         } else
92           continue;
93         break;
94       case Intrinsic::coro_async_size_replace:
95         auto *Target = cast<ConstantStruct>(
96             cast<GlobalVariable>(II->getArgOperand(0)->stripPointerCasts())
97                 ->getInitializer());
98         auto *Source = cast<ConstantStruct>(
99             cast<GlobalVariable>(II->getArgOperand(1)->stripPointerCasts())
100                 ->getInitializer());
101         auto *TargetSize = Target->getOperand(1);
102         auto *SourceSize = Source->getOperand(1);
103         if (TargetSize->isElementWiseEqual(SourceSize)) {
104           break;
105         }
106         auto *TargetRelativeFunOffset = Target->getOperand(0);
107         auto *NewFuncPtrStruct = ConstantStruct::get(
108             Target->getType(), TargetRelativeFunOffset, SourceSize);
109         Target->replaceAllUsesWith(NewFuncPtrStruct);
110         break;
111       }
112       II->eraseFromParent();
113     }
114   }
115 
116   // After replacement were made we can cleanup the function body a little.
117   simplifyCFG(F);
118 }
119 
120 static bool declaresCoroCleanupIntrinsics(const Module &M) {
121   return coro::declaresIntrinsics(
122       M, {"llvm.coro.alloc", "llvm.coro.begin", "llvm.coro.subfn.addr",
123           "llvm.coro.free", "llvm.coro.id", "llvm.coro.id.retcon",
124           "llvm.coro.id.retcon.once", "llvm.coro.async.size.replace",
125           "llvm.coro.async.resume"});
126 }
127 
128 PreservedAnalyses CoroCleanupPass::run(Module &M,
129                                        ModuleAnalysisManager &MAM) {
130   if (!declaresCoroCleanupIntrinsics(M))
131     return PreservedAnalyses::all();
132 
133   Lowerer L(M);
134   for (auto &F : M)
135     L.lower(F);
136 
137   return PreservedAnalyses::none();
138 }
139