clang-format GCStrategy.cpp & GCRootLowering.cpp (NFC)
[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/GCStrategy.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/IntrinsicInst.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetFrameLowering.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31
32 using namespace llvm;
33
34 namespace {
35
36 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
37 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
38 /// directed by the GCStrategy. It also performs automatic root initialization
39 /// and custom intrinsic lowering.
40 class LowerIntrinsics : public FunctionPass {
41   static bool NeedsDefaultLoweringPass(const GCStrategy &C);
42   static bool NeedsCustomLoweringPass(const GCStrategy &C);
43   static bool CouldBecomeSafePoint(Instruction *I);
44   bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
45   static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
46                                      unsigned Count);
47
48 public:
49   static char ID;
50
51   LowerIntrinsics();
52   const char *getPassName() const override;
53   void getAnalysisUsage(AnalysisUsage &AU) const override;
54
55   bool doInitialization(Module &M) override;
56   bool runOnFunction(Function &F) override;
57 };
58
59 /// GCMachineCodeAnalysis - 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 GCMachineCodeAnalysis : public MachineFunctionPass {
64   const TargetMachine *TM;
65   GCFunctionInfo *FI;
66   MachineModuleInfo *MMI;
67   const TargetInstrInfo *TII;
68
69   void FindSafePoints(MachineFunction &MF);
70   void VisitCallPoint(MachineBasicBlock::iterator MI);
71   MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
72                         DebugLoc DL) const;
73
74   void FindStackOffsets(MachineFunction &MF);
75
76 public:
77   static char ID;
78
79   GCMachineCodeAnalysis();
80   void getAnalysisUsage(AnalysisUsage &AU) const override;
81
82   bool runOnMachineFunction(MachineFunction &MF) override;
83 };
84 }
85
86 // -----------------------------------------------------------------------------
87
88 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
89                       false)
90 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
91 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
92
93 FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
94
95 char LowerIntrinsics::ID = 0;
96
97 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
98   initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
99 }
100
101 const char *LowerIntrinsics::getPassName() const {
102   return "Lower Garbage Collection Instructions";
103 }
104
105 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
106   FunctionPass::getAnalysisUsage(AU);
107   AU.addRequired<GCModuleInfo>();
108   AU.addPreserved<DominatorTreeWrapperPass>();
109 }
110
111 /// doInitialization - If this module uses the GC intrinsics, find them now.
112 bool LowerIntrinsics::doInitialization(Module &M) {
113   // FIXME: This is rather antisocial in the context of a JIT since it performs
114   //        work against the entire module. But this cannot be done at
115   //        runFunction time (initializeCustomLowering likely needs to change
116   //        the module).
117   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
118   assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
119   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
120     if (!I->isDeclaration() && I->hasGC())
121       MI->getFunctionInfo(*I); // Instantiate the GC strategy.
122
123   bool MadeChange = false;
124   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
125     if (NeedsCustomLoweringPass(**I))
126       if ((*I)->initializeCustomLowering(M))
127         MadeChange = true;
128
129   return MadeChange;
130 }
131
132 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
133                                              unsigned Count) {
134   // Scroll past alloca instructions.
135   BasicBlock::iterator IP = F.getEntryBlock().begin();
136   while (isa<AllocaInst>(IP))
137     ++IP;
138
139   // Search for initializers in the initial BB.
140   SmallPtrSet<AllocaInst *, 16> InitedRoots;
141   for (; !CouldBecomeSafePoint(IP); ++IP)
142     if (StoreInst *SI = dyn_cast<StoreInst>(IP))
143       if (AllocaInst *AI =
144               dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
145         InitedRoots.insert(AI);
146
147   // Add root initializers.
148   bool MadeChange = false;
149
150   for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
151     if (!InitedRoots.count(*I)) {
152       StoreInst *SI = new StoreInst(
153           ConstantPointerNull::get(cast<PointerType>(
154               cast<PointerType>((*I)->getType())->getElementType())),
155           *I);
156       SI->insertAfter(*I);
157       MadeChange = true;
158     }
159
160   return MadeChange;
161 }
162
163 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
164   // Default lowering is necessary only if read or write barriers have a default
165   // action. The default for roots is no action.
166   return !C.customWriteBarrier() || !C.customReadBarrier() ||
167          C.initializeRoots();
168 }
169
170 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
171   // Custom lowering is only necessary if enabled for some action.
172   return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
173 }
174
175 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
176 /// instruction could introduce a safe point.
177 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
178   // The natural definition of instructions which could introduce safe points
179   // are:
180   //
181   //   - call, invoke (AfterCall, BeforeCall)
182   //   - phis (Loops)
183   //   - invoke, ret, unwind (Exit)
184   //
185   // However, instructions as seemingly inoccuous as arithmetic can become
186   // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
187   // it is necessary to take a conservative approach.
188
189   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
190       isa<LoadInst>(I))
191     return false;
192
193   // llvm.gcroot is safe because it doesn't do anything at runtime.
194   if (CallInst *CI = dyn_cast<CallInst>(I))
195     if (Function *F = CI->getCalledFunction())
196       if (unsigned IID = F->getIntrinsicID())
197         if (IID == Intrinsic::gcroot)
198           return false;
199
200   return true;
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         VisitCallPoint(MI);
335 }
336
337 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
338   const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
339   assert(TFI && "TargetRegisterInfo not available!");
340
341   for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
342        RI != FI->roots_end();) {
343     // If the root references a dead object, no need to keep it.
344     if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
345       RI = FI->removeStackRoot(RI);
346     } else {
347       RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
348       ++RI;
349     }
350   }
351 }
352
353 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
354   // Quick exit for functions that do not use GC.
355   if (!MF.getFunction()->hasGC())
356     return false;
357
358   FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
359   if (!FI->getStrategy().needsSafePoints())
360     return false;
361
362   TM = &MF.getTarget();
363   MMI = &getAnalysis<MachineModuleInfo>();
364   TII = TM->getSubtargetImpl()->getInstrInfo();
365
366   // Find the size of the stack frame.
367   FI->setFrameSize(MF.getFrameInfo()->getStackSize());
368
369   // Find all safe points.
370   if (FI->getStrategy().customSafePoints()) {
371     FI->getStrategy().findCustomSafePoints(*FI, MF);
372   } else {
373     FindSafePoints(MF);
374   }
375
376   // Find the stack offsets for all roots.
377   FindStackOffsets(MF);
378
379   return false;
380 }