blob: 32cb62223b5f87cdae2125c910794d79584fe3fc [file] [log] [blame]
Andrew Trick14e8d712010-10-22 23:09:15 +00001//===-- 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.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000016#include "LiveDebugVariables.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000017#include "LiveIntervalUnion.h"
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +000018#include "LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000019#include "RegAllocBase.h"
20#include "RenderMachineFunction.h"
21#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000022#include "VirtRegMap.h"
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000023#include "llvm/ADT/OwningPtr.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000025#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000026#include "llvm/Function.h"
27#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000029#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000030#include "llvm/CodeGen/LiveStackAnalysis.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineLoopInfo.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/Passes.h"
36#include "llvm/CodeGen/RegAllocRegistry.h"
37#include "llvm/CodeGen/RegisterCoalescer.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000040#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000041#ifndef NDEBUG
42#include "llvm/ADT/SparseBitVector.h"
43#endif
Andrew Tricke141a492010-11-08 18:02:08 +000044#include "llvm/Support/Debug.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000047#include "llvm/Support/Timer.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000048
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000049#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000050#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000051
Andrew Trick14e8d712010-10-22 23:09:15 +000052using namespace llvm;
53
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000054STATISTIC(NumAssigned , "Number of registers assigned");
55STATISTIC(NumUnassigned , "Number of registers unassigned");
56STATISTIC(NumNewQueued , "Number of new live ranges queued");
57
Andrew Trick14e8d712010-10-22 23:09:15 +000058static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
59 createBasicRegisterAllocator);
60
Andrew Trick071d1c02010-11-09 21:04:34 +000061// Temporary verification option until we can put verification inside
62// MachineVerifier.
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000063static cl::opt<bool, true>
64VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled),
65 cl::desc("Verify during register allocation"));
Andrew Trick071d1c02010-11-09 21:04:34 +000066
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000067const char *RegAllocBase::TimerGroupName = "Register Allocation";
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000068bool RegAllocBase::VerifyEnabled = false;
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000069
Benjamin Kramerc62feda2010-11-25 16:42:51 +000070namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000071 struct CompSpillWeight {
72 bool operator()(LiveInterval *A, LiveInterval *B) const {
73 return A->weight < B->weight;
74 }
75 };
76}
77
78namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000079/// RABasic provides a minimal implementation of the basic register allocation
80/// algorithm. It prioritizes live virtual registers by spill weight and spills
81/// whenever a register is unavailable. This is not practical in production but
82/// provides a useful baseline both for measuring other allocators and comparing
83/// the speed of the basic algorithm against other styles of allocators.
84class RABasic : public MachineFunctionPass, public RegAllocBase
85{
86 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000087 MachineFunction *MF;
Andrew Trick18c57a82010-11-30 23:18:47 +000088 BitVector ReservedRegs;
Andrew Trick14e8d712010-10-22 23:09:15 +000089
90 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000091 LiveStacks *LS;
92 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000093
94 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000095 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000096 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
97 CompSpillWeight> Queue;
Andrew Trick14e8d712010-10-22 23:09:15 +000098public:
99 RABasic();
100
101 /// Return the pass name.
102 virtual const char* getPassName() const {
103 return "Basic Register Allocator";
104 }
105
106 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000107 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +0000108
109 virtual void releaseMemory();
110
Andrew Trick18c57a82010-11-30 23:18:47 +0000111 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000112
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000113 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
114
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000115 virtual void enqueue(LiveInterval *LI) {
116 Queue.push(LI);
117 }
118
119 virtual LiveInterval *dequeue() {
120 if (Queue.empty())
121 return 0;
122 LiveInterval *LI = Queue.top();
123 Queue.pop();
124 return LI;
125 }
126
Andrew Trick18c57a82010-11-30 23:18:47 +0000127 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
128 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000129
130 /// Perform register allocation.
131 virtual bool runOnMachineFunction(MachineFunction &mf);
132
133 static char ID;
134};
135
136char RABasic::ID = 0;
137
138} // end anonymous namespace
139
Andrew Trick14e8d712010-10-22 23:09:15 +0000140RABasic::RABasic(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000141 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000142 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
143 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
144 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
145 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
146 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
147 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000148 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000149 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
150 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
151 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
152}
153
Andrew Trick18c57a82010-11-30 23:18:47 +0000154void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.setPreservesCFG();
156 AU.addRequired<AliasAnalysis>();
157 AU.addPreserved<AliasAnalysis>();
158 AU.addRequired<LiveIntervals>();
159 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000160 AU.addRequired<LiveDebugVariables>();
161 AU.addPreserved<LiveDebugVariables>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000162 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000163 AU.addRequiredID(StrongPHIEliminationID);
164 AU.addRequiredTransitive<RegisterCoalescer>();
165 AU.addRequired<CalculateSpillWeights>();
166 AU.addRequired<LiveStacks>();
167 AU.addPreserved<LiveStacks>();
168 AU.addRequiredID(MachineDominatorsID);
169 AU.addPreservedID(MachineDominatorsID);
170 AU.addRequired<MachineLoopInfo>();
171 AU.addPreserved<MachineLoopInfo>();
172 AU.addRequired<VirtRegMap>();
173 AU.addPreserved<VirtRegMap>();
174 DEBUG(AU.addRequired<RenderMachineFunction>());
175 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000176}
177
178void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000179 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000180 RegAllocBase::releaseMemory();
181}
182
Andrew Trick071d1c02010-11-09 21:04:34 +0000183#ifndef NDEBUG
184// Verify each LiveIntervalUnion.
185void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000186 LiveVirtRegBitSet VisitedVRegs;
187 OwningArrayPtr<LiveVirtRegBitSet>
188 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
189
Andrew Trick071d1c02010-11-09 21:04:34 +0000190 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000191 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
Jakob Stoklund Olesen4a84cce2010-12-14 18:53:47 +0000192 DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
Andrew Trick18c57a82010-11-30 23:18:47 +0000193 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
194 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000195 // Union + intersection test could be done efficiently in one pass, but
196 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000197 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
198 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000199 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000200
Andrew Trick071d1c02010-11-09 21:04:34 +0000201 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000202 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000203 liItr != liEnd; ++liItr) {
204 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000205 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000206 if (!VRM->hasPhys(reg)) continue; // spilled?
207 unsigned PhysReg = VRM->getPhys(reg);
208 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000209 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000210 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000211 llvm_unreachable("unallocated live vreg");
212 }
213 }
214 // FIXME: I'm not sure how to verify spilled intervals.
215}
216#endif //!NDEBUG
217
Andrew Trick14e8d712010-10-22 23:09:15 +0000218//===----------------------------------------------------------------------===//
219// RegAllocBase Implementation
220//===----------------------------------------------------------------------===//
221
222// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000223void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
224 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000225 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000226 Array =
227 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
228 for (unsigned r = 0; r != NRegs; ++r)
229 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000230}
231
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000232void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000233 NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000234 TRI = &vrm.getTargetRegInfo();
235 MRI = &vrm.getRegInfo();
Andrew Trick18c57a82010-11-30 23:18:47 +0000236 VRM = &vrm;
237 LIS = &lis;
Jakob Stoklund Olesen560ab9e2011-04-11 23:57:14 +0000238 const unsigned NumRegs = TRI->getNumRegs();
239 if (NumRegs != PhysReg2LiveUnion.numRegs()) {
240 PhysReg2LiveUnion.init(UnionAllocator, NumRegs);
241 // Cache an interferece query for each physical reg
242 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
243 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000244}
245
Andrew Trick18c57a82010-11-30 23:18:47 +0000246void RegAllocBase::LiveUnionArray::clear() {
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000247 if (!Array)
248 return;
249 for (unsigned r = 0; r != NumRegs; ++r)
250 Array[r].~LiveIntervalUnion();
251 free(Array);
Andrew Trick18c57a82010-11-30 23:18:47 +0000252 NumRegs = 0;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000253 Array = 0;
Andrew Trick14e8d712010-10-22 23:09:15 +0000254}
255
256void RegAllocBase::releaseMemory() {
Jakob Stoklund Olesen560ab9e2011-04-11 23:57:14 +0000257 for (unsigned r = 0, e = PhysReg2LiveUnion.numRegs(); r != e; ++r)
258 PhysReg2LiveUnion[r].clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000259}
260
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000261// Visit all the live registers. If they are already assigned to a physical
262// register, unify them with the corresponding LiveIntervalUnion, otherwise push
263// them on the priority queue for later assignment.
264void RegAllocBase::seedLiveRegs() {
Jakob Stoklund Olesenbd1926d2011-04-11 15:00:42 +0000265 NamedRegionTimer T("Seed Live Regs", TimerGroupName, TimePassesIsEnabled);
Andrew Trick18c57a82010-11-30 23:18:47 +0000266 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
267 unsigned RegNum = I->first;
268 LiveInterval &VirtReg = *I->second;
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000269 if (TargetRegisterInfo::isPhysicalRegister(RegNum))
Andrew Trick18c57a82010-11-30 23:18:47 +0000270 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000271 else
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000272 enqueue(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000273 }
274}
275
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000276void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000277 DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
278 << " to " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000279 assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
280 VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000281 MRI->setPhysRegUsed(PhysReg);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000282 PhysReg2LiveUnion[PhysReg].unify(VirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000283 ++NumAssigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000284}
285
286void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000287 DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
288 << " from " << PrintReg(PhysReg, TRI) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000289 assert(VRM->getPhys(VirtReg.reg) == PhysReg && "Inconsistent unassign");
290 PhysReg2LiveUnion[PhysReg].extract(VirtReg);
291 VRM->clearVirt(VirtReg.reg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000292 ++NumUnassigned;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000293}
294
Andrew Trick18c57a82010-11-30 23:18:47 +0000295// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000296// selectOrSplit implementation.
297void RegAllocBase::allocatePhysRegs() {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000298 seedLiveRegs();
Andrew Trick18c57a82010-11-30 23:18:47 +0000299
300 // Continue assigning vregs one at a time to available physical registers.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000301 while (LiveInterval *VirtReg = dequeue()) {
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000302 assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned");
303
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000304 // Unused registers can appear when the spiller coalesces snippets.
305 if (MRI->reg_nodbg_empty(VirtReg->reg)) {
306 DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
307 LIS->removeInterval(VirtReg->reg);
308 continue;
309 }
310
Jakob Stoklund Olesen29267332011-03-16 22:56:11 +0000311 // Invalidate all interference queries, live ranges could have changed.
312 ++UserTag;
313
Andrew Trick18c57a82010-11-30 23:18:47 +0000314 // selectOrSplit requests the allocator to return an available physical
315 // register if possible and populate a list of new live intervals that
316 // result from splitting.
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000317 DEBUG(dbgs() << "\nselectOrSplit "
318 << MRI->getRegClass(VirtReg->reg)->getName()
319 << ':' << *VirtReg << '\n');
Andrew Trick18c57a82010-11-30 23:18:47 +0000320 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
321 VirtRegVec SplitVRegs;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000322 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
Andrew Trick18c57a82010-11-30 23:18:47 +0000323
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000324 if (AvailablePhysReg == ~0u) {
325 // selectOrSplit failed to find a register!
326 std::string msg;
327 raw_string_ostream Msg(msg);
328 Msg << "Ran out of registers during register allocation!"
329 "\nCannot allocate: " << *VirtReg;
330 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(VirtReg->reg);
331 MachineInstr *MI = I.skipInstruction();) {
332 if (!MI->isInlineAsm())
333 continue;
334 Msg << "\nPlease check your inline asm statement for "
335 "invalid constraints:\n";
336 MI->print(Msg, &VRM->getMachineFunction().getTarget());
337 }
338 report_fatal_error(Msg.str());
339 }
340
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000341 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000342 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000343
Andrew Trick18c57a82010-11-30 23:18:47 +0000344 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
345 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000346 LiveInterval *SplitVirtReg = *I;
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000347 assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned");
348 if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) {
349 DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
350 LIS->removeInterval(SplitVirtReg->reg);
351 continue;
352 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000353 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
354 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000355 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000356 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000357 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000358 }
359 }
360}
361
Andrew Trick18c57a82010-11-30 23:18:47 +0000362// Check if this live virtual register interferes with a physical register. If
363// not, then check for interference on each register that aliases with the
364// physical register. Return the interfering register.
365unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
366 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000367 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000368 if (query(VirtReg, *AliasI).checkInterference())
369 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000370 return 0;
371}
372
Andrew Trick18c57a82010-11-30 23:18:47 +0000373// Helper for spillInteferences() that spills all interfering vregs currently
374// assigned to this physical register.
375void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
376 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
377 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
378 assert(Q.seenAllInterferences() && "need collectInterferences()");
379 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000380
Andrew Trick18c57a82010-11-30 23:18:47 +0000381 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
382 E = PendingSpills.end(); I != E; ++I) {
383 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000384 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000385 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000386
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000387 // Deallocate the interfering vreg by removing it from the union.
388 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000389 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000390
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000391 // Spill the extracted interval.
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000392 LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
393 spiller().spill(LRE);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000394 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000395 // After extracting segments, the query's results are invalid. But keep the
396 // contents valid until we're done accessing pendingSpills.
397 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000398}
399
Andrew Trick18c57a82010-11-30 23:18:47 +0000400// Spill or split all live virtual registers currently unified under PhysReg
401// that interfere with VirtReg. The newly spilled or split live intervals are
402// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000403bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000404RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
405 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000406 // Record each interference and determine if all are spillable before mutating
407 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000408 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000409 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000410 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000411 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
412 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000413 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000414 return false;
415 }
416 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000417 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
418 " interferences with " << VirtReg << "\n");
419 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000420
Andrew Trick18c57a82010-11-30 23:18:47 +0000421 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000422 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000423 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000424 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000425}
426
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000427// Add newly allocated physical registers to the MBB live in sets.
428void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000429 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000430 SlotIndexes *Indexes = LIS->getSlotIndexes();
431 if (MF->size() <= 1)
432 return;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000433
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000434 LiveIntervalUnion::SegmentIter SI;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000435 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
436 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
437 if (LiveUnion.empty())
438 continue;
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000439 MachineFunction::iterator MBB = llvm::next(MF->begin());
440 MachineFunction::iterator MFE = MF->end();
441 SlotIndex Start, Stop;
442 tie(Start, Stop) = Indexes->getMBBRange(MBB);
443 SI.setMap(LiveUnion.getMap());
444 SI.find(Start);
445 while (SI.valid()) {
446 if (SI.start() <= Start) {
447 if (!MBB->isLiveIn(PhysReg))
448 MBB->addLiveIn(PhysReg);
449 } else if (SI.start() > Stop)
Jakob Stoklund Olesendfaf0e22011-04-12 18:11:28 +0000450 MBB = Indexes->getMBBFromIndex(SI.start().getPrevIndex());
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000451 if (++MBB == MFE)
452 break;
453 tie(Start, Stop) = Indexes->getMBBRange(MBB);
454 SI.advanceTo(Start);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000455 }
456 }
457}
458
459
Andrew Trick14e8d712010-10-22 23:09:15 +0000460//===----------------------------------------------------------------------===//
461// RABasic Implementation
462//===----------------------------------------------------------------------===//
463
464// Driver for the register assignment and splitting heuristics.
465// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000466//
Andrew Trick18c57a82010-11-30 23:18:47 +0000467// This is a minimal implementation of register assignment and splitting that
468// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000469//
470// selectOrSplit can only be called once per live virtual register. We then do a
471// single interference test for each register the correct class until we find an
472// available register. So, the number of interference tests in the worst case is
473// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000474// minimal, there is no value in caching them outside the scope of
475// selectOrSplit().
476unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
477 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000478 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000479 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000480
Andrew Trick13bdbb02010-11-20 02:43:55 +0000481 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000482 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000483
Andrew Trick18c57a82010-11-30 23:18:47 +0000484 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
485 E = TRC->allocation_order_end(*MF);
486 I != E; ++I) {
487
488 unsigned PhysReg = *I;
489 if (ReservedRegs.test(PhysReg)) continue;
490
491 // Check interference and as a side effect, intialize queries for this
492 // VirtReg and its aliases.
493 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000494 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000495 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000496 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000497 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000498 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000499 Queries[interfReg].firstInterference().liveUnionPos().value();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000500
Andrew Trickb853e6c2010-12-09 18:15:21 +0000501 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000502 // must have less spill weight.
503 if (interferingVirtReg->weight < VirtReg.weight ) {
504 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000505 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000506 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000507 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000508 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
509 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000510
Andrew Trick18c57a82010-11-30 23:18:47 +0000511 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000512
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000513 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
514 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000515 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000516 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000517 }
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000518
Andrew Trick18c57a82010-11-30 23:18:47 +0000519 // No other spill candidates were found, so spill the current VirtReg.
520 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000521 if (!VirtReg.isSpillable())
522 return ~0u;
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000523 LiveRangeEdit LRE(VirtReg, SplitVRegs);
524 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000525
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000526 // The live virtual register requesting allocation was spilled, so tell
527 // the caller not to allocate anything during this round.
528 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000529}
Andrew Trick14e8d712010-10-22 23:09:15 +0000530
Andrew Trick14e8d712010-10-22 23:09:15 +0000531bool RABasic::runOnMachineFunction(MachineFunction &mf) {
532 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
533 << "********** Function: "
534 << ((Value*)mf.getFunction())->getName() << '\n');
535
Andrew Trick18c57a82010-11-30 23:18:47 +0000536 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000537 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000538
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000539 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Andrew Trick14e8d712010-10-22 23:09:15 +0000540
Andrew Trick18c57a82010-11-30 23:18:47 +0000541 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000542
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000543 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000544
Andrew Tricke16eecc2010-10-26 18:34:01 +0000545 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000546
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000547 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000548
Andrew Trick14e8d712010-10-22 23:09:15 +0000549 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000550 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000551
552 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000553 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000554
Andrew Trick071d1c02010-11-09 21:04:34 +0000555 // FIXME: Verification currently must run before VirtRegRewriter. We should
556 // make the rewriter a separate pass and override verifyAnalysis instead. When
557 // that happens, verification naturally falls under VerifyMachineCode.
558#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000559 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000560 // Verify accuracy of LiveIntervals. The standard machine code verifier
561 // ensures that each LiveIntervals covers all uses of the virtual reg.
562
Andrew Trick18c57a82010-11-30 23:18:47 +0000563 // FIXME: MachineVerifier is badly broken when using the standard
564 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
565 // inline spiller, some tests fail to verify because the coalescer does not
566 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000567 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000568
Andrew Trick071d1c02010-11-09 21:04:34 +0000569 // Verify that LiveIntervals are partitioned into unions and disjoint within
570 // the unions.
571 verify();
572 }
573#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000574
Andrew Trick14e8d712010-10-22 23:09:15 +0000575 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000576 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000577
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000578 // Write out new DBG_VALUE instructions.
579 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
580
Andrew Tricke16eecc2010-10-26 18:34:01 +0000581 // The pass output is in VirtRegMap. Release all the transient data.
582 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000583
Andrew Trick14e8d712010-10-22 23:09:15 +0000584 return true;
585}
586
Andrew Trick13bdbb02010-11-20 02:43:55 +0000587FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000588{
589 return new RABasic();
590}