1 //===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
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 defines the RABasic function pass, which provides a minimal
11 // implementation of the basic register allocator.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "RegAllocBase.h"
17 #include "LiveDebugVariables.h"
18 #include "LiveRangeEdit.h"
19 #include "RenderMachineFunction.h"
21 #include "VirtRegMap.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Function.h"
24 #include "llvm/PassAnalysisSupport.h"
25 #include "llvm/CodeGen/CalcSpillWeights.h"
26 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
27 #include "llvm/CodeGen/LiveStackAnalysis.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/RegAllocRegistry.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
45 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
46 createBasicRegisterAllocator);
49 struct CompSpillWeight {
50 bool operator()(LiveInterval *A, LiveInterval *B) const {
51 return A->weight < B->weight;
57 /// RABasic provides a minimal implementation of the basic register allocation
58 /// algorithm. It prioritizes live virtual registers by spill weight and spills
59 /// whenever a register is unavailable. This is not practical in production but
60 /// provides a useful baseline both for measuring other allocators and comparing
61 /// the speed of the basic algorithm against other styles of allocators.
62 class RABasic : public MachineFunctionPass, public RegAllocBase
69 RenderMachineFunction *RMF;
72 std::auto_ptr<Spiller> SpillerInstance;
73 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
74 CompSpillWeight> Queue;
78 /// Return the pass name.
79 virtual const char* getPassName() const {
80 return "Basic Register Allocator";
83 /// RABasic analysis usage.
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
86 virtual void releaseMemory();
88 virtual Spiller &spiller() { return *SpillerInstance; }
90 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
92 virtual void enqueue(LiveInterval *LI) {
96 virtual LiveInterval *dequeue() {
99 LiveInterval *LI = Queue.top();
104 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
105 SmallVectorImpl<LiveInterval*> &SplitVRegs);
107 /// Perform register allocation.
108 virtual bool runOnMachineFunction(MachineFunction &mf);
113 char RABasic::ID = 0;
115 } // end anonymous namespace
117 RABasic::RABasic(): MachineFunctionPass(ID) {
118 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
119 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
120 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
121 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
122 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
123 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
124 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
125 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
126 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
127 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
128 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
131 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
132 AU.setPreservesCFG();
133 AU.addRequired<AliasAnalysis>();
134 AU.addPreserved<AliasAnalysis>();
135 AU.addRequired<LiveIntervals>();
136 AU.addPreserved<SlotIndexes>();
137 AU.addRequired<LiveDebugVariables>();
138 AU.addPreserved<LiveDebugVariables>();
140 AU.addRequiredID(StrongPHIEliminationID);
141 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
142 AU.addRequired<CalculateSpillWeights>();
143 AU.addRequired<LiveStacks>();
144 AU.addPreserved<LiveStacks>();
145 AU.addRequiredID(MachineDominatorsID);
146 AU.addPreservedID(MachineDominatorsID);
147 AU.addRequired<MachineLoopInfo>();
148 AU.addPreserved<MachineLoopInfo>();
149 AU.addRequired<VirtRegMap>();
150 AU.addPreserved<VirtRegMap>();
151 DEBUG(AU.addRequired<RenderMachineFunction>());
152 MachineFunctionPass::getAnalysisUsage(AU);
155 void RABasic::releaseMemory() {
156 SpillerInstance.reset(0);
157 RegAllocBase::releaseMemory();
160 // Driver for the register assignment and splitting heuristics.
161 // Manages iteration over the LiveIntervalUnions.
163 // This is a minimal implementation of register assignment and splitting that
164 // spills whenever we run out of registers.
166 // selectOrSplit can only be called once per live virtual register. We then do a
167 // single interference test for each register the correct class until we find an
168 // available register. So, the number of interference tests in the worst case is
169 // |vregs| * |machineregs|. And since the number of interference tests is
170 // minimal, there is no value in caching them outside the scope of
172 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
173 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
174 // Populate a list of physical register spill candidates.
175 SmallVector<unsigned, 8> PhysRegSpillCands;
177 // Check for an available register in this class.
178 ArrayRef<unsigned> Order =
179 RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
180 for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
182 unsigned PhysReg = *I;
184 // Check interference and as a side effect, intialize queries for this
185 // VirtReg and its aliases.
186 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
187 if (interfReg == 0) {
188 // Found an available register.
191 Queries[interfReg].collectInterferingVRegs(1);
192 LiveInterval *interferingVirtReg =
193 Queries[interfReg].interferingVRegs().front();
195 // The current VirtReg must either be spillable, or one of its interferences
196 // must have less spill weight.
197 if (interferingVirtReg->weight < VirtReg.weight ) {
198 PhysRegSpillCands.push_back(PhysReg);
201 // Try to spill another interfering reg with less spill weight.
202 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
203 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
205 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
207 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
208 "Interference after spill.");
209 // Tell the caller to allocate to this newly freed physical register.
213 // No other spill candidates were found, so spill the current VirtReg.
214 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
215 if (!VirtReg.isSpillable())
217 LiveRangeEdit LRE(VirtReg, SplitVRegs);
218 spiller().spill(LRE);
220 // The live virtual register requesting allocation was spilled, so tell
221 // the caller not to allocate anything during this round.
225 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
226 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
227 << "********** Function: "
228 << ((Value*)mf.getFunction())->getName() << '\n');
231 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
233 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
234 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
240 // Diagnostic output before rewriting
241 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
243 // optional HTML output
244 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
246 // FIXME: Verification currently must run before VirtRegRewriter. We should
247 // make the rewriter a separate pass and override verifyAnalysis instead. When
248 // that happens, verification naturally falls under VerifyMachineCode.
251 // Verify accuracy of LiveIntervals. The standard machine code verifier
252 // ensures that each LiveIntervals covers all uses of the virtual reg.
254 // FIXME: MachineVerifier is badly broken when using the standard
255 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
256 // inline spiller, some tests fail to verify because the coalescer does not
257 // always generate verifiable code.
258 MF->verify(this, "In RABasic::verify");
260 // Verify that LiveIntervals are partitioned into unions and disjoint within
267 VRM->rewrite(LIS->getSlotIndexes());
269 // Write out new DBG_VALUE instructions.
270 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
272 // The pass output is in VirtRegMap. Release all the transient data.
278 FunctionPass* llvm::createBasicRegisterAllocator()
280 return new RABasic();