blob: df6be1e4242f696b6e1913f4586d218dae838d0b [file] [log] [blame]
Philip Reamesf27f3732015-01-15 19:29:42 +00001//===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the lowering for the gc.root mechanism.
11//
12//===----------------------------------------------------------------------===//
13
Philip Reames2b453952015-01-16 20:07:33 +000014#include "llvm/CodeGen/GCMetadata.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000015#include "llvm/CodeGen/GCStrategy.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000016#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineModuleInfo.h"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/IR/Dominators.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/Target/TargetFrameLowering.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31#include "llvm/Target/TargetSubtargetInfo.h"
32
33using namespace llvm;
34
35namespace {
36
Philip Reamesb8714412015-01-15 19:39:17 +000037/// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
38/// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
39/// directed by the GCStrategy. It also performs automatic root initialization
40/// and custom intrinsic lowering.
41class LowerIntrinsics : public FunctionPass {
Philip Reamesb8714412015-01-15 19:39:17 +000042 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
Philip Reamesf27f3732015-01-15 19:29:42 +000043
Philip Reamesb8714412015-01-15 19:39:17 +000044public:
45 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000046
Philip Reamesb8714412015-01-15 19:39:17 +000047 LowerIntrinsics();
48 const char *getPassName() const override;
49 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000050
Philip Reamesb8714412015-01-15 19:39:17 +000051 bool doInitialization(Module &M) override;
52 bool runOnFunction(Function &F) override;
53};
Philip Reamesf27f3732015-01-15 19:29:42 +000054
Philip Reamesb8714412015-01-15 19:39:17 +000055/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
56/// function representation to identify safe points for the garbage collector
57/// in the machine code. It inserts labels at safe points and populates a
58/// GCMetadata record for each function.
59class GCMachineCodeAnalysis : public MachineFunctionPass {
Philip Reamesb8714412015-01-15 19:39:17 +000060 GCFunctionInfo *FI;
61 MachineModuleInfo *MMI;
62 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000063
Philip Reamesb8714412015-01-15 19:39:17 +000064 void FindSafePoints(MachineFunction &MF);
65 void VisitCallPoint(MachineBasicBlock::iterator MI);
66 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
67 DebugLoc DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000068
Philip Reamesb8714412015-01-15 19:39:17 +000069 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000070
Philip Reamesb8714412015-01-15 19:39:17 +000071public:
72 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000073
Philip Reamesb8714412015-01-15 19:39:17 +000074 GCMachineCodeAnalysis();
75 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000076
Philip Reamesb8714412015-01-15 19:39:17 +000077 bool runOnMachineFunction(MachineFunction &MF) override;
78};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000079}
Philip Reamesf27f3732015-01-15 19:29:42 +000080
81// -----------------------------------------------------------------------------
82
Philip Reamesb8714412015-01-15 19:39:17 +000083INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
84 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000085INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
86INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
87
Philip Reamesb8714412015-01-15 19:39:17 +000088FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000089
90char LowerIntrinsics::ID = 0;
91
Philip Reamesb8714412015-01-15 19:39:17 +000092LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
93 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
94}
Philip Reamesf27f3732015-01-15 19:29:42 +000095
96const char *LowerIntrinsics::getPassName() const {
97 return "Lower Garbage Collection Instructions";
98}
99
100void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
101 FunctionPass::getAnalysisUsage(AU);
102 AU.addRequired<GCModuleInfo>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
104}
105
Philip Reames66c9fb02015-01-15 19:49:25 +0000106static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
107 // Default lowering is necessary only if read or write barriers have a default
108 // action. The default for roots is no action.
109 return !C.customWriteBarrier() || !C.customReadBarrier() ||
110 C.initializeRoots();
111}
112
Philip Reamesf27f3732015-01-15 19:29:42 +0000113/// doInitialization - If this module uses the GC intrinsics, find them now.
114bool LowerIntrinsics::doInitialization(Module &M) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000115 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
116 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
117 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
118 if (!I->isDeclaration() && I->hasGC())
119 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
120
Philip Reames23cf2e22015-01-28 19:28:03 +0000121 return false;
Philip Reamesf27f3732015-01-15 19:29:42 +0000122}
123
Philip Reames66c9fb02015-01-15 19:49:25 +0000124/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
125/// instruction could introduce a safe point.
126static bool CouldBecomeSafePoint(Instruction *I) {
127 // The natural definition of instructions which could introduce safe points
128 // are:
129 //
130 // - call, invoke (AfterCall, BeforeCall)
131 // - phis (Loops)
132 // - invoke, ret, unwind (Exit)
133 //
134 // However, instructions as seemingly inoccuous as arithmetic can become
135 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
136 // it is necessary to take a conservative approach.
137
138 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
139 isa<LoadInst>(I))
140 return false;
141
142 // llvm.gcroot is safe because it doesn't do anything at runtime.
143 if (CallInst *CI = dyn_cast<CallInst>(I))
144 if (Function *F = CI->getCalledFunction())
Pete Cooper9e1d3352015-05-20 17:16:39 +0000145 if (Intrinsic::ID IID = F->getIntrinsicID())
Philip Reames66c9fb02015-01-15 19:49:25 +0000146 if (IID == Intrinsic::gcroot)
147 return false;
148
149 return true;
150}
151
152static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
153 unsigned Count) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000154 // Scroll past alloca instructions.
155 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000156 while (isa<AllocaInst>(IP))
157 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000158
159 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000160 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000161 for (; !CouldBecomeSafePoint(&*IP); ++IP)
Philip Reamesf27f3732015-01-15 19:29:42 +0000162 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
163 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000164 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000165 InitedRoots.insert(AI);
166
167 // Add root initializers.
168 bool MadeChange = false;
169
170 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
171 if (!InitedRoots.count(*I)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000172 StoreInst *SI = new StoreInst(
Eduard Burtescu90c44492016-01-18 00:10:01 +0000173 ConstantPointerNull::get(cast<PointerType>((*I)->getAllocatedType())),
Philip Reamesb8714412015-01-15 19:39:17 +0000174 *I);
Philip Reamesf27f3732015-01-15 19:29:42 +0000175 SI->insertAfter(*I);
176 MadeChange = true;
177 }
178
179 return MadeChange;
180}
181
Philip Reamesf27f3732015-01-15 19:29:42 +0000182/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
183/// Leave gcroot intrinsics; the code generator needs to see those.
184bool LowerIntrinsics::runOnFunction(Function &F) {
185 // Quick exit for functions that do not use GC.
186 if (!F.hasGC())
187 return false;
188
189 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
190 GCStrategy &S = FI.getStrategy();
191
192 bool MadeChange = false;
193
194 if (NeedsDefaultLoweringPass(S))
195 MadeChange |= PerformDefaultLowering(F, S);
196
Philip Reamesf27f3732015-01-15 19:29:42 +0000197 return MadeChange;
198}
199
200bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
201 bool LowerWr = !S.customWriteBarrier();
202 bool LowerRd = !S.customReadBarrier();
203 bool InitRoots = S.initializeRoots();
204
Philip Reamesb8714412015-01-15 19:39:17 +0000205 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000206
207 bool MadeChange = false;
208 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
209 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
210 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
211 Function *F = CI->getCalledFunction();
212 switch (F->getIntrinsicID()) {
213 case Intrinsic::gcwrite:
214 if (LowerWr) {
215 // Replace a write barrier with a simple store.
Philip Reamesb8714412015-01-15 19:39:17 +0000216 Value *St =
217 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
Philip Reamesf27f3732015-01-15 19:29:42 +0000218 CI->replaceAllUsesWith(St);
219 CI->eraseFromParent();
220 }
221 break;
222 case Intrinsic::gcread:
223 if (LowerRd) {
224 // Replace a read barrier with a simple load.
225 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
226 Ld->takeName(CI);
227 CI->replaceAllUsesWith(Ld);
228 CI->eraseFromParent();
229 }
230 break;
231 case Intrinsic::gcroot:
232 if (InitRoots) {
233 // Initialize the GC root, but do not delete the intrinsic. The
234 // backend needs the intrinsic to flag the stack slot.
Philip Reamesb8714412015-01-15 19:39:17 +0000235 Roots.push_back(
236 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
Philip Reamesf27f3732015-01-15 19:29:42 +0000237 }
238 break;
239 default:
240 continue;
241 }
242
243 MadeChange = true;
244 }
245 }
246 }
247
248 if (Roots.size())
249 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
250
251 return MadeChange;
252}
253
254// -----------------------------------------------------------------------------
255
256char GCMachineCodeAnalysis::ID = 0;
257char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
258
259INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
260 "Analyze Machine Code For Garbage Collection", false, false)
261
Philip Reamesb8714412015-01-15 19:39:17 +0000262GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000263
264void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
265 MachineFunctionPass::getAnalysisUsage(AU);
266 AU.setPreservesAll();
267 AU.addRequired<MachineModuleInfo>();
268 AU.addRequired<GCModuleInfo>();
269}
270
271MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
272 MachineBasicBlock::iterator MI,
273 DebugLoc DL) const {
Jim Grosbach6f482002015-05-18 18:43:14 +0000274 MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
Philip Reamesf27f3732015-01-15 19:29:42 +0000275 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
276 return Label;
277}
278
279void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
280 // Find the return address (next instruction), too, so as to bracket the call
281 // instruction.
282 MachineBasicBlock::iterator RAI = CI;
283 ++RAI;
284
285 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000286 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000287 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
288 }
289
290 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000291 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000292 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
293 }
294}
295
296void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reamesb8714412015-01-15 19:39:17 +0000297 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
298 ++BBI)
299 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
300 MI != ME; ++MI)
Philip Reames7de640a2015-01-16 19:33:28 +0000301 if (MI->isCall()) {
302 // Do not treat tail or sibling call sites as safe points. This is
303 // legal since any arguments passed to the callee which live in the
304 // remnants of the callers frame will be owned and updated by the
305 // callee if required.
306 if (MI->isTerminator())
307 continue;
Philip Reamesf27f3732015-01-15 19:29:42 +0000308 VisitCallPoint(MI);
Philip Reames7de640a2015-01-16 19:33:28 +0000309 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000310}
311
312void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
Eric Christopher1df0c512015-02-20 18:44:15 +0000313 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Philip Reamesf27f3732015-01-15 19:29:42 +0000314 assert(TFI && "TargetRegisterInfo not available!");
315
316 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
317 RI != FI->roots_end();) {
318 // If the root references a dead object, no need to keep it.
319 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
320 RI = FI->removeStackRoot(RI);
321 } else {
James Y Knight5567baf2015-08-15 02:32:35 +0000322 unsigned FrameReg; // FIXME: surely GCRoot ought to store the
323 // register that the offset is from?
324 RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
Philip Reamesf27f3732015-01-15 19:29:42 +0000325 ++RI;
326 }
327 }
328}
329
330bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
331 // Quick exit for functions that do not use GC.
332 if (!MF.getFunction()->hasGC())
333 return false;
334
335 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Philip Reamesf27f3732015-01-15 19:29:42 +0000336 MMI = &getAnalysis<MachineModuleInfo>();
Eric Christopher1df0c512015-02-20 18:44:15 +0000337 TII = MF.getSubtarget().getInstrInfo();
Philip Reamesf27f3732015-01-15 19:29:42 +0000338
Philip Reames2df78272015-04-02 05:00:40 +0000339 // Find the size of the stack frame. There may be no correct static frame
340 // size, we use UINT64_MAX to represent this.
341 const MachineFrameInfo *MFI = MF.getFrameInfo();
342 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
343 const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
344 RegInfo->needsStackRealignment(MF);
345 FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI->getStackSize());
Philip Reamesf27f3732015-01-15 19:29:42 +0000346
347 // Find all safe points.
Philip Reames2df78272015-04-02 05:00:40 +0000348 if (FI->getStrategy().needsSafePoints())
349 FindSafePoints(MF);
Philip Reamesf27f3732015-01-15 19:29:42 +0000350
Philip Reames2df78272015-04-02 05:00:40 +0000351 // Find the concrete stack offsets for all roots (stack slots)
Philip Reamesf27f3732015-01-15 19:29:42 +0000352 FindStackOffsets(MF);
353
354 return false;
355}