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/GCMetadata.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/GCStrategy.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetFrameLowering.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetSubtargetInfo.h"
37 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
38 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
39 /// directed by the GCStrategy. It also performs automatic root initialization
40 /// and custom intrinsic lowering.
41 class LowerIntrinsics : public FunctionPass {
42 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
48 const char *getPassName() const override;
49 void getAnalysisUsage(AnalysisUsage &AU) const override;
51 bool doInitialization(Module &M) override;
52 bool runOnFunction(Function &F) override;
55 /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
56 /// function representation to identify safe points for the garbage collector
57 /// in the machine code. It inserts labels at safe points and populates a
58 /// GCMetadata record for each function.
59 class GCMachineCodeAnalysis : public MachineFunctionPass {
60 const TargetMachine *TM;
62 MachineModuleInfo *MMI;
63 const TargetInstrInfo *TII;
65 void FindSafePoints(MachineFunction &MF);
66 void VisitCallPoint(MachineBasicBlock::iterator MI);
67 MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
70 void FindStackOffsets(MachineFunction &MF);
75 GCMachineCodeAnalysis();
76 void getAnalysisUsage(AnalysisUsage &AU) const override;
78 bool runOnMachineFunction(MachineFunction &MF) override;
82 // -----------------------------------------------------------------------------
84 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
86 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
87 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
89 FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
91 char LowerIntrinsics::ID = 0;
93 LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
94 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
97 const char *LowerIntrinsics::getPassName() const {
98 return "Lower Garbage Collection Instructions";
101 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
102 FunctionPass::getAnalysisUsage(AU);
103 AU.addRequired<GCModuleInfo>();
104 AU.addPreserved<DominatorTreeWrapperPass>();
107 static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
108 // Default lowering is necessary only if read or write barriers have a default
109 // action. The default for roots is no action.
110 return !C.customWriteBarrier() || !C.customReadBarrier() ||
114 static bool NeedsCustomLoweringPass(const GCStrategy &C) {
115 // Custom lowering is only necessary if enabled for some action.
116 return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
121 /// doInitialization - If this module uses the GC intrinsics, find them now.
122 bool LowerIntrinsics::doInitialization(Module &M) {
123 // FIXME: This is rather antisocial in the context of a JIT since it performs
124 // work against the entire module. But this cannot be done at
125 // runFunction time (initializeCustomLowering likely needs to change
127 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
128 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
129 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
130 if (!I->isDeclaration() && I->hasGC())
131 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
133 bool MadeChange = false;
134 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
135 if (NeedsCustomLoweringPass(**I))
136 if ((*I)->initializeCustomLowering(M))
143 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
144 /// instruction could introduce a safe point.
145 static bool CouldBecomeSafePoint(Instruction *I) {
146 // The natural definition of instructions which could introduce safe points
149 // - call, invoke (AfterCall, BeforeCall)
151 // - invoke, ret, unwind (Exit)
153 // However, instructions as seemingly inoccuous as arithmetic can become
154 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
155 // it is necessary to take a conservative approach.
157 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
161 // llvm.gcroot is safe because it doesn't do anything at runtime.
162 if (CallInst *CI = dyn_cast<CallInst>(I))
163 if (Function *F = CI->getCalledFunction())
164 if (unsigned IID = F->getIntrinsicID())
165 if (IID == Intrinsic::gcroot)
171 static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
173 // Scroll past alloca instructions.
174 BasicBlock::iterator IP = F.getEntryBlock().begin();
175 while (isa<AllocaInst>(IP))
178 // Search for initializers in the initial BB.
179 SmallPtrSet<AllocaInst *, 16> InitedRoots;
180 for (; !CouldBecomeSafePoint(IP); ++IP)
181 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
183 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
184 InitedRoots.insert(AI);
186 // Add root initializers.
187 bool MadeChange = false;
189 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
190 if (!InitedRoots.count(*I)) {
191 StoreInst *SI = new StoreInst(
192 ConstantPointerNull::get(cast<PointerType>(
193 cast<PointerType>((*I)->getType())->getElementType())),
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();
334 // Do not treat tail or sibling call sites as safe points. This is
335 // legal since any arguments passed to the callee which live in the
336 // remnants of the callers frame will be owned and updated by the
337 // callee if required.
338 if (MI->isTerminator())
344 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
345 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
346 assert(TFI && "TargetRegisterInfo not available!");
348 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
349 RI != FI->roots_end();) {
350 // If the root references a dead object, no need to keep it.
351 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
352 RI = FI->removeStackRoot(RI);
354 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
360 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
361 // Quick exit for functions that do not use GC.
362 if (!MF.getFunction()->hasGC())
365 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
366 if (!FI->getStrategy().needsSafePoints())
369 TM = &MF.getTarget();
370 MMI = &getAnalysis<MachineModuleInfo>();
371 TII = TM->getSubtargetImpl()->getInstrInfo();
373 // Find the size of the stack frame.
374 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
376 // Find all safe points.
379 // Find the stack offsets for all roots.
380 FindStackOffsets(MF);