RegAllocBasic.cpp revision 239462
1234353Sdim//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===//
2218885Sdim//
3218885Sdim//                     The LLVM Compiler Infrastructure
4218885Sdim//
5218885Sdim// This file is distributed under the University of Illinois Open Source
6218885Sdim// License. See LICENSE.TXT for details.
7218885Sdim//
8218885Sdim//===----------------------------------------------------------------------===//
9218885Sdim//
10218885Sdim// This file defines the RABasic function pass, which provides a minimal
11218885Sdim// implementation of the basic register allocator.
12218885Sdim//
13218885Sdim//===----------------------------------------------------------------------===//
14218885Sdim
15218885Sdim#define DEBUG_TYPE "regalloc"
16239462Sdim#include "AllocationOrder.h"
17223017Sdim#include "RegAllocBase.h"
18221345Sdim#include "LiveDebugVariables.h"
19218885Sdim#include "Spiller.h"
20218885Sdim#include "VirtRegMap.h"
21239462Sdim#include "LiveRegMatrix.h"
22218885Sdim#include "llvm/Analysis/AliasAnalysis.h"
23218885Sdim#include "llvm/Function.h"
24218885Sdim#include "llvm/PassAnalysisSupport.h"
25218885Sdim#include "llvm/CodeGen/CalcSpillWeights.h"
26218885Sdim#include "llvm/CodeGen/LiveIntervalAnalysis.h"
27234353Sdim#include "llvm/CodeGen/LiveRangeEdit.h"
28218885Sdim#include "llvm/CodeGen/LiveStackAnalysis.h"
29218885Sdim#include "llvm/CodeGen/MachineFunctionPass.h"
30218885Sdim#include "llvm/CodeGen/MachineInstr.h"
31218885Sdim#include "llvm/CodeGen/MachineLoopInfo.h"
32218885Sdim#include "llvm/CodeGen/MachineRegisterInfo.h"
33218885Sdim#include "llvm/CodeGen/Passes.h"
34218885Sdim#include "llvm/CodeGen/RegAllocRegistry.h"
35218885Sdim#include "llvm/Target/TargetMachine.h"
36218885Sdim#include "llvm/Target/TargetOptions.h"
37218885Sdim#include "llvm/Target/TargetRegisterInfo.h"
38218885Sdim#include "llvm/Support/Debug.h"
39218885Sdim#include "llvm/Support/raw_ostream.h"
40218885Sdim
41218885Sdim#include <cstdlib>
42219077Sdim#include <queue>
43218885Sdim
44218885Sdimusing namespace llvm;
45218885Sdim
46218885Sdimstatic RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
47218885Sdim                                      createBasicRegisterAllocator);
48218885Sdim
49218885Sdimnamespace {
50219077Sdim  struct CompSpillWeight {
51219077Sdim    bool operator()(LiveInterval *A, LiveInterval *B) const {
52219077Sdim      return A->weight < B->weight;
53219077Sdim    }
54219077Sdim  };
55219077Sdim}
56219077Sdim
57219077Sdimnamespace {
58218885Sdim/// RABasic provides a minimal implementation of the basic register allocation
59218885Sdim/// algorithm. It prioritizes live virtual registers by spill weight and spills
60218885Sdim/// whenever a register is unavailable. This is not practical in production but
61218885Sdim/// provides a useful baseline both for measuring other allocators and comparing
62218885Sdim/// the speed of the basic algorithm against other styles of allocators.
63218885Sdimclass RABasic : public MachineFunctionPass, public RegAllocBase
64218885Sdim{
65218885Sdim  // context
66218885Sdim  MachineFunction *MF;
67218885Sdim
68218885Sdim  // state
69218885Sdim  std::auto_ptr<Spiller> SpillerInstance;
70219077Sdim  std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
71219077Sdim                      CompSpillWeight> Queue;
72234353Sdim
73234353Sdim  // Scratch space.  Allocated here to avoid repeated malloc calls in
74234353Sdim  // selectOrSplit().
75234353Sdim  BitVector UsableRegs;
76234353Sdim
77218885Sdimpublic:
78218885Sdim  RABasic();
79218885Sdim
80218885Sdim  /// Return the pass name.
81218885Sdim  virtual const char* getPassName() const {
82218885Sdim    return "Basic Register Allocator";
83218885Sdim  }
84218885Sdim
85218885Sdim  /// RABasic analysis usage.
86218885Sdim  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
87218885Sdim
88218885Sdim  virtual void releaseMemory();
89218885Sdim
90218885Sdim  virtual Spiller &spiller() { return *SpillerInstance; }
91218885Sdim
92218885Sdim  virtual float getPriority(LiveInterval *LI) { return LI->weight; }
93218885Sdim
94219077Sdim  virtual void enqueue(LiveInterval *LI) {
95219077Sdim    Queue.push(LI);
96219077Sdim  }
97219077Sdim
98219077Sdim  virtual LiveInterval *dequeue() {
99219077Sdim    if (Queue.empty())
100219077Sdim      return 0;
101219077Sdim    LiveInterval *LI = Queue.top();
102219077Sdim    Queue.pop();
103219077Sdim    return LI;
104219077Sdim  }
105219077Sdim
106218885Sdim  virtual unsigned selectOrSplit(LiveInterval &VirtReg,
107218885Sdim                                 SmallVectorImpl<LiveInterval*> &SplitVRegs);
108218885Sdim
109218885Sdim  /// Perform register allocation.
110218885Sdim  virtual bool runOnMachineFunction(MachineFunction &mf);
111218885Sdim
112234353Sdim  // Helper for spilling all live virtual registers currently unified under preg
113234353Sdim  // that interfere with the most recently queried lvr.  Return true if spilling
114234353Sdim  // was successful, and append any new spilled/split intervals to splitLVRs.
115234353Sdim  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
116234353Sdim                          SmallVectorImpl<LiveInterval*> &SplitVRegs);
117234353Sdim
118218885Sdim  static char ID;
119218885Sdim};
120218885Sdim
121218885Sdimchar RABasic::ID = 0;
122218885Sdim
123218885Sdim} // end anonymous namespace
124218885Sdim
125218885SdimRABasic::RABasic(): MachineFunctionPass(ID) {
126221345Sdim  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
127218885Sdim  initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
128218885Sdim  initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
129224145Sdim  initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
130234353Sdim  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
131218885Sdim  initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
132218885Sdim  initializeLiveStacksPass(*PassRegistry::getPassRegistry());
133218885Sdim  initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
134218885Sdim  initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
135218885Sdim  initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
136239462Sdim  initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
137218885Sdim}
138218885Sdim
139218885Sdimvoid RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
140218885Sdim  AU.setPreservesCFG();
141218885Sdim  AU.addRequired<AliasAnalysis>();
142218885Sdim  AU.addPreserved<AliasAnalysis>();
143218885Sdim  AU.addRequired<LiveIntervals>();
144239462Sdim  AU.addPreserved<LiveIntervals>();
145218885Sdim  AU.addPreserved<SlotIndexes>();
146221345Sdim  AU.addRequired<LiveDebugVariables>();
147221345Sdim  AU.addPreserved<LiveDebugVariables>();
148218885Sdim  AU.addRequired<CalculateSpillWeights>();
149218885Sdim  AU.addRequired<LiveStacks>();
150218885Sdim  AU.addPreserved<LiveStacks>();
151218885Sdim  AU.addRequiredID(MachineDominatorsID);
152218885Sdim  AU.addPreservedID(MachineDominatorsID);
153218885Sdim  AU.addRequired<MachineLoopInfo>();
154218885Sdim  AU.addPreserved<MachineLoopInfo>();
155218885Sdim  AU.addRequired<VirtRegMap>();
156218885Sdim  AU.addPreserved<VirtRegMap>();
157239462Sdim  AU.addRequired<LiveRegMatrix>();
158239462Sdim  AU.addPreserved<LiveRegMatrix>();
159218885Sdim  MachineFunctionPass::getAnalysisUsage(AU);
160218885Sdim}
161218885Sdim
162218885Sdimvoid RABasic::releaseMemory() {
163218885Sdim  SpillerInstance.reset(0);
164218885Sdim}
165218885Sdim
166218885Sdim
167218885Sdim// Spill or split all live virtual registers currently unified under PhysReg
168218885Sdim// that interfere with VirtReg. The newly spilled or split live intervals are
169218885Sdim// returned by appending them to SplitVRegs.
170234353Sdimbool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
171218885Sdim                                 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
172218885Sdim  // Record each interference and determine if all are spillable before mutating
173218885Sdim  // either the union or live intervals.
174239462Sdim  SmallVector<LiveInterval*, 8> Intfs;
175239462Sdim
176218885Sdim  // Collect interferences assigned to any alias of the physical register.
177239462Sdim  for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
178239462Sdim    LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
179239462Sdim    Q.collectInterferingVRegs();
180239462Sdim    if (Q.seenUnspillableVReg())
181218885Sdim      return false;
182239462Sdim    for (unsigned i = Q.interferingVRegs().size(); i; --i) {
183239462Sdim      LiveInterval *Intf = Q.interferingVRegs()[i - 1];
184239462Sdim      if (!Intf->isSpillable() || Intf->weight > VirtReg.weight)
185239462Sdim        return false;
186239462Sdim      Intfs.push_back(Intf);
187218885Sdim    }
188218885Sdim  }
189218885Sdim  DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
190218885Sdim        " interferences with " << VirtReg << "\n");
191239462Sdim  assert(!Intfs.empty() && "expected interference");
192218885Sdim
193218885Sdim  // Spill each interfering vreg allocated to PhysReg or an alias.
194239462Sdim  for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
195239462Sdim    LiveInterval &Spill = *Intfs[i];
196239462Sdim
197239462Sdim    // Skip duplicates.
198239462Sdim    if (!VRM->hasPhys(Spill.reg))
199239462Sdim      continue;
200239462Sdim
201239462Sdim    // Deallocate the interfering vreg by removing it from the union.
202239462Sdim    // A LiveInterval instance may not be in a union during modification!
203239462Sdim    Matrix->unassign(Spill);
204239462Sdim
205239462Sdim    // Spill the extracted interval.
206239462Sdim    LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM);
207239462Sdim    spiller().spill(LRE);
208239462Sdim  }
209218885Sdim  return true;
210218885Sdim}
211218885Sdim
212218885Sdim// Driver for the register assignment and splitting heuristics.
213218885Sdim// Manages iteration over the LiveIntervalUnions.
214218885Sdim//
215218885Sdim// This is a minimal implementation of register assignment and splitting that
216218885Sdim// spills whenever we run out of registers.
217218885Sdim//
218218885Sdim// selectOrSplit can only be called once per live virtual register. We then do a
219218885Sdim// single interference test for each register the correct class until we find an
220218885Sdim// available register. So, the number of interference tests in the worst case is
221218885Sdim// |vregs| * |machineregs|. And since the number of interference tests is
222218885Sdim// minimal, there is no value in caching them outside the scope of
223218885Sdim// selectOrSplit().
224218885Sdimunsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
225218885Sdim                                SmallVectorImpl<LiveInterval*> &SplitVRegs) {
226218885Sdim  // Populate a list of physical register spill candidates.
227218885Sdim  SmallVector<unsigned, 8> PhysRegSpillCands;
228218885Sdim
229218885Sdim  // Check for an available register in this class.
230239462Sdim  AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
231239462Sdim  while (unsigned PhysReg = Order.next()) {
232239462Sdim    // Check for interference in PhysReg
233239462Sdim    switch (Matrix->checkInterference(VirtReg, PhysReg)) {
234239462Sdim    case LiveRegMatrix::IK_Free:
235239462Sdim      // PhysReg is available, allocate it.
236239462Sdim      return PhysReg;
237218885Sdim
238239462Sdim    case LiveRegMatrix::IK_VirtReg:
239239462Sdim      // Only virtual registers in the way, we may be able to spill them.
240239462Sdim      PhysRegSpillCands.push_back(PhysReg);
241234353Sdim      continue;
242234353Sdim
243239462Sdim    default:
244239462Sdim      // RegMask or RegUnit interference.
245239462Sdim      continue;
246218885Sdim    }
247239462Sdim  }
248218885Sdim
249218885Sdim  // Try to spill another interfering reg with less spill weight.
250218885Sdim  for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
251239462Sdim       PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
252239462Sdim    if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs))
253239462Sdim      continue;
254218885Sdim
255239462Sdim    assert(!Matrix->checkInterference(VirtReg, *PhysRegI) &&
256218885Sdim           "Interference after spill.");
257218885Sdim    // Tell the caller to allocate to this newly freed physical register.
258218885Sdim    return *PhysRegI;
259218885Sdim  }
260223017Sdim
261218885Sdim  // No other spill candidates were found, so spill the current VirtReg.
262218885Sdim  DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
263223017Sdim  if (!VirtReg.isSpillable())
264223017Sdim    return ~0u;
265239462Sdim  LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
266221345Sdim  spiller().spill(LRE);
267218885Sdim
268218885Sdim  // The live virtual register requesting allocation was spilled, so tell
269218885Sdim  // the caller not to allocate anything during this round.
270218885Sdim  return 0;
271218885Sdim}
272218885Sdim
273218885Sdimbool RABasic::runOnMachineFunction(MachineFunction &mf) {
274218885Sdim  DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
275218885Sdim               << "********** Function: "
276218885Sdim               << ((Value*)mf.getFunction())->getName() << '\n');
277218885Sdim
278218885Sdim  MF = &mf;
279239462Sdim  RegAllocBase::init(getAnalysis<VirtRegMap>(),
280239462Sdim                     getAnalysis<LiveIntervals>(),
281239462Sdim                     getAnalysis<LiveRegMatrix>());
282221345Sdim  SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
283218885Sdim
284218885Sdim  allocatePhysRegs();
285218885Sdim
286218885Sdim  // Diagnostic output before rewriting
287218885Sdim  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
288218885Sdim
289218885Sdim  releaseMemory();
290218885Sdim  return true;
291218885Sdim}
292218885Sdim
293218885SdimFunctionPass* llvm::createBasicRegisterAllocator()
294218885Sdim{
295218885Sdim  return new RABasic();
296218885Sdim}
297