1 //===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the lowering for the gc.root mechanism.
12 //===----------------------------------------------------------------------===//
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"
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,
52 const char *getPassName() const override;
53 void getAnalysisUsage(AnalysisUsage &AU) const override;
55 bool doInitialization(Module &M) override;
56 bool runOnFunction(Function &F) override;
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;
66 MachineModuleInfo *MMI;
67 const TargetInstrInfo *TII;
69 void FindSafePoints(MachineFunction &MF);
70 void VisitCallPoint(MachineBasicBlock::iterator MI);
71 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
74 void FindStackOffsets(MachineFunction &MF);
79 GCMachineCodeAnalysis();
80 void getAnalysisUsage(AnalysisUsage &AU) const override;
82 bool runOnMachineFunction(MachineFunction &MF) override;
86 // -----------------------------------------------------------------------------
88 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
90 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
91 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
93 FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
95 char LowerIntrinsics::ID = 0;
97 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
98 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
101 const char *LowerIntrinsics::getPassName() const {
102 return "Lower Garbage Collection Instructions";
105 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
106 FunctionPass::getAnalysisUsage(AU);
107 AU.addRequired<GCModuleInfo>();
108 AU.addPreserved<DominatorTreeWrapperPass>();
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
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.
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))
132 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
134 // Scroll past alloca instructions.
135 BasicBlock::iterator IP = F.getEntryBlock().begin();
136 while (isa<AllocaInst>(IP))
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))
144 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
145 InitedRoots.insert(AI);
147 // Add root initializers.
148 bool MadeChange = false;
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())),
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() ||
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();
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
181 // - call, invoke (AfterCall, BeforeCall)
183 // - invoke, ret, unwind (Exit)
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.
189 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
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)
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.
210 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
211 GCStrategy &S = FI.getStrategy();
213 bool MadeChange = false;
215 if (NeedsDefaultLoweringPass(S))
216 MadeChange |= PerformDefaultLowering(F, S);
218 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
219 if (UseCustomLoweringPass)
220 MadeChange |= S.performCustomLowering(F);
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);
232 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
233 bool LowerWr = !S.customWriteBarrier();
234 bool LowerRd = !S.customReadBarrier();
235 bool InitRoots = S.initializeRoots();
237 SmallVector<AllocaInst *, 32> Roots;
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:
247 // Replace a write barrier with a simple store.
249 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
250 CI->replaceAllUsesWith(St);
251 CI->eraseFromParent();
254 case Intrinsic::gcread:
256 // Replace a read barrier with a simple load.
257 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
259 CI->replaceAllUsesWith(Ld);
260 CI->eraseFromParent();
263 case Intrinsic::gcroot:
265 // Initialize the GC root, but do not delete the intrinsic. The
266 // backend needs the intrinsic to flag the stack slot.
268 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
281 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
286 // -----------------------------------------------------------------------------
288 char GCMachineCodeAnalysis::ID = 0;
289 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
291 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
292 "Analyze Machine Code For Garbage Collection", false, false)
294 GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
296 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
297 MachineFunctionPass::getAnalysisUsage(AU);
298 AU.setPreservesAll();
299 AU.addRequired<MachineModuleInfo>();
300 AU.addRequired<GCModuleInfo>();
303 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
304 MachineBasicBlock::iterator MI,
306 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
307 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
311 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
312 // Find the return address (next instruction), too, so as to bracket the call
314 MachineBasicBlock::iterator RAI = CI;
317 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
318 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
319 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
322 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
323 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
324 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
328 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
329 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
331 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
337 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
338 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
339 assert(TFI && "TargetRegisterInfo not available!");
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);
347 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
353 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
354 // Quick exit for functions that do not use GC.
355 if (!MF.getFunction()->hasGC())
358 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
359 if (!FI->getStrategy().needsSafePoints())
362 TM = &MF.getTarget();
363 MMI = &getAnalysis<MachineModuleInfo>();
364 TII = TM->getSubtargetImpl()->getInstrInfo();
366 // Find the size of the stack frame.
367 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
369 // Find all safe points.
370 if (FI->getStrategy().customSafePoints()) {
371 FI->getStrategy().findCustomSafePoints(*FI, MF);
376 // Find the stack offsets for all roots.
377 FindStackOffsets(MF);