blob: 545a6bd5bc7e3ded4d8951db1842dcd44e3cd473 [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"
Andrew Tricke16eecc2010-10-26 18:34:01 +000016#include "LiveIntervalUnion.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000017#include "RegAllocBase.h"
18#include "RenderMachineFunction.h"
19#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000020#include "VirtRegMap.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000021#include "VirtRegRewriter.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000022#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000023#include "llvm/Function.h"
24#include "llvm/PassAnalysisSupport.h"
25#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000026#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000027#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/CodeGen/RegisterCoalescer.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000037#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000038#ifndef NDEBUG
39#include "llvm/ADT/SparseBitVector.h"
40#endif
Andrew Tricke141a492010-11-08 18:02:08 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000044
45#include <vector>
46#include <queue>
47
Andrew Trick14e8d712010-10-22 23:09:15 +000048using namespace llvm;
49
50static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
51 createBasicRegisterAllocator);
52
Andrew Trick071d1c02010-11-09 21:04:34 +000053// Temporary verification option until we can put verification inside
54// MachineVerifier.
55static cl::opt<bool>
56VerifyRegAlloc("verify-regalloc",
57 cl::desc("Verify live intervals before renaming"));
58
Benjamin Kramerc62feda2010-11-25 16:42:51 +000059namespace {
60
Andrew Trick071d1c02010-11-09 21:04:34 +000061class PhysicalRegisterDescription : public AbstractRegisterDescription {
Andrew Trick18c57a82010-11-30 23:18:47 +000062 const TargetRegisterInfo *TRI;
Andrew Trick071d1c02010-11-09 21:04:34 +000063public:
Andrew Trick18c57a82010-11-30 23:18:47 +000064 PhysicalRegisterDescription(const TargetRegisterInfo *T): TRI(T) {}
65 virtual const char *getName(unsigned Reg) const { return TRI->getName(Reg); }
Andrew Trick071d1c02010-11-09 21:04:34 +000066};
67
Andrew Trick14e8d712010-10-22 23:09:15 +000068/// RABasic provides a minimal implementation of the basic register allocation
69/// algorithm. It prioritizes live virtual registers by spill weight and spills
70/// whenever a register is unavailable. This is not practical in production but
71/// provides a useful baseline both for measuring other allocators and comparing
72/// the speed of the basic algorithm against other styles of allocators.
73class RABasic : public MachineFunctionPass, public RegAllocBase
74{
75 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000076 MachineFunction *MF;
77 const TargetMachine *TM;
78 MachineRegisterInfo *MRI;
79
80 BitVector ReservedRegs;
Andrew Trick14e8d712010-10-22 23:09:15 +000081
82 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000083 LiveStacks *LS;
84 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000085
86 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000087 std::auto_ptr<Spiller> SpillerInstance;
Andrew Trick14e8d712010-10-22 23:09:15 +000088
89public:
90 RABasic();
91
92 /// Return the pass name.
93 virtual const char* getPassName() const {
94 return "Basic Register Allocator";
95 }
96
97 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +000098 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +000099
100 virtual void releaseMemory();
101
Andrew Trick18c57a82010-11-30 23:18:47 +0000102 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000103
Andrew Trick18c57a82010-11-30 23:18:47 +0000104 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
105 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000106
107 /// Perform register allocation.
108 virtual bool runOnMachineFunction(MachineFunction &mf);
109
110 static char ID;
Andrew Trick316df4b2010-11-20 02:57:05 +0000111
112private:
113 void addMBBLiveIns();
Andrew Trick14e8d712010-10-22 23:09:15 +0000114};
115
116char RABasic::ID = 0;
117
118} // end anonymous namespace
119
Andrew Trick14e8d712010-10-22 23:09:15 +0000120RABasic::RABasic(): MachineFunctionPass(ID) {
121 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
122 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
123 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
124 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
125 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
126 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000127 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000128 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
129 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
130 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
131}
132
Andrew Trick18c57a82010-11-30 23:18:47 +0000133void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
134 AU.setPreservesCFG();
135 AU.addRequired<AliasAnalysis>();
136 AU.addPreserved<AliasAnalysis>();
137 AU.addRequired<LiveIntervals>();
138 AU.addPreserved<SlotIndexes>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000139 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000140 AU.addRequiredID(StrongPHIEliminationID);
141 AU.addRequiredTransitive<RegisterCoalescer>();
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);
Andrew Trick14e8d712010-10-22 23:09:15 +0000153}
154
155void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000156 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000157 RegAllocBase::releaseMemory();
158}
159
Andrew Trick071d1c02010-11-09 21:04:34 +0000160#ifndef NDEBUG
161// Verify each LiveIntervalUnion.
162void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000163 LiveVirtRegBitSet VisitedVRegs;
164 OwningArrayPtr<LiveVirtRegBitSet>
165 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
166
Andrew Trick071d1c02010-11-09 21:04:34 +0000167 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000168 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
169 DEBUG(PhysicalRegisterDescription PRD(TRI);
170 PhysReg2LiveUnion[PhysReg].dump(&PRD));
171 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
172 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000173 // Union + intersection test could be done efficiently in one pass, but
174 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000175 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
176 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000177 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000178
Andrew Trick071d1c02010-11-09 21:04:34 +0000179 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000180 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000181 liItr != liEnd; ++liItr) {
182 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000183 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000184 if (!VRM->hasPhys(reg)) continue; // spilled?
185 unsigned PhysReg = VRM->getPhys(reg);
186 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000187 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000188 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000189 llvm_unreachable("unallocated live vreg");
190 }
191 }
192 // FIXME: I'm not sure how to verify spilled intervals.
193}
194#endif //!NDEBUG
195
Andrew Trick14e8d712010-10-22 23:09:15 +0000196//===----------------------------------------------------------------------===//
197// RegAllocBase Implementation
198//===----------------------------------------------------------------------===//
199
200// Instantiate a LiveIntervalUnion for each physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000201void RegAllocBase::LiveUnionArray::init(unsigned NRegs) {
202 Array.reset(new LiveIntervalUnion[NRegs]);
203 NumRegs = NRegs;
204 for (unsigned RegNum = 0; RegNum < NRegs; ++RegNum) {
205 Array[RegNum].init(RegNum);
Andrew Trick14e8d712010-10-22 23:09:15 +0000206 }
207}
208
209void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
210 LiveIntervals &lis) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000211 TRI = &tri;
212 VRM = &vrm;
213 LIS = &lis;
214 PhysReg2LiveUnion.init(TRI->getNumRegs());
Andrew Tricke141a492010-11-08 18:02:08 +0000215 // Cache an interferece query for each physical reg
Andrew Trick18c57a82010-11-30 23:18:47 +0000216 Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
Andrew Trick14e8d712010-10-22 23:09:15 +0000217}
218
Andrew Trick18c57a82010-11-30 23:18:47 +0000219void RegAllocBase::LiveUnionArray::clear() {
220 NumRegs = 0;
221 Array.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000222}
223
224void RegAllocBase::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000225 PhysReg2LiveUnion.clear();
Andrew Trick14e8d712010-10-22 23:09:15 +0000226}
227
Andrew Tricke16eecc2010-10-26 18:34:01 +0000228namespace llvm {
229/// This class defines a queue of live virtual registers prioritized by spill
230/// weight. The heaviest vreg is popped first.
231///
232/// Currently, this is trivial wrapper that gives us an opaque type in the
233/// header, but we may later give it a virtual interface for register allocators
234/// to override the priority queue comparator.
235class LiveVirtRegQueue {
236 typedef std::priority_queue
Andrew Trick18c57a82010-11-30 23:18:47 +0000237 <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority>
238 PriorityQ;
239 PriorityQ PQ;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000240
Andrew Tricke16eecc2010-10-26 18:34:01 +0000241public:
242 // Is the queue empty?
Andrew Trick18c57a82010-11-30 23:18:47 +0000243 bool empty() { return PQ.empty(); }
Andrew Trick13bdbb02010-11-20 02:43:55 +0000244
Andrew Tricke16eecc2010-10-26 18:34:01 +0000245 // Get the highest priority lvr (top + pop)
246 LiveInterval *get() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000247 LiveInterval *VirtReg = PQ.top();
248 PQ.pop();
249 return VirtReg;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000250 }
251 // Add this lvr to the queue
Andrew Trick18c57a82010-11-30 23:18:47 +0000252 void push(LiveInterval *VirtReg) {
253 PQ.push(VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000254 }
255};
256} // end namespace llvm
257
258// Visit all the live virtual registers. If they are already assigned to a
259// physical register, unify them with the corresponding LiveIntervalUnion,
260// otherwise push them on the priority queue for later assignment.
Andrew Trick18c57a82010-11-30 23:18:47 +0000261void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &VirtRegQ) {
262 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
263 unsigned RegNum = I->first;
264 LiveInterval &VirtReg = *I->second;
265 if (TargetRegisterInfo::isPhysicalRegister(RegNum)) {
266 PhysReg2LiveUnion[RegNum].unify(VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000267 }
268 else {
Andrew Trick18c57a82010-11-30 23:18:47 +0000269 VirtRegQ.push(&VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000270 }
271 }
272}
273
Andrew Trick18c57a82010-11-30 23:18:47 +0000274// Top-level driver to manage the queue of unassigned VirtRegs and call the
Andrew Tricke16eecc2010-10-26 18:34:01 +0000275// selectOrSplit implementation.
276void RegAllocBase::allocatePhysRegs() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000277
278 // Push each vreg onto a queue or "precolor" by adding it to a physreg union.
279 LiveVirtRegQueue VirtRegQ;
280 seedLiveVirtRegs(VirtRegQ);
281
282 // Continue assigning vregs one at a time to available physical registers.
283 while (!VirtRegQ.empty()) {
284 // Pop the highest priority vreg.
285 LiveInterval *VirtReg = VirtRegQ.get();
286
287 // selectOrSplit requests the allocator to return an available physical
288 // register if possible and populate a list of new live intervals that
289 // result from splitting.
290 typedef SmallVector<LiveInterval*, 4> VirtRegVec;
291 VirtRegVec SplitVRegs;
292 unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
293
294 if (AvailablePhysReg) {
295 DEBUG(dbgs() << "allocating: " << TRI->getName(AvailablePhysReg) <<
296 " " << *VirtReg << '\n');
297 assert(!VRM->hasPhys(VirtReg->reg) && "duplicate vreg in union");
298 VRM->assignVirt2Phys(VirtReg->reg, AvailablePhysReg);
299 PhysReg2LiveUnion[AvailablePhysReg].unify(*VirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000300 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000301 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
302 I != E; ++I) {
303 LiveInterval* SplitVirtReg = *I;
304 if (SplitVirtReg->empty()) continue;
305 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
306 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000307 "expect split value in virtual register");
Andrew Trick18c57a82010-11-30 23:18:47 +0000308 VirtRegQ.push(SplitVirtReg);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000309 }
310 }
311}
312
Andrew Trick18c57a82010-11-30 23:18:47 +0000313// Check if this live virtual register interferes with a physical register. If
314// not, then check for interference on each register that aliases with the
315// physical register. Return the interfering register.
316unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
317 unsigned PhysReg) {
318 if (query(VirtReg, PhysReg).checkInterference())
319 return PhysReg;
320 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
321 if (query(VirtReg, *AliasI).checkInterference())
322 return *AliasI;
Andrew Trick14e8d712010-10-22 23:09:15 +0000323 }
Andrew Tricke141a492010-11-08 18:02:08 +0000324 return 0;
325}
326
Andrew Trick18c57a82010-11-30 23:18:47 +0000327// Helper for spillInteferences() that spills all interfering vregs currently
328// assigned to this physical register.
329void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
330 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
331 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
332 assert(Q.seenAllInterferences() && "need collectInterferences()");
333 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000334
Andrew Trick18c57a82010-11-30 23:18:47 +0000335 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
336 E = PendingSpills.end(); I != E; ++I) {
337 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000338 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000339 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000340
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000341 // Deallocate the interfering vreg by removing it from the union.
342 // A LiveInterval instance may not be in a union during modification!
Andrew Trick18c57a82010-11-30 23:18:47 +0000343 PhysReg2LiveUnion[PhysReg].extract(SpilledVReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000344
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000345 // Clear the vreg assignment.
Andrew Trick18c57a82010-11-30 23:18:47 +0000346 VRM->clearVirt(SpilledVReg.reg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000347
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000348 // Spill the extracted interval.
Andrew Trick18c57a82010-11-30 23:18:47 +0000349 spiller().spill(&SpilledVReg, SplitVRegs, PendingSpills);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000350 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000351 // After extracting segments, the query's results are invalid. But keep the
352 // contents valid until we're done accessing pendingSpills.
353 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000354}
355
Andrew Trick18c57a82010-11-30 23:18:47 +0000356// Spill or split all live virtual registers currently unified under PhysReg
357// that interfere with VirtReg. The newly spilled or split live intervals are
358// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000359bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000360RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
361 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000362 // Record each interference and determine if all are spillable before mutating
363 // either the union or live intervals.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000364
Andrew Trick8a83d542010-11-11 17:46:29 +0000365 // Collect interferences assigned to the requested physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000366 LiveIntervalUnion::Query &QPreg = query(VirtReg, PhysReg);
367 unsigned NumInterferences = QPreg.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000368 if (QPreg.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000369 return false;
Andrew Tricke141a492010-11-08 18:02:08 +0000370 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000371 // Collect interferences assigned to any alias of the physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000372 for (const unsigned *asI = TRI->getAliasSet(PhysReg); *asI; ++asI) {
373 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
374 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000375 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000376 return false;
377 }
378 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000379 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
380 " interferences with " << VirtReg << "\n");
381 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000382
Andrew Trick18c57a82010-11-30 23:18:47 +0000383 // Spill each interfering vreg allocated to PhysReg or an alias.
384 spillReg(VirtReg, PhysReg, SplitVRegs);
385 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI)
386 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000387 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000388}
389
390//===----------------------------------------------------------------------===//
391// RABasic Implementation
392//===----------------------------------------------------------------------===//
393
394// Driver for the register assignment and splitting heuristics.
395// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000396//
Andrew Trick18c57a82010-11-30 23:18:47 +0000397// This is a minimal implementation of register assignment and splitting that
398// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000399//
400// selectOrSplit can only be called once per live virtual register. We then do a
401// single interference test for each register the correct class until we find an
402// available register. So, the number of interference tests in the worst case is
403// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000404// minimal, there is no value in caching them outside the scope of
405// selectOrSplit().
406unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
407 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000408 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000409 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000410
Andrew Trick13bdbb02010-11-20 02:43:55 +0000411 // Check for an available register in this class.
Andrew Trick18c57a82010-11-30 23:18:47 +0000412 const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
413 DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000414
Andrew Trick18c57a82010-11-30 23:18:47 +0000415 for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
416 E = TRC->allocation_order_end(*MF);
417 I != E; ++I) {
418
419 unsigned PhysReg = *I;
420 if (ReservedRegs.test(PhysReg)) continue;
421
422 // Check interference and as a side effect, intialize queries for this
423 // VirtReg and its aliases.
424 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000425 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000426 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000427 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000428 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000429 LiveInterval *interferingVirtReg =
Andrew Trick18c57a82010-11-30 23:18:47 +0000430 Queries[interfReg].firstInterference().liveUnionPos()->VirtReg;
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000431
Andrew Trick18c57a82010-11-30 23:18:47 +0000432 // The current VirtReg must either spillable, or one of its interferences
433 // must have less spill weight.
434 if (interferingVirtReg->weight < VirtReg.weight ) {
435 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000436 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000437 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000438 // Try to spill another interfering reg with less spill weight.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000439 //
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000440 // FIXME: RAGreedy will sort this list by spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000441 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
442 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000443
Andrew Trick18c57a82010-11-30 23:18:47 +0000444 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000445
Andrew Trick18c57a82010-11-30 23:18:47 +0000446 unsigned InterferingReg = checkPhysRegInterference(VirtReg, *PhysRegI);
447 if (InterferingReg != 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000448 const LiveSegment &seg =
Andrew Trick18c57a82010-11-30 23:18:47 +0000449 *Queries[InterferingReg].firstInterference().liveUnionPos();
450
451 dbgs() << "spilling cannot free " << TRI->getName(*PhysRegI) <<
452 " for " << VirtReg.reg << " with interference " << *seg.VirtReg << "\n";
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000453 llvm_unreachable("Interference after spill.");
454 }
455 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000456 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000457 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000458 // No other spill candidates were found, so spill the current VirtReg.
459 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000460 SmallVector<LiveInterval*, 1> pendingSpills;
Andrew Trick18c57a82010-11-30 23:18:47 +0000461
462 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000463
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000464 // The live virtual register requesting allocation was spilled, so tell
465 // the caller not to allocate anything during this round.
466 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000467}
Andrew Trick14e8d712010-10-22 23:09:15 +0000468
Andrew Trick18c57a82010-11-30 23:18:47 +0000469// Add newly allocated physical registers to the MBB live in sets.
Andrew Trick316df4b2010-11-20 02:57:05 +0000470void RABasic::addMBBLiveIns() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000471 typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
472 MBBVec liveInMBBs;
473 MachineBasicBlock &entryMBB = *MF->begin();
Andrew Trick316df4b2010-11-20 02:57:05 +0000474
Andrew Trick18c57a82010-11-30 23:18:47 +0000475 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
476 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
477
478 for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(),
479 SegEnd = LiveUnion.end();
480 SI != SegEnd; ++SI) {
481
Andrew Trick316df4b2010-11-20 02:57:05 +0000482 // Find the set of basic blocks which this range is live into...
Andrew Trick18c57a82010-11-30 23:18:47 +0000483 liveInMBBs.clear();
484 if (!LIS->findLiveInMBBs(SI->Start, SI->End, liveInMBBs)) continue;
485
486 // And add the physreg for this interval to their live-in sets.
487 for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
488 I != E; ++I) {
489 MachineBasicBlock *MBB = *I;
490 if (MBB == &entryMBB) continue;
491 if (MBB->isLiveIn(PhysReg)) continue;
492 MBB->addLiveIn(PhysReg);
Andrew Trick316df4b2010-11-20 02:57:05 +0000493 }
494 }
495 }
496}
497
Andrew Trick14e8d712010-10-22 23:09:15 +0000498bool RABasic::runOnMachineFunction(MachineFunction &mf) {
499 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
500 << "********** Function: "
501 << ((Value*)mf.getFunction())->getName() << '\n');
502
Andrew Trick18c57a82010-11-30 23:18:47 +0000503 MF = &mf;
504 TM = &mf.getTarget();
505 MRI = &mf.getRegInfo();
Andrew Trick14e8d712010-10-22 23:09:15 +0000506
Andrew Trick18c57a82010-11-30 23:18:47 +0000507 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000508
Andrew Trick18c57a82010-11-30 23:18:47 +0000509 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Andrew Trick8a83d542010-11-11 17:46:29 +0000510 RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
Andrew Trick14e8d712010-10-22 23:09:15 +0000511 getAnalysis<LiveIntervals>());
512
Andrew Trick18c57a82010-11-30 23:18:47 +0000513 ReservedRegs = TRI->getReservedRegs(*MF);
Andrew Trick8a83d542010-11-11 17:46:29 +0000514
Andrew Trick18c57a82010-11-30 23:18:47 +0000515 SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000516
Andrew Tricke16eecc2010-10-26 18:34:01 +0000517 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000518
Andrew Trick316df4b2010-11-20 02:57:05 +0000519 addMBBLiveIns();
520
Andrew Trick14e8d712010-10-22 23:09:15 +0000521 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000522 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000523
524 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000525 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000526
Andrew Trick071d1c02010-11-09 21:04:34 +0000527 // FIXME: Verification currently must run before VirtRegRewriter. We should
528 // make the rewriter a separate pass and override verifyAnalysis instead. When
529 // that happens, verification naturally falls under VerifyMachineCode.
530#ifndef NDEBUG
531 if (VerifyRegAlloc) {
532 // Verify accuracy of LiveIntervals. The standard machine code verifier
533 // ensures that each LiveIntervals covers all uses of the virtual reg.
534
Andrew Trick18c57a82010-11-30 23:18:47 +0000535 // FIXME: MachineVerifier is badly broken when using the standard
536 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
537 // inline spiller, some tests fail to verify because the coalescer does not
538 // always generate verifiable code.
539 MF->verify(this);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000540
Andrew Trick071d1c02010-11-09 21:04:34 +0000541 // Verify that LiveIntervals are partitioned into unions and disjoint within
542 // the unions.
543 verify();
544 }
545#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000546
Andrew Trick14e8d712010-10-22 23:09:15 +0000547 // Run rewriter
548 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
Andrew Trick18c57a82010-11-30 23:18:47 +0000549 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
Andrew Tricke16eecc2010-10-26 18:34:01 +0000550
551 // The pass output is in VirtRegMap. Release all the transient data.
552 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000553
Andrew Trick14e8d712010-10-22 23:09:15 +0000554 return true;
555}
556
Andrew Trick13bdbb02010-11-20 02:43:55 +0000557FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000558{
559 return new RABasic();
560}