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/CodeGen/Passes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/Target/TargetFrameInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Compiler.h"
33 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
34 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
35 /// directed by the Collector. It also performs automatic root initialization
36 /// and custom intrinsic lowering.
37 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
38 /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the
39 /// llvm.gc* intrinsics.
40 Function *GCRootInt, *GCReadInt, *GCWriteInt;
42 static bool NeedsDefaultLoweringPass(const Collector &C);
43 static bool NeedsCustomLoweringPass(const Collector &C);
44 static bool CouldBecomeSafePoint(Instruction *I);
45 bool PerformDefaultLowering(Function &F, Collector &Coll);
46 static bool InsertRootInitializers(Function &F,
47 AllocaInst **Roots, unsigned Count);
53 const char *getPassName() const;
54 void getAnalysisUsage(AnalysisUsage &AU) const;
56 bool doInitialization(Module &M);
57 bool runOnFunction(Function &F);
61 /// MachineCodeAnalysis - This is a target-independent pass over the machine
62 /// function representation to identify safe points for the garbage collector
63 /// in the machine code. It inserts labels at safe points and populates a
64 /// CollectorMetadata record for each function.
65 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
66 const TargetMachine *TM;
67 CollectorMetadata *MD;
68 MachineModuleInfo *MMI;
69 const TargetInstrInfo *TII;
70 MachineFrameInfo *MFI;
72 void FindSafePoints(MachineFunction &MF);
73 void VisitCallPoint(MachineBasicBlock::iterator MI);
74 unsigned InsertLabel(MachineBasicBlock &MBB,
75 MachineBasicBlock::iterator MI) const;
77 void FindStackOffsets(MachineFunction &MF);
82 MachineCodeAnalysis();
83 const char *getPassName() const;
84 void getAnalysisUsage(AnalysisUsage &AU) const;
86 bool runOnMachineFunction(MachineFunction &MF);
91 // -----------------------------------------------------------------------------
93 Collector::Collector() :
95 CustomReadBarriers(false),
96 CustomWriteBarriers(false),
101 Collector::~Collector() {
102 for (iterator I = begin(), E = end(); I != E; ++I)
108 bool Collector::initializeCustomLowering(Module &M) { return false; }
110 bool Collector::performCustomLowering(Function &F) {
111 cerr << "gc " << getName() << " must override performCustomLowering.\n";
116 void Collector::beginAssembly(std::ostream &OS, AsmPrinter &AP,
117 const TargetAsmInfo &TAI) {
118 // Default is no action.
121 void Collector::finishAssembly(std::ostream &OS, AsmPrinter &AP,
122 const TargetAsmInfo &TAI) {
123 // Default is no action.
126 CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
127 CollectorMetadata *CM = new CollectorMetadata(F, *this);
128 Functions.push_back(CM);
132 // -----------------------------------------------------------------------------
134 FunctionPass *llvm::createGCLoweringPass() {
135 return new LowerIntrinsics();
138 char LowerIntrinsics::ID = 0;
140 LowerIntrinsics::LowerIntrinsics()
141 : FunctionPass((intptr_t)&ID),
142 GCRootInt(0), GCReadInt(0), GCWriteInt(0) {}
144 const char *LowerIntrinsics::getPassName() const {
145 return "Lower Garbage Collection Instructions";
148 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
149 FunctionPass::getAnalysisUsage(AU);
150 AU.addRequired<CollectorModuleMetadata>();
153 /// doInitialization - If this module uses the GC intrinsics, find them now.
154 bool LowerIntrinsics::doInitialization(Module &M) {
155 GCReadInt = M.getFunction("llvm.gcread");
156 GCWriteInt = M.getFunction("llvm.gcwrite");
157 GCRootInt = M.getFunction("llvm.gcroot");
159 // FIXME: This is rather antisocial in the context of a JIT since it performs
160 // work against the entire module. But this cannot be done at
161 // runFunction time (initializeCustomLowering likely needs to change
163 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
164 assert(CMM && "LowerIntrinsics didn't require CollectorModuleMetadata!?");
165 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
166 if (I->hasCollector())
167 CMM->get(*I); // Instantiate the Collector.
169 bool MadeChange = false;
170 for (CollectorModuleMetadata::iterator I = CMM->begin(),
171 E = CMM->end(); I != E; ++I)
172 if (NeedsCustomLoweringPass(**I))
173 if ((*I)->initializeCustomLowering(M))
179 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
181 // Scroll past alloca instructions.
182 BasicBlock::iterator IP = F.getEntryBlock().begin();
183 while (isa<AllocaInst>(IP)) ++IP;
185 // Search for initializers in the initial BB.
186 SmallPtrSet<AllocaInst*,16> InitedRoots;
187 for (; !CouldBecomeSafePoint(IP); ++IP)
188 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
189 if (AllocaInst *AI = dyn_cast<AllocaInst>(
190 IntrinsicInst::StripPointerCasts(SI->getOperand(1))))
191 InitedRoots.insert(AI);
193 // Add root initializers.
194 bool MadeChange = false;
196 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
197 if (!InitedRoots.count(*I)) {
198 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
199 cast<PointerType>((*I)->getType())->getElementType())),
207 bool LowerIntrinsics::NeedsDefaultLoweringPass(const Collector &C) {
208 // Default lowering is necessary only if read or write barriers have a default
209 // action. The default for roots is no action.
210 return !C.customWriteBarrier()
211 || !C.customReadBarrier()
212 || C.initializeRoots();
215 bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
216 // Custom lowering is only necessary if enabled for some action.
217 return C.customWriteBarrier()
218 || C.customReadBarrier()
222 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
223 /// instruction could introduce a safe point.
224 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
225 // The natural definition of instructions which could introduce safe points
228 // - call, invoke (AfterCall, BeforeCall)
230 // - invoke, ret, unwind (Exit)
232 // However, instructions as seemingly inoccuous as arithmetic can become
233 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
234 // it is necessary to take a conservative approach.
236 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
237 isa<StoreInst>(I) || isa<LoadInst>(I))
240 // llvm.gcroot is safe because it doesn't do anything at runtime.
241 if (CallInst *CI = dyn_cast<CallInst>(I))
242 if (Function *F = CI->getCalledFunction())
243 if (unsigned IID = F->getIntrinsicID())
244 if (IID == Intrinsic::gcroot)
250 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
251 /// Leave gcroot intrinsics; the code generator needs to see those.
252 bool LowerIntrinsics::runOnFunction(Function &F) {
253 // Quick exit for functions that do not use GC.
254 if (!F.hasCollector()) return false;
256 CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
257 Collector &Coll = MD.getCollector();
259 bool MadeChange = false;
261 if (NeedsDefaultLoweringPass(Coll))
262 MadeChange |= PerformDefaultLowering(F, Coll);
264 if (NeedsCustomLoweringPass(Coll))
265 MadeChange |= Coll.performCustomLowering(F);
270 bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
271 bool LowerWr = !Coll.customWriteBarrier();
272 bool LowerRd = !Coll.customReadBarrier();
273 bool InitRoots = Coll.initializeRoots();
275 SmallVector<AllocaInst*,32> Roots;
277 bool MadeChange = false;
278 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
279 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
280 if (CallInst *CI = dyn_cast<CallInst>(II++)) {
281 Function *F = CI->getCalledFunction();
282 if (F == GCWriteInt && LowerWr) {
283 // Replace a write barrier with a simple store.
284 Value *St = new StoreInst(CI->getOperand(1), CI->getOperand(3), CI);
285 CI->replaceAllUsesWith(St);
286 CI->eraseFromParent();
287 } else if (F == GCReadInt && LowerRd) {
288 // Replace a read barrier with a simple load.
289 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
291 CI->replaceAllUsesWith(Ld);
292 CI->eraseFromParent();
293 } else if (F == GCRootInt && InitRoots) {
294 // Initialize the GC root, but do not delete the intrinsic. The
295 // backend needs the intrinsic to flag the stack slot.
296 Roots.push_back(cast<AllocaInst>(
297 IntrinsicInst::StripPointerCasts(CI->getOperand(1))));
308 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
313 // -----------------------------------------------------------------------------
315 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
316 return new MachineCodeAnalysis();
319 char MachineCodeAnalysis::ID = 0;
321 MachineCodeAnalysis::MachineCodeAnalysis()
322 : MachineFunctionPass(intptr_t(&ID)) {}
324 const char *MachineCodeAnalysis::getPassName() const {
325 return "Analyze Machine Code For Garbage Collection";
328 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
329 MachineFunctionPass::getAnalysisUsage(AU);
330 AU.setPreservesAll();
331 AU.addRequired<MachineModuleInfo>();
332 AU.addRequired<CollectorModuleMetadata>();
335 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
336 MachineBasicBlock::iterator MI) const {
337 unsigned Label = MMI->NextLabelID();
338 BuildMI(MBB, MI, TII->get(TargetInstrInfo::LABEL)).addImm(Label);
342 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
343 // Find the return address (next instruction), too, so as to bracket the call
345 MachineBasicBlock::iterator RAI = CI;
348 if (MD->getCollector().needsSafePoint(GC::PreCall))
349 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
351 if (MD->getCollector().needsSafePoint(GC::PostCall))
352 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
355 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
356 for (MachineFunction::iterator BBI = MF.begin(),
357 BBE = MF.end(); BBI != BBE; ++BBI)
358 for (MachineBasicBlock::iterator MI = BBI->begin(),
359 ME = BBI->end(); MI != ME; ++MI)
360 if (TII->isCall(MI->getOpcode()))
364 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
365 uint64_t StackSize = MFI->getStackSize();
366 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
367 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
369 for (CollectorMetadata::roots_iterator RI = MD->roots_begin(),
370 RE = MD->roots_end(); RI != RE; ++RI)
371 RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
372 - OffsetOfLocalArea + OffsetAdjustment;
375 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
376 // Quick exit for functions that do not use GC.
377 if (!MF.getFunction()->hasCollector()) return false;
379 MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
380 if (!MD->getCollector().needsSafePoints())
383 TM = &MF.getTarget();
384 MMI = &getAnalysis<MachineModuleInfo>();
385 TII = TM->getInstrInfo();
386 MFI = MF.getFrameInfo();
388 // Find the size of the stack frame.
389 MD->setFrameSize(MFI->getStackSize());
391 // Find all safe points.
394 // Find the stack offsets for all roots.
395 FindStackOffsets(MF);