blob: 6fd018961a4cb6d5f334b1c789b74f29c127763f [file] [log] [blame]
Gordon Henriksen364caf02007-09-29 02:13:43 +00001//===-- Collector.cpp - Garbage collection infrastructure -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Gordon Henriksen364caf02007-09-29 02:13:43 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements target- and collector-independent garbage collection
11// infrastructure.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/Collector.h"
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000016#include "llvm/CodeGen/Passes.h"
Gordon Henriksen364caf02007-09-29 02:13:43 +000017#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"
Chris Lattner84bc5422007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Gordon Henriksen364caf02007-09-29 02:13:43 +000025#include "llvm/Target/TargetFrameInfo.h"
26#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Support/Compiler.h"
29
30using namespace llvm;
31
32namespace {
33
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000034 /// 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.
Gordon Henriksen364caf02007-09-29 02:13:43 +000038 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000039 static bool NeedsDefaultLoweringPass(const Collector &C);
40 static bool NeedsCustomLoweringPass(const Collector &C);
Gordon Henriksen364caf02007-09-29 02:13:43 +000041 static bool CouldBecomeSafePoint(Instruction *I);
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000042 bool PerformDefaultLowering(Function &F, Collector &Coll);
43 static bool InsertRootInitializers(Function &F,
Gordon Henriksen364caf02007-09-29 02:13:43 +000044 AllocaInst **Roots, unsigned Count);
45
46 public:
47 static char ID;
48
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000049 LowerIntrinsics();
Gordon Henriksen364caf02007-09-29 02:13:43 +000050 const char *getPassName() const;
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000051 void getAnalysisUsage(AnalysisUsage &AU) const;
Gordon Henriksen364caf02007-09-29 02:13:43 +000052
53 bool doInitialization(Module &M);
54 bool runOnFunction(Function &F);
55 };
56
57
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000058 /// 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.
Gordon Henriksen364caf02007-09-29 02:13:43 +000062 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000063 const TargetMachine *TM;
Gordon Henriksen364caf02007-09-29 02:13:43 +000064 CollectorMetadata *MD;
65 MachineModuleInfo *MMI;
66 const TargetInstrInfo *TII;
67 MachineFrameInfo *MFI;
68
69 void FindSafePoints(MachineFunction &MF);
70 void VisitCallPoint(MachineBasicBlock::iterator MI);
71 unsigned InsertLabel(MachineBasicBlock &MBB,
72 MachineBasicBlock::iterator MI) const;
73
74 void FindStackOffsets(MachineFunction &MF);
75
76 public:
77 static char ID;
78
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000079 MachineCodeAnalysis();
Gordon Henriksen364caf02007-09-29 02:13:43 +000080 const char *getPassName() const;
81 void getAnalysisUsage(AnalysisUsage &AU) const;
82
83 bool runOnMachineFunction(MachineFunction &MF);
84 };
85
86}
87
88// -----------------------------------------------------------------------------
89
Gordon Henriksen364caf02007-09-29 02:13:43 +000090Collector::Collector() :
91 NeededSafePoints(0),
92 CustomReadBarriers(false),
93 CustomWriteBarriers(false),
94 CustomRoots(false),
Gordon Henriksenc317a602008-08-17 12:08:44 +000095 InitRoots(true),
96 UsesMetadata(false)
Gordon Henriksen364caf02007-09-29 02:13:43 +000097{}
98
Gordon Henriksenad93c4f2007-12-11 00:30:17 +000099Collector::~Collector() {
100 for (iterator I = begin(), E = end(); I != E; ++I)
101 delete *I;
102
103 Functions.clear();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000104}
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000105
106bool Collector::initializeCustomLowering(Module &M) { return false; }
107
108bool Collector::performCustomLowering(Function &F) {
109 cerr << "gc " << getName() << " must override performCustomLowering.\n";
Gordon Henriksen364caf02007-09-29 02:13:43 +0000110 abort();
111 return 0;
112}
113
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000114CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
115 CollectorMetadata *CM = new CollectorMetadata(F, *this);
116 Functions.push_back(CM);
117 return CM;
118}
Gordon Henriksen364caf02007-09-29 02:13:43 +0000119
120// -----------------------------------------------------------------------------
121
Gordon Henriksenc317a602008-08-17 12:08:44 +0000122GCMetadataPrinter::GCMetadataPrinter() { }
123
124GCMetadataPrinter::~GCMetadataPrinter() { }
125
126void GCMetadataPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
127 const TargetAsmInfo &TAI) {
128 // Default is no action.
129}
130
131void GCMetadataPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
132 const TargetAsmInfo &TAI) {
133 // Default is no action.
134}
135
136// -----------------------------------------------------------------------------
137
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000138FunctionPass *llvm::createGCLoweringPass() {
139 return new LowerIntrinsics();
140}
141
Gordon Henriksen364caf02007-09-29 02:13:43 +0000142char LowerIntrinsics::ID = 0;
143
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000144LowerIntrinsics::LowerIntrinsics()
Gordon Henriksena6c99252007-12-22 17:27:01 +0000145 : FunctionPass((intptr_t)&ID) {}
Gordon Henriksen364caf02007-09-29 02:13:43 +0000146
147const char *LowerIntrinsics::getPassName() const {
148 return "Lower Garbage Collection Instructions";
149}
150
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000151void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
152 FunctionPass::getAnalysisUsage(AU);
153 AU.addRequired<CollectorModuleMetadata>();
154}
155
156/// doInitialization - If this module uses the GC intrinsics, find them now.
Gordon Henriksen364caf02007-09-29 02:13:43 +0000157bool LowerIntrinsics::doInitialization(Module &M) {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000158 // 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
161 // the module).
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.
167
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))
173 MadeChange = true;
174
175 return MadeChange;
Gordon Henriksen364caf02007-09-29 02:13:43 +0000176}
177
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000178bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
Gordon Henriksen364caf02007-09-29 02:13:43 +0000179 unsigned Count) {
180 // Scroll past alloca instructions.
181 BasicBlock::iterator IP = F.getEntryBlock().begin();
182 while (isa<AllocaInst>(IP)) ++IP;
183
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))
Anton Korobeynikovb04addd2008-05-06 22:52:30 +0000188 if (AllocaInst *AI =
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000189 dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
Gordon Henriksen364caf02007-09-29 02:13:43 +0000190 InitedRoots.insert(AI);
191
192 // Add root initializers.
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000193 bool MadeChange = false;
194
Gordon Henriksen364caf02007-09-29 02:13:43 +0000195 for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000196 if (!InitedRoots.count(*I)) {
Gordon Henriksen364caf02007-09-29 02:13:43 +0000197 new StoreInst(ConstantPointerNull::get(cast<PointerType>(
198 cast<PointerType>((*I)->getType())->getElementType())),
199 *I, IP);
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000200 MadeChange = true;
201 }
202
203 return MadeChange;
204}
205
206bool 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();
212}
213
214bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
215 // Custom lowering is only necessary if enabled for some action.
216 return C.customWriteBarrier()
217 || C.customReadBarrier()
218 || C.customRoots();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000219}
220
221/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
222/// instruction could introduce a safe point.
223bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
224 // The natural definition of instructions which could introduce safe points
225 // are:
226 //
227 // - call, invoke (AfterCall, BeforeCall)
228 // - phis (Loops)
229 // - invoke, ret, unwind (Exit)
230 //
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.
234
235 if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
236 isa<StoreInst>(I) || isa<LoadInst>(I))
237 return false;
238
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)
244 return false;
245
246 return true;
247}
248
249/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
250/// Leave gcroot intrinsics; the code generator needs to see those.
251bool LowerIntrinsics::runOnFunction(Function &F) {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000252 // Quick exit for functions that do not use GC.
253 if (!F.hasCollector()) return false;
Gordon Henriksen364caf02007-09-29 02:13:43 +0000254
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000255 CollectorMetadata &MD = getAnalysis<CollectorModuleMetadata>().get(F);
256 Collector &Coll = MD.getCollector();
257
258 bool MadeChange = false;
259
260 if (NeedsDefaultLoweringPass(Coll))
261 MadeChange |= PerformDefaultLowering(F, Coll);
262
263 if (NeedsCustomLoweringPass(Coll))
264 MadeChange |= Coll.performCustomLowering(F);
265
266 return MadeChange;
267}
268
269bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
Gordon Henriksen364caf02007-09-29 02:13:43 +0000270 bool LowerWr = !Coll.customWriteBarrier();
271 bool LowerRd = !Coll.customReadBarrier();
272 bool InitRoots = Coll.initializeRoots();
273
274 SmallVector<AllocaInst*,32> Roots;
275
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;) {
Gordon Henriksena6c99252007-12-22 17:27:01 +0000279 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
Gordon Henriksen364caf02007-09-29 02:13:43 +0000280 Function *F = CI->getCalledFunction();
Gordon Henriksena6c99252007-12-22 17:27:01 +0000281 switch (F->getIntrinsicID()) {
282 case Intrinsic::gcwrite:
283 if (LowerWr) {
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();
288 }
289 break;
290 case Intrinsic::gcread:
291 if (LowerRd) {
292 // Replace a read barrier with a simple load.
293 Value *Ld = new LoadInst(CI->getOperand(2), "", CI);
294 Ld->takeName(CI);
295 CI->replaceAllUsesWith(Ld);
296 CI->eraseFromParent();
297 }
298 break;
299 case Intrinsic::gcroot:
300 if (InitRoots) {
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>(
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000304 CI->getOperand(1)->stripPointerCasts()));
Gordon Henriksena6c99252007-12-22 17:27:01 +0000305 }
306 break;
307 default:
Gordon Henriksen364caf02007-09-29 02:13:43 +0000308 continue;
309 }
310
311 MadeChange = true;
312 }
313 }
314 }
315
316 if (Roots.size())
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000317 MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
Gordon Henriksen364caf02007-09-29 02:13:43 +0000318
319 return MadeChange;
320}
321
322// -----------------------------------------------------------------------------
323
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000324FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
325 return new MachineCodeAnalysis();
326}
327
Gordon Henriksen364caf02007-09-29 02:13:43 +0000328char MachineCodeAnalysis::ID = 0;
329
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000330MachineCodeAnalysis::MachineCodeAnalysis()
331 : MachineFunctionPass(intptr_t(&ID)) {}
Gordon Henriksen364caf02007-09-29 02:13:43 +0000332
333const char *MachineCodeAnalysis::getPassName() const {
334 return "Analyze Machine Code For Garbage Collection";
335}
336
337void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
338 MachineFunctionPass::getAnalysisUsage(AU);
339 AU.setPreservesAll();
340 AU.addRequired<MachineModuleInfo>();
341 AU.addRequired<CollectorModuleMetadata>();
342}
343
344unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
345 MachineBasicBlock::iterator MI) const {
346 unsigned Label = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +0000347 BuildMI(MBB, MI, TII->get(TargetInstrInfo::GC_LABEL)).addImm(Label);
Gordon Henriksen364caf02007-09-29 02:13:43 +0000348 return Label;
349}
350
351void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
352 // Find the return address (next instruction), too, so as to bracket the call
353 // instruction.
354 MachineBasicBlock::iterator RAI = CI;
355 ++RAI;
356
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000357 if (MD->getCollector().needsSafePoint(GC::PreCall))
Gordon Henriksen364caf02007-09-29 02:13:43 +0000358 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
359
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000360 if (MD->getCollector().needsSafePoint(GC::PostCall))
Gordon Henriksen364caf02007-09-29 02:13:43 +0000361 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
362}
363
364void 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)
Chris Lattner749c6f62008-01-07 07:27:27 +0000369 if (MI->getDesc().isCall())
Dan Gohmanfd3ff032008-07-07 20:08:05 +0000370 VisitCallPoint(MI);
Gordon Henriksen364caf02007-09-29 02:13:43 +0000371}
372
373void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
374 uint64_t StackSize = MFI->getStackSize();
375 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000376 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000377
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;
382}
383
384bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000385 // Quick exit for functions that do not use GC.
386 if (!MF.getFunction()->hasCollector()) return false;
387
388 MD = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
389 if (!MD->getCollector().needsSafePoints())
Gordon Henriksen364caf02007-09-29 02:13:43 +0000390 return false;
391
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000392 TM = &MF.getTarget();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000393 MMI = &getAnalysis<MachineModuleInfo>();
Gordon Henriksenad93c4f2007-12-11 00:30:17 +0000394 TII = TM->getInstrInfo();
Gordon Henriksen364caf02007-09-29 02:13:43 +0000395 MFI = MF.getFrameInfo();
396
397 // Find the size of the stack frame.
398 MD->setFrameSize(MFI->getStackSize());
399
400 // Find all safe points.
401 FindSafePoints(MF);
402
403 // Find the stack offsets for all roots.
404 FindStackOffsets(MF);
405
406 return false;
407}