blob: 7cb459874ef27146bf8279e60900b881ae899f75 [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
Philip Reamesf27f3732015-01-15 19:29:42 +0000119/// doInitialization - If this module uses the GC intrinsics, find them now.
120bool LowerIntrinsics::doInitialization(Module &M) {
121 // FIXME: This is rather antisocial in the context of a JIT since it performs
122 // work against the entire module. But this cannot be done at
123 // runFunction time (initializeCustomLowering likely needs to change
124 // the module).
125 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
126 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
127 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
128 if (!I->isDeclaration() && I->hasGC())
129 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
130
131 bool MadeChange = false;
132 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
133 if (NeedsCustomLoweringPass(**I))
134 if ((*I)->initializeCustomLowering(M))
135 MadeChange = true;
136
137 return MadeChange;
138}
139
Philip Reames66c9fb02015-01-15 19:49:25 +0000140/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
141/// instruction could introduce a safe point.
142static bool CouldBecomeSafePoint(Instruction *I) {
143 // The natural definition of instructions which could introduce safe points
144 // are:
145 //
146 // - call, invoke (AfterCall, BeforeCall)
147 // - phis (Loops)
148 // - invoke, ret, unwind (Exit)
149 //
150 // However, instructions as seemingly inoccuous as arithmetic can become
151 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
152 // it is necessary to take a conservative approach.
153
154 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
155 isa<LoadInst>(I))
156 return false;
157
158 // llvm.gcroot is safe because it doesn't do anything at runtime.
159 if (CallInst *CI = dyn_cast<CallInst>(I))
160 if (Function *F = CI->getCalledFunction())
161 if (unsigned IID = F->getIntrinsicID())
162 if (IID == Intrinsic::gcroot)
163 return false;
164
165 return true;
166}
167
168static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
169 unsigned Count) {
Philip Reamesf27f3732015-01-15 19:29:42 +0000170 // Scroll past alloca instructions.
171 BasicBlock::iterator IP = F.getEntryBlock().begin();
Philip Reamesb8714412015-01-15 19:39:17 +0000172 while (isa<AllocaInst>(IP))
173 ++IP;
Philip Reamesf27f3732015-01-15 19:29:42 +0000174
175 // Search for initializers in the initial BB.
Philip Reamesb8714412015-01-15 19:39:17 +0000176 SmallPtrSet<AllocaInst *, 16> InitedRoots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000177 for (; !CouldBecomeSafePoint(IP); ++IP)
178 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
179 if (AllocaInst *AI =
Philip Reamesb8714412015-01-15 19:39:17 +0000180 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Philip Reamesf27f3732015-01-15 19:29:42 +0000181 InitedRoots.insert(AI);
182
183 // Add root initializers.
184 bool MadeChange = false;
185
186 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
187 if (!InitedRoots.count(*I)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000188 StoreInst *SI = new StoreInst(
189 ConstantPointerNull::get(cast<PointerType>(
190 cast<PointerType>((*I)->getType())->getElementType())),
191 *I);
Philip Reamesf27f3732015-01-15 19:29:42 +0000192 SI->insertAfter(*I);
193 MadeChange = true;
194 }
195
196 return MadeChange;
197}
198
Philip Reamesf27f3732015-01-15 19:29:42 +0000199/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
200/// Leave gcroot intrinsics; the code generator needs to see those.
201bool LowerIntrinsics::runOnFunction(Function &F) {
202 // Quick exit for functions that do not use GC.
203 if (!F.hasGC())
204 return false;
205
206 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
207 GCStrategy &S = FI.getStrategy();
208
209 bool MadeChange = false;
210
211 if (NeedsDefaultLoweringPass(S))
212 MadeChange |= PerformDefaultLowering(F, S);
213
214 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
215 if (UseCustomLoweringPass)
216 MadeChange |= S.performCustomLowering(F);
217
218 // Custom lowering may modify the CFG, so dominators must be recomputed.
219 if (UseCustomLoweringPass) {
220 if (DominatorTreeWrapperPass *DTWP =
221 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
222 DTWP->getDomTree().recalculate(F);
223 }
224
225 return MadeChange;
226}
227
228bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
229 bool LowerWr = !S.customWriteBarrier();
230 bool LowerRd = !S.customReadBarrier();
231 bool InitRoots = S.initializeRoots();
232
Philip Reamesb8714412015-01-15 19:39:17 +0000233 SmallVector<AllocaInst *, 32> Roots;
Philip Reamesf27f3732015-01-15 19:29:42 +0000234
235 bool MadeChange = false;
236 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
237 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
238 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
239 Function *F = CI->getCalledFunction();
240 switch (F->getIntrinsicID()) {
241 case Intrinsic::gcwrite:
242 if (LowerWr) {
243 // Replace a write barrier with a simple store.
Philip Reamesb8714412015-01-15 19:39:17 +0000244 Value *St =
245 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
Philip Reamesf27f3732015-01-15 19:29:42 +0000246 CI->replaceAllUsesWith(St);
247 CI->eraseFromParent();
248 }
249 break;
250 case Intrinsic::gcread:
251 if (LowerRd) {
252 // Replace a read barrier with a simple load.
253 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
254 Ld->takeName(CI);
255 CI->replaceAllUsesWith(Ld);
256 CI->eraseFromParent();
257 }
258 break;
259 case Intrinsic::gcroot:
260 if (InitRoots) {
261 // Initialize the GC root, but do not delete the intrinsic. The
262 // backend needs the intrinsic to flag the stack slot.
Philip Reamesb8714412015-01-15 19:39:17 +0000263 Roots.push_back(
264 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
Philip Reamesf27f3732015-01-15 19:29:42 +0000265 }
266 break;
267 default:
268 continue;
269 }
270
271 MadeChange = true;
272 }
273 }
274 }
275
276 if (Roots.size())
277 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
278
279 return MadeChange;
280}
281
282// -----------------------------------------------------------------------------
283
284char GCMachineCodeAnalysis::ID = 0;
285char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
286
287INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
288 "Analyze Machine Code For Garbage Collection", false, false)
289
Philip Reamesb8714412015-01-15 19:39:17 +0000290GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
Philip Reamesf27f3732015-01-15 19:29:42 +0000291
292void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
293 MachineFunctionPass::getAnalysisUsage(AU);
294 AU.setPreservesAll();
295 AU.addRequired<MachineModuleInfo>();
296 AU.addRequired<GCModuleInfo>();
297}
298
299MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
300 MachineBasicBlock::iterator MI,
301 DebugLoc DL) const {
302 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
303 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
304 return Label;
305}
306
307void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
308 // Find the return address (next instruction), too, so as to bracket the call
309 // instruction.
310 MachineBasicBlock::iterator RAI = CI;
311 ++RAI;
312
313 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000314 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000315 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
316 }
317
318 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
Philip Reamesb8714412015-01-15 19:39:17 +0000319 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
Philip Reamesf27f3732015-01-15 19:29:42 +0000320 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
321 }
322}
323
324void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
Philip Reamesb8714412015-01-15 19:39:17 +0000325 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
326 ++BBI)
327 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
328 MI != ME; ++MI)
Philip Reames7de640a2015-01-16 19:33:28 +0000329 if (MI->isCall()) {
330 // Do not treat tail or sibling call sites as safe points. This is
331 // legal since any arguments passed to the callee which live in the
332 // remnants of the callers frame will be owned and updated by the
333 // callee if required.
334 if (MI->isTerminator())
335 continue;
Philip Reamesf27f3732015-01-15 19:29:42 +0000336 VisitCallPoint(MI);
Philip Reames7de640a2015-01-16 19:33:28 +0000337 }
Philip Reamesf27f3732015-01-15 19:29:42 +0000338}
339
340void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
341 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
342 assert(TFI && "TargetRegisterInfo not available!");
343
344 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
345 RI != FI->roots_end();) {
346 // If the root references a dead object, no need to keep it.
347 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
348 RI = FI->removeStackRoot(RI);
349 } else {
350 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
351 ++RI;
352 }
353 }
354}
355
356bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
357 // Quick exit for functions that do not use GC.
358 if (!MF.getFunction()->hasGC())
359 return false;
360
361 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
362 if (!FI->getStrategy().needsSafePoints())
363 return false;
364
365 TM = &MF.getTarget();
366 MMI = &getAnalysis<MachineModuleInfo>();
367 TII = TM->getSubtargetImpl()->getInstrInfo();
368
369 // Find the size of the stack frame.
370 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
371
372 // Find all safe points.
Philip Reames7de640a2015-01-16 19:33:28 +0000373 FindSafePoints(MF);
Philip Reamesf27f3732015-01-15 19:29:42 +0000374
375 // Find the stack offsets for all roots.
376 FindStackOffsets(MF);
377
378 return false;
379}