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