1 //===-- Collector.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 //===----------------------------------------------------------------------===//
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/CodeGen/MachineModuleInfo.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Compiler.h"
34 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
35 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
36 /// directed by the Collector. It also performs automatic root initialization
37 /// and custom intrinsic lowering.
38 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
39 static bool NeedsDefaultLoweringPass(const Collector &C);
40 static bool NeedsCustomLoweringPass(const Collector &C);
41 static bool CouldBecomeSafePoint(Instruction *I);
42 bool PerformDefaultLowering(Function &F, Collector &Coll);
43 static bool InsertRootInitializers(Function &F,
44 AllocaInst **Roots, unsigned Count);
50 const char *getPassName() const;
51 void getAnalysisUsage(AnalysisUsage &AU) const;
53 bool doInitialization(Module &M);
54 bool runOnFunction(Function &F);
58 /// MachineCodeAnalysis - This is a target-independent pass over the machine
59 /// function representation to identify safe points for the garbage collector
60 /// in the machine code. It inserts labels at safe points and populates a
61 /// CollectorMetadata record for each function.
62 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
63 const TargetMachine *TM;
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();
80 const char *getPassName() const;
81 void getAnalysisUsage(AnalysisUsage &AU) const;
83 bool runOnMachineFunction(MachineFunction &MF);
88 // -----------------------------------------------------------------------------
90 Collector::Collector() :
92 CustomReadBarriers(false),
93 CustomWriteBarriers(false),
99 Collector::~Collector() {
100 for (iterator I = begin(), E = end(); I != E; ++I)
106 bool Collector::initializeCustomLowering(Module &M) { return false; }
108 bool Collector::performCustomLowering(Function &F) {
109 cerr << "gc " << getName() << " must override performCustomLowering.\n";
114 CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
115 CollectorMetadata *CM = new CollectorMetadata(F, *this);
116 Functions.push_back(CM);
120 // -----------------------------------------------------------------------------
122 GCMetadataPrinter::GCMetadataPrinter() { }
124 GCMetadataPrinter::~GCMetadataPrinter() { }
126 void GCMetadataPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
127 const TargetAsmInfo &TAI) {
128 // Default is no action.
131 void GCMetadataPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
132 const TargetAsmInfo &TAI) {
133 // Default is no action.
136 // -----------------------------------------------------------------------------
138 FunctionPass *llvm::createGCLoweringPass() {
139 return new LowerIntrinsics();
142 char LowerIntrinsics::ID = 0;
144 LowerIntrinsics::LowerIntrinsics()
145 : FunctionPass((intptr_t)&ID) {}
147 const char *LowerIntrinsics::getPassName() const {
148 return "Lower Garbage Collection Instructions";
151 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
152 FunctionPass::getAnalysisUsage(AU);
153 AU.addRequired<CollectorModuleMetadata>();
156 /// doInitialization - If this module uses the GC intrinsics, find them now.
157 bool LowerIntrinsics::doInitialization(Module &M) {
158 // FIXME: This is rather antisocial in the context of a JIT since it performs
159 // work against the entire module. But this cannot be done at
160 // runFunction time (initializeCustomLowering likely needs to change
162 CollectorModuleMetadata *CMM = getAnalysisToUpdate<CollectorModuleMetadata>();
163 assert(CMM && "LowerIntrinsics didn't require CollectorModuleMetadata!?");
164 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
165 if (I->hasCollector())
166 CMM->get(*I); // Instantiate the Collector.
168 bool MadeChange = false;
169 for (CollectorModuleMetadata::iterator I = CMM->begin(),
170 E = CMM->end(); I != E; ++I)
171 if (NeedsCustomLoweringPass(**I))
172 if ((*I)->initializeCustomLowering(M))
178 bool 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))
189 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
190 InitedRoots.insert(AI);
192 // Add root initializers.
193 bool MadeChange = false;
195 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
196 if (!InitedRoots.count(*I)) {
197 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
198 cast<PointerType>((*I)->getType())->getElementType())),
206 bool LowerIntrinsics::NeedsDefaultLoweringPass(const Collector &C) {
207 // Default lowering is necessary only if read or write barriers have a default
208 // action. The default for roots is no action.
209 return !C.customWriteBarrier()
210 || !C.customReadBarrier()
211 || C.initializeRoots();
214 bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
215 // Custom lowering is only necessary if enabled for some action.
216 return C.customWriteBarrier()
217 || C.customReadBarrier()
221 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
222 /// instruction could introduce a safe point.
223 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
224 // The natural definition of instructions which could introduce safe points
227 // - call, invoke (AfterCall, BeforeCall)
229 // - invoke, ret, unwind (Exit)
231 // However, instructions as seemingly inoccuous as arithmetic can become
232 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
233 // it is necessary to take a conservative approach.
235 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
236 isa<StoreInst>(I) || isa<LoadInst>(I))
239 // llvm.gcroot is safe because it doesn't do anything at runtime.
240 if (CallInst *CI = dyn_cast<CallInst>(I))
241 if (Function *F = CI->getCalledFunction())
242 if (unsigned IID = F->getIntrinsicID())
243 if (IID == Intrinsic::gcroot)
249 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
250 /// Leave gcroot intrinsics; the code generator needs to see those.
251 bool LowerIntrinsics::runOnFunction(Function &F) {
252 // Quick exit for functions that do not use GC.
253 if (!F.hasCollector()) return false;
255 CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
256 Collector &Coll = MD.getCollector();
258 bool MadeChange = false;
260 if (NeedsDefaultLoweringPass(Coll))
261 MadeChange |= PerformDefaultLowering(F, Coll);
263 if (NeedsCustomLoweringPass(Coll))
264 MadeChange |= Coll.performCustomLowering(F);
269 bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
270 bool LowerWr = !Coll.customWriteBarrier();
271 bool LowerRd = !Coll.customReadBarrier();
272 bool InitRoots = Coll.initializeRoots();
274 SmallVector<AllocaInst*,32> Roots;
276 bool MadeChange = false;
277 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
278 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
279 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
280 Function *F = CI->getCalledFunction();
281 switch (F->getIntrinsicID()) {
282 case Intrinsic::gcwrite:
284 // Replace a write barrier with a simple store.
285 Value *St = new StoreInst(CI->getOperand(1), CI->getOperand(3), CI);
286 CI->replaceAllUsesWith(St);
287 CI->eraseFromParent();
290 case Intrinsic::gcread:
292 // Replace a read barrier with a simple load.
293 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
295 CI->replaceAllUsesWith(Ld);
296 CI->eraseFromParent();
299 case Intrinsic::gcroot:
301 // Initialize the GC root, but do not delete the intrinsic. The
302 // backend needs the intrinsic to flag the stack slot.
303 Roots.push_back(cast<AllocaInst>(
304 CI->getOperand(1)->stripPointerCasts()));
317 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
322 // -----------------------------------------------------------------------------
324 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
325 return new MachineCodeAnalysis();
328 char MachineCodeAnalysis::ID = 0;
330 MachineCodeAnalysis::MachineCodeAnalysis()
331 : MachineFunctionPass(intptr_t(&ID)) {}
333 const char *MachineCodeAnalysis::getPassName() const {
334 return "Analyze Machine Code For Garbage Collection";
337 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
338 MachineFunctionPass::getAnalysisUsage(AU);
339 AU.setPreservesAll();
340 AU.addRequired<MachineModuleInfo>();
341 AU.addRequired<CollectorModuleMetadata>();
344 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
345 MachineBasicBlock::iterator MI) const {
346 unsigned Label = MMI->NextLabelID();
347 BuildMI(MBB, MI, TII->get(TargetInstrInfo::GC_LABEL)).addImm(Label);
351 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
352 // Find the return address (next instruction), too, so as to bracket the call
354 MachineBasicBlock::iterator RAI = CI;
357 if (MD->getCollector().needsSafePoint(GC::PreCall))
358 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
360 if (MD->getCollector().needsSafePoint(GC::PostCall))
361 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
364 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
365 for (MachineFunction::iterator BBI = MF.begin(),
366 BBE = MF.end(); BBI != BBE; ++BBI)
367 for (MachineBasicBlock::iterator MI = BBI->begin(),
368 ME = BBI->end(); MI != ME; ++MI)
369 if (MI->getDesc().isCall())
373 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
374 uint64_t StackSize = MFI->getStackSize();
375 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
376 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
378 for (CollectorMetadata::roots_iterator RI = MD->roots_begin(),
379 RE = MD->roots_end(); RI != RE; ++RI)
380 RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
381 - OffsetOfLocalArea + OffsetAdjustment;
384 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
385 // Quick exit for functions that do not use GC.
386 if (!MF.getFunction()->hasCollector()) return false;
388 MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
389 if (!MD->getCollector().needsSafePoints())
392 TM = &MF.getTarget();
393 MMI = &getAnalysis<MachineModuleInfo>();
394 TII = TM->getInstrInfo();
395 MFI = MF.getFrameInfo();
397 // Find the size of the stack frame.
398 MD->setFrameSize(MFI->getStackSize());
400 // Find all safe points.
403 // Find the stack offsets for all roots.
404 FindStackOffsets(MF);