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 "RenderMachineFunction.h"
20 #include "VirtRegMap.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Function.h"
23 #include "llvm/PassAnalysisSupport.h"
24 #include "llvm/CodeGen/CalcSpillWeights.h"
25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
26 #include "llvm/CodeGen/LiveRangeEdit.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
68 RenderMachineFunction *RMF;
71 std::auto_ptr<Spiller> SpillerInstance;
72 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
73 CompSpillWeight> Queue;
75 // Scratch space. Allocated here to avoid repeated malloc calls in
82 /// Return the pass name.
83 virtual const char* getPassName() const {
84 return "Basic Register Allocator";
87 /// RABasic analysis usage.
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
90 virtual void releaseMemory();
92 virtual Spiller &spiller() { return *SpillerInstance; }
94 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
96 virtual void enqueue(LiveInterval *LI) {
100 virtual LiveInterval *dequeue() {
103 LiveInterval *LI = Queue.top();
108 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
109 SmallVectorImpl<LiveInterval*> &SplitVRegs);
111 /// Perform register allocation.
112 virtual bool runOnMachineFunction(MachineFunction &mf);
114 // Helper for spilling all live virtual registers currently unified under preg
115 // that interfere with the most recently queried lvr. Return true if spilling
116 // was successful, and append any new spilled/split intervals to splitLVRs.
117 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
118 SmallVectorImpl<LiveInterval*> &SplitVRegs);
120 void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
121 SmallVectorImpl<LiveInterval*> &SplitVRegs);
126 char RABasic::ID = 0;
128 } // end anonymous namespace
130 RABasic::RABasic(): MachineFunctionPass(ID) {
131 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
132 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
133 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
134 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
135 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
136 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
137 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
138 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
139 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
140 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
141 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
144 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
145 AU.setPreservesCFG();
146 AU.addRequired<AliasAnalysis>();
147 AU.addPreserved<AliasAnalysis>();
148 AU.addRequired<LiveIntervals>();
149 AU.addPreserved<SlotIndexes>();
150 AU.addRequired<LiveDebugVariables>();
151 AU.addPreserved<LiveDebugVariables>();
152 AU.addRequired<CalculateSpillWeights>();
153 AU.addRequired<LiveStacks>();
154 AU.addPreserved<LiveStacks>();
155 AU.addRequiredID(MachineDominatorsID);
156 AU.addPreservedID(MachineDominatorsID);
157 AU.addRequired<MachineLoopInfo>();
158 AU.addPreserved<MachineLoopInfo>();
159 AU.addRequired<VirtRegMap>();
160 AU.addPreserved<VirtRegMap>();
161 DEBUG(AU.addRequired<RenderMachineFunction>());
162 MachineFunctionPass::getAnalysisUsage(AU);
165 void RABasic::releaseMemory() {
166 SpillerInstance.reset(0);
167 RegAllocBase::releaseMemory();
170 // Helper for spillInterferences() that spills all interfering vregs currently
171 // assigned to this physical register.
172 void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
173 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
174 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
175 assert(Q.seenAllInterferences() && "need collectInterferences()");
176 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
178 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
179 E = PendingSpills.end(); I != E; ++I) {
180 LiveInterval &SpilledVReg = **I;
181 DEBUG(dbgs() << "extracting from " <<
182 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
184 // Deallocate the interfering vreg by removing it from the union.
185 // A LiveInterval instance may not be in a union during modification!
186 unassign(SpilledVReg, PhysReg);
188 // Spill the extracted interval.
189 LiveRangeEdit LRE(&SpilledVReg, SplitVRegs, *MF, *LIS, VRM);
190 spiller().spill(LRE);
192 // After extracting segments, the query's results are invalid. But keep the
193 // contents valid until we're done accessing pendingSpills.
197 // Spill or split all live virtual registers currently unified under PhysReg
198 // that interfere with VirtReg. The newly spilled or split live intervals are
199 // returned by appending them to SplitVRegs.
200 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
201 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
202 // Record each interference and determine if all are spillable before mutating
203 // either the union or live intervals.
204 unsigned NumInterferences = 0;
205 // Collect interferences assigned to any alias of the physical register.
206 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
207 LiveIntervalUnion::Query &QAlias = query(VirtReg, *AI);
208 NumInterferences += QAlias.collectInterferingVRegs();
209 if (QAlias.seenUnspillableVReg()) {
213 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
214 " interferences with " << VirtReg << "\n");
215 assert(NumInterferences > 0 && "expect interference");
217 // Spill each interfering vreg allocated to PhysReg or an alias.
218 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI)
219 spillReg(VirtReg, *AI, SplitVRegs);
223 // Driver for the register assignment and splitting heuristics.
224 // Manages iteration over the LiveIntervalUnions.
226 // This is a minimal implementation of register assignment and splitting that
227 // spills whenever we run out of registers.
229 // selectOrSplit can only be called once per live virtual register. We then do a
230 // single interference test for each register the correct class until we find an
231 // available register. So, the number of interference tests in the worst case is
232 // |vregs| * |machineregs|. And since the number of interference tests is
233 // minimal, there is no value in caching them outside the scope of
235 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
236 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
237 // Check for register mask interference. When live ranges cross calls, the
238 // set of usable registers is reduced to the callee-saved ones.
239 bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs);
241 // Populate a list of physical register spill candidates.
242 SmallVector<unsigned, 8> PhysRegSpillCands;
244 // Check for an available register in this class.
245 ArrayRef<unsigned> Order =
246 RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
247 for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
249 unsigned PhysReg = *I;
251 // If PhysReg is clobbered by a register mask, it isn't useful for
252 // allocation or spilling.
253 if (CrossRegMasks && !UsableRegs.test(PhysReg))
256 // Check interference and as a side effect, intialize queries for this
257 // VirtReg and its aliases.
258 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
259 if (interfReg == 0) {
260 // Found an available register.
263 LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg);
264 IntfQ.collectInterferingVRegs(1);
265 LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front();
267 // The current VirtReg must either be spillable, or one of its interferences
268 // must have less spill weight.
269 if (interferingVirtReg->weight < VirtReg.weight ) {
270 PhysRegSpillCands.push_back(PhysReg);
273 // Try to spill another interfering reg with less spill weight.
274 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
275 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
277 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
279 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
280 "Interference after spill.");
281 // Tell the caller to allocate to this newly freed physical register.
285 // No other spill candidates were found, so spill the current VirtReg.
286 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
287 if (!VirtReg.isSpillable())
289 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
290 spiller().spill(LRE);
292 // The live virtual register requesting allocation was spilled, so tell
293 // the caller not to allocate anything during this round.
297 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
298 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
299 << "********** Function: "
300 << ((Value*)mf.getFunction())->getName() << '\n');
303 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
305 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
306 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
312 // Diagnostic output before rewriting
313 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
315 // optional HTML output
316 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
318 // FIXME: Verification currently must run before VirtRegRewriter. We should
319 // make the rewriter a separate pass and override verifyAnalysis instead. When
320 // that happens, verification naturally falls under VerifyMachineCode.
323 // Verify accuracy of LiveIntervals. The standard machine code verifier
324 // ensures that each LiveIntervals covers all uses of the virtual reg.
326 // FIXME: MachineVerifier is badly broken when using the standard
327 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
328 // inline spiller, some tests fail to verify because the coalescer does not
329 // always generate verifiable code.
330 MF->verify(this, "In RABasic::verify");
332 // Verify that LiveIntervals are partitioned into unions and disjoint within
339 VRM->rewrite(LIS->getSlotIndexes());
341 // Write out new DBG_VALUE instructions.
342 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
344 // All machine operands and other references to virtual registers have been
345 // replaced. Remove the virtual registers and release all the transient data.
347 MRI->clearVirtRegs();
353 FunctionPass* llvm::createBasicRegisterAllocator()
355 return new RABasic();