Rename some GC classes so that their roll will hopefully be clearer.
[oota-llvm.git] / lib / CodeGen / GCStrategy.cpp
1 //===-- GCStrategy.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 target- and collector-independent garbage collection
11 // infrastructure.
12 //
13 // MachineCodeAnalysis identifies the GC safe points in the machine code. Roots
14 // are identified in SelectionDAGISel.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/CodeGen/GCStrategy.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Compiler.h"
30
31 using namespace llvm;
32
33 namespace {
34   
35   /// 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.
39   class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
40     static bool NeedsDefaultLoweringPass(const GCStrategy &C);
41     static bool NeedsCustomLoweringPass(const GCStrategy &C);
42     static bool CouldBecomeSafePoint(Instruction *I);
43     bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
44     static bool InsertRootInitializers(Function &F,
45                                        AllocaInst **Roots, unsigned Count);
46     
47   public:
48     static char ID;
49     
50     LowerIntrinsics();
51     const char *getPassName() const;
52     void getAnalysisUsage(AnalysisUsage &AU) const;
53     
54     bool doInitialization(Module &M);
55     bool runOnFunction(Function &F);
56   };
57   
58   
59   /// MachineCodeAnalysis - This is a target-independent pass over the machine 
60   /// function representation to identify safe points for the garbage collector
61   /// in the machine code. It inserts labels at safe points and populates a
62   /// GCMetadata record for each function.
63   class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
64     const TargetMachine *TM;
65     GCFunctionInfo *FI;
66     MachineModuleInfo *MMI;
67     const TargetInstrInfo *TII;
68     MachineFrameInfo *MFI;
69     
70     void FindSafePoints(MachineFunction &MF);
71     void VisitCallPoint(MachineBasicBlock::iterator MI);
72     unsigned InsertLabel(MachineBasicBlock &MBB, 
73                          MachineBasicBlock::iterator MI) const;
74     
75     void FindStackOffsets(MachineFunction &MF);
76     
77   public:
78     static char ID;
79     
80     MachineCodeAnalysis();
81     const char *getPassName() const;
82     void getAnalysisUsage(AnalysisUsage &AU) const;
83     
84     bool runOnMachineFunction(MachineFunction &MF);
85   };
86   
87 }
88
89 // -----------------------------------------------------------------------------
90
91 template<> GCRegistry::node *GCRegistry::Head = 0;
92 template<> GCRegistry::node *GCRegistry::Tail = 0;
93 template<> GCRegistry::listener *GCRegistry::ListenerHead = 0;
94 template<> GCRegistry::listener *GCRegistry::ListenerTail = 0;
95
96 // -----------------------------------------------------------------------------
97
98 GCStrategy::GCStrategy() :
99   NeededSafePoints(0),
100   CustomReadBarriers(false),
101   CustomWriteBarriers(false),
102   CustomRoots(false),
103   InitRoots(true),
104   UsesMetadata(false)
105 {}
106
107 GCStrategy::~GCStrategy() {
108   for (iterator I = begin(), E = end(); I != E; ++I)
109     delete *I;
110   
111   Functions.clear();
112 }
113  
114 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
115  
116 bool GCStrategy::performCustomLowering(Function &F) {
117   cerr << "gc " << getName() << " must override performCustomLowering.\n";
118   abort();
119   return 0;
120 }
121
122 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
123   GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
124   Functions.push_back(FI);
125   return FI;
126 }
127
128 // -----------------------------------------------------------------------------
129
130 FunctionPass *llvm::createGCLoweringPass() {
131   return new LowerIntrinsics();
132 }
133  
134 char LowerIntrinsics::ID = 0;
135
136 LowerIntrinsics::LowerIntrinsics()
137   : FunctionPass((intptr_t)&ID) {}
138
139 const char *LowerIntrinsics::getPassName() const {
140   return "Lower Garbage Collection Instructions";
141 }
142     
143 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
144   FunctionPass::getAnalysisUsage(AU);
145   AU.addRequired<GCModuleInfo>();
146 }
147
148 /// doInitialization - If this module uses the GC intrinsics, find them now.
149 bool LowerIntrinsics::doInitialization(Module &M) {
150   // FIXME: This is rather antisocial in the context of a JIT since it performs
151   //        work against the entire module. But this cannot be done at
152   //        runFunction time (initializeCustomLowering likely needs to change
153   //        the module).
154   GCModuleInfo *MI = getAnalysisToUpdate<GCModuleInfo>();
155   assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
156   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
157     if (!I->isDeclaration() && I->hasGC())
158       MI->getFunctionInfo(*I); // Instantiate the GC strategy.
159   
160   bool MadeChange = false;
161   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
162     if (NeedsCustomLoweringPass(**I))
163       if ((*I)->initializeCustomLowering(M))
164         MadeChange = true;
165   
166   return MadeChange;
167 }
168
169 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots, 
170                                                           unsigned Count) {
171   // Scroll past alloca instructions.
172   BasicBlock::iterator IP = F.getEntryBlock().begin();
173   while (isa<AllocaInst>(IP)) ++IP;
174   
175   // Search for initializers in the initial BB.
176   SmallPtrSet<AllocaInst*,16> InitedRoots;
177   for (; !CouldBecomeSafePoint(IP); ++IP)
178     if (StoreInst *SI = dyn_cast<StoreInst>(IP))
179       if (AllocaInst *AI =
180           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
181         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)) {
188       new StoreInst(ConstantPointerNull::get(cast<PointerType>(
189                       cast<PointerType>((*I)->getType())->getElementType())),
190                     *I, IP);
191       MadeChange = true;
192     }
193   
194   return MadeChange;
195 }
196
197 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
198   // Default lowering is necessary only if read or write barriers have a default
199   // action. The default for roots is no action.
200   return !C.customWriteBarrier()
201       || !C.customReadBarrier()
202       || C.initializeRoots();
203 }
204
205 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
206   // Custom lowering is only necessary if enabled for some action.
207   return C.customWriteBarrier()
208       || C.customReadBarrier()
209       || C.customRoots();
210 }
211
212 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
213 /// instruction could introduce a safe point.
214 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
215   // The natural definition of instructions which could introduce safe points
216   // are:
217   // 
218   //   - call, invoke (AfterCall, BeforeCall)
219   //   - phis (Loops)
220   //   - invoke, ret, unwind (Exit)
221   // 
222   // However, instructions as seemingly inoccuous as arithmetic can become
223   // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
224   // it is necessary to take a conservative approach.
225   
226   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
227       isa<StoreInst>(I) || isa<LoadInst>(I))
228     return false;
229   
230   // llvm.gcroot is safe because it doesn't do anything at runtime.
231   if (CallInst *CI = dyn_cast<CallInst>(I))
232     if (Function *F = CI->getCalledFunction())
233       if (unsigned IID = F->getIntrinsicID())
234         if (IID == Intrinsic::gcroot)
235           return false;
236   
237   return true;
238 }
239
240 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
241 /// Leave gcroot intrinsics; the code generator needs to see those.
242 bool LowerIntrinsics::runOnFunction(Function &F) {
243   // Quick exit for functions that do not use GC.
244   if (!F.hasGC())
245     return false;
246   
247   GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
248   GCStrategy &S = FI.getStrategy();
249   
250   bool MadeChange = false;
251   
252   if (NeedsDefaultLoweringPass(S))
253     MadeChange |= PerformDefaultLowering(F, S);
254   
255   if (NeedsCustomLoweringPass(S))
256     MadeChange |= S.performCustomLowering(F);
257   
258   return MadeChange;
259 }
260
261 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
262   bool LowerWr = !S.customWriteBarrier();
263   bool LowerRd = !S.customReadBarrier();
264   bool InitRoots = S.initializeRoots();
265   
266   SmallVector<AllocaInst*,32> Roots;
267   
268   bool MadeChange = false;
269   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
270     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
271       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
272         Function *F = CI->getCalledFunction();
273         switch (F->getIntrinsicID()) {
274         case Intrinsic::gcwrite:
275           if (LowerWr) {
276             // Replace a write barrier with a simple store.
277             Value *St = new StoreInst(CI->getOperand(1), CI->getOperand(3), CI);
278             CI->replaceAllUsesWith(St);
279             CI->eraseFromParent();
280           }
281           break;
282         case Intrinsic::gcread:
283           if (LowerRd) {
284             // Replace a read barrier with a simple load.
285             Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
286             Ld->takeName(CI);
287             CI->replaceAllUsesWith(Ld);
288             CI->eraseFromParent();
289           }
290           break;
291         case Intrinsic::gcroot:
292           if (InitRoots) {
293             // Initialize the GC root, but do not delete the intrinsic. The
294             // backend needs the intrinsic to flag the stack slot.
295             Roots.push_back(cast<AllocaInst>(
296                               CI->getOperand(1)->stripPointerCasts()));
297           }
298           break;
299         default:
300           continue;
301         }
302         
303         MadeChange = true;
304       }
305     }
306   }
307   
308   if (Roots.size())
309     MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
310   
311   return MadeChange;
312 }
313
314 // -----------------------------------------------------------------------------
315
316 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
317   return new MachineCodeAnalysis();
318 }
319
320 char MachineCodeAnalysis::ID = 0;
321
322 MachineCodeAnalysis::MachineCodeAnalysis()
323   : MachineFunctionPass(intptr_t(&ID)) {}
324
325 const char *MachineCodeAnalysis::getPassName() const {
326   return "Analyze Machine Code For Garbage Collection";
327 }
328
329 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
330   MachineFunctionPass::getAnalysisUsage(AU);
331   AU.setPreservesAll();
332   AU.addRequired<MachineModuleInfo>();
333   AU.addRequired<GCModuleInfo>();
334 }
335
336 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB, 
337                                      MachineBasicBlock::iterator MI) const {
338   unsigned Label = MMI->NextLabelID();
339   BuildMI(MBB, MI, TII->get(TargetInstrInfo::GC_LABEL)).addImm(Label);
340   return Label;
341 }
342
343 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
344   // Find the return address (next instruction), too, so as to bracket the call
345   // instruction.
346   MachineBasicBlock::iterator RAI = CI; 
347   ++RAI;                                
348   
349   if (FI->getStrategy().needsSafePoint(GC::PreCall))
350     FI->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
351   
352   if (FI->getStrategy().needsSafePoint(GC::PostCall))
353     FI->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
354 }
355
356 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
357   for (MachineFunction::iterator BBI = MF.begin(),
358                                  BBE = MF.end(); BBI != BBE; ++BBI)
359     for (MachineBasicBlock::iterator MI = BBI->begin(),
360                                      ME = BBI->end(); MI != ME; ++MI)
361       if (MI->getDesc().isCall())
362         VisitCallPoint(MI);
363 }
364
365 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
366   uint64_t StackSize = MFI->getStackSize();
367   uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
368   uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
369   
370   for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
371                                       RE = FI->roots_end(); RI != RE; ++RI)
372     RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
373                       - OffsetOfLocalArea + OffsetAdjustment;
374 }
375
376 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
377   // Quick exit for functions that do not use GC.
378   if (!MF.getFunction()->hasGC())
379     return false;
380   
381   FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
382   if (!FI->getStrategy().needsSafePoints())
383     return false;
384   
385   TM = &MF.getTarget();
386   MMI = &getAnalysis<MachineModuleInfo>();
387   TII = TM->getInstrInfo();
388   MFI = MF.getFrameInfo();
389   
390   // Find the size of the stack frame.
391   FI->setFrameSize(MFI->getStackSize());
392   
393   // Find all safe points.
394   FindSafePoints(MF);
395   
396   // Find the stack offsets for all roots.
397   FindStackOffsets(MF);
398   
399   return false;
400 }