Move ownership of GCStrategy objects to LLVMContext
[oota-llvm.git] / lib / CodeGen / GCRootLowering.cpp
1 //===-- 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
14 #include "llvm/CodeGen/GCMetadata.h"
15 #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"
21 #include "llvm/IR/GCStrategy.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
33 using namespace llvm;
34
35 namespace {
36
37 /// 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.
41 class LowerIntrinsics : public FunctionPass {
42   bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
43
44 public:
45   static char ID;
46
47   LowerIntrinsics();
48   const char *getPassName() const override;
49   void getAnalysisUsage(AnalysisUsage &AU) const override;
50
51   bool doInitialization(Module &M) override;
52   bool runOnFunction(Function &F) override;
53 };
54
55 /// 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.
59 class GCMachineCodeAnalysis : public MachineFunctionPass {
60   const TargetMachine *TM;
61   GCFunctionInfo *FI;
62   MachineModuleInfo *MMI;
63   const TargetInstrInfo *TII;
64
65   void FindSafePoints(MachineFunction &MF);
66   void VisitCallPoint(MachineBasicBlock::iterator MI);
67   MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
68                         DebugLoc DL) const;
69
70   void FindStackOffsets(MachineFunction &MF);
71
72 public:
73   static char ID;
74
75   GCMachineCodeAnalysis();
76   void getAnalysisUsage(AnalysisUsage &AU) const override;
77
78   bool runOnMachineFunction(MachineFunction &MF) override;
79 };
80 }
81
82 // -----------------------------------------------------------------------------
83
84 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
85                       false)
86 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
87 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
88
89 FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
90
91 char LowerIntrinsics::ID = 0;
92
93 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
94   initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
95 }
96
97 const char *LowerIntrinsics::getPassName() const {
98   return "Lower Garbage Collection Instructions";
99 }
100
101 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
102   FunctionPass::getAnalysisUsage(AU);
103   AU.addRequired<GCModuleInfo>();
104   AU.addPreserved<DominatorTreeWrapperPass>();
105 }
106
107 static 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
114 static 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
121 /// doInitialization - If this module uses the GC intrinsics, find them now.
122 bool 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
142
143 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
144 /// instruction could introduce a safe point.
145 static 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
171 static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
172                                    unsigned Count) {
173   // Scroll past alloca instructions.
174   BasicBlock::iterator IP = F.getEntryBlock().begin();
175   while (isa<AllocaInst>(IP))
176     ++IP;
177
178   // Search for initializers in the initial BB.
179   SmallPtrSet<AllocaInst *, 16> InitedRoots;
180   for (; !CouldBecomeSafePoint(IP); ++IP)
181     if (StoreInst *SI = dyn_cast<StoreInst>(IP))
182       if (AllocaInst *AI =
183               dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
184         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)) {
191       StoreInst *SI = new StoreInst(
192           ConstantPointerNull::get(cast<PointerType>(
193               cast<PointerType>((*I)->getType())->getElementType())),
194           *I);
195       SI->insertAfter(*I);
196       MadeChange = true;
197     }
198
199   return MadeChange;
200 }
201
202
203 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
204 /// Leave gcroot intrinsics; the code generator needs to see those.
205 bool 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
232 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
233   bool LowerWr = !S.customWriteBarrier();
234   bool LowerRd = !S.customReadBarrier();
235   bool InitRoots = S.initializeRoots();
236
237   SmallVector<AllocaInst *, 32> Roots;
238
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.
248             Value *St =
249                 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
250             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.
267             Roots.push_back(
268                 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
269           }
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
288 char GCMachineCodeAnalysis::ID = 0;
289 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
290
291 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
292                 "Analyze Machine Code For Garbage Collection", false, false)
293
294 GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
295
296 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
297   MachineFunctionPass::getAnalysisUsage(AU);
298   AU.setPreservesAll();
299   AU.addRequired<MachineModuleInfo>();
300   AU.addRequired<GCModuleInfo>();
301 }
302
303 MCSymbol *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
311 void 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)) {
318     MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
319     FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
320   }
321
322   if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
323     MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
324     FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
325   }
326 }
327
328 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
329   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)
333       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;
340         VisitCallPoint(MI);
341       }
342 }
343
344 void 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
360 bool 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.
377   FindSafePoints(MF);
378
379   // Find the stack offsets for all roots.
380   FindStackOffsets(MF);
381
382   return false;
383 }