01946c0db4a1c12c3c3574b3ee2520255af93def
[oota-llvm.git] / lib / CodeGen / RegAllocGreedy.cpp
1 //===-- 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"
16 #include "AllocationOrder.h"
17 #include "LiveIntervalUnion.h"
18 #include "RegAllocBase.h"
19 #include "Spiller.h"
20 #include "VirtRegMap.h"
21 #include "VirtRegRewriter.h"
22 #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"
29 #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"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 using namespace llvm;
40
41 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
42                                        createGreedyRegisterAllocator);
43
44 namespace {
45 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
46   // context
47   MachineFunction *MF;
48   BitVector ReservedRegs;
49
50   // analyses
51   LiveStacks *LS;
52
53   // state
54   std::auto_ptr<Spiller> SpillerInstance;
55
56 public:
57   RAGreedy();
58
59   /// Return the pass name.
60   virtual const char* getPassName() const {
61     return "Basic Register Allocator";
62   }
63
64   /// RAGreedy analysis usage.
65   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
66
67   virtual void releaseMemory();
68
69   virtual Spiller &spiller() { return *SpillerInstance; }
70
71   virtual float getPriority(LiveInterval *LI);
72
73   virtual unsigned selectOrSplit(LiveInterval &VirtReg,
74                                  SmallVectorImpl<LiveInterval*> &SplitVRegs);
75
76   /// Perform register allocation.
77   virtual bool runOnMachineFunction(MachineFunction &mf);
78
79   static char ID;
80
81 private:
82   bool checkUncachedInterference(LiveInterval &, unsigned);
83   bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
84   bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
85 };
86 } // end anonymous namespace
87
88 char RAGreedy::ID = 0;
89
90 FunctionPass* llvm::createGreedyRegisterAllocator() {
91   return new RAGreedy();
92 }
93
94 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
95   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
97   initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
98   initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
99   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
100   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
101   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
102   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
103   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
104 }
105
106 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
107   AU.setPreservesCFG();
108   AU.addRequired<AliasAnalysis>();
109   AU.addPreserved<AliasAnalysis>();
110   AU.addRequired<LiveIntervals>();
111   AU.addPreserved<SlotIndexes>();
112   if (StrongPHIElim)
113     AU.addRequiredID(StrongPHIEliminationID);
114   AU.addRequiredTransitive<RegisterCoalescer>();
115   AU.addRequired<CalculateSpillWeights>();
116   AU.addRequired<LiveStacks>();
117   AU.addPreserved<LiveStacks>();
118   AU.addRequiredID(MachineDominatorsID);
119   AU.addPreservedID(MachineDominatorsID);
120   AU.addRequired<MachineLoopInfo>();
121   AU.addPreserved<MachineLoopInfo>();
122   AU.addRequired<VirtRegMap>();
123   AU.addPreserved<VirtRegMap>();
124   MachineFunctionPass::getAnalysisUsage(AU);
125 }
126
127 void RAGreedy::releaseMemory() {
128   SpillerInstance.reset(0);
129   RegAllocBase::releaseMemory();
130 }
131
132 float RAGreedy::getPriority(LiveInterval *LI) {
133   float Priority = LI->weight;
134
135   // Prioritize hinted registers so they are allocated first.
136   std::pair<unsigned, unsigned> Hint;
137   if (Hint.first || Hint.second) {
138     // The hint can be target specific, a virtual register, or a physreg.
139     Priority *= 2;
140
141     // Prefer physreg hints above anything else.
142     if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
143       Priority *= 2;
144   }
145   return Priority;
146 }
147
148 // Check interference without using the cache.
149 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
150                                          unsigned PhysReg) {
151   LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
152   if (subQ.checkInterference())
153       return true;
154   for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
155     subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
156     if (subQ.checkInterference())
157       return true;
158   }
159   return false;
160 }
161
162 // Attempt to reassign this virtual register to a different physical register.
163 //
164 // FIXME: we are not yet caching these "second-level" interferences discovered
165 // in the sub-queries. These interferences can change with each call to
166 // selectOrSplit. However, we could implement a "may-interfere" cache that
167 // could be conservatively dirtied when we reassign or split.
168 //
169 // FIXME: This may result in a lot of alias queries. We could summarize alias
170 // live intervals in their parent register's live union, but it's messy.
171 bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
172                             unsigned OldPhysReg) {
173   assert(OldPhysReg == VRM->getPhys(InterferingVReg.reg) &&
174          "inconsistent phys reg assigment");
175
176   AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
177   while (unsigned PhysReg = Order.next()) {
178     if (PhysReg == OldPhysReg)
179       continue;
180
181     if (checkUncachedInterference(InterferingVReg, PhysReg))
182       continue;
183
184     DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
185           TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
186
187     // Reassign the interfering virtual reg to this physical reg.
188     PhysReg2LiveUnion[OldPhysReg].extract(InterferingVReg);
189     VRM->clearVirt(InterferingVReg.reg);
190     VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
191     PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
192
193     return true;
194   }
195   return false;
196 }
197
198 // Collect all virtual regs currently assigned to PhysReg that interfere with
199 // VirtReg.
200 //
201 // Currently, for simplicity, we only attempt to reassign a single interference
202 // within the same register class.
203 bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
204   LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
205
206   // Limit the interference search to one interference.
207   Q.collectInterferingVRegs(1);
208   assert(Q.interferingVRegs().size() == 1 &&
209          "expected at least one interference");
210
211   // Do not attempt reassignment unless we find only a single interference.
212   if (!Q.seenAllInterferences())
213     return false;
214
215   // Don't allow any interferences on aliases.
216   for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
217     if (query(VirtReg, *AliasI).checkInterference())
218       return false;
219   }
220
221   return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
222 }
223
224 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
225                                 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
226   // Populate a list of physical register spill candidates.
227   SmallVector<unsigned, 8> PhysRegSpillCands, ReassignCands;
228
229   // Check for an available register in this class.
230   AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
231   while (unsigned PhysReg = Order.next()) {
232     // Check interference and as a side effect, intialize queries for this
233     // VirtReg and its aliases.
234     unsigned InterfReg = checkPhysRegInterference(VirtReg, PhysReg);
235     if (InterfReg == 0) {
236       // Found an available register.
237       return PhysReg;
238     }
239     assert(!VirtReg.empty() && "Empty VirtReg has interference");
240     LiveInterval *InterferingVirtReg =
241       Queries[InterfReg].firstInterference().liveUnionPos().value();
242
243     // The current VirtReg must either be spillable, or one of its interferences
244     // must have less spill weight.
245     if (InterferingVirtReg->weight < VirtReg.weight ) {
246       // For simplicity, only consider reassigning registers in the same class.
247       if (InterfReg == PhysReg)
248         ReassignCands.push_back(PhysReg);
249       else
250         PhysRegSpillCands.push_back(PhysReg);
251     }
252   }
253
254   // Try to reassign interfering physical register. Priority among
255   // PhysRegSpillCands does not matter yet, because the reassigned virtual
256   // registers will still be assigned to physical registers.
257   for (SmallVectorImpl<unsigned>::iterator PhysRegI = ReassignCands.begin(),
258          PhysRegE = ReassignCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
259     if (reassignInterferences(VirtReg, *PhysRegI))
260       // Reassignment successfull. The caller may allocate now to this PhysReg.
261       return *PhysRegI;
262   }
263
264   PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
265                            ReassignCands.end());
266
267   // Try to spill another interfering reg with less spill weight.
268   //
269   // FIXME: do this in two steps: (1) check for unspillable interferences while
270   // accumulating spill weight; (2) spill the interferences with lowest
271   // aggregate spill weight.
272   for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
273          PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
274
275     if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
276
277     assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
278            "Interference after spill.");
279     // Tell the caller to allocate to this newly freed physical register.
280     return *PhysRegI;
281   }
282
283   // No other spill candidates were found, so spill the current VirtReg.
284   DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
285   SmallVector<LiveInterval*, 1> pendingSpills;
286
287   spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
288
289   // The live virtual register requesting allocation was spilled, so tell
290   // the caller not to allocate anything during this round.
291   return 0;
292 }
293
294 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
295   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
296                << "********** Function: "
297                << ((Value*)mf.getFunction())->getName() << '\n');
298
299   MF = &mf;
300   RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
301
302   ReservedRegs = TRI->getReservedRegs(*MF);
303   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
304   allocatePhysRegs();
305   addMBBLiveIns(MF);
306
307   // Run rewriter
308   std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
309   rewriter->runOnMachineFunction(*MF, *VRM, LIS);
310
311   // The pass output is in VirtRegMap. Release all the transient data.
312   releaseMemory();
313
314   return true;
315 }