1 //===-- GCStrategy.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 target- and collector-independent garbage collection
13 // GCMachineCodeAnalysis identifies the GC safe points in the machine code.
14 // Roots are identified in SelectionDAGISel.
16 //===----------------------------------------------------------------------===//
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"
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);
56 const char *getPassName() const override;
57 void getAnalysisUsage(AnalysisUsage &AU) const override;
59 bool doInitialization(Module &M) override;
60 bool runOnFunction(Function &F) override;
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;
71 MachineModuleInfo *MMI;
72 const TargetInstrInfo *TII;
74 void FindSafePoints(MachineFunction &MF);
75 void VisitCallPoint(MachineBasicBlock::iterator MI);
76 MCSymbol *InsertLabel(MachineBasicBlock &MBB,
77 MachineBasicBlock::iterator MI,
80 void FindStackOffsets(MachineFunction &MF);
85 GCMachineCodeAnalysis();
86 void getAnalysisUsage(AnalysisUsage &AU) const override;
88 bool runOnMachineFunction(MachineFunction &MF) override;
93 // -----------------------------------------------------------------------------
95 GCStrategy::GCStrategy() :
97 CustomReadBarriers(false),
98 CustomWriteBarriers(false),
100 CustomSafePoints(false),
105 // -----------------------------------------------------------------------------
107 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
109 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
110 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
112 FunctionPass *llvm::createGCLoweringPass() {
113 return new LowerIntrinsics();
116 char LowerIntrinsics::ID = 0;
118 LowerIntrinsics::LowerIntrinsics()
120 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
123 const char *LowerIntrinsics::getPassName() const {
124 return "Lower Garbage Collection Instructions";
127 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
128 FunctionPass::getAnalysisUsage(AU);
129 AU.addRequired<GCModuleInfo>();
130 AU.addPreserved<DominatorTreeWrapperPass>();
133 /// doInitialization - If this module uses the GC intrinsics, find them now.
134 bool LowerIntrinsics::doInitialization(Module &M) {
135 // FIXME: This is rather antisocial in the context of a JIT since it performs
136 // work against the entire module. But this cannot be done at
137 // runFunction time (initializeCustomLowering likely needs to change
139 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
140 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
141 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
142 if (!I->isDeclaration() && I->hasGC())
143 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
145 bool MadeChange = false;
146 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
147 if (NeedsCustomLoweringPass(**I))
148 if ((*I)->initializeCustomLowering(M))
154 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
156 // Scroll past alloca instructions.
157 BasicBlock::iterator IP = F.getEntryBlock().begin();
158 while (isa<AllocaInst>(IP)) ++IP;
160 // Search for initializers in the initial BB.
161 SmallPtrSet<AllocaInst*,16> InitedRoots;
162 for (; !CouldBecomeSafePoint(IP); ++IP)
163 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
165 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
166 InitedRoots.insert(AI);
168 // Add root initializers.
169 bool MadeChange = false;
171 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
172 if (!InitedRoots.count(*I)) {
173 StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
174 cast<PointerType>((*I)->getType())->getElementType())),
183 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
184 // Default lowering is necessary only if read or write barriers have a default
185 // action. The default for roots is no action.
186 return !C.customWriteBarrier()
187 || !C.customReadBarrier()
188 || C.initializeRoots();
191 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
192 // Custom lowering is only necessary if enabled for some action.
193 return C.customWriteBarrier()
194 || C.customReadBarrier()
198 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
199 /// instruction could introduce a safe point.
200 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
201 // The natural definition of instructions which could introduce safe points
204 // - call, invoke (AfterCall, BeforeCall)
206 // - invoke, ret, unwind (Exit)
208 // However, instructions as seemingly inoccuous as arithmetic can become
209 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
210 // it is necessary to take a conservative approach.
212 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
213 isa<StoreInst>(I) || isa<LoadInst>(I))
216 // llvm.gcroot is safe because it doesn't do anything at runtime.
217 if (CallInst *CI = dyn_cast<CallInst>(I))
218 if (Function *F = CI->getCalledFunction())
219 if (unsigned IID = F->getIntrinsicID())
220 if (IID == Intrinsic::gcroot)
226 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
227 /// Leave gcroot intrinsics; the code generator needs to see those.
228 bool LowerIntrinsics::runOnFunction(Function &F) {
229 // Quick exit for functions that do not use GC.
233 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
234 GCStrategy &S = FI.getStrategy();
236 bool MadeChange = false;
238 if (NeedsDefaultLoweringPass(S))
239 MadeChange |= PerformDefaultLowering(F, S);
241 bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
242 if (UseCustomLoweringPass)
243 MadeChange |= S.performCustomLowering(F);
245 // Custom lowering may modify the CFG, so dominators must be recomputed.
246 if (UseCustomLoweringPass) {
247 if (DominatorTreeWrapperPass *DTWP =
248 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
249 DTWP->getDomTree().recalculate(F);
255 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
256 bool LowerWr = !S.customWriteBarrier();
257 bool LowerRd = !S.customReadBarrier();
258 bool InitRoots = S.initializeRoots();
260 SmallVector<AllocaInst*, 32> Roots;
262 bool MadeChange = false;
263 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
264 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
265 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
266 Function *F = CI->getCalledFunction();
267 switch (F->getIntrinsicID()) {
268 case Intrinsic::gcwrite:
270 // Replace a write barrier with a simple store.
271 Value *St = new StoreInst(CI->getArgOperand(0),
272 CI->getArgOperand(2), CI);
273 CI->replaceAllUsesWith(St);
274 CI->eraseFromParent();
277 case Intrinsic::gcread:
279 // Replace a read barrier with a simple load.
280 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
282 CI->replaceAllUsesWith(Ld);
283 CI->eraseFromParent();
286 case Intrinsic::gcroot:
288 // Initialize the GC root, but do not delete the intrinsic. The
289 // backend needs the intrinsic to flag the stack slot.
290 Roots.push_back(cast<AllocaInst>(
291 CI->getArgOperand(0)->stripPointerCasts()));
304 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
309 // -----------------------------------------------------------------------------
311 char GCMachineCodeAnalysis::ID = 0;
312 char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
314 INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
315 "Analyze Machine Code For Garbage Collection", false, false)
317 GCMachineCodeAnalysis::GCMachineCodeAnalysis()
318 : MachineFunctionPass(ID) {}
320 void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
321 MachineFunctionPass::getAnalysisUsage(AU);
322 AU.setPreservesAll();
323 AU.addRequired<MachineModuleInfo>();
324 AU.addRequired<GCModuleInfo>();
327 MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
328 MachineBasicBlock::iterator MI,
330 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
331 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
335 void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
336 // Find the return address (next instruction), too, so as to bracket the call
338 MachineBasicBlock::iterator RAI = CI;
341 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
342 MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
343 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
346 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
347 MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
348 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
352 void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
353 for (MachineFunction::iterator BBI = MF.begin(),
354 BBE = MF.end(); BBI != BBE; ++BBI)
355 for (MachineBasicBlock::iterator MI = BBI->begin(),
356 ME = BBI->end(); MI != ME; ++MI)
361 void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
362 const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
363 assert(TFI && "TargetRegisterInfo not available!");
365 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
366 RI != FI->roots_end();) {
367 // If the root references a dead object, no need to keep it.
368 if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
369 RI = FI->removeStackRoot(RI);
371 RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
377 bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
378 // Quick exit for functions that do not use GC.
379 if (!MF.getFunction()->hasGC())
382 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
383 if (!FI->getStrategy().needsSafePoints())
386 TM = &MF.getTarget();
387 MMI = &getAnalysis<MachineModuleInfo>();
388 TII = TM->getSubtargetImpl()->getInstrInfo();
390 // Find the size of the stack frame.
391 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
393 // Find all safe points.
394 if (FI->getStrategy().customSafePoints()) {
395 FI->getStrategy().findCustomSafePoints(*FI, MF);
400 // Find the stack offsets for all roots.
401 FindStackOffsets(MF);