Fixed some bugs.
[llvm/zpu.git] / lib / CodeGen / GCStrategy.cpp
blob4793ba84ddf82e730809ebc00cbe67c68157d536
1 //===-- GCStrategy.cpp - Garbage collection infrastructure -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements target- and collector-independent garbage collection
11 // infrastructure.
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/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
36 namespace {
38 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
39 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
40 /// directed by the GCStrategy. It also performs automatic root initialization
41 /// and custom intrinsic lowering.
42 class LowerIntrinsics : public FunctionPass {
43 static bool NeedsDefaultLoweringPass(const GCStrategy &C);
44 static bool NeedsCustomLoweringPass(const GCStrategy &C);
45 static bool CouldBecomeSafePoint(Instruction *I);
46 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
47 static bool InsertRootInitializers(Function &F,
48 AllocaInst **Roots, unsigned Count);
50 public:
51 static char ID;
53 LowerIntrinsics();
54 const char *getPassName() const;
55 void getAnalysisUsage(AnalysisUsage &AU) const;
57 bool doInitialization(Module &M);
58 bool runOnFunction(Function &F);
62 /// MachineCodeAnalysis - This is a target-independent pass over the machine
63 /// function representation to identify safe points for the garbage collector
64 /// in the machine code. It inserts labels at safe points and populates a
65 /// GCMetadata record for each function.
66 class MachineCodeAnalysis : public MachineFunctionPass {
67 const TargetMachine *TM;
68 GCFunctionInfo *FI;
69 MachineModuleInfo *MMI;
70 const TargetInstrInfo *TII;
72 void FindSafePoints(MachineFunction &MF);
73 void VisitCallPoint(MachineBasicBlock::iterator MI);
74 MCSymbol *InsertLabel(MachineBasicBlock &MBB,
75 MachineBasicBlock::iterator MI,
76 DebugLoc DL) const;
78 void FindStackOffsets(MachineFunction &MF);
80 public:
81 static char ID;
83 MachineCodeAnalysis();
84 const char *getPassName() const;
85 void getAnalysisUsage(AnalysisUsage &AU) const;
87 bool runOnMachineFunction(MachineFunction &MF);
92 // -----------------------------------------------------------------------------
94 GCStrategy::GCStrategy() :
95 NeededSafePoints(0),
96 CustomReadBarriers(false),
97 CustomWriteBarriers(false),
98 CustomRoots(false),
99 InitRoots(true),
100 UsesMetadata(false)
103 GCStrategy::~GCStrategy() {
104 for (iterator I = begin(), E = end(); I != E; ++I)
105 delete *I;
107 Functions.clear();
110 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
112 bool GCStrategy::performCustomLowering(Function &F) {
113 dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
114 llvm_unreachable(0);
115 return 0;
118 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
119 GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
120 Functions.push_back(FI);
121 return FI;
124 // -----------------------------------------------------------------------------
126 INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
127 false, false)
128 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
129 INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
131 FunctionPass *llvm::createGCLoweringPass() {
132 return new LowerIntrinsics();
135 char LowerIntrinsics::ID = 0;
137 LowerIntrinsics::LowerIntrinsics()
138 : FunctionPass(ID) {
139 initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
142 const char *LowerIntrinsics::getPassName() const {
143 return "Lower Garbage Collection Instructions";
146 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
147 FunctionPass::getAnalysisUsage(AU);
148 AU.addRequired<GCModuleInfo>();
151 /// doInitialization - If this module uses the GC intrinsics, find them now.
152 bool LowerIntrinsics::doInitialization(Module &M) {
153 // FIXME: This is rather antisocial in the context of a JIT since it performs
154 // work against the entire module. But this cannot be done at
155 // runFunction time (initializeCustomLowering likely needs to change
156 // the module).
157 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
158 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
159 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
160 if (!I->isDeclaration() && I->hasGC())
161 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
163 bool MadeChange = false;
164 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
165 if (NeedsCustomLoweringPass(**I))
166 if ((*I)->initializeCustomLowering(M))
167 MadeChange = true;
169 return MadeChange;
172 bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
173 unsigned Count) {
174 // Scroll past alloca instructions.
175 BasicBlock::iterator IP = F.getEntryBlock().begin();
176 while (isa<AllocaInst>(IP)) ++IP;
178 // Search for initializers in the initial BB.
179 SmallPtrSet<AllocaInst*,16> InitedRoots;
180 for (; !CouldBecomeSafePoint(IP); ++IP)
181 if (StoreInst *SI = dyn_cast<StoreInst>(IP))
182 if (AllocaInst *AI =
183 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
184 InitedRoots.insert(AI);
186 // Add root initializers.
187 bool MadeChange = false;
189 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
190 if (!InitedRoots.count(*I)) {
191 StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
192 cast<PointerType>((*I)->getType())->getElementType())),
193 *I);
194 SI->insertAfter(*I);
195 MadeChange = true;
198 return MadeChange;
201 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
202 // Default lowering is necessary only if read or write barriers have a default
203 // action. The default for roots is no action.
204 return !C.customWriteBarrier()
205 || !C.customReadBarrier()
206 || C.initializeRoots();
209 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
210 // Custom lowering is only necessary if enabled for some action.
211 return C.customWriteBarrier()
212 || C.customReadBarrier()
213 || C.customRoots();
216 /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
217 /// instruction could introduce a safe point.
218 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
219 // The natural definition of instructions which could introduce safe points
220 // are:
222 // - call, invoke (AfterCall, BeforeCall)
223 // - phis (Loops)
224 // - invoke, ret, unwind (Exit)
226 // However, instructions as seemingly inoccuous as arithmetic can become
227 // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
228 // it is necessary to take a conservative approach.
230 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
231 isa<StoreInst>(I) || isa<LoadInst>(I))
232 return false;
234 // llvm.gcroot is safe because it doesn't do anything at runtime.
235 if (CallInst *CI = dyn_cast<CallInst>(I))
236 if (Function *F = CI->getCalledFunction())
237 if (unsigned IID = F->getIntrinsicID())
238 if (IID == Intrinsic::gcroot)
239 return false;
241 return true;
244 /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
245 /// Leave gcroot intrinsics; the code generator needs to see those.
246 bool LowerIntrinsics::runOnFunction(Function &F) {
247 // Quick exit for functions that do not use GC.
248 if (!F.hasGC())
249 return false;
251 GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
252 GCStrategy &S = FI.getStrategy();
254 bool MadeChange = false;
256 if (NeedsDefaultLoweringPass(S))
257 MadeChange |= PerformDefaultLowering(F, S);
259 if (NeedsCustomLoweringPass(S))
260 MadeChange |= S.performCustomLowering(F);
262 return MadeChange;
265 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
266 bool LowerWr = !S.customWriteBarrier();
267 bool LowerRd = !S.customReadBarrier();
268 bool InitRoots = S.initializeRoots();
270 SmallVector<AllocaInst*, 32> Roots;
272 bool MadeChange = false;
273 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
274 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
275 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
276 Function *F = CI->getCalledFunction();
277 switch (F->getIntrinsicID()) {
278 case Intrinsic::gcwrite:
279 if (LowerWr) {
280 // Replace a write barrier with a simple store.
281 Value *St = new StoreInst(CI->getArgOperand(0),
282 CI->getArgOperand(2), CI);
283 CI->replaceAllUsesWith(St);
284 CI->eraseFromParent();
286 break;
287 case Intrinsic::gcread:
288 if (LowerRd) {
289 // Replace a read barrier with a simple load.
290 Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
291 Ld->takeName(CI);
292 CI->replaceAllUsesWith(Ld);
293 CI->eraseFromParent();
295 break;
296 case Intrinsic::gcroot:
297 if (InitRoots) {
298 // Initialize the GC root, but do not delete the intrinsic. The
299 // backend needs the intrinsic to flag the stack slot.
300 Roots.push_back(cast<AllocaInst>(
301 CI->getArgOperand(0)->stripPointerCasts()));
303 break;
304 default:
305 continue;
308 MadeChange = true;
313 if (Roots.size())
314 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
316 return MadeChange;
319 // -----------------------------------------------------------------------------
321 FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
322 return new MachineCodeAnalysis();
325 char MachineCodeAnalysis::ID = 0;
327 MachineCodeAnalysis::MachineCodeAnalysis()
328 : MachineFunctionPass(ID) {}
330 const char *MachineCodeAnalysis::getPassName() const {
331 return "Analyze Machine Code For Garbage Collection";
334 void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
335 MachineFunctionPass::getAnalysisUsage(AU);
336 AU.setPreservesAll();
337 AU.addRequired<MachineModuleInfo>();
338 AU.addRequired<GCModuleInfo>();
341 MCSymbol *MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
342 MachineBasicBlock::iterator MI,
343 DebugLoc DL) const {
344 MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
345 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
346 return Label;
349 void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
350 // Find the return address (next instruction), too, so as to bracket the call
351 // instruction.
352 MachineBasicBlock::iterator RAI = CI;
353 ++RAI;
355 if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
356 MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
357 FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
360 if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
361 MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
362 FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
366 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
367 for (MachineFunction::iterator BBI = MF.begin(),
368 BBE = MF.end(); BBI != BBE; ++BBI)
369 for (MachineBasicBlock::iterator MI = BBI->begin(),
370 ME = BBI->end(); MI != ME; ++MI)
371 if (MI->getDesc().isCall())
372 VisitCallPoint(MI);
375 void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
376 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
377 assert(TRI && "TargetRegisterInfo not available!");
379 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
380 RE = FI->roots_end(); RI != RE; ++RI)
381 RI->StackOffset = TRI->getFrameIndexOffset(MF, RI->Num);
384 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
385 // Quick exit for functions that do not use GC.
386 if (!MF.getFunction()->hasGC())
387 return false;
389 FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
390 if (!FI->getStrategy().needsSafePoints())
391 return false;
393 TM = &MF.getTarget();
394 MMI = &getAnalysis<MachineModuleInfo>();
395 TII = TM->getInstrInfo();
397 // Find the size of the stack frame.
398 FI->setFrameSize(MF.getFrameInfo()->getStackSize());
400 // Find all safe points.
401 FindSafePoints(MF);
403 // Find the stack offsets for all roots.
404 FindStackOffsets(MF);
406 return false;