LLVM 24.0.0git
CoroCleanup.cpp
Go to the documentation of this file.
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
10#include "CoroInternal.h"
12#include "llvm/IR/DIBuilder.h"
13#include "llvm/IR/Function.h"
14#include "llvm/IR/IRBuilder.h"
16#include "llvm/IR/Module.h"
17#include "llvm/IR/PassManager.h"
21
22using namespace llvm;
23
24#define DEBUG_TYPE "coro-cleanup"
25
26namespace {
27// Created on demand if CoroCleanup pass has work to do.
28struct Lowerer : coro::LowererBase {
29 IRBuilder<> Builder;
30 Constant *NoopCoro = nullptr;
31
32 Lowerer(Module &M) : LowererBase(M), Builder(Context) {}
33 bool lower(Function &F);
34
35private:
36 void lowerCoroNoop(IntrinsicInst *II);
37};
38
39// Recursively walk and eliminate resume/destroy call on noop coro
40class NoopCoroElider : public PtrUseVisitor<NoopCoroElider> {
42
43 IRBuilder<> Builder;
44
45public:
46 NoopCoroElider(const DataLayout &DL, LLVMContext &C) : Base(DL), Builder(C) {}
47
48 void run(IntrinsicInst *II);
49
50 void visitLoadInst(LoadInst &I) { enqueueUsers(I); }
51 void visitCallBase(CallBase &CB);
52 void visitIntrinsicInst(IntrinsicInst &II);
53
54private:
55 bool tryEraseCallInvoke(Instruction *I);
56 void eraseFromWorklist(Instruction *I);
57};
58}
59
60static void lowerSubFn(IRBuilder<> &Builder, CoroSubFnInst *SubFn) {
61 Builder.SetInsertPoint(SubFn);
62 Value *FramePtr = SubFn->getFrame();
63 int Index = SubFn->getIndex();
64
65 auto *FrameTy = StructType::get(SubFn->getContext(),
66 {Builder.getPtrTy(), Builder.getPtrTy()});
67
68 Builder.SetInsertPoint(SubFn);
69 auto *Gep = Builder.CreateConstInBoundsGEP2_32(FrameTy, FramePtr, 0, Index);
70 auto *Load = Builder.CreateLoad(FrameTy->getElementType(Index), Gep);
71
73}
74
76 Module &M = *NoopFn->getParent();
77 if (M.debug_compile_units().empty())
78 return;
79
80 DICompileUnit *CU = *M.debug_compile_units_begin();
81 DIBuilder DB(M, /*AllowUnresolved*/ false, CU);
82 std::array<Metadata *, 2> Params{nullptr, nullptr};
83 auto *SubroutineType =
84 DB.createSubroutineType(DB.getOrCreateTypeArray(Params));
85 StringRef Name = NoopFn->getName();
86 auto *SP = DB.createFunction(
87 CU, /*Name=*/Name, /*LinkageName=*/Name, /*File=*/CU->getFile(),
88 /*LineNo=*/0, SubroutineType, /*ScopeLine=*/0, DINode::FlagArtificial,
89 DISubprogram::SPFlagDefinition);
90 NoopFn->setSubprogram(SP);
91 DB.finalize();
92}
93
94bool Lowerer::lower(Function &F) {
95 bool IsPrivateAndUnprocessed = F.isPresplitCoroutine() && F.hasLocalLinkage();
96 bool Changed = false;
97
98 NoopCoroElider NCE(F.getDataLayout(), F.getContext());
99 SmallPtrSet<Instruction *, 8> DeadInsts{};
100 for (Instruction &I : instructions(F)) {
101 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
102 switch (II->getIntrinsicID()) {
103 default:
104 continue;
105 case Intrinsic::coro_begin:
106 case Intrinsic::coro_begin_custom_abi:
107 II->replaceAllUsesWith(II->getArgOperand(1));
108 break;
109 case Intrinsic::coro_free:
110 II->replaceAllUsesWith(II->getArgOperand(1));
111 break;
112 case Intrinsic::coro_dead:
113 break;
114 case Intrinsic::coro_alloc:
115 II->replaceAllUsesWith(ConstantInt::getTrue(Context));
116 break;
117 case Intrinsic::coro_async_resume:
118 II->replaceAllUsesWith(
120 break;
121 case Intrinsic::coro_id:
122 case Intrinsic::coro_id_retcon:
123 case Intrinsic::coro_id_retcon_once:
124 case Intrinsic::coro_id_async:
125 II->replaceAllUsesWith(ConstantTokenNone::get(Context));
126 break;
127 case Intrinsic::coro_noop:
128 NCE.run(II);
129 if (!II->user_empty())
130 lowerCoroNoop(II);
131 break;
132 case Intrinsic::coro_subfn_addr:
134 break;
135 case Intrinsic::coro_suspend_retcon:
136 case Intrinsic::coro_is_in_ramp:
137 if (IsPrivateAndUnprocessed) {
138 II->replaceAllUsesWith(PoisonValue::get(II->getType()));
139 } else
140 continue;
141 break;
142 case Intrinsic::coro_async_size_replace:
145 II->getArgOperand(0)->stripPointerCastsAndAliases())
146 ->getInitializer());
149 II->getArgOperand(1)->stripPointerCastsAndAliases())
150 ->getInitializer());
151 auto *TargetSize = Target->getOperand(1);
152 auto *SourceSize = Source->getOperand(1);
153 if (TargetSize->isElementWiseEqual(SourceSize)) {
154 break;
155 }
156 auto *TargetRelativeFunOffset = Target->getOperand(0);
157 auto *NewFuncPtrStruct = ConstantStruct::get(
158 Target->getType(), TargetRelativeFunOffset, SourceSize);
159 Target->replaceAllUsesWith(NewFuncPtrStruct);
160 break;
161 }
162 DeadInsts.insert(II);
163 Changed = true;
164 }
165 }
166
167 for (auto *I : DeadInsts)
168 I->eraseFromParent();
169 return Changed;
170}
171
172void Lowerer::lowerCoroNoop(IntrinsicInst *II) {
173 if (!NoopCoro) {
174 LLVMContext &C = Builder.getContext();
175 Module &M = *II->getModule();
176
177 // Create a noop.frame struct type.
178 auto *FnTy = FunctionType::get(Type::getVoidTy(C), Builder.getPtrTy(0),
179 /*isVarArg=*/false);
180 auto *FnPtrTy = Builder.getPtrTy(0);
181 StructType *FrameTy =
182 StructType::create({FnPtrTy, FnPtrTy}, "NoopCoro.Frame");
183
184 // Create a Noop function that does nothing.
186 FnTy, GlobalValue::LinkageTypes::InternalLinkage,
187 M.getDataLayout().getProgramAddressSpace(), "__NoopCoro_ResumeDestroy",
188 &M);
189
190 // Mark this synthetic function's entry count as explicitly unknown.
192
194 auto *Entry = BasicBlock::Create(C, "entry", NoopFn);
195 ReturnInst::Create(C, Entry);
196
197 // Create a constant struct for the frame.
198 Constant *Values[] = {NoopFn, NoopFn};
199 Constant *NoopCoroConst = ConstantStruct::get(FrameTy, Values);
200 NoopCoro = new GlobalVariable(
201 M, NoopCoroConst->getType(), /*isConstant=*/true,
202 GlobalVariable::PrivateLinkage, NoopCoroConst, "NoopCoro.Frame.Const");
203 cast<GlobalVariable>(NoopCoro)->setNoSanitizeMetadata();
204 }
205
206 Builder.SetInsertPoint(II);
207 auto *NoopCoroVoidPtr = Builder.CreateBitCast(NoopCoro, Int8Ptr);
208 II->replaceAllUsesWith(NoopCoroVoidPtr);
209}
210
211void NoopCoroElider::run(IntrinsicInst *II) {
212 visitPtr(*II);
213
214 Worklist.clear();
215 VisitedUses.clear();
216}
217
218void NoopCoroElider::visitCallBase(CallBase &CB) {
219 auto *V = U->get();
220 bool ResumeOrDestroy = V == CB.getCalledOperand();
221 if (ResumeOrDestroy) {
222 [[maybe_unused]] bool Success = tryEraseCallInvoke(&CB);
223 assert(Success && "Unexpected CallBase");
224
225 auto AboutToDeleteCallback = [this](Value *V) {
226 eraseFromWorklist(cast<Instruction>(V));
227 };
229 AboutToDeleteCallback);
230 }
231}
232
233void NoopCoroElider::visitIntrinsicInst(IntrinsicInst &II) {
234 if (auto *SubFn = dyn_cast<CoroSubFnInst>(&II)) {
235 auto *User = SubFn->getUniqueUndroppableUser();
236 assert(User && "Broken module");
237 if (!tryEraseCallInvoke(cast<Instruction>(User)))
238 return;
239 SubFn->eraseFromParent();
240 }
241}
242
243bool NoopCoroElider::tryEraseCallInvoke(Instruction *I) {
244 if (auto *Call = dyn_cast<CallInst>(I)) {
245 eraseFromWorklist(Call);
247 return true;
248 }
249
250 if (auto *II = dyn_cast<InvokeInst>(I)) {
251 Builder.SetInsertPoint(II);
252 Builder.CreateBr(II->getNormalDest());
253 eraseFromWorklist(II);
254 II->getUnwindDest()->removePredecessor(II->getParent());
255 II->eraseFromParent();
256 return true;
257 }
258 return false;
259}
260
261void NoopCoroElider::eraseFromWorklist(Instruction *I) {
262 erase_if(Worklist, [I](UseToVisit &U) {
263 return I == U.UseAndIsOffsetKnown.getPointer()->getUser();
264 });
265}
266
269 M, {Intrinsic::coro_alloc, Intrinsic::coro_begin,
270 Intrinsic::coro_subfn_addr, Intrinsic::coro_free,
271 Intrinsic::coro_dead, Intrinsic::coro_id, Intrinsic::coro_id_retcon,
272 Intrinsic::coro_id_async, Intrinsic::coro_id_retcon_once,
273 Intrinsic::coro_noop, Intrinsic::coro_async_size_replace,
274 Intrinsic::coro_async_resume, Intrinsic::coro_begin_custom_abi});
275}
276
280 return PreservedAnalyses::all();
281
283 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
284
287
288 PreservedAnalyses FuncPA;
289 FuncPA.preserveSet<CFGAnalyses>();
290
291 Lowerer L(M);
292 for (auto &F : M) {
293 if (L.lower(F)) {
294 FAM.invalidate(F, FuncPA);
295 FPM.run(F, FAM);
296 }
297 }
298
300}
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static bool declaresCoroCleanupIntrinsics(const Module &M)
static void lowerSubFn(IRBuilder<> &Builder, CoroSubFnInst *SubFn)
static void buildDebugInfoForNoopResumeDestroyFunc(Function *NoopFn)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains the declarations for profiling metadata utility functions.
This file provides a collection of visitors which walk the (instruction) uses of a pointer.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
static const unsigned FramePtr
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getCalledOperand() const
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
This is an important base class in LLVM.
Definition Constant.h:43
This class represents the llvm.coro.subfn.addr instruction.
Definition CoroInstr.h:36
Value * getFrame() const
Definition CoroInstr.h:49
ResumeKind getIndex() const
Definition CoroInstr.h:50
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition Function.cpp:373
Module * getParent()
Get the module that this global value is contained inside of...
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1210
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2243
LLVMContext & getContext() const
Definition IRBuilder.h:177
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:577
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
A base class for visitors over the uses of a pointer value.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
A pass to simplify and canonicalize the CFG of a function.
Definition SimplifyCFG.h:30
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:683
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
CallInst * Call
Changed
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool declaresIntrinsics(const Module &M, ArrayRef< Intrinsic::ID > List)
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:535
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void setExplicitlyUnknownFunctionEntryCount(Function &F, StringRef PassName)
Analogous to setExplicitlyUnknownBranchWeights, but for functions and their entry counts.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)