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 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
47 const char *getPassName() const override;
48 void getAnalysisUsage(AnalysisUsage &AU) const override;
50 bool doInitialization(Module &M) override;
51 bool runOnFunction(Function &F) override;
54 /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
55 /// function representation to identify safe points for the garbage collector
56 /// in the machine code. It inserts labels at safe points and populates a
57 /// GCMetadata record for each function.
58 class GCMachineCodeAnalysis : public MachineFunctionPass {
59 const TargetMachine *TM;
61 MachineModuleInfo *MMI;
62 const TargetInstrInfo *TII;
64 void FindSafePoints(MachineFunction &MF);
65 void VisitCallPoint(MachineBasicBlock::iterator MI);
66 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
69 void FindStackOffsets(MachineFunction &MF);
74 GCMachineCodeAnalysis();
75 void getAnalysisUsage(AnalysisUsage &AU) const override;
77 bool runOnMachineFunction(MachineFunction &MF) override;
81 // -----------------------------------------------------------------------------
83 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
85 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
86 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
88 FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
90 char LowerIntrinsics::ID = 0;
92 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
93 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
96 const char *LowerIntrinsics::getPassName() const {
97 return "Lower Garbage Collection Instructions";
100 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
101 FunctionPass::getAnalysisUsage(AU);
102 AU.addRequired<GCModuleInfo>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
106 static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
107 // Default lowering is necessary only if read or write barriers have a default
108 // action. The default for roots is no action.
109 return !C.customWriteBarrier() || !C.customReadBarrier() ||
113 static bool NeedsCustomLoweringPass(const GCStrategy &C) {
114 // Custom lowering is only necessary if enabled for some action.
115 return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
120 /// doInitialization - If this module uses the GC intrinsics, find them now.
121 bool LowerIntrinsics::doInitialization(Module &M) {
122 // FIXME: This is rather antisocial in the context of a JIT since it performs
123 // work against the entire module. But this cannot be done at
124 // runFunction time (initializeCustomLowering likely needs to change
126 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
127 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
128 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
129 if (!I->isDeclaration() && I->hasGC())
130 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
132 bool MadeChange = false;
133 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
134 if (NeedsCustomLoweringPass(**I))
135 if ((*I)->initializeCustomLowering(M))
142 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
143 /// instruction could introduce a safe point.
144 static bool CouldBecomeSafePoint(Instruction *I) {
145 // The natural definition of instructions which could introduce safe points
148 // - call, invoke (AfterCall, BeforeCall)
150 // - invoke, ret, unwind (Exit)
152 // However, instructions as seemingly inoccuous as arithmetic can become
153 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
154 // it is necessary to take a conservative approach.
156 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
160 // llvm.gcroot is safe because it doesn't do anything at runtime.
161 if (CallInst *CI = dyn_cast<CallInst>(I))
162 if (Function *F = CI->getCalledFunction())
163 if (unsigned IID = F->getIntrinsicID())
164 if (IID == Intrinsic::gcroot)
170 static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
172 // Scroll past alloca instructions.
173 BasicBlock::iterator IP = F.getEntryBlock().begin();
174 while (isa<AllocaInst>(IP))
177 // Search for initializers in the initial BB.
178 SmallPtrSet<AllocaInst *, 16> InitedRoots;
179 for (; !CouldBecomeSafePoint(IP); ++IP)
180 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
182 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
183 InitedRoots.insert(AI);
185 // Add root initializers.
186 bool MadeChange = false;
188 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
189 if (!InitedRoots.count(*I)) {
190 StoreInst *SI = new StoreInst(
191 ConstantPointerNull::get(cast<PointerType>(
192 cast<PointerType>((*I)->getType())->getElementType())),
202 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
203 /// Leave gcroot intrinsics; the code generator needs to see those.
204 bool LowerIntrinsics::runOnFunction(Function &F) {
205 // Quick exit for functions that do not use GC.
209 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
210 GCStrategy &S = FI.getStrategy();
212 bool MadeChange = false;
214 if (NeedsDefaultLoweringPass(S))
215 MadeChange |= PerformDefaultLowering(F, S);
217 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
218 if (UseCustomLoweringPass)
219 MadeChange |= S.performCustomLowering(F);
221 // Custom lowering may modify the CFG, so dominators must be recomputed.
222 if (UseCustomLoweringPass) {
223 if (DominatorTreeWrapperPass *DTWP =
224 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
225 DTWP->getDomTree().recalculate(F);
231 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
232 bool LowerWr = !S.customWriteBarrier();
233 bool LowerRd = !S.customReadBarrier();
234 bool InitRoots = S.initializeRoots();
236 SmallVector<AllocaInst *, 32> Roots;
238 bool MadeChange = false;
239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
240 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
241 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
242 Function *F = CI->getCalledFunction();
243 switch (F->getIntrinsicID()) {
244 case Intrinsic::gcwrite:
246 // Replace a write barrier with a simple store.
248 new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
249 CI->replaceAllUsesWith(St);
250 CI->eraseFromParent();
253 case Intrinsic::gcread:
255 // Replace a read barrier with a simple load.
256 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
258 CI->replaceAllUsesWith(Ld);
259 CI->eraseFromParent();
262 case Intrinsic::gcroot:
264 // Initialize the GC root, but do not delete the intrinsic. The
265 // backend needs the intrinsic to flag the stack slot.
267 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
280 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
285 // -----------------------------------------------------------------------------
287 char GCMachineCodeAnalysis::ID = 0;
288 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
290 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
291 "Analyze Machine Code For Garbage Collection", false, false)
293 GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
295 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
296 MachineFunctionPass::getAnalysisUsage(AU);
297 AU.setPreservesAll();
298 AU.addRequired<MachineModuleInfo>();
299 AU.addRequired<GCModuleInfo>();
302 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
303 MachineBasicBlock::iterator MI,
305 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
306 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
310 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
311 // Find the return address (next instruction), too, so as to bracket the call
313 MachineBasicBlock::iterator RAI = CI;
316 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
317 MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
318 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
321 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
322 MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
323 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
327 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
328 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
330 for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
336 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
337 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
338 assert(TFI && "TargetRegisterInfo not available!");
340 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
341 RI != FI->roots_end();) {
342 // If the root references a dead object, no need to keep it.
343 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
344 RI = FI->removeStackRoot(RI);
346 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
352 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
353 // Quick exit for functions that do not use GC.
354 if (!MF.getFunction()->hasGC())
357 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
358 if (!FI->getStrategy().needsSafePoints())
361 TM = &MF.getTarget();
362 MMI = &getAnalysis<MachineModuleInfo>();
363 TII = TM->getSubtargetImpl()->getInstrInfo();
365 // Find the size of the stack frame.
366 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
368 // Find all safe points.
369 if (FI->getStrategy().customSafePoints()) {
370 FI->getStrategy().findCustomSafePoints(*FI, MF);
375 // Find the stack offsets for all roots.
376 FindStackOffsets(MF);