blob: 8b74cc8b80065651deba540433ef29f3f28028b2 [file] [log] [blame]
Jakob Stoklund Olesenccc95812012-01-11 22:28:30 +00001//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
Andrew Trick14e8d712010-10-22 23:09:15 +00002//
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 Trick14e8d712010-10-22 23:09:15 +000018#include "RenderMachineFunction.h"
19#include "Spiller.h"
Andrew Tricke141a492010-11-08 18:02:08 +000020#include "VirtRegMap.h"
Andrew Trick8a83d542010-11-11 17:46:29 +000021#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000022#include "llvm/Function.h"
23#include "llvm/PassAnalysisSupport.h"
24#include "llvm/CodeGen/CalcSpillWeights.h"
Andrew Tricke141a492010-11-08 18:02:08 +000025#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000026#include "llvm/CodeGen/LiveRangeEdit.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000027#include "llvm/CodeGen/LiveStackAnalysis.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/MachineLoopInfo.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
32#include "llvm/CodeGen/Passes.h"
33#include "llvm/CodeGen/RegAllocRegistry.h"
Andrew Trick14e8d712010-10-22 23:09:15 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000036#include "llvm/Target/TargetRegisterInfo.h"
Andrew Tricke141a492010-11-08 18:02:08 +000037#include "llvm/Support/Debug.h"
Andrew Tricke141a492010-11-08 18:02:08 +000038#include "llvm/Support/raw_ostream.h"
Andrew Tricke16eecc2010-10-26 18:34:01 +000039
Jakob Stoklund Olesen953af2c2010-12-07 23:18:47 +000040#include <cstdlib>
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000041#include <queue>
Andrew Tricke16eecc2010-10-26 18:34:01 +000042
Andrew Trick14e8d712010-10-22 23:09:15 +000043using namespace llvm;
44
45static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
46 createBasicRegisterAllocator);
47
Benjamin Kramerc62feda2010-11-25 16:42:51 +000048namespace {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000049 struct CompSpillWeight {
50 bool operator()(LiveInterval *A, LiveInterval *B) const {
51 return A->weight < B->weight;
52 }
53 };
54}
55
56namespace {
Andrew Trick14e8d712010-10-22 23:09:15 +000057/// RABasic provides a minimal implementation of the basic register allocation
58/// algorithm. It prioritizes live virtual registers by spill weight and spills
59/// whenever a register is unavailable. This is not practical in production but
60/// provides a useful baseline both for measuring other allocators and comparing
61/// the speed of the basic algorithm against other styles of allocators.
62class RABasic : public MachineFunctionPass, public RegAllocBase
63{
64 // context
Andrew Trick18c57a82010-11-30 23:18:47 +000065 MachineFunction *MF;
Andrew Trick14e8d712010-10-22 23:09:15 +000066
67 // analyses
Andrew Trick18c57a82010-11-30 23:18:47 +000068 RenderMachineFunction *RMF;
Andrew Trick14e8d712010-10-22 23:09:15 +000069
70 // state
Andrew Trick18c57a82010-11-30 23:18:47 +000071 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000072 std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
73 CompSpillWeight> Queue;
Jakob Stoklund Olesena94e6352012-02-08 18:54:35 +000074
75 // Scratch space. Allocated here to avoid repeated malloc calls in
76 // selectOrSplit().
77 BitVector UsableRegs;
78
Andrew Trick14e8d712010-10-22 23:09:15 +000079public:
80 RABasic();
81
82 /// Return the pass name.
83 virtual const char* getPassName() const {
84 return "Basic Register Allocator";
85 }
86
87 /// RABasic analysis usage.
Andrew Trick18c57a82010-11-30 23:18:47 +000088 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Andrew Trick14e8d712010-10-22 23:09:15 +000089
90 virtual void releaseMemory();
91
Andrew Trick18c57a82010-11-30 23:18:47 +000092 virtual Spiller &spiller() { return *SpillerInstance; }
Andrew Trickf4baeaf2010-11-10 19:18:47 +000093
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000094 virtual float getPriority(LiveInterval *LI) { return LI->weight; }
95
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000096 virtual void enqueue(LiveInterval *LI) {
97 Queue.push(LI);
98 }
99
100 virtual LiveInterval *dequeue() {
101 if (Queue.empty())
102 return 0;
103 LiveInterval *LI = Queue.top();
104 Queue.pop();
105 return LI;
106 }
107
Andrew Trick18c57a82010-11-30 23:18:47 +0000108 virtual unsigned selectOrSplit(LiveInterval &VirtReg,
109 SmallVectorImpl<LiveInterval*> &SplitVRegs);
Andrew Trick14e8d712010-10-22 23:09:15 +0000110
111 /// Perform register allocation.
112 virtual bool runOnMachineFunction(MachineFunction &mf);
113
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000114 // Helper for spilling all live virtual registers currently unified under preg
115 // that interfere with the most recently queried lvr. Return true if spilling
116 // was successful, and append any new spilled/split intervals to splitLVRs.
117 bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
118 SmallVectorImpl<LiveInterval*> &SplitVRegs);
119
120 void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
121 SmallVectorImpl<LiveInterval*> &SplitVRegs);
122
Andrew Trick14e8d712010-10-22 23:09:15 +0000123 static char ID;
124};
125
126char RABasic::ID = 0;
127
128} // end anonymous namespace
129
Andrew Trick14e8d712010-10-22 23:09:15 +0000130RABasic::RABasic(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000131 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000132 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
133 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000134 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000135 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000136 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
137 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen964bc252010-11-03 20:39:26 +0000138 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
Andrew Trick14e8d712010-10-22 23:09:15 +0000139 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
140 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
141 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
142}
143
Andrew Trick18c57a82010-11-30 23:18:47 +0000144void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
145 AU.setPreservesCFG();
146 AU.addRequired<AliasAnalysis>();
147 AU.addPreserved<AliasAnalysis>();
148 AU.addRequired<LiveIntervals>();
149 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000150 AU.addRequired<LiveDebugVariables>();
151 AU.addPreserved<LiveDebugVariables>();
Andrew Trick18c57a82010-11-30 23:18:47 +0000152 AU.addRequired<CalculateSpillWeights>();
153 AU.addRequired<LiveStacks>();
154 AU.addPreserved<LiveStacks>();
155 AU.addRequiredID(MachineDominatorsID);
156 AU.addPreservedID(MachineDominatorsID);
157 AU.addRequired<MachineLoopInfo>();
158 AU.addPreserved<MachineLoopInfo>();
159 AU.addRequired<VirtRegMap>();
160 AU.addPreserved<VirtRegMap>();
161 DEBUG(AU.addRequired<RenderMachineFunction>());
162 MachineFunctionPass::getAnalysisUsage(AU);
Andrew Trick14e8d712010-10-22 23:09:15 +0000163}
164
165void RABasic::releaseMemory() {
Andrew Trick18c57a82010-11-30 23:18:47 +0000166 SpillerInstance.reset(0);
Andrew Trick14e8d712010-10-22 23:09:15 +0000167 RegAllocBase::releaseMemory();
168}
169
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000170// Helper for spillInterferences() that spills all interfering vregs currently
171// assigned to this physical register.
172void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
173 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
174 LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
175 assert(Q.seenAllInterferences() && "need collectInterferences()");
176 const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
177
178 for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
179 E = PendingSpills.end(); I != E; ++I) {
180 LiveInterval &SpilledVReg = **I;
181 DEBUG(dbgs() << "extracting from " <<
182 TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
183
184 // Deallocate the interfering vreg by removing it from the union.
185 // A LiveInterval instance may not be in a union during modification!
186 unassign(SpilledVReg, PhysReg);
187
188 // Spill the extracted interval.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +0000189 LiveRangeEdit LRE(&SpilledVReg, SplitVRegs, *MF, *LIS, VRM);
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000190 spiller().spill(LRE);
191 }
192 // After extracting segments, the query's results are invalid. But keep the
193 // contents valid until we're done accessing pendingSpills.
194 Q.clear();
195}
196
197// Spill or split all live virtual registers currently unified under PhysReg
198// that interfere with VirtReg. The newly spilled or split live intervals are
199// returned by appending them to SplitVRegs.
200bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
201 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
202 // Record each interference and determine if all are spillable before mutating
203 // either the union or live intervals.
204 unsigned NumInterferences = 0;
205 // Collect interferences assigned to any alias of the physical register.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000206 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
207 LiveIntervalUnion::Query &QAlias = query(VirtReg, *AI);
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000208 NumInterferences += QAlias.collectInterferingVRegs();
209 if (QAlias.seenUnspillableVReg()) {
210 return false;
211 }
212 }
213 DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
214 " interferences with " << VirtReg << "\n");
215 assert(NumInterferences > 0 && "expect interference");
216
217 // Spill each interfering vreg allocated to PhysReg or an alias.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000218 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI)
219 spillReg(VirtReg, *AI, SplitVRegs);
Jakob Stoklund Olesena8bd9a62012-01-11 22:52:14 +0000220 return true;
221}
222
Andrew Trick14e8d712010-10-22 23:09:15 +0000223// Driver for the register assignment and splitting heuristics.
224// Manages iteration over the LiveIntervalUnions.
Andrew Trick13bdbb02010-11-20 02:43:55 +0000225//
Andrew Trick18c57a82010-11-30 23:18:47 +0000226// This is a minimal implementation of register assignment and splitting that
227// spills whenever we run out of registers.
Andrew Trick14e8d712010-10-22 23:09:15 +0000228//
229// selectOrSplit can only be called once per live virtual register. We then do a
230// single interference test for each register the correct class until we find an
231// available register. So, the number of interference tests in the worst case is
232// |vregs| * |machineregs|. And since the number of interference tests is
Andrew Trick18c57a82010-11-30 23:18:47 +0000233// minimal, there is no value in caching them outside the scope of
234// selectOrSplit().
235unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
236 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
Jakob Stoklund Olesena94e6352012-02-08 18:54:35 +0000237 // Check for register mask interference. When live ranges cross calls, the
238 // set of usable registers is reduced to the callee-saved ones.
239 bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs);
240
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000241 // Populate a list of physical register spill candidates.
Andrew Trick18c57a82010-11-30 23:18:47 +0000242 SmallVector<unsigned, 8> PhysRegSpillCands;
Andrew Tricke141a492010-11-08 18:02:08 +0000243
Andrew Trick13bdbb02010-11-20 02:43:55 +0000244 // Check for an available register in this class.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +0000245 ArrayRef<unsigned> Order =
246 RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
247 for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
248 ++I) {
Andrew Trick18c57a82010-11-30 23:18:47 +0000249 unsigned PhysReg = *I;
Andrew Trick18c57a82010-11-30 23:18:47 +0000250
Jakob Stoklund Olesena94e6352012-02-08 18:54:35 +0000251 // If PhysReg is clobbered by a register mask, it isn't useful for
252 // allocation or spilling.
253 if (CrossRegMasks && !UsableRegs.test(PhysReg))
254 continue;
255
Andrew Trick18c57a82010-11-30 23:18:47 +0000256 // Check interference and as a side effect, intialize queries for this
257 // VirtReg and its aliases.
258 unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000259 if (interfReg == 0) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000260 // Found an available register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000261 return PhysReg;
Andrew Trick14e8d712010-10-22 23:09:15 +0000262 }
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +0000263 LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg);
264 IntfQ.collectInterferingVRegs(1);
265 LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front();
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000266
Andrew Trickb853e6c2010-12-09 18:15:21 +0000267 // The current VirtReg must either be spillable, or one of its interferences
Andrew Trick18c57a82010-11-30 23:18:47 +0000268 // must have less spill weight.
269 if (interferingVirtReg->weight < VirtReg.weight ) {
270 PhysRegSpillCands.push_back(PhysReg);
Andrew Tricke141a492010-11-08 18:02:08 +0000271 }
Andrew Trick14e8d712010-10-22 23:09:15 +0000272 }
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000273 // Try to spill another interfering reg with less spill weight.
Andrew Trick18c57a82010-11-30 23:18:47 +0000274 for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
275 PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000276
Andrew Trick18c57a82010-11-30 23:18:47 +0000277 if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
Andrew Trick13bdbb02010-11-20 02:43:55 +0000278
Jakob Stoklund Olesen2b38c512010-12-07 18:51:27 +0000279 assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
280 "Interference after spill.");
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000281 // Tell the caller to allocate to this newly freed physical register.
Andrew Trick18c57a82010-11-30 23:18:47 +0000282 return *PhysRegI;
Andrew Tricke141a492010-11-08 18:02:08 +0000283 }
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000284
Andrew Trick18c57a82010-11-30 23:18:47 +0000285 // No other spill candidates were found, so spill the current VirtReg.
286 DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +0000287 if (!VirtReg.isSpillable())
288 return ~0u;
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +0000289 LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +0000290 spiller().spill(LRE);
Andrew Trick13bdbb02010-11-20 02:43:55 +0000291
Andrew Trickf4baeaf2010-11-10 19:18:47 +0000292 // The live virtual register requesting allocation was spilled, so tell
293 // the caller not to allocate anything during this round.
294 return 0;
Andrew Tricke141a492010-11-08 18:02:08 +0000295}
Andrew Trick14e8d712010-10-22 23:09:15 +0000296
Andrew Trick14e8d712010-10-22 23:09:15 +0000297bool RABasic::runOnMachineFunction(MachineFunction &mf) {
298 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
299 << "********** Function: "
300 << ((Value*)mf.getFunction())->getName() << '\n');
301
Andrew Trick18c57a82010-11-30 23:18:47 +0000302 MF = &mf;
Andrew Trick18c57a82010-11-30 23:18:47 +0000303 DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
Andrew Trick8a83d542010-11-11 17:46:29 +0000304
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000305 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesen84275962011-03-31 23:02:17 +0000306 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Andrew Trick13bdbb02010-11-20 02:43:55 +0000307
Andrew Tricke16eecc2010-10-26 18:34:01 +0000308 allocatePhysRegs();
Andrew Trick14e8d712010-10-22 23:09:15 +0000309
Jakob Stoklund Olesen1b19dc12010-12-08 01:06:06 +0000310 addMBBLiveIns(MF);
Andrew Trick316df4b2010-11-20 02:57:05 +0000311
Andrew Trick14e8d712010-10-22 23:09:15 +0000312 // Diagnostic output before rewriting
Andrew Trick18c57a82010-11-30 23:18:47 +0000313 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
Andrew Trick14e8d712010-10-22 23:09:15 +0000314
315 // optional HTML output
Andrew Trick18c57a82010-11-30 23:18:47 +0000316 DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
Andrew Trick14e8d712010-10-22 23:09:15 +0000317
Andrew Trick071d1c02010-11-09 21:04:34 +0000318 // FIXME: Verification currently must run before VirtRegRewriter. We should
319 // make the rewriter a separate pass and override verifyAnalysis instead. When
320 // that happens, verification naturally falls under VerifyMachineCode.
321#ifndef NDEBUG
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000322 if (VerifyEnabled) {
Andrew Trick071d1c02010-11-09 21:04:34 +0000323 // Verify accuracy of LiveIntervals. The standard machine code verifier
324 // ensures that each LiveIntervals covers all uses of the virtual reg.
325
Andrew Trick18c57a82010-11-30 23:18:47 +0000326 // FIXME: MachineVerifier is badly broken when using the standard
327 // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
328 // inline spiller, some tests fail to verify because the coalescer does not
329 // always generate verifiable code.
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000330 MF->verify(this, "In RABasic::verify");
Andrew Trick13bdbb02010-11-20 02:43:55 +0000331
Andrew Trick071d1c02010-11-09 21:04:34 +0000332 // Verify that LiveIntervals are partitioned into unions and disjoint within
333 // the unions.
334 verify();
335 }
336#endif // !NDEBUG
Andrew Trick13bdbb02010-11-20 02:43:55 +0000337
Andrew Trick14e8d712010-10-22 23:09:15 +0000338 // Run rewriter
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000339 VRM->rewrite(LIS->getSlotIndexes());
Andrew Tricke16eecc2010-10-26 18:34:01 +0000340
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000341 // Write out new DBG_VALUE instructions.
342 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
343
Andrew Trick19273ae2012-02-21 04:51:23 +0000344 // All machine operands and other references to virtual registers have been
345 // replaced. Remove the virtual registers and release all the transient data.
346 VRM->clearAllVirt();
347 MRI->clearVirtRegs();
Andrew Tricke16eecc2010-10-26 18:34:01 +0000348 releaseMemory();
Andrew Trick13bdbb02010-11-20 02:43:55 +0000349
Andrew Trick14e8d712010-10-22 23:09:15 +0000350 return true;
351}
352
Andrew Trick13bdbb02010-11-20 02:43:55 +0000353FunctionPass* llvm::createBasicRegisterAllocator()
Andrew Trick14e8d712010-10-22 23:09:15 +0000354{
355 return new RABasic();
356}