1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RAGreedy function pass for register allocation in
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "AllocationOrder.h"
17 #include "LiveIntervalUnion.h"
18 #include "RegAllocBase.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"
42 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
43 createGreedyRegisterAllocator);
46 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
49 BitVector ReservedRegs;
55 std::auto_ptr<Spiller> SpillerInstance;
60 /// Return the pass name.
61 virtual const char* getPassName() const {
62 return "Greedy Register Allocator";
65 /// RAGreedy analysis usage.
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
68 virtual void releaseMemory();
70 virtual Spiller &spiller() { return *SpillerInstance; }
72 virtual float getPriority(LiveInterval *LI);
74 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
75 SmallVectorImpl<LiveInterval*> &SplitVRegs);
77 /// Perform register allocation.
78 virtual bool runOnMachineFunction(MachineFunction &mf);
83 bool checkUncachedInterference(LiveInterval &, unsigned);
84 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
85 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
87 } // end anonymous namespace
89 char RAGreedy::ID = 0;
91 FunctionPass* llvm::createGreedyRegisterAllocator() {
92 return new RAGreedy();
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());
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>();
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);
128 void RAGreedy::releaseMemory() {
129 SpillerInstance.reset(0);
130 RegAllocBase::releaseMemory();
133 float RAGreedy::getPriority(LiveInterval *LI) {
134 float Priority = LI->weight;
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.
142 // Prefer physreg hints above anything else.
143 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
149 // Check interference without using the cache.
150 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
152 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[PhysReg]);
153 if (subQ.checkInterference())
155 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
156 subQ.init(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
157 if (subQ.checkInterference())
163 // Attempt to reassign this virtual register to a different physical register.
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.
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");
177 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
178 while (unsigned PhysReg = Order.next()) {
179 if (PhysReg == OldPhysReg)
182 if (checkUncachedInterference(InterferingVReg, PhysReg))
185 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
186 TRI->getName(OldPhysReg) << " to " << TRI->getName(PhysReg) << '\n');
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);
199 // Collect all virtual regs currently assigned to PhysReg that interfere with
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);
207 // Limit the interference search to one interference.
208 Q.collectInterferingVRegs(1);
209 assert(Q.interferingVRegs().size() == 1 &&
210 "expected at least one interference");
212 // Do not attempt reassignment unless we find only a single interference.
213 if (!Q.seenAllInterferences())
216 // Don't allow any interferences on aliases.
217 for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
218 if (query(VirtReg, *AliasI).checkInterference())
222 return reassignVReg(*Q.interferingVRegs()[0], PhysReg);
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;
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.
240 assert(!VirtReg.empty() && "Empty VirtReg has interference");
241 LiveInterval *InterferingVirtReg =
242 Queries[InterfReg].firstInterference().liveUnionPos().value();
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);
251 PhysRegSpillCands.push_back(PhysReg);
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.
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.
266 PhysRegSpillCands.insert(PhysRegSpillCands.end(), ReassignCands.begin(),
267 ReassignCands.end());
269 // Try to spill another interfering reg with less spill weight.
270 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
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) {
278 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
280 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
281 "Interference after spill.");
282 // Tell the caller to allocate to this newly freed physical register.
286 // No other spill candidates were found, so spill the current VirtReg.
287 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
288 SmallVector<LiveInterval*, 1> pendingSpills;
290 spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
292 // The live virtual register requesting allocation was spilled, so tell
293 // the caller not to allocate anything during this round.
297 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
298 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
299 << "********** Function: "
300 << ((Value*)mf.getFunction())->getName() << '\n');
303 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
305 ReservedRegs = TRI->getReservedRegs(*MF);
306 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
312 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
313 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
314 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
317 // The pass output is in VirtRegMap. Release all the transient data.