Remove the TargetMachine forwards for TargetSubtargetInfo based
[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 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
120   Functions.push_back(make_unique<GCFunctionInfo>(F, *this));
121   return Functions.back().get();
122 }
123
124 // -----------------------------------------------------------------------------
125
126 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
127                       false, false)
128 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
129 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
130
131 FunctionPass *llvm::createGCLoweringPass() {
132   return new LowerIntrinsics();
133 }
134
135 char LowerIntrinsics::ID = 0;
136
137 LowerIntrinsics::LowerIntrinsics()
138   : FunctionPass(ID) {
139     initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
140   }
141
142 const char *LowerIntrinsics::getPassName() const {
143   return "Lower Garbage Collection Instructions";
144 }
145
146 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
147   FunctionPass::getAnalysisUsage(AU);
148   AU.addRequired<GCModuleInfo>();
149   AU.addPreserved<DominatorTreeWrapperPass>();
150 }
151
152 /// doInitialization - If this module uses the GC intrinsics, find them now.
153 bool LowerIntrinsics::doInitialization(Module &M) {
154   // FIXME: This is rather antisocial in the context of a JIT since it performs
155   //        work against the entire module. But this cannot be done at
156   //        runFunction time (initializeCustomLowering likely needs to change
157   //        the module).
158   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
159   assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
160   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
161     if (!I->isDeclaration() && I->hasGC())
162       MI->getFunctionInfo(*I); // Instantiate the GC strategy.
163
164   bool MadeChange = false;
165   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
166     if (NeedsCustomLoweringPass(**I))
167       if ((*I)->initializeCustomLowering(M))
168         MadeChange = true;
169
170   return MadeChange;
171 }
172
173 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
174                                                           unsigned Count) {
175   // Scroll past alloca instructions.
176   BasicBlock::iterator IP = F.getEntryBlock().begin();
177   while (isa<AllocaInst>(IP)) ++IP;
178
179   // Search for initializers in the initial BB.
180   SmallPtrSet<AllocaInst*,16> InitedRoots;
181   for (; !CouldBecomeSafePoint(IP); ++IP)
182     if (StoreInst *SI = dyn_cast<StoreInst>(IP))
183       if (AllocaInst *AI =
184           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
185         InitedRoots.insert(AI);
186
187   // Add root initializers.
188   bool MadeChange = false;
189
190   for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
191     if (!InitedRoots.count(*I)) {
192       StoreInst* SI = new StoreInst(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 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
203   // Default lowering is necessary only if read or write barriers have a default
204   // action. The default for roots is no action.
205   return !C.customWriteBarrier()
206       || !C.customReadBarrier()
207       || C.initializeRoots();
208 }
209
210 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
211   // Custom lowering is only necessary if enabled for some action.
212   return C.customWriteBarrier()
213       || C.customReadBarrier()
214       || C.customRoots();
215 }
216
217 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
218 /// instruction could introduce a safe point.
219 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
220   // The natural definition of instructions which could introduce safe points
221   // are:
222   //
223   //   - call, invoke (AfterCall, BeforeCall)
224   //   - phis (Loops)
225   //   - invoke, ret, unwind (Exit)
226   //
227   // However, instructions as seemingly inoccuous as arithmetic can become
228   // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
229   // it is necessary to take a conservative approach.
230
231   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
232       isa<StoreInst>(I) || isa<LoadInst>(I))
233     return false;
234
235   // llvm.gcroot is safe because it doesn't do anything at runtime.
236   if (CallInst *CI = dyn_cast<CallInst>(I))
237     if (Function *F = CI->getCalledFunction())
238       if (unsigned IID = F->getIntrinsicID())
239         if (IID == Intrinsic::gcroot)
240           return false;
241
242   return true;
243 }
244
245 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
246 /// Leave gcroot intrinsics; the code generator needs to see those.
247 bool LowerIntrinsics::runOnFunction(Function &F) {
248   // Quick exit for functions that do not use GC.
249   if (!F.hasGC())
250     return false;
251
252   GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
253   GCStrategy &S = FI.getStrategy();
254
255   bool MadeChange = false;
256
257   if (NeedsDefaultLoweringPass(S))
258     MadeChange |= PerformDefaultLowering(F, S);
259
260   bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
261   if (UseCustomLoweringPass)
262     MadeChange |= S.performCustomLowering(F);
263
264   // Custom lowering may modify the CFG, so dominators must be recomputed.
265   if (UseCustomLoweringPass) {
266     if (DominatorTreeWrapperPass *DTWP =
267             getAnalysisIfAvailable<DominatorTreeWrapperPass>())
268       DTWP->getDomTree().recalculate(F);
269   }
270
271   return MadeChange;
272 }
273
274 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
275   bool LowerWr = !S.customWriteBarrier();
276   bool LowerRd = !S.customReadBarrier();
277   bool InitRoots = S.initializeRoots();
278
279   SmallVector<AllocaInst*, 32> Roots;
280
281   bool MadeChange = false;
282   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
283     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
284       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
285         Function *F = CI->getCalledFunction();
286         switch (F->getIntrinsicID()) {
287         case Intrinsic::gcwrite:
288           if (LowerWr) {
289             // Replace a write barrier with a simple store.
290             Value *St = new StoreInst(CI->getArgOperand(0),
291                                       CI->getArgOperand(2), CI);
292             CI->replaceAllUsesWith(St);
293             CI->eraseFromParent();
294           }
295           break;
296         case Intrinsic::gcread:
297           if (LowerRd) {
298             // Replace a read barrier with a simple load.
299             Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
300             Ld->takeName(CI);
301             CI->replaceAllUsesWith(Ld);
302             CI->eraseFromParent();
303           }
304           break;
305         case Intrinsic::gcroot:
306           if (InitRoots) {
307             // Initialize the GC root, but do not delete the intrinsic. The
308             // backend needs the intrinsic to flag the stack slot.
309             Roots.push_back(cast<AllocaInst>(
310                               CI->getArgOperand(0)->stripPointerCasts()));
311           }
312           break;
313         default:
314           continue;
315         }
316
317         MadeChange = true;
318       }
319     }
320   }
321
322   if (Roots.size())
323     MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
324
325   return MadeChange;
326 }
327
328 // -----------------------------------------------------------------------------
329
330 char GCMachineCodeAnalysis::ID = 0;
331 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
332
333 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
334                 "Analyze Machine Code For Garbage Collection", false, false)
335
336 GCMachineCodeAnalysis::GCMachineCodeAnalysis()
337   : MachineFunctionPass(ID) {}
338
339 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
340   MachineFunctionPass::getAnalysisUsage(AU);
341   AU.setPreservesAll();
342   AU.addRequired<MachineModuleInfo>();
343   AU.addRequired<GCModuleInfo>();
344 }
345
346 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
347                                              MachineBasicBlock::iterator MI,
348                                              DebugLoc DL) const {
349   MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
350   BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
351   return Label;
352 }
353
354 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
355   // Find the return address (next instruction), too, so as to bracket the call
356   // instruction.
357   MachineBasicBlock::iterator RAI = CI;
358   ++RAI;
359
360   if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
361     MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
362     FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
363   }
364
365   if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
366     MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
367     FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
368   }
369 }
370
371 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
372   for (MachineFunction::iterator BBI = MF.begin(),
373                                  BBE = MF.end(); BBI != BBE; ++BBI)
374     for (MachineBasicBlock::iterator MI = BBI->begin(),
375                                      ME = BBI->end(); MI != ME; ++MI)
376       if (MI->isCall())
377         VisitCallPoint(MI);
378 }
379
380 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
381   const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
382   assert(TFI && "TargetRegisterInfo not available!");
383
384   for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
385        RI != FI->roots_end();) {
386     // If the root references a dead object, no need to keep it.
387     if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
388       RI = FI->removeStackRoot(RI);
389     } else {
390       RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
391       ++RI;
392     }
393   }
394 }
395
396 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
397   // Quick exit for functions that do not use GC.
398   if (!MF.getFunction()->hasGC())
399     return false;
400
401   FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
402   if (!FI->getStrategy().needsSafePoints())
403     return false;
404
405   TM = &MF.getTarget();
406   MMI = &getAnalysis<MachineModuleInfo>();
407   TII = TM->getSubtargetImpl()->getInstrInfo();
408
409   // Find the size of the stack frame.
410   FI->setFrameSize(MF.getFrameInfo()->getStackSize());
411
412   // Find all safe points.
413   if (FI->getStrategy().customSafePoints()) {
414     FI->getStrategy().findCustomSafePoints(*FI, MF);
415   } else {
416     FindSafePoints(MF);
417   }
418
419   // Find the stack offsets for all roots.
420   FindStackOffsets(MF);
421
422   return false;
423 }