blob: 90571d090bfbc170bf590cdb726dd8a6ae553356 [file] [log] [blame]
Philip Reamesf27f3732015-01-15 19:29:42 +00001//===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Philip Reamesf27f3732015-01-15 19:29:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the lowering for the gc.root mechanism.
10//
11//===----------------------------------------------------------------------===//
12
Philip Reames2b453952015-01-16 20:07:33 +000013#include "llvm/CodeGen/GCMetadata.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000014#include "llvm/CodeGen/GCStrategy.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000015#include "llvm/CodeGen/MachineFrameInfo.h"
16#include "llvm/CodeGen/MachineFunctionPass.h"
17#include "llvm/CodeGen/MachineInstrBuilder.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000020#include "llvm/CodeGen/TargetFrameLowering.h"
21#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000022#include "llvm/CodeGen/TargetRegisterInfo.h"
23#include "llvm/CodeGen/TargetSubtargetInfo.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000024#include "llvm/IR/Dominators.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000030
31using namespace llvm;
32
33namespace {
34
Philip Reamesb8714412015-01-15 19:39:17 +000035/// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
36/// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
37/// directed by the GCStrategy. It also performs automatic root initialization
38/// and custom intrinsic lowering.
39class LowerIntrinsics : public FunctionPass {
Philip Reames18945d62018-11-11 21:13:09 +000040 bool DoLowering(Function &F, GCStrategy &S);
Philip Reamesf27f3732015-01-15 19:29:42 +000041
Philip Reamesb8714412015-01-15 19:39:17 +000042public:
43 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000044
Philip Reamesb8714412015-01-15 19:39:17 +000045 LowerIntrinsics();
Mehdi Amini117296c2016-10-01 02:56:57 +000046 StringRef getPassName() const override;
Philip Reamesb8714412015-01-15 19:39:17 +000047 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000048
Philip Reamesb8714412015-01-15 19:39:17 +000049 bool doInitialization(Module &M) override;
50 bool runOnFunction(Function &F) override;
51};
Philip Reamesf27f3732015-01-15 19:29:42 +000052
Philip Reamesb8714412015-01-15 19:39:17 +000053/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
54/// function representation to identify safe points for the garbage collector
55/// in the machine code. It inserts labels at safe points and populates a
56/// GCMetadata record for each function.
57class GCMachineCodeAnalysis : public MachineFunctionPass {
Philip Reamesb8714412015-01-15 19:39:17 +000058 GCFunctionInfo *FI;
59 MachineModuleInfo *MMI;
60 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000061
Philip Reamesb8714412015-01-15 19:39:17 +000062 void FindSafePoints(MachineFunction &MF);
Fangrui Songcb0bab82018-07-16 18:51:40 +000063 void VisitCallPoint(MachineBasicBlock::iterator CI);
Philip Reamesb8714412015-01-15 19:39:17 +000064 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +000065 const DebugLoc &DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000066
Philip Reamesb8714412015-01-15 19:39:17 +000067 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000068
Philip Reamesb8714412015-01-15 19:39:17 +000069public:
70 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000071
Philip Reamesb8714412015-01-15 19:39:17 +000072 GCMachineCodeAnalysis();
73 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000074
Philip Reamesb8714412015-01-15 19:39:17 +000075 bool runOnMachineFunction(MachineFunction &MF) override;
76};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000077}
Philip Reamesf27f3732015-01-15 19:29:42 +000078
79// -----------------------------------------------------------------------------
80
Philip Reamesb8714412015-01-15 19:39:17 +000081INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
82 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000083INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
84INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
85
Philip Reamesb8714412015-01-15 19:39:17 +000086FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000087
88char LowerIntrinsics::ID = 0;
89
Philip Reamesb8714412015-01-15 19:39:17 +000090LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
91 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
92}
Philip Reamesf27f3732015-01-15 19:29:42 +000093
Mehdi Amini117296c2016-10-01 02:56:57 +000094StringRef LowerIntrinsics::getPassName() const {
Philip Reamesf27f3732015-01-15 19:29:42 +000095 return "Lower Garbage Collection Instructions";
96}
97
98void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
99 FunctionPass::getAnalysisUsage(AU);
100 AU.addRequired<GCModuleInfo>();
101 AU.addPreserved<DominatorTreeWrapperPass>();
102}
103
104/// doInitialization - If this module uses the GC intrinsics, find them now.
105bool LowerIntrinsics::doInitialization(Module &M) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000106 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
107 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
108 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
109 if (!I->isDeclaration() && I->hasGC())
110 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
111
Philip Reames23cf2e22015-01-28 19:28:03 +0000112 return false;
Philip Reamesf27f3732015-01-15 19:29:42 +0000113}
114
Philip Reames66c9fb02015-01-15 19:49:25 +0000115/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
116/// instruction could introduce a safe point.
117static bool CouldBecomeSafePoint(Instruction *I) {
118 // The natural definition of instructions which could introduce safe points
119 // are:
120 //
121 // - call, invoke (AfterCall, BeforeCall)
122 // - phis (Loops)
123 // - invoke, ret, unwind (Exit)
124 //
125 // However, instructions as seemingly inoccuous as arithmetic can become
126 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
127 // it is necessary to take a conservative approach.
128
129 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
130 isa<LoadInst>(I))
131 return false;
132
133 // llvm.gcroot is safe because it doesn't do anything at runtime.
134 if (CallInst *CI = dyn_cast<CallInst>(I))
135 if (Function *F = CI->getCalledFunction())
Pete Cooper9e1d3352015-05-20 17:16:39 +0000136 if (Intrinsic::ID IID = F->getIntrinsicID())
Philip Reames66c9fb02015-01-15 19:49:25 +0000137 if (IID == Intrinsic::gcroot)
138 return false;
139
140 return true;
141}
142
Philip Reames15590212018-11-12 02:26:26 +0000143static bool InsertRootInitializers(Function &F, ArrayRef<AllocaInst *> Roots) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000144 // Scroll past alloca instructions.
145 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000146 while (isa<AllocaInst>(IP))
147 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000148
149 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000150 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000151 for (; !CouldBecomeSafePoint(&*IP); ++IP)
Philip Reamesf27f3732015-01-15 19:29:42 +0000152 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
153 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000154 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000155 InitedRoots.insert(AI);
156
157 // Add root initializers.
158 bool MadeChange = false;
159
Philip Reames15590212018-11-12 02:26:26 +0000160 for (AllocaInst *Root : Roots)
161 if (!InitedRoots.count(Root)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000162 StoreInst *SI = new StoreInst(
Philip Reames15590212018-11-12 02:26:26 +0000163 ConstantPointerNull::get(cast<PointerType>(Root->getAllocatedType())),
164 Root);
165 SI->insertAfter(Root);
Philip Reamesf27f3732015-01-15 19:29:42 +0000166 MadeChange = true;
167 }
168
169 return MadeChange;
170}
171
Philip Reamesf27f3732015-01-15 19:29:42 +0000172/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
173/// Leave gcroot intrinsics; the code generator needs to see those.
174bool LowerIntrinsics::runOnFunction(Function &F) {
175 // Quick exit for functions that do not use GC.
176 if (!F.hasGC())
177 return false;
178
179 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
180 GCStrategy &S = FI.getStrategy();
181
Philip Reames18945d62018-11-11 21:13:09 +0000182 return DoLowering(F, S);
Philip Reamesf27f3732015-01-15 19:29:42 +0000183}
184
Philip Reames18945d62018-11-11 21:13:09 +0000185/// Lower barriers out of existance (if the associated GCStrategy hasn't
186/// already done so...), and insert initializing stores to roots as a defensive
187/// measure. Given we're going to report all roots live at all safepoints, we
188/// need to be able to ensure each root has been initialized by the point the
189/// first safepoint is reached. This really should have been done by the
190/// frontend, but the old API made this non-obvious, so we do a potentially
191/// redundant store just in case.
192bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
Philip Reamesb8714412015-01-15 19:39:17 +0000193 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000194
195 bool MadeChange = false;
Philip Reames15590212018-11-12 02:26:26 +0000196 for (BasicBlock &BB : F)
197 for (BasicBlock::iterator II = BB.begin(), E = BB.end(); II != E;) {
198 IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++);
199 if (!CI)
200 continue;
201
202 Function *F = CI->getCalledFunction();
203 switch (F->getIntrinsicID()) {
204 default: break;
205 case Intrinsic::gcwrite: {
206 // Replace a write barrier with a simple store.
207 Value *St = new StoreInst(CI->getArgOperand(0),
208 CI->getArgOperand(2), CI);
209 CI->replaceAllUsesWith(St);
210 CI->eraseFromParent();
211 MadeChange = true;
212 break;
213 }
214 case Intrinsic::gcread: {
215 // Replace a read barrier with a simple load.
James Y Knight14359ef2019-02-01 20:44:24 +0000216 Value *Ld = new LoadInst(CI->getType(), CI->getArgOperand(1), "", CI);
Philip Reames15590212018-11-12 02:26:26 +0000217 Ld->takeName(CI);
218 CI->replaceAllUsesWith(Ld);
219 CI->eraseFromParent();
220 MadeChange = true;
221 break;
222 }
223 case Intrinsic::gcroot: {
224 // Initialize the GC root, but do not delete the intrinsic. The
225 // backend needs the intrinsic to flag the stack slot.
226 Roots.push_back(
227 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
228 break;
229 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000230 }
231 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000232
233 if (Roots.size())
Philip Reames15590212018-11-12 02:26:26 +0000234 MadeChange |= InsertRootInitializers(F, Roots);
Philip Reamesf27f3732015-01-15 19:29:42 +0000235
236 return MadeChange;
237}
238
239// -----------------------------------------------------------------------------
240
241char GCMachineCodeAnalysis::ID = 0;
242char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
243
244INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
245 "Analyze Machine Code For Garbage Collection", false, false)
246
Philip Reamesb8714412015-01-15 19:39:17 +0000247GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000248
249void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
250 MachineFunctionPass::getAnalysisUsage(AU);
251 AU.setPreservesAll();
252 AU.addRequired<MachineModuleInfo>();
253 AU.addRequired<GCModuleInfo>();
254}
255
256MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
257 MachineBasicBlock::iterator MI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000258 const DebugLoc &DL) const {
Jim Grosbach6f482002015-05-18 18:43:14 +0000259 MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
Philip Reamesf27f3732015-01-15 19:29:42 +0000260 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
261 return Label;
262}
263
264void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
Philip Reamesc75a0c32018-11-12 20:15:34 +0000265 // Find the return address (next instruction), since that's what will be on
266 // the stack when the call is suspended and we need to inspect the stack.
Philip Reamesf27f3732015-01-15 19:29:42 +0000267 MachineBasicBlock::iterator RAI = CI;
268 ++RAI;
269
Philip Reamese44a55d2018-11-12 22:03:53 +0000270 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
271 FI->addSafePoint(Label, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000272}
273
274void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reames15590212018-11-12 02:26:26 +0000275 for (MachineBasicBlock &MBB : MF)
276 for (MachineBasicBlock::iterator MI = MBB.begin(), ME = MBB.end();
Philip Reamesb8714412015-01-15 19:39:17 +0000277 MI != ME; ++MI)
Philip Reames7de640a2015-01-16 19:33:28 +0000278 if (MI->isCall()) {
279 // Do not treat tail or sibling call sites as safe points. This is
280 // legal since any arguments passed to the callee which live in the
281 // remnants of the callers frame will be owned and updated by the
282 // callee if required.
283 if (MI->isTerminator())
284 continue;
Philip Reamesf27f3732015-01-15 19:29:42 +0000285 VisitCallPoint(MI);
Philip Reames7de640a2015-01-16 19:33:28 +0000286 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000287}
288
289void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
Eric Christopher1df0c512015-02-20 18:44:15 +0000290 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Philip Reamesf27f3732015-01-15 19:29:42 +0000291 assert(TFI && "TargetRegisterInfo not available!");
292
293 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
294 RI != FI->roots_end();) {
295 // If the root references a dead object, no need to keep it.
Matthias Braun941a7052016-07-28 18:40:00 +0000296 if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000297 RI = FI->removeStackRoot(RI);
298 } else {
James Y Knight5567baf2015-08-15 02:32:35 +0000299 unsigned FrameReg; // FIXME: surely GCRoot ought to store the
300 // register that the offset is from?
301 RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
Philip Reamesf27f3732015-01-15 19:29:42 +0000302 ++RI;
303 }
304 }
305}
306
307bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
308 // Quick exit for functions that do not use GC.
Matthias Braunf1caa282017-12-15 22:22:58 +0000309 if (!MF.getFunction().hasGC())
Philip Reamesf27f3732015-01-15 19:29:42 +0000310 return false;
311
Matthias Braunf1caa282017-12-15 22:22:58 +0000312 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
Philip Reamesf27f3732015-01-15 19:29:42 +0000313 MMI = &getAnalysis<MachineModuleInfo>();
Eric Christopher1df0c512015-02-20 18:44:15 +0000314 TII = MF.getSubtarget().getInstrInfo();
Philip Reamesf27f3732015-01-15 19:29:42 +0000315
Philip Reames2df78272015-04-02 05:00:40 +0000316 // Find the size of the stack frame. There may be no correct static frame
317 // size, we use UINT64_MAX to represent this.
Matthias Braun941a7052016-07-28 18:40:00 +0000318 const MachineFrameInfo &MFI = MF.getFrameInfo();
Philip Reames2df78272015-04-02 05:00:40 +0000319 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000320 const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
Philip Reames2df78272015-04-02 05:00:40 +0000321 RegInfo->needsStackRealignment(MF);
Matthias Braun941a7052016-07-28 18:40:00 +0000322 FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());
Philip Reamesf27f3732015-01-15 19:29:42 +0000323
324 // Find all safe points.
Philip Reames2df78272015-04-02 05:00:40 +0000325 if (FI->getStrategy().needsSafePoints())
326 FindSafePoints(MF);
Philip Reamesf27f3732015-01-15 19:29:42 +0000327
Philip Reames2df78272015-04-02 05:00:40 +0000328 // Find the concrete stack offsets for all roots (stack slots)
Philip Reamesf27f3732015-01-15 19:29:42 +0000329 FindStackOffsets(MF);
330
331 return false;
332}