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 // MachineCodeAnalysis identifies the GC safe points in the machine code. Roots
14 // are identified in SelectionDAGISel.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/CodeGen/GCStrategy.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/Compiler.h"
36 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
37 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
38 /// directed by the GCStrategy. It also performs automatic root initialization
39 /// and custom intrinsic lowering.
40 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
41 static bool NeedsDefaultLoweringPass(const GCStrategy &C);
42 static bool NeedsCustomLoweringPass(const GCStrategy &C);
43 static bool CouldBecomeSafePoint(Instruction *I);
44 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
45 static bool InsertRootInitializers(Function &F,
46 AllocaInst **Roots, unsigned Count);
52 const char *getPassName() const;
53 void getAnalysisUsage(AnalysisUsage &AU) const;
55 bool doInitialization(Module &M);
56 bool runOnFunction(Function &F);
60 /// MachineCodeAnalysis - This is a target-independent pass over the machine
61 /// function representation to identify safe points for the garbage collector
62 /// in the machine code. It inserts labels at safe points and populates a
63 /// GCMetadata record for each function.
64 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
65 const TargetMachine *TM;
67 MachineModuleInfo *MMI;
68 const TargetInstrInfo *TII;
69 MachineFrameInfo *MFI;
71 void FindSafePoints(MachineFunction &MF);
72 void VisitCallPoint(MachineBasicBlock::iterator MI);
73 unsigned InsertLabel(MachineBasicBlock &MBB,
74 MachineBasicBlock::iterator MI) const;
76 void FindStackOffsets(MachineFunction &MF);
81 MachineCodeAnalysis();
82 const char *getPassName() const;
83 void getAnalysisUsage(AnalysisUsage &AU) const;
85 bool runOnMachineFunction(MachineFunction &MF);
90 // -----------------------------------------------------------------------------
92 GCStrategy::GCStrategy() :
94 CustomReadBarriers(false),
95 CustomWriteBarriers(false),
101 GCStrategy::~GCStrategy() {
102 for (iterator I = begin(), E = end(); I != E; ++I)
108 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
110 bool GCStrategy::performCustomLowering(Function &F) {
111 cerr << "gc " << getName() << " must override performCustomLowering.\n";
116 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
117 GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
118 Functions.push_back(FI);
122 // -----------------------------------------------------------------------------
124 FunctionPass *llvm::createGCLoweringPass() {
125 return new LowerIntrinsics();
128 char LowerIntrinsics::ID = 0;
130 LowerIntrinsics::LowerIntrinsics()
131 : FunctionPass((intptr_t)&ID) {}
133 const char *LowerIntrinsics::getPassName() const {
134 return "Lower Garbage Collection Instructions";
137 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
138 FunctionPass::getAnalysisUsage(AU);
139 AU.addRequired<GCModuleInfo>();
142 /// doInitialization - If this module uses the GC intrinsics, find them now.
143 bool LowerIntrinsics::doInitialization(Module &M) {
144 // FIXME: This is rather antisocial in the context of a JIT since it performs
145 // work against the entire module. But this cannot be done at
146 // runFunction time (initializeCustomLowering likely needs to change
148 GCModuleInfo *MI = getAnalysisToUpdate<GCModuleInfo>();
149 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
150 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
151 if (!I->isDeclaration() && I->hasGC())
152 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
154 bool MadeChange = false;
155 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
156 if (NeedsCustomLoweringPass(**I))
157 if ((*I)->initializeCustomLowering(M))
163 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
165 // Scroll past alloca instructions.
166 BasicBlock::iterator IP = F.getEntryBlock().begin();
167 while (isa<AllocaInst>(IP)) ++IP;
169 // Search for initializers in the initial BB.
170 SmallPtrSet<AllocaInst*,16> InitedRoots;
171 for (; !CouldBecomeSafePoint(IP); ++IP)
172 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
174 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
175 InitedRoots.insert(AI);
177 // Add root initializers.
178 bool MadeChange = false;
180 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
181 if (!InitedRoots.count(*I)) {
182 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
183 cast<PointerType>((*I)->getType())->getElementType())),
191 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
192 // Default lowering is necessary only if read or write barriers have a default
193 // action. The default for roots is no action.
194 return !C.customWriteBarrier()
195 || !C.customReadBarrier()
196 || C.initializeRoots();
199 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
200 // Custom lowering is only necessary if enabled for some action.
201 return C.customWriteBarrier()
202 || C.customReadBarrier()
206 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
207 /// instruction could introduce a safe point.
208 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
209 // The natural definition of instructions which could introduce safe points
212 // - call, invoke (AfterCall, BeforeCall)
214 // - invoke, ret, unwind (Exit)
216 // However, instructions as seemingly inoccuous as arithmetic can become
217 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
218 // it is necessary to take a conservative approach.
220 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
221 isa<StoreInst>(I) || isa<LoadInst>(I))
224 // llvm.gcroot is safe because it doesn't do anything at runtime.
225 if (CallInst *CI = dyn_cast<CallInst>(I))
226 if (Function *F = CI->getCalledFunction())
227 if (unsigned IID = F->getIntrinsicID())
228 if (IID == Intrinsic::gcroot)
234 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
235 /// Leave gcroot intrinsics; the code generator needs to see those.
236 bool LowerIntrinsics::runOnFunction(Function &F) {
237 // Quick exit for functions that do not use GC.
241 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
242 GCStrategy &S = FI.getStrategy();
244 bool MadeChange = false;
246 if (NeedsDefaultLoweringPass(S))
247 MadeChange |= PerformDefaultLowering(F, S);
249 if (NeedsCustomLoweringPass(S))
250 MadeChange |= S.performCustomLowering(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->getOperand(1), CI->getOperand(3), CI);
272 CI->replaceAllUsesWith(St);
273 CI->eraseFromParent();
276 case Intrinsic::gcread:
278 // Replace a read barrier with a simple load.
279 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
281 CI->replaceAllUsesWith(Ld);
282 CI->eraseFromParent();
285 case Intrinsic::gcroot:
287 // Initialize the GC root, but do not delete the intrinsic. The
288 // backend needs the intrinsic to flag the stack slot.
289 Roots.push_back(cast<AllocaInst>(
290 CI->getOperand(1)->stripPointerCasts()));
303 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
308 // -----------------------------------------------------------------------------
310 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
311 return new MachineCodeAnalysis();
314 char MachineCodeAnalysis::ID = 0;
316 MachineCodeAnalysis::MachineCodeAnalysis()
317 : MachineFunctionPass(intptr_t(&ID)) {}
319 const char *MachineCodeAnalysis::getPassName() const {
320 return "Analyze Machine Code For Garbage Collection";
323 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
324 MachineFunctionPass::getAnalysisUsage(AU);
325 AU.setPreservesAll();
326 AU.addRequired<MachineModuleInfo>();
327 AU.addRequired<GCModuleInfo>();
330 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
331 MachineBasicBlock::iterator MI) const {
332 unsigned Label = MMI->NextLabelID();
333 BuildMI(MBB, MI, TII->get(TargetInstrInfo::GC_LABEL)).addImm(Label);
337 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
338 // Find the return address (next instruction), too, so as to bracket the call
340 MachineBasicBlock::iterator RAI = CI;
343 if (FI->getStrategy().needsSafePoint(GC::PreCall))
344 FI->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
346 if (FI->getStrategy().needsSafePoint(GC::PostCall))
347 FI->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
350 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
351 for (MachineFunction::iterator BBI = MF.begin(),
352 BBE = MF.end(); BBI != BBE; ++BBI)
353 for (MachineBasicBlock::iterator MI = BBI->begin(),
354 ME = BBI->end(); MI != ME; ++MI)
355 if (MI->getDesc().isCall())
359 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
360 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
361 assert(TRI && "TargetRegisterInfo not available!");
363 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
364 RE = FI->roots_end(); RI != RE; ++RI)
365 RI->StackOffset = TRI->getFrameIndexOffset(MF, RI->Num);
368 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
369 // Quick exit for functions that do not use GC.
370 if (!MF.getFunction()->hasGC())
373 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
374 if (!FI->getStrategy().needsSafePoints())
377 TM = &MF.getTarget();
378 MMI = &getAnalysis<MachineModuleInfo>();
379 TII = TM->getInstrInfo();
381 // Find the size of the stack frame.
382 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
384 // Find all safe points.
387 // Find the stack offsets for all roots.
388 FindStackOffsets(MF);