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