blob: 5496d69fd3df1aa381faee2de9cdb4a3b9911100 [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 Olesen5f2316a2011-06-03 20:34:53 +000016#include "RegAllocBase.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000017#include "LiveDebugVariables.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000018#include "LiveIntervalUnion.h"
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +000019#include "LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000020#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"
Andrew Trick14e8d712010-10-22 23:09:15 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000039#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick071d1c02010-11-09 21:04:34 +000040#ifndef NDEBUG
41#include "llvm/ADT/SparseBitVector.h"
42#endif
Andrew Tricke141a492010-11-08 18:02:08 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000046#include "llvm/Support/Timer.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000047
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000048#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000049#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000050
Andrew Trick14e8d712010-10-22 23:09:15 +000051using namespace llvm;
52
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumAssigned , "Number of registers assigned");
54STATISTIC(NumUnassigned , "Number of registers unassigned");
55STATISTIC(NumNewQueued , "Number of new live ranges queued");
56
Andrew Trick14e8d712010-10-22 23:09:15 +000057static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
58 createBasicRegisterAllocator);
59
Andrew Trick071d1c02010-11-09 21:04:34 +000060// Temporary verification option until we can put verification inside
61// MachineVerifier.
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000062static cl::opt<bool, true>
63VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled),
64 cl::desc("Verify during register allocation"));
Andrew Trick071d1c02010-11-09 21:04:34 +000065
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000066const char *RegAllocBase::TimerGroupName = "Register Allocation";
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +000067bool RegAllocBase::VerifyEnabled = false;
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000068
Benjamin Kramerc62feda2010-11-25 16:42:51 +000069namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000070 struct CompSpillWeight {
71 bool operator()(LiveInterval *A, LiveInterval *B) const {
72 return A->weight < B->weight;
73 }
74 };
75}
76
77namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000078/// RABasic provides a minimal implementation of the basic register allocation
79/// algorithm. It prioritizes live virtual registers by spill weight and spills
80/// whenever a register is unavailable. This is not practical in production but
81/// provides a useful baseline both for measuring other allocators and comparing
82/// the speed of the basic algorithm against other styles of allocators.
83class RABasic : public MachineFunctionPass, public RegAllocBase
84{
85 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000086 MachineFunction *MF;
Andrew Trick14e8d712010-10-22 23:09:15 +000087
88 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000089 LiveStacks *LS;
90 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000091
92 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000093 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000094 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
95 CompSpillWeight> Queue;
Andrew Trick14e8d712010-10-22 23:09:15 +000096public:
97 RABasic();
98
99 /// Return the pass name.
100 virtual const char* getPassName() const {
101 return "Basic Register Allocator";
102 }
103
104 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000105 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +0000106
107 virtual void releaseMemory();
108
Andrew Trick18c57a82010-11-30 23:18:47 +0000109 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000110
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000111 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
112
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000113 virtual void enqueue(LiveInterval *LI) {
114 Queue.push(LI);
115 }
116
117 virtual LiveInterval *dequeue() {
118 if (Queue.empty())
119 return 0;
120 LiveInterval *LI = Queue.top();
121 Queue.pop();
122 return LI;
123 }
124
Andrew Trick18c57a82010-11-30 23:18:47 +0000125 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
126 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000127
128 /// Perform register allocation.
129 virtual bool runOnMachineFunction(MachineFunction &mf);
130
131 static char ID;
132};
133
134char RABasic::ID = 0;
135
136} // end anonymous namespace
137
Andrew Trick14e8d712010-10-22 23:09:15 +0000138RABasic::RABasic(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000139 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000140 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
141 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
142 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000143 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000144 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
145 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000146 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000147 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
148 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
149 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
150}
151
Andrew Trick18c57a82010-11-30 23:18:47 +0000152void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.setPreservesCFG();
154 AU.addRequired<AliasAnalysis>();
155 AU.addPreserved<AliasAnalysis>();
156 AU.addRequired<LiveIntervals>();
157 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000158 AU.addRequired<LiveDebugVariables>();
159 AU.addPreserved<LiveDebugVariables>();
Andrew Trick14e8d712010-10-22 23:09:15 +0000160 if (StrongPHIElim)
Andrew Trick18c57a82010-11-30 23:18:47 +0000161 AU.addRequiredID(StrongPHIEliminationID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000162 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
Andrew Trick18c57a82010-11-30 23:18:47 +0000163 AU.addRequired<CalculateSpillWeights>();
164 AU.addRequired<LiveStacks>();
165 AU.addPreserved<LiveStacks>();
166 AU.addRequiredID(MachineDominatorsID);
167 AU.addPreservedID(MachineDominatorsID);
168 AU.addRequired<MachineLoopInfo>();
169 AU.addPreserved<MachineLoopInfo>();
170 AU.addRequired<VirtRegMap>();
171 AU.addPreserved<VirtRegMap>();
172 DEBUG(AU.addRequired<RenderMachineFunction>());
173 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000174}
175
176void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000177 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000178 RegAllocBase::releaseMemory();
179}
180
Andrew Trick071d1c02010-11-09 21:04:34 +0000181#ifndef NDEBUG
182// Verify each LiveIntervalUnion.
183void RegAllocBase::verify() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000184 LiveVirtRegBitSet VisitedVRegs;
185 OwningArrayPtr<LiveVirtRegBitSet>
186 unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
187
Andrew Trick071d1c02010-11-09 21:04:34 +0000188 // Verify disjoint unions.
Andrew Trick18c57a82010-11-30 23:18:47 +0000189 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
Jakob Stoklund Olesen4a84cce2010-12-14 18:53:47 +0000190 DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
Andrew Trick18c57a82010-11-30 23:18:47 +0000191 LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
192 PhysReg2LiveUnion[PhysReg].verify(VRegs);
Andrew Trick071d1c02010-11-09 21:04:34 +0000193 // Union + intersection test could be done efficiently in one pass, but
194 // don't add a method to SparseBitVector unless we really need it.
Andrew Trick18c57a82010-11-30 23:18:47 +0000195 assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
196 VisitedVRegs |= VRegs;
Andrew Trick071d1c02010-11-09 21:04:34 +0000197 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000198
Andrew Trick071d1c02010-11-09 21:04:34 +0000199 // Verify vreg coverage.
Andrew Trick18c57a82010-11-30 23:18:47 +0000200 for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
Andrew Trick071d1c02010-11-09 21:04:34 +0000201 liItr != liEnd; ++liItr) {
202 unsigned reg = liItr->first;
Andrew Trick071d1c02010-11-09 21:04:34 +0000203 if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
Andrew Trick18c57a82010-11-30 23:18:47 +0000204 if (!VRM->hasPhys(reg)) continue; // spilled?
205 unsigned PhysReg = VRM->getPhys(reg);
206 if (!unionVRegs[PhysReg].test(reg)) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000207 dbgs() << "LiveVirtReg " << reg << " not in union " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000208 TRI->getName(PhysReg) << "\n";
Andrew Trick071d1c02010-11-09 21:04:34 +0000209 llvm_unreachable("unallocated live vreg");
210 }
211 }
212 // FIXME: I'm not sure how to verify spilled intervals.
213}
214#endif //!NDEBUG
215
Andrew Trick14e8d712010-10-22 23:09:15 +0000216//===----------------------------------------------------------------------===//
217// RegAllocBase Implementation
218//===----------------------------------------------------------------------===//
219
220// Instantiate a LiveIntervalUnion for each physical register.
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000221void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
222 unsigned NRegs) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000223 NumRegs = NRegs;
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +0000224 Array =
225 static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
226 for (unsigned r = 0; r != NRegs; ++r)
227 new(Array + r) LiveIntervalUnion(r, allocator);
Andrew Trick14e8d712010-10-22 23:09:15 +0000228}
229
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000230void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000231 NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000232 TRI = &vrm.getTargetRegInfo();
233 MRI = &vrm.getRegInfo();
Andrew Trick18c57a82010-11-30 23:18:47 +0000234 VRM = &vrm;
235 LIS = &lis;
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +0000236 RegClassInfo.runOnMachineFunction(vrm.getMachineFunction());
237
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.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +0000312 invalidateVirtRegs();
Jakob Stoklund Olesen29267332011-03-16 22:56:11 +0000313
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!
Jakob Stoklund Olesen9d812a22011-07-02 07:17:37 +0000326 const char *Msg = "ran out of registers during register allocation";
327 // Probably caused by an inline asm.
328 MachineInstr *MI;
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000329 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(VirtReg->reg);
Jakob Stoklund Olesen9d812a22011-07-02 07:17:37 +0000330 (MI = I.skipInstruction());)
331 if (MI->isInlineAsm())
332 break;
333 if (MI)
334 MI->emitError(Msg);
335 else
336 report_fatal_error(Msg);
337 // Keep going after reporting the error.
338 VRM->assignVirt2Phys(VirtReg->reg,
339 RegClassInfo.getOrder(MRI->getRegClass(VirtReg->reg)).front());
340 continue;
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000341 }
342
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000343 if (AvailablePhysReg)
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000344 assign(*VirtReg, AvailablePhysReg);
Jakob Stoklund Olesenfebb0bd2011-02-18 00:32:47 +0000345
Andrew Trick18c57a82010-11-30 23:18:47 +0000346 for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
347 I != E; ++I) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000348 LiveInterval *SplitVirtReg = *I;
Jakob Stoklund Olesen0b501512011-03-23 04:32:51 +0000349 assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned");
350 if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) {
351 DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n');
352 LIS->removeInterval(SplitVirtReg->reg);
353 continue;
354 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000355 DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
356 assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
Andrew Tricke141a492010-11-08 18:02:08 +0000357 "expect split value in virtual register");
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000358 enqueue(SplitVirtReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000359 ++NumNewQueued;
Andrew Tricke16eecc2010-10-26 18:34:01 +0000360 }
361 }
362}
363
Andrew Trick18c57a82010-11-30 23:18:47 +0000364// Check if this live virtual register interferes with a physical register. If
365// not, then check for interference on each register that aliases with the
366// physical register. Return the interfering register.
367unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
368 unsigned PhysReg) {
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000369 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000370 if (query(VirtReg, *AliasI).checkInterference())
371 return *AliasI;
Andrew Tricke141a492010-11-08 18:02:08 +0000372 return 0;
373}
374
Andrew Trick18c57a82010-11-30 23:18:47 +0000375// Helper for spillInteferences() that spills all interfering vregs currently
376// assigned to this physical register.
377void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
378 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
379 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
380 assert(Q.seenAllInterferences() && "need collectInterferences()");
381 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000382
Andrew Trick18c57a82010-11-30 23:18:47 +0000383 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
384 E = PendingSpills.end(); I != E; ++I) {
385 LiveInterval &SpilledVReg = **I;
Andrew Trick8a83d542010-11-11 17:46:29 +0000386 DEBUG(dbgs() << "extracting from " <<
Andrew Trick18c57a82010-11-30 23:18:47 +0000387 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
Andrew Trick13bdbb02010-11-20 02:43:55 +0000388
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000389 // Deallocate the interfering vreg by removing it from the union.
390 // A LiveInterval instance may not be in a union during modification!
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000391 unassign(SpilledVReg, PhysReg);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000392
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000393 // Spill the extracted interval.
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000394 LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
395 spiller().spill(LRE);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000396 }
Andrew Trick8a83d542010-11-11 17:46:29 +0000397 // After extracting segments, the query's results are invalid. But keep the
398 // contents valid until we're done accessing pendingSpills.
399 Q.clear();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000400}
401
Andrew Trick18c57a82010-11-30 23:18:47 +0000402// Spill or split all live virtual registers currently unified under PhysReg
403// that interfere with VirtReg. The newly spilled or split live intervals are
404// returned by appending them to SplitVRegs.
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000405bool
Andrew Trick18c57a82010-11-30 23:18:47 +0000406RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
407 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000408 // Record each interference and determine if all are spillable before mutating
409 // either the union or live intervals.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000410 unsigned NumInterferences = 0;
Andrew Trick8a83d542010-11-11 17:46:29 +0000411 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000412 for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000413 LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
414 NumInterferences += QAlias.collectInterferingVRegs();
Andrew Trick8a83d542010-11-11 17:46:29 +0000415 if (QAlias.seenUnspillableVReg()) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000416 return false;
417 }
418 }
Andrew Trick18c57a82010-11-30 23:18:47 +0000419 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
420 " interferences with " << VirtReg << "\n");
421 assert(NumInterferences > 0 && "expect interference");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000422
Andrew Trick18c57a82010-11-30 23:18:47 +0000423 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen16999da2010-12-14 23:10:48 +0000424 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
Andrew Trick18c57a82010-11-30 23:18:47 +0000425 spillReg(VirtReg, *AliasI, SplitVRegs);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000426 return true;
Andrew Trick14e8d712010-10-22 23:09:15 +0000427}
428
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000429// Add newly allocated physical registers to the MBB live in sets.
430void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000431 NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000432 SlotIndexes *Indexes = LIS->getSlotIndexes();
433 if (MF->size() <= 1)
434 return;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000435
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000436 LiveIntervalUnion::SegmentIter SI;
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000437 for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
438 LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
439 if (LiveUnion.empty())
440 continue;
Jakob Stoklund Olesen3b925272011-07-26 23:12:08 +0000441 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " live-in:");
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000442 MachineFunction::iterator MBB = llvm::next(MF->begin());
443 MachineFunction::iterator MFE = MF->end();
444 SlotIndex Start, Stop;
445 tie(Start, Stop) = Indexes->getMBBRange(MBB);
446 SI.setMap(LiveUnion.getMap());
447 SI.find(Start);
448 while (SI.valid()) {
449 if (SI.start() <= Start) {
450 if (!MBB->isLiveIn(PhysReg))
451 MBB->addLiveIn(PhysReg);
Jakob Stoklund Olesen3b925272011-07-26 23:12:08 +0000452 DEBUG(dbgs() << "\tBB#" << MBB->getNumber() << ':'
453 << PrintReg(SI.value()->reg, TRI));
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000454 } else if (SI.start() > Stop)
Jakob Stoklund Olesendfaf0e22011-04-12 18:11:28 +0000455 MBB = Indexes->getMBBFromIndex(SI.start().getPrevIndex());
Jakob Stoklund Olesen6d73c7d2011-04-11 20:01:41 +0000456 if (++MBB == MFE)
457 break;
458 tie(Start, Stop) = Indexes->getMBBRange(MBB);
459 SI.advanceTo(Start);
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000460 }
Jakob Stoklund Olesen3b925272011-07-26 23:12:08 +0000461 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000462 }
463}
464
465
Andrew Trick14e8d712010-10-22 23:09:15 +0000466//===----------------------------------------------------------------------===//
467// RABasic Implementation
468//===----------------------------------------------------------------------===//
469
470// Driver for the register assignment and splitting heuristics.
471// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000472//
Andrew Trick18c57a82010-11-30 23:18:47 +0000473// This is a minimal implementation of register assignment and splitting that
474// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000475//
476// selectOrSplit can only be called once per live virtual register. We then do a
477// single interference test for each register the correct class until we find an
478// available register. So, the number of interference tests in the worst case is
479// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000480// minimal, there is no value in caching them outside the scope of
481// selectOrSplit().
482unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
483 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000484 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000485 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000486
Andrew Trick13bdbb02010-11-20 02:43:55 +0000487 // Check for an available register in this class.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +0000488 ArrayRef<unsigned> Order =
489 RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
490 for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
491 ++I) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000492 unsigned PhysReg = *I;
Andrew Trick18c57a82010-11-30 23:18:47 +0000493
494 // Check interference and as a side effect, intialize queries for this
495 // VirtReg and its aliases.
496 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000497 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000498 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000499 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000500 }
Jakob Stoklund Olesen98985f92011-08-11 21:00:42 +0000501 Queries[interfReg].collectInterferingVRegs(1);
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000502 LiveInterval *interferingVirtReg =
Jakob Stoklund Olesen98985f92011-08-11 21:00:42 +0000503 Queries[interfReg].interferingVRegs().front();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000504
Andrew Trickb853e6c2010-12-09 18:15:21 +0000505 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000506 // must have less spill weight.
507 if (interferingVirtReg->weight < VirtReg.weight ) {
508 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000509 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000510 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000511 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000512 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
513 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000514
Andrew Trick18c57a82010-11-30 23:18:47 +0000515 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000516
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000517 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
518 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000519 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000520 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000521 }
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000522
Andrew Trick18c57a82010-11-30 23:18:47 +0000523 // No other spill candidates were found, so spill the current VirtReg.
524 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000525 if (!VirtReg.isSpillable())
526 return ~0u;
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000527 LiveRangeEdit LRE(VirtReg, SplitVRegs);
528 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000529
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000530 // The live virtual register requesting allocation was spilled, so tell
531 // the caller not to allocate anything during this round.
532 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000533}
Andrew Trick14e8d712010-10-22 23:09:15 +0000534
Andrew Trick14e8d712010-10-22 23:09:15 +0000535bool RABasic::runOnMachineFunction(MachineFunction &mf) {
536 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
537 << "********** Function: "
538 << ((Value*)mf.getFunction())->getName() << '\n');
539
Andrew Trick18c57a82010-11-30 23:18:47 +0000540 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000541 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000542
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000543 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000544 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000545
Andrew Tricke16eecc2010-10-26 18:34:01 +0000546 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000547
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000548 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000549
Andrew Trick14e8d712010-10-22 23:09:15 +0000550 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000551 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000552
553 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000554 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000555
Andrew Trick071d1c02010-11-09 21:04:34 +0000556 // FIXME: Verification currently must run before VirtRegRewriter. We should
557 // make the rewriter a separate pass and override verifyAnalysis instead. When
558 // that happens, verification naturally falls under VerifyMachineCode.
559#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000560 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000561 // Verify accuracy of LiveIntervals. The standard machine code verifier
562 // ensures that each LiveIntervals covers all uses of the virtual reg.
563
Andrew Trick18c57a82010-11-30 23:18:47 +0000564 // FIXME: MachineVerifier is badly broken when using the standard
565 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
566 // inline spiller, some tests fail to verify because the coalescer does not
567 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000568 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000569
Andrew Trick071d1c02010-11-09 21:04:34 +0000570 // Verify that LiveIntervals are partitioned into unions and disjoint within
571 // the unions.
572 verify();
573 }
574#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000575
Andrew Trick14e8d712010-10-22 23:09:15 +0000576 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000577 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000578
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000579 // Write out new DBG_VALUE instructions.
580 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
581
Andrew Tricke16eecc2010-10-26 18:34:01 +0000582 // The pass output is in VirtRegMap. Release all the transient data.
583 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000584
Andrew Trick14e8d712010-10-22 23:09:15 +0000585 return true;
586}
587
Andrew Trick13bdbb02010-11-20 02:43:55 +0000588FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000589{
590 return new RABasic();
591}