zpu: managed to compile program that writes constant to global variable
[llvm/zpu.git] / lib / CodeGen / RegAllocBasic.cpp
blob6c592c8e25ed66e8d94d821eb9ca63f2d24d5cd0
1 //===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
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 defines the RABasic function pass, which provides a minimal
11 // implementation of the basic register allocator.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "LiveIntervalUnion.h"
17 #include "RegAllocBase.h"
18 #include "RenderMachineFunction.h"
19 #include "Spiller.h"
20 #include "VirtRegRewriter.h"
21 #include "llvm/Function.h"
22 #include "llvm/PassAnalysisSupport.h"
23 #include "llvm/CodeGen/CalcSpillWeights.h"
24 #include "llvm/CodeGen/LiveStackAnalysis.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegAllocRegistry.h"
31 #include "llvm/CodeGen/RegisterCoalescer.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
37 #include "VirtRegMap.h"
38 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
42 #include <vector>
43 #include <queue>
45 using namespace llvm;
47 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
48 createBasicRegisterAllocator);
50 namespace {
52 /// RABasic provides a minimal implementation of the basic register allocation
53 /// algorithm. It prioritizes live virtual registers by spill weight and spills
54 /// whenever a register is unavailable. This is not practical in production but
55 /// provides a useful baseline both for measuring other allocators and comparing
56 /// the speed of the basic algorithm against other styles of allocators.
57 class RABasic : public MachineFunctionPass, public RegAllocBase
59 // context
60 MachineFunction *mf_;
61 const TargetMachine *tm_;
62 MachineRegisterInfo *mri_;
64 // analyses
65 LiveStacks *ls_;
66 RenderMachineFunction *rmf_;
68 // state
69 std::auto_ptr<Spiller> spiller_;
71 public:
72 RABasic();
74 /// Return the pass name.
75 virtual const char* getPassName() const {
76 return "Basic Register Allocator";
79 /// RABasic analysis usage.
80 virtual void getAnalysisUsage(AnalysisUsage &au) const;
82 virtual void releaseMemory();
84 virtual unsigned selectOrSplit(LiveInterval &lvr,
85 SmallVectorImpl<LiveInterval*> &splitLVRs);
87 /// Perform register allocation.
88 virtual bool runOnMachineFunction(MachineFunction &mf);
90 static char ID;
93 char RABasic::ID = 0;
95 } // end anonymous namespace
97 // We should not need to publish the initializer as long as no other passes
98 // require RABasic.
99 #if 0 // disable INITIALIZE_PASS
100 INITIALIZE_PASS_BEGIN(RABasic, "basic-regalloc",
101 "Basic Register Allocator", false, false)
102 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
103 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
104 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
105 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
106 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
107 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
108 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
109 #ifndef NDEBUG
110 INITIALIZE_PASS_DEPENDENCY(RenderMachineFunction)
111 #endif
112 INITIALIZE_PASS_END(RABasic, "basic-regalloc",
113 "Basic Register Allocator", false, false)
114 #endif // disable INITIALIZE_PASS
116 RABasic::RABasic(): MachineFunctionPass(ID) {
117 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
118 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
119 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
120 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
121 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
122 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
123 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
124 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
125 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
126 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
129 void RABasic::getAnalysisUsage(AnalysisUsage &au) const {
130 au.setPreservesCFG();
131 au.addRequired<LiveIntervals>();
132 au.addPreserved<SlotIndexes>();
133 if (StrongPHIElim)
134 au.addRequiredID(StrongPHIEliminationID);
135 au.addRequiredTransitive<RegisterCoalescer>();
136 au.addRequired<CalculateSpillWeights>();
137 au.addRequired<LiveStacks>();
138 au.addPreserved<LiveStacks>();
139 au.addRequiredID(MachineDominatorsID);
140 au.addPreservedID(MachineDominatorsID);
141 au.addRequired<MachineLoopInfo>();
142 au.addPreserved<MachineLoopInfo>();
143 au.addRequired<VirtRegMap>();
144 au.addPreserved<VirtRegMap>();
145 DEBUG(au.addRequired<RenderMachineFunction>());
146 MachineFunctionPass::getAnalysisUsage(au);
149 void RABasic::releaseMemory() {
150 spiller_.reset(0);
151 RegAllocBase::releaseMemory();
154 //===----------------------------------------------------------------------===//
155 // RegAllocBase Implementation
156 //===----------------------------------------------------------------------===//
158 // Instantiate a LiveIntervalUnion for each physical register.
159 void RegAllocBase::LIUArray::init(unsigned nRegs) {
160 array_.reset(new LiveIntervalUnion[nRegs]);
161 nRegs_ = nRegs;
162 for (unsigned pr = 0; pr < nRegs; ++pr) {
163 array_[pr].init(pr);
167 void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
168 LiveIntervals &lis) {
169 tri_ = &tri;
170 vrm_ = &vrm;
171 lis_ = &lis;
172 physReg2liu_.init(tri_->getNumRegs());
175 void RegAllocBase::LIUArray::clear() {
176 nRegs_ = 0;
177 array_.reset(0);
180 void RegAllocBase::releaseMemory() {
181 physReg2liu_.clear();
184 namespace llvm {
185 /// This class defines a queue of live virtual registers prioritized by spill
186 /// weight. The heaviest vreg is popped first.
188 /// Currently, this is trivial wrapper that gives us an opaque type in the
189 /// header, but we may later give it a virtual interface for register allocators
190 /// to override the priority queue comparator.
191 class LiveVirtRegQueue {
192 typedef std::priority_queue
193 <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority> PQ;
194 PQ pq_;
196 public:
197 // Is the queue empty?
198 bool empty() { return pq_.empty(); }
200 // Get the highest priority lvr (top + pop)
201 LiveInterval *get() {
202 LiveInterval *lvr = pq_.top();
203 pq_.pop();
204 return lvr;
206 // Add this lvr to the queue
207 void push(LiveInterval *lvr) {
208 pq_.push(lvr);
211 } // end namespace llvm
213 // Visit all the live virtual registers. If they are already assigned to a
214 // physical register, unify them with the corresponding LiveIntervalUnion,
215 // otherwise push them on the priority queue for later assignment.
216 void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &lvrQ) {
217 for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
218 liItr != liEnd; ++liItr) {
219 unsigned reg = liItr->first;
220 LiveInterval &li = *liItr->second;
221 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
222 physReg2liu_[reg].unify(li);
224 else {
225 lvrQ.push(&li);
230 // Top-level driver to manage the queue of unassigned LiveVirtRegs and call the
231 // selectOrSplit implementation.
232 void RegAllocBase::allocatePhysRegs() {
233 LiveVirtRegQueue lvrQ;
234 seedLiveVirtRegs(lvrQ);
235 while (!lvrQ.empty()) {
236 LiveInterval *lvr = lvrQ.get();
237 typedef SmallVector<LiveInterval*, 4> LVRVec;
238 LVRVec splitLVRs;
239 unsigned availablePhysReg = selectOrSplit(*lvr, splitLVRs);
240 if (availablePhysReg) {
241 assert(splitLVRs.empty() && "inconsistent splitting");
242 assert(!vrm_->hasPhys(lvr->reg) && "duplicate vreg in interval unions");
243 vrm_->assignVirt2Phys(lvr->reg, availablePhysReg);
244 physReg2liu_[availablePhysReg].unify(*lvr);
246 else {
247 for (LVRVec::iterator lvrI = splitLVRs.begin(), lvrEnd = splitLVRs.end();
248 lvrI != lvrEnd; ++lvrI) {
249 assert(TargetRegisterInfo::isVirtualRegister((*lvrI)->reg) &&
250 "expect split value in virtual register");
251 lvrQ.push(*lvrI);
257 // Check if this live virtual reg interferes with a physical register. If not,
258 // then check for interference on each register that aliases with the physical
259 // register.
260 bool RegAllocBase::checkPhysRegInterference(LiveIntervalUnion::Query &query,
261 unsigned preg) {
262 if (query.checkInterference())
263 return true;
264 for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
265 // We assume it's very unlikely for a register in the alias set to also be
266 // in the original register class. So we don't bother caching the
267 // interference.
268 LiveIntervalUnion::Query subQuery(query.lvr(), physReg2liu_[*asI] );
269 if (subQuery.checkInterference())
270 return true;
272 return false;
275 //===----------------------------------------------------------------------===//
276 // RABasic Implementation
277 //===----------------------------------------------------------------------===//
279 // Driver for the register assignment and splitting heuristics.
280 // Manages iteration over the LiveIntervalUnions.
282 // Minimal implementation of register assignment and splitting--spills whenever
283 // we run out of registers.
285 // selectOrSplit can only be called once per live virtual register. We then do a
286 // single interference test for each register the correct class until we find an
287 // available register. So, the number of interference tests in the worst case is
288 // |vregs| * |machineregs|. And since the number of interference tests is
289 // minimal, there is no value in caching them.
290 unsigned RABasic::selectOrSplit(LiveInterval &lvr,
291 SmallVectorImpl<LiveInterval*> &splitLVRs) {
292 // Check for an available reg in this class.
293 const TargetRegisterClass *trc = mri_->getRegClass(lvr.reg);
294 for (TargetRegisterClass::iterator trcI = trc->allocation_order_begin(*mf_),
295 trcEnd = trc->allocation_order_end(*mf_);
296 trcI != trcEnd; ++trcI) {
297 unsigned preg = *trcI;
298 LiveIntervalUnion::Query query(lvr, physReg2liu_[preg]);
299 if (!checkPhysRegInterference(query, preg)) {
300 DEBUG(dbgs() << "\tallocating: " << tri_->getName(preg) << lvr << '\n');
301 return preg;
304 DEBUG(dbgs() << "\tspilling: " << lvr << '\n');
305 SmallVector<LiveInterval*, 1> spillIs; // ignored
306 spiller_->spill(&lvr, splitLVRs, spillIs);
308 // FIXME: update LiveStacks
309 return 0;
312 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
313 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
314 << "********** Function: "
315 << ((Value*)mf.getFunction())->getName() << '\n');
317 mf_ = &mf;
318 tm_ = &mf.getTarget();
319 mri_ = &mf.getRegInfo();
321 DEBUG(rmf_ = &getAnalysis<RenderMachineFunction>());
323 RegAllocBase::init(*tm_->getRegisterInfo(), getAnalysis<VirtRegMap>(),
324 getAnalysis<LiveIntervals>());
326 spiller_.reset(createSpiller(*this, *mf_, *vrm_));
328 allocatePhysRegs();
330 // Diagnostic output before rewriting
331 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm_ << "\n");
333 // optional HTML output
334 DEBUG(rmf_->renderMachineFunction("After basic register allocation.", vrm_));
336 // Run rewriter
337 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
338 rewriter->runOnMachineFunction(*mf_, *vrm_, lis_);
340 // The pass output is in VirtRegMap. Release all the transient data.
341 releaseMemory();
343 return true;
346 FunctionPass* llvm::createBasicRegisterAllocator()
348 return new RABasic();