1 //===-- Collector.cpp - Garbage collection infrastructure -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Gordon Henriksen and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements target- and collector-independent garbage collection
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/Collector.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetFrameInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Compiler.h"
32 /// This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,
33 /// replacing them with simple loads and stores as directed by the Collector.
34 /// This is useful for most garbage collectors.
35 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
36 const Collector &Coll;
38 /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the
39 /// llvm.gc* intrinsics.
40 Function *GCRootInt, *GCReadInt, *GCWriteInt;
42 static bool CouldBecomeSafePoint(Instruction *I);
43 static void InsertRootInitializers(Function &F,
44 AllocaInst **Roots, unsigned Count);
49 LowerIntrinsics(const Collector &GC);
50 const char *getPassName() const;
52 bool doInitialization(Module &M);
53 bool runOnFunction(Function &F);
57 /// This is a target-independent pass over the machine function representation
58 /// to identify safe points for the garbage collector in the machine code. It
59 /// inserts labels at safe points and populates the GCInfo class.
60 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
61 const Collector &Coll;
62 const TargetMachine &Targ;
64 CollectorMetadata *MD;
65 MachineModuleInfo *MMI;
66 const TargetInstrInfo *TII;
67 MachineFrameInfo *MFI;
69 void FindSafePoints(MachineFunction &MF);
70 void VisitCallPoint(MachineBasicBlock::iterator MI);
71 unsigned InsertLabel(MachineBasicBlock &MBB,
72 MachineBasicBlock::iterator MI) const;
74 void FindStackOffsets(MachineFunction &MF);
79 MachineCodeAnalysis(const Collector &C, const TargetMachine &T);
80 const char *getPassName() const;
81 void getAnalysisUsage(AnalysisUsage &AU) const;
83 bool runOnMachineFunction(MachineFunction &MF);
88 // -----------------------------------------------------------------------------
90 const Collector *llvm::TheCollector = 0;
92 Collector::Collector() :
94 CustomReadBarriers(false),
95 CustomWriteBarriers(false),
100 Collector::~Collector() {}
102 void Collector::addLoweringPasses(FunctionPassManager &PM) const {
103 if (NeedsDefaultLoweringPass())
104 PM.add(new LowerIntrinsics(*this));
106 if (NeedsCustomLoweringPass())
107 PM.add(createCustomLoweringPass());
110 void Collector::addLoweringPasses(PassManager &PM) const {
111 if (NeedsDefaultLoweringPass())
112 PM.add(new LowerIntrinsics(*this));
114 if (NeedsCustomLoweringPass())
115 PM.add(createCustomLoweringPass());
118 void Collector::addGenericMachineCodePass(FunctionPassManager &PM,
119 const TargetMachine &TM,
121 if (needsSafePoints())
122 PM.add(new MachineCodeAnalysis(*this, TM));
125 bool Collector::NeedsDefaultLoweringPass() const {
126 // Default lowering is necessary only if read or write barriers have a default
127 // action. The default for roots is no action.
128 return !customWriteBarrier()
129 || !customReadBarrier()
130 || initializeRoots();
133 bool Collector::NeedsCustomLoweringPass() const {
134 // Custom lowering is only necessary if enabled for some action.
135 return customWriteBarrier()
136 || customReadBarrier()
140 Pass *Collector::createCustomLoweringPass() const {
141 cerr << "Collector must override createCustomLoweringPass.\n";
146 void Collector::beginAssembly(Module &M, std::ostream &OS, AsmPrinter &AP,
147 const TargetAsmInfo &TAI) const {
148 // Default is no action.
151 void Collector::finishAssembly(Module &M, CollectorModuleMetadata &CMM,
152 std::ostream &OS, AsmPrinter &AP,
153 const TargetAsmInfo &TAI) const {
154 // Default is no action.
157 // -----------------------------------------------------------------------------
159 char LowerIntrinsics::ID = 0;
161 LowerIntrinsics::LowerIntrinsics(const Collector &C)
162 : FunctionPass((intptr_t)&ID), Coll(C),
163 GCRootInt(0), GCReadInt(0), GCWriteInt(0) {}
165 const char *LowerIntrinsics::getPassName() const {
166 return "Lower Garbage Collection Instructions";
169 /// doInitialization - If this module uses the GC intrinsics, find them now. If
170 /// not, this pass does not do anything.
171 bool LowerIntrinsics::doInitialization(Module &M) {
172 GCReadInt = M.getFunction("llvm.gcread");
173 GCWriteInt = M.getFunction("llvm.gcwrite");
174 GCRootInt = M.getFunction("llvm.gcroot");
178 void LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
180 // Scroll past alloca instructions.
181 BasicBlock::iterator IP = F.getEntryBlock().begin();
182 while (isa<AllocaInst>(IP)) ++IP;
184 // Search for initializers in the initial BB.
185 SmallPtrSet<AllocaInst*,16> InitedRoots;
186 for (; !CouldBecomeSafePoint(IP); ++IP)
187 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
188 if (AllocaInst *AI = dyn_cast<AllocaInst>(
189 IntrinsicInst::StripPointerCasts(SI->getOperand(1))))
190 InitedRoots.insert(AI);
192 // Add root initializers.
193 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
194 if (!InitedRoots.count(*I))
195 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
196 cast<PointerType>((*I)->getType())->getElementType())),
200 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
201 /// instruction could introduce a safe point.
202 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
203 // The natural definition of instructions which could introduce safe points
206 // - call, invoke (AfterCall, BeforeCall)
208 // - invoke, ret, unwind (Exit)
210 // However, instructions as seemingly inoccuous as arithmetic can become
211 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
212 // it is necessary to take a conservative approach.
214 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
215 isa<StoreInst>(I) || isa<LoadInst>(I))
218 // llvm.gcroot is safe because it doesn't do anything at runtime.
219 if (CallInst *CI = dyn_cast<CallInst>(I))
220 if (Function *F = CI->getCalledFunction())
221 if (unsigned IID = F->getIntrinsicID())
222 if (IID == Intrinsic::gcroot)
228 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
229 /// Leave gcroot intrinsics; the code generator needs to see those.
230 bool LowerIntrinsics::runOnFunction(Function &F) {
231 // Quick exit for programs that do not declare the intrinsics.
232 if (!GCReadInt && !GCWriteInt && !GCRootInt) return false;
234 bool LowerWr = !Coll.customWriteBarrier();
235 bool LowerRd = !Coll.customReadBarrier();
236 bool InitRoots = Coll.initializeRoots();
238 SmallVector<AllocaInst*,32> Roots;
240 bool MadeChange = false;
241 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
242 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
243 if (CallInst *CI = dyn_cast<CallInst>(II++)) {
244 Function *F = CI->getCalledFunction();
245 if (F == GCWriteInt && LowerWr) {
246 // Replace a write barrier with a simple store.
247 Value *St = new StoreInst(CI->getOperand(1), CI->getOperand(3), CI);
248 CI->replaceAllUsesWith(St);
249 CI->eraseFromParent();
250 } else if (F == GCReadInt && LowerRd) {
251 // Replace a read barrier with a simple load.
252 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
254 CI->replaceAllUsesWith(Ld);
255 CI->eraseFromParent();
256 } else if (F == GCRootInt && InitRoots) {
257 // Initialize the GC root, but do not delete the intrinsic. The
258 // backend needs the intrinsic to flag the stack slot.
259 Roots.push_back(cast<AllocaInst>(
260 IntrinsicInst::StripPointerCasts(CI->getOperand(1))));
271 InsertRootInitializers(F, Roots.begin(), Roots.size());
276 // -----------------------------------------------------------------------------
278 char MachineCodeAnalysis::ID = 0;
280 MachineCodeAnalysis::MachineCodeAnalysis(const Collector &C, const TargetMachine &T)
281 : MachineFunctionPass(intptr_t(&ID)), Coll(C), Targ(T) {}
283 const char *MachineCodeAnalysis::getPassName() const {
284 return "Analyze Machine Code For Garbage Collection";
287 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
288 MachineFunctionPass::getAnalysisUsage(AU);
289 AU.setPreservesAll();
290 AU.addRequired<MachineModuleInfo>();
291 AU.addRequired<CollectorModuleMetadata>();
294 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
295 MachineBasicBlock::iterator MI) const {
296 unsigned Label = MMI->NextLabelID();
297 BuildMI(MBB, MI, TII->get(TargetInstrInfo::LABEL)).addImm(Label);
301 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
302 // Find the return address (next instruction), too, so as to bracket the call
304 MachineBasicBlock::iterator RAI = CI;
307 if (Coll.needsSafePoint(GC::PreCall))
308 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
310 if (Coll.needsSafePoint(GC::PostCall))
311 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
314 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
315 for (MachineFunction::iterator BBI = MF.begin(),
316 BBE = MF.end(); BBI != BBE; ++BBI)
317 for (MachineBasicBlock::iterator MI = BBI->begin(),
318 ME = BBI->end(); MI != ME; ++MI)
319 if (TII->isCall(MI->getOpcode()))
323 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
324 uint64_t StackSize = MFI->getStackSize();
325 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
326 uint64_t OffsetOfLocalArea = Targ.getFrameInfo()->getOffsetOfLocalArea();
328 for (CollectorMetadata::roots_iterator RI = MD->roots_begin(),
329 RE = MD->roots_end(); RI != RE; ++RI)
330 RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
331 - OffsetOfLocalArea + OffsetAdjustment;
334 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
335 if (!Coll.needsSafePoints())
338 MD = getAnalysis<CollectorModuleMetadata>().get(MF.getFunction());
339 MMI = &getAnalysis<MachineModuleInfo>();
340 TII = MF.getTarget().getInstrInfo();
341 MFI = MF.getFrameInfo();
343 // Find the size of the stack frame.
344 MD->setFrameSize(MFI->getStackSize());
346 // Find all safe points.
349 // Find the stack offsets for all roots.
350 FindStackOffsets(MF);