blob: 8ff08ece76e41e485b63e76a899c38a2dfa1889c [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"
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"
20#include "llvm/IR/Dominators.h"
Philip Reames2b453952015-01-16 20:07:33 +000021#include "llvm/IR/GCStrategy.h"
Philip Reamesf27f3732015-01-15 19:29:42 +000022#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 {
60 const TargetMachine *TM;
61 GCFunctionInfo *FI;
62 MachineModuleInfo *MMI;
63 const TargetInstrInfo *TII;
Philip Reamesf27f3732015-01-15 19:29:42 +000064
Philip Reamesb8714412015-01-15 19:39:17 +000065 void FindSafePoints(MachineFunction &MF);
66 void VisitCallPoint(MachineBasicBlock::iterator MI);
67 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
68 DebugLoc DL) const;
Philip Reamesf27f3732015-01-15 19:29:42 +000069
Philip Reamesb8714412015-01-15 19:39:17 +000070 void FindStackOffsets(MachineFunction &MF);
Philip Reamesf27f3732015-01-15 19:29:42 +000071
Philip Reamesb8714412015-01-15 19:39:17 +000072public:
73 static char ID;
Philip Reamesf27f3732015-01-15 19:29:42 +000074
Philip Reamesb8714412015-01-15 19:39:17 +000075 GCMachineCodeAnalysis();
76 void getAnalysisUsage(AnalysisUsage &AU) const override;
Philip Reamesf27f3732015-01-15 19:29:42 +000077
Philip Reamesb8714412015-01-15 19:39:17 +000078 bool runOnMachineFunction(MachineFunction &MF) override;
79};
Philip Reamesf27f3732015-01-15 19:29:42 +000080}
81
82// -----------------------------------------------------------------------------
83
Philip Reamesb8714412015-01-15 19:39:17 +000084INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
85 false)
Philip Reamesf27f3732015-01-15 19:29:42 +000086INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
87INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
88
Philip Reamesb8714412015-01-15 19:39:17 +000089FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
Philip Reamesf27f3732015-01-15 19:29:42 +000090
91char LowerIntrinsics::ID = 0;
92
Philip Reamesb8714412015-01-15 19:39:17 +000093LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
94 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
95}
Philip Reamesf27f3732015-01-15 19:29:42 +000096
97const char *LowerIntrinsics::getPassName() const {
98 return "Lower Garbage Collection Instructions";
99}
100
101void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
102 FunctionPass::getAnalysisUsage(AU);
103 AU.addRequired<GCModuleInfo>();
104 AU.addPreserved<DominatorTreeWrapperPass>();
105}
106
Philip Reames66c9fb02015-01-15 19:49:25 +0000107static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
108 // Default lowering is necessary only if read or write barriers have a default
109 // action. The default for roots is no action.
110 return !C.customWriteBarrier() || !C.customReadBarrier() ||
111 C.initializeRoots();
112}
113
114static bool NeedsCustomLoweringPass(const GCStrategy &C) {
115 // Custom lowering is only necessary if enabled for some action.
116 return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
117}
118
119
120
Philip Reamesf27f3732015-01-15 19:29:42 +0000121/// doInitialization - If this module uses the GC intrinsics, find them now.
122bool LowerIntrinsics::doInitialization(Module &M) {
123 // FIXME: This is rather antisocial in the context of a JIT since it performs
124 // work against the entire module. But this cannot be done at
125 // runFunction time (initializeCustomLowering likely needs to change
126 // the module).
127 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
128 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
129 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
130 if (!I->isDeclaration() && I->hasGC())
131 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
132
133 bool MadeChange = false;
134 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
135 if (NeedsCustomLoweringPass(**I))
136 if ((*I)->initializeCustomLowering(M))
137 MadeChange = true;
138
139 return MadeChange;
140}
141
Philip Reames66c9fb02015-01-15 19:49:25 +0000142
143/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
144/// instruction could introduce a safe point.
145static bool CouldBecomeSafePoint(Instruction *I) {
146 // The natural definition of instructions which could introduce safe points
147 // are:
148 //
149 // - call, invoke (AfterCall, BeforeCall)
150 // - phis (Loops)
151 // - invoke, ret, unwind (Exit)
152 //
153 // However, instructions as seemingly inoccuous as arithmetic can become
154 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
155 // it is necessary to take a conservative approach.
156
157 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
158 isa<LoadInst>(I))
159 return false;
160
161 // llvm.gcroot is safe because it doesn't do anything at runtime.
162 if (CallInst *CI = dyn_cast<CallInst>(I))
163 if (Function *F = CI->getCalledFunction())
164 if (unsigned IID = F->getIntrinsicID())
165 if (IID == Intrinsic::gcroot)
166 return false;
167
168 return true;
169}
170
171static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
172 unsigned Count) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000173 // Scroll past alloca instructions.
174 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000175 while (isa<AllocaInst>(IP))
176 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000177
178 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000179 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000180 for (; !CouldBecomeSafePoint(IP); ++IP)
181 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
182 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000183 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000184 InitedRoots.insert(AI);
185
186 // Add root initializers.
187 bool MadeChange = false;
188
189 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
190 if (!InitedRoots.count(*I)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000191 StoreInst *SI = new StoreInst(
192 ConstantPointerNull::get(cast<PointerType>(
193 cast<PointerType>((*I)->getType())->getElementType())),
194 *I);
Philip Reamesf27f3732015-01-15 19:29:42 +0000195 SI->insertAfter(*I);
196 MadeChange = true;
197 }
198
199 return MadeChange;
200}
201
Philip Reamesf27f3732015-01-15 19:29:42 +0000202
203/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
204/// Leave gcroot intrinsics; the code generator needs to see those.
205bool LowerIntrinsics::runOnFunction(Function &F) {
206 // Quick exit for functions that do not use GC.
207 if (!F.hasGC())
208 return false;
209
210 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
211 GCStrategy &S = FI.getStrategy();
212
213 bool MadeChange = false;
214
215 if (NeedsDefaultLoweringPass(S))
216 MadeChange |= PerformDefaultLowering(F, S);
217
218 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
219 if (UseCustomLoweringPass)
220 MadeChange |= S.performCustomLowering(F);
221
222 // Custom lowering may modify the CFG, so dominators must be recomputed.
223 if (UseCustomLoweringPass) {
224 if (DominatorTreeWrapperPass *DTWP =
225 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
226 DTWP->getDomTree().recalculate(F);
227 }
228
229 return MadeChange;
230}
231
232bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
233 bool LowerWr = !S.customWriteBarrier();
234 bool LowerRd = !S.customReadBarrier();
235 bool InitRoots = S.initializeRoots();
236
Philip Reamesb8714412015-01-15 19:39:17 +0000237 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000238
239 bool MadeChange = false;
240 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
241 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
242 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
243 Function *F = CI->getCalledFunction();
244 switch (F->getIntrinsicID()) {
245 case Intrinsic::gcwrite:
246 if (LowerWr) {
247 // Replace a write barrier with a simple store.
Philip Reamesb8714412015-01-15 19:39:17 +0000248 Value *St =
249 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
Philip Reamesf27f3732015-01-15 19:29:42 +0000250 CI->replaceAllUsesWith(St);
251 CI->eraseFromParent();
252 }
253 break;
254 case Intrinsic::gcread:
255 if (LowerRd) {
256 // Replace a read barrier with a simple load.
257 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
258 Ld->takeName(CI);
259 CI->replaceAllUsesWith(Ld);
260 CI->eraseFromParent();
261 }
262 break;
263 case Intrinsic::gcroot:
264 if (InitRoots) {
265 // Initialize the GC root, but do not delete the intrinsic. The
266 // backend needs the intrinsic to flag the stack slot.
Philip Reamesb8714412015-01-15 19:39:17 +0000267 Roots.push_back(
268 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
Philip Reamesf27f3732015-01-15 19:29:42 +0000269 }
270 break;
271 default:
272 continue;
273 }
274
275 MadeChange = true;
276 }
277 }
278 }
279
280 if (Roots.size())
281 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
282
283 return MadeChange;
284}
285
286// -----------------------------------------------------------------------------
287
288char GCMachineCodeAnalysis::ID = 0;
289char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
290
291INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
292 "Analyze Machine Code For Garbage Collection", false, false)
293
Philip Reamesb8714412015-01-15 19:39:17 +0000294GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000295
296void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
297 MachineFunctionPass::getAnalysisUsage(AU);
298 AU.setPreservesAll();
299 AU.addRequired<MachineModuleInfo>();
300 AU.addRequired<GCModuleInfo>();
301}
302
303MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
304 MachineBasicBlock::iterator MI,
305 DebugLoc DL) const {
306 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
307 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
308 return Label;
309}
310
311void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
312 // Find the return address (next instruction), too, so as to bracket the call
313 // instruction.
314 MachineBasicBlock::iterator RAI = CI;
315 ++RAI;
316
317 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000318 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000319 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
320 }
321
322 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000323 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000324 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
325 }
326}
327
328void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reamesb8714412015-01-15 19:39:17 +0000329 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
330 ++BBI)
331 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
332 MI != ME; ++MI)
Philip Reames7de640a2015-01-16 19:33:28 +0000333 if (MI->isCall()) {
334 // Do not treat tail or sibling call sites as safe points. This is
335 // legal since any arguments passed to the callee which live in the
336 // remnants of the callers frame will be owned and updated by the
337 // callee if required.
338 if (MI->isTerminator())
339 continue;
Philip Reamesf27f3732015-01-15 19:29:42 +0000340 VisitCallPoint(MI);
Philip Reames7de640a2015-01-16 19:33:28 +0000341 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000342}
343
344void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
345 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
346 assert(TFI && "TargetRegisterInfo not available!");
347
348 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
349 RI != FI->roots_end();) {
350 // If the root references a dead object, no need to keep it.
351 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
352 RI = FI->removeStackRoot(RI);
353 } else {
354 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
355 ++RI;
356 }
357 }
358}
359
360bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
361 // Quick exit for functions that do not use GC.
362 if (!MF.getFunction()->hasGC())
363 return false;
364
365 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
366 if (!FI->getStrategy().needsSafePoints())
367 return false;
368
369 TM = &MF.getTarget();
370 MMI = &getAnalysis<MachineModuleInfo>();
371 TII = TM->getSubtargetImpl()->getInstrInfo();
372
373 // Find the size of the stack frame.
374 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
375
376 // Find all safe points.
Philip Reames7de640a2015-01-16 19:33:28 +0000377 FindSafePoints(MF);
Philip Reamesf27f3732015-01-15 19:29:42 +0000378
379 // Find the stack offsets for all roots.
380 FindStackOffsets(MF);
381
382 return false;
383}