blob: 5d2cc9937deda0d9953c566e9facd7d271858968 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy 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 RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000017#include "LiveIntervalUnion.h"
18#include "RegAllocBase.h"
19#include "Spiller.h"
20#include "VirtRegMap.h"
21#include "VirtRegRewriter.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Function.h"
24#include "llvm/PassAnalysisSupport.h"
25#include "llvm/CodeGen/CalcSpillWeights.h"
26#include "llvm/CodeGen/LiveIntervalAnalysis.h"
27#include "llvm/CodeGen/LiveStackAnalysis.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000029#include "llvm/CodeGen/MachineLoopInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/CodeGen/RegAllocRegistry.h"
33#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000038#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000039
40using namespace llvm;
41
42static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
43 createGreedyRegisterAllocator);
44
45namespace {
46class RAGreedy : public MachineFunctionPass, public RegAllocBase {
47 // context
48 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049 BitVector ReservedRegs;
50
51 // analyses
52 LiveStacks *LS;
53
54 // state
55 std::auto_ptr<Spiller> SpillerInstance;
56
57public:
58 RAGreedy();
59
60 /// Return the pass name.
61 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000062 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063 }
64
65 /// RAGreedy analysis usage.
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
67
68 virtual void releaseMemory();
69
70 virtual Spiller &spiller() { return *SpillerInstance; }
71
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +000072 virtual float getPriority(LiveInterval *LI);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000073
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000074 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
75 SmallVectorImpl<LiveInterval*> &SplitVRegs);
76
77 /// Perform register allocation.
78 virtual bool runOnMachineFunction(MachineFunction &mf);
79
80 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +000081
82private:
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +000083 bool checkUncachedInterference(LiveInterval&, unsigned);
84 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +000085 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
86 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +000087
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +000088 unsigned tryReassign(LiveInterval&, AllocationOrder&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +000089 unsigned trySplit(LiveInterval&, AllocationOrder&,
90 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000091};
92} // end anonymous namespace
93
94char RAGreedy::ID = 0;
95
96FunctionPass* llvm::createGreedyRegisterAllocator() {
97 return new RAGreedy();
98}
99
100RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
101 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
102 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
103 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
104 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
105 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
106 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
107 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
108 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
109 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
110}
111
112void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
114 AU.addRequired<AliasAnalysis>();
115 AU.addPreserved<AliasAnalysis>();
116 AU.addRequired<LiveIntervals>();
117 AU.addPreserved<SlotIndexes>();
118 if (StrongPHIElim)
119 AU.addRequiredID(StrongPHIEliminationID);
120 AU.addRequiredTransitive<RegisterCoalescer>();
121 AU.addRequired<CalculateSpillWeights>();
122 AU.addRequired<LiveStacks>();
123 AU.addPreserved<LiveStacks>();
124 AU.addRequiredID(MachineDominatorsID);
125 AU.addPreservedID(MachineDominatorsID);
126 AU.addRequired<MachineLoopInfo>();
127 AU.addPreserved<MachineLoopInfo>();
128 AU.addRequired<VirtRegMap>();
129 AU.addPreserved<VirtRegMap>();
130 MachineFunctionPass::getAnalysisUsage(AU);
131}
132
133void RAGreedy::releaseMemory() {
134 SpillerInstance.reset(0);
135 RegAllocBase::releaseMemory();
136}
137
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000138float RAGreedy::getPriority(LiveInterval *LI) {
139 float Priority = LI->weight;
140
141 // Prioritize hinted registers so they are allocated first.
142 std::pair<unsigned, unsigned> Hint;
143 if (Hint.first || Hint.second) {
144 // The hint can be target specific, a virtual register, or a physreg.
145 Priority *= 2;
146
147 // Prefer physreg hints above anything else.
148 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
149 Priority *= 2;
150 }
151 return Priority;
152}
153
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000154// Check interference without using the cache.
155bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
156 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000157 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
158 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000159 if (subQ.checkInterference())
160 return true;
161 }
162 return false;
163}
164
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000165/// getSingleInterference - Return the single interfering virtual register
166/// assigned to PhysReg. Return 0 if more than one virtual register is
167/// interfering.
168LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
169 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000170 // Check physreg and aliases.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000171 LiveInterval *Interference = 0;
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000172 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000173 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
174 if (Q.checkInterference()) {
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000175 if (Interference)
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000176 return 0;
177 Q.collectInterferingVRegs(1);
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000178 if (!Q.seenAllInterferences())
179 return 0;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000180 Interference = Q.interferingVRegs().front();
181 }
182 }
183 return Interference;
184}
185
Andrew Trickb853e6c2010-12-09 18:15:21 +0000186// Attempt to reassign this virtual register to a different physical register.
187//
188// FIXME: we are not yet caching these "second-level" interferences discovered
189// in the sub-queries. These interferences can change with each call to
190// selectOrSplit. However, we could implement a "may-interfere" cache that
191// could be conservatively dirtied when we reassign or split.
192//
193// FIXME: This may result in a lot of alias queries. We could summarize alias
194// live intervals in their parent register's live union, but it's messy.
195bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000196 unsigned WantedPhysReg) {
197 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
198 "Can only reassign virtual registers");
199 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
Andrew Trickb853e6c2010-12-09 18:15:21 +0000200 "inconsistent phys reg assigment");
201
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000202 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
203 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000204 // Don't reassign to a WantedPhysReg alias.
205 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000206 continue;
207
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000208 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000209 continue;
210
Andrew Trickb853e6c2010-12-09 18:15:21 +0000211 // Reassign the interfering virtual reg to this physical reg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000212 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
213 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
214 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
215 PhysReg2LiveUnion[OldAssign].extract(InterferingVReg);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000216 VRM->clearVirt(InterferingVReg.reg);
217 VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
218 PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
219
220 return true;
221 }
222 return false;
223}
224
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000225/// reassignInterferences - Reassign all interferences to different physical
226/// registers such that Virtreg can be assigned to PhysReg.
227/// Currently this only works with a single interference.
228/// @param VirtReg Currently unassigned virtual register.
229/// @param PhysReg Physical register to be cleared.
230/// @return True on success, false if nothing was changed.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000231bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000232 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
233 if (!InterferingVReg)
Andrew Trickb853e6c2010-12-09 18:15:21 +0000234 return false;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000235 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
236 return false;
237 return reassignVReg(*InterferingVReg, PhysReg);
238}
Andrew Trickb853e6c2010-12-09 18:15:21 +0000239
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000240/// tryReassign - Try to reassign interferences to different physregs.
241/// @param VirtReg Currently unassigned virtual register.
242/// @param Order Physregs to try.
243/// @return Physreg to assign VirtReg, or 0.
244unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order) {
245 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
246 Order.rewind();
247 while (unsigned PhysReg = Order.next())
248 if (reassignInterferences(VirtReg, PhysReg))
249 return PhysReg;
250 return 0;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000251}
252
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000253/// trySplit - Try to split VirtReg or one of its interferences, making it
254/// assignable.
255/// @return Physreg when VirtReg may be assigned and/or new SplitVRegs.
256unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
257 SmallVectorImpl<LiveInterval*>&SplitVRegs) {
258 NamedRegionTimer T("Splitter", TimerGroupName, TimePassesIsEnabled);
Matt Beaumont-Gay3ef9f3d2010-12-14 21:14:55 +0000259 DEBUG({
260 Order.rewind();
261 while (unsigned PhysReg = Order.next()) {
262 query(VirtReg, PhysReg).print(dbgs(), TRI);
263 for (const unsigned *AI = TRI->getAliasSet(PhysReg); *AI; ++AI)
264 query(VirtReg, *AI).print(dbgs(), TRI);
265 }
266 });
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000267 return 0;
268}
269
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000270unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
271 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
272 // Populate a list of physical register spill candidates.
Jakob Stoklund Olesen885b3282010-12-14 00:58:47 +0000273 SmallVector<unsigned, 8> PhysRegSpillCands;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000274
275 // Check for an available register in this class.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000276 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
277 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000278 // Check interference and as a side effect, intialize queries for this
279 // VirtReg and its aliases.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000280 unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
281 if (InterfReg == 0) {
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000282 // Found an available register.
283 return PhysReg;
284 }
Jakob Stoklund Olesen9b0c4f82010-12-08 23:51:35 +0000285 assert(!VirtReg.empty() && "Empty VirtReg has interference");
Andrew Trickb853e6c2010-12-09 18:15:21 +0000286 LiveInterval *InterferingVirtReg =
287 Queries[InterfReg].firstInterference().liveUnionPos().value();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000288
Andrew Trickb853e6c2010-12-09 18:15:21 +0000289 // The current VirtReg must either be spillable, or one of its interferences
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000290 // must have less spill weight.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000291 if (InterferingVirtReg->weight < VirtReg.weight )
292 PhysRegSpillCands.push_back(PhysReg);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000293 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000294
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000295 // Try to reassign interferences.
296 if (unsigned PhysReg = tryReassign(VirtReg, Order))
297 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000298
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000299 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000300 unsigned PhysReg = trySplit(VirtReg, Order, SplitVRegs);
301 if (PhysReg || !SplitVRegs.empty())
302 return PhysReg;
303
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000304 // Try to spill another interfering reg with less spill weight.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000305 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000306 //
Andrew Trickb853e6c2010-12-09 18:15:21 +0000307 // FIXME: do this in two steps: (1) check for unspillable interferences while
308 // accumulating spill weight; (2) spill the interferences with lowest
309 // aggregate spill weight.
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000310 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
311 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
312
313 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
314
315 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
316 "Interference after spill.");
317 // Tell the caller to allocate to this newly freed physical register.
318 return *PhysRegI;
319 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000320
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000321 // No other spill candidates were found, so spill the current VirtReg.
322 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
323 SmallVector<LiveInterval*, 1> pendingSpills;
324
325 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
326
327 // The live virtual register requesting allocation was spilled, so tell
328 // the caller not to allocate anything during this round.
329 return 0;
330}
331
332bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
333 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
334 << "********** Function: "
335 << ((Value*)mf.getFunction())->getName() << '\n');
336
337 MF = &mf;
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000338 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000339
340 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +0000341 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000342 allocatePhysRegs();
343 addMBBLiveIns(MF);
344
345 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000346 {
347 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
348 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
349 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
350 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000351
352 // The pass output is in VirtRegMap. Release all the transient data.
353 releaseMemory();
354
355 return true;
356}