RegisterScavenging.cpp revision bdaa9dc4a45b8831c942437f726895eb24a956ba
1//===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
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 implements the machine register scavenger. It can provide
11// information, such as unused registers, at any point in a machine basic block.
12// It also provides a mechanism to make registers available by evicting them to
13// spill slots.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "reg-scavenging"
18#include "llvm/CodeGen/RegisterScavenging.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineInstr.h"
23#include "llvm/CodeGen/MachineRegisterInfo.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/Target/TargetRegisterInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/STLExtras.h"
34using namespace llvm;
35
36/// setUsed - Set the register and its sub-registers as being used.
37void RegScavenger::setUsed(unsigned Reg) {
38  RegsAvailable.reset(Reg);
39
40  for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
41       unsigned SubReg = *SubRegs; ++SubRegs)
42    RegsAvailable.reset(SubReg);
43}
44
45bool RegScavenger::isAliasUsed(unsigned Reg) const {
46  if (isUsed(Reg))
47    return true;
48  for (const unsigned *R = TRI->getAliasSet(Reg); *R; ++R)
49    if (isUsed(*R))
50      return true;
51  return false;
52}
53
54void RegScavenger::initRegState() {
55  ScavengedReg = 0;
56  ScavengedRC = NULL;
57  ScavengeRestore = NULL;
58
59  // All registers started out unused.
60  RegsAvailable.set();
61
62  // Reserved registers are always used.
63  RegsAvailable ^= ReservedRegs;
64
65  if (!MBB)
66    return;
67
68  // Live-in registers are in use.
69  for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
70         E = MBB->livein_end(); I != E; ++I)
71    setUsed(*I);
72
73  // Pristine CSRs are also unavailable.
74  BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
75  for (int I = PR.find_first(); I>0; I = PR.find_next(I))
76    setUsed(I);
77}
78
79void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
80  MachineFunction &MF = *mbb->getParent();
81  const TargetMachine &TM = MF.getTarget();
82  TII = TM.getInstrInfo();
83  TRI = TM.getRegisterInfo();
84  MRI = &MF.getRegInfo();
85
86  assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
87         "Target changed?");
88
89  // Self-initialize.
90  if (!MBB) {
91    NumPhysRegs = TRI->getNumRegs();
92    RegsAvailable.resize(NumPhysRegs);
93
94    // Create reserved registers bitvector.
95    ReservedRegs = TRI->getReservedRegs(MF);
96
97    // Create callee-saved registers bitvector.
98    CalleeSavedRegs.resize(NumPhysRegs);
99    const unsigned *CSRegs = TRI->getCalleeSavedRegs();
100    if (CSRegs != NULL)
101      for (unsigned i = 0; CSRegs[i]; ++i)
102        CalleeSavedRegs.set(CSRegs[i]);
103  }
104
105  MBB = mbb;
106  initRegState();
107
108  Tracking = false;
109}
110
111void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
112  BV.set(Reg);
113  for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
114    BV.set(*R);
115}
116
117void RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) {
118  BV.set(Reg);
119  for (const unsigned *R = TRI->getAliasSet(Reg); *R; R++)
120    BV.set(*R);
121}
122
123void RegScavenger::forward() {
124  // Move ptr forward.
125  if (!Tracking) {
126    MBBI = MBB->begin();
127    Tracking = true;
128  } else {
129    assert(MBBI != MBB->end() && "Already past the end of the basic block!");
130    MBBI = llvm::next(MBBI);
131  }
132  assert(MBBI != MBB->end() && "Already at the end of the basic block!");
133
134  MachineInstr *MI = MBBI;
135
136  if (MI == ScavengeRestore) {
137    ScavengedReg = 0;
138    ScavengedRC = NULL;
139    ScavengeRestore = NULL;
140  }
141
142  if (MI->isDebugValue())
143    return;
144
145  // Find out which registers are early clobbered, killed, defined, and marked
146  // def-dead in this instruction.
147  // FIXME: The scavenger is not predication aware. If the instruction is
148  // predicated, conservatively assume "kill" markers do not actually kill the
149  // register. Similarly ignores "dead" markers.
150  bool isPred = TII->isPredicated(MI);
151  BitVector EarlyClobberRegs(NumPhysRegs);
152  BitVector KillRegs(NumPhysRegs);
153  BitVector DefRegs(NumPhysRegs);
154  BitVector DeadRegs(NumPhysRegs);
155  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
156    const MachineOperand &MO = MI->getOperand(i);
157    if (!MO.isReg() || MO.isUndef())
158      continue;
159    unsigned Reg = MO.getReg();
160    if (!Reg || isReserved(Reg))
161      continue;
162
163    if (MO.isUse()) {
164      // Two-address operands implicitly kill.
165      if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i)))
166        addRegWithSubRegs(KillRegs, Reg);
167    } else {
168      assert(MO.isDef());
169      if (!isPred && MO.isDead())
170        addRegWithSubRegs(DeadRegs, Reg);
171      else
172        addRegWithSubRegs(DefRegs, Reg);
173      if (MO.isEarlyClobber())
174        addRegWithAliases(EarlyClobberRegs, Reg);
175    }
176  }
177
178  // Verify uses and defs.
179  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
180    const MachineOperand &MO = MI->getOperand(i);
181    if (!MO.isReg() || MO.isUndef())
182      continue;
183    unsigned Reg = MO.getReg();
184    if (!Reg || isReserved(Reg))
185      continue;
186    if (MO.isUse()) {
187      if (!isUsed(Reg)) {
188        // Check if it's partial live: e.g.
189        // D0 = insert_subreg D0<undef>, S0
190        // ... D0
191        // The problem is the insert_subreg could be eliminated. The use of
192        // D0 is using a partially undef value. This is not *incorrect* since
193        // S1 is can be freely clobbered.
194        // Ideally we would like a way to model this, but leaving the
195        // insert_subreg around causes both correctness and performance issues.
196        bool SubUsed = false;
197        for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
198             unsigned SubReg = *SubRegs; ++SubRegs)
199          if (isUsed(SubReg)) {
200            SubUsed = true;
201            break;
202          }
203        assert(SubUsed && "Using an undefined register!");
204      }
205      assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i)) &&
206             "Using an early clobbered register!");
207    } else {
208      assert(MO.isDef());
209#if 0
210      // FIXME: Enable this once we've figured out how to correctly transfer
211      // implicit kills during codegen passes like the coalescer.
212      assert((KillRegs.test(Reg) || isUnused(Reg) ||
213              isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
214             "Re-defining a live register!");
215#endif
216    }
217  }
218
219  // Commit the changes.
220  setUnused(KillRegs);
221  setUnused(DeadRegs);
222  setUsed(DefRegs);
223}
224
225void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
226  if (includeReserved)
227    used = ~RegsAvailable;
228  else
229    used = ~RegsAvailable & ~ReservedRegs;
230}
231
232unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
233  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
234       I != E; ++I)
235    if (!isAliasUsed(*I)) {
236      DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
237            "\n");
238      return *I;
239    }
240  return 0;
241}
242
243/// getRegsAvailable - Return all available registers in the register class
244/// in Mask.
245BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
246  BitVector Mask(TRI->getNumRegs());
247  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
248       I != E; ++I)
249    if (!isAliasUsed(*I))
250      Mask.set(*I);
251  return Mask;
252}
253
254/// findSurvivorReg - Return the candidate register that is unused for the
255/// longest after StargMII. UseMI is set to the instruction where the search
256/// stopped.
257///
258/// No more than InstrLimit instructions are inspected.
259///
260unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
261                                       BitVector &Candidates,
262                                       unsigned InstrLimit,
263                                       MachineBasicBlock::iterator &UseMI) {
264  int Survivor = Candidates.find_first();
265  assert(Survivor > 0 && "No candidates for scavenging");
266
267  MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
268  assert(StartMI != ME && "MI already at terminator");
269  MachineBasicBlock::iterator RestorePointMI = StartMI;
270  MachineBasicBlock::iterator MI = StartMI;
271
272  bool inVirtLiveRange = false;
273  for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
274    if (MI->isDebugValue()) {
275      ++InstrLimit; // Don't count debug instructions
276      continue;
277    }
278    bool isVirtKillInsn = false;
279    bool isVirtDefInsn = false;
280    // Remove any candidates touched by instruction.
281    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282      const MachineOperand &MO = MI->getOperand(i);
283      if (!MO.isReg() || MO.isUndef() || !MO.getReg())
284        continue;
285      if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
286        if (MO.isDef())
287          isVirtDefInsn = true;
288        else if (MO.isKill())
289          isVirtKillInsn = true;
290        continue;
291      }
292      Candidates.reset(MO.getReg());
293      for (const unsigned *R = TRI->getAliasSet(MO.getReg()); *R; R++)
294        Candidates.reset(*R);
295    }
296    // If we're not in a virtual reg's live range, this is a valid
297    // restore point.
298    if (!inVirtLiveRange) RestorePointMI = MI;
299
300    // Update whether we're in the live range of a virtual register
301    if (isVirtKillInsn) inVirtLiveRange = false;
302    if (isVirtDefInsn) inVirtLiveRange = true;
303
304    // Was our survivor untouched by this instruction?
305    if (Candidates.test(Survivor))
306      continue;
307
308    // All candidates gone?
309    if (Candidates.none())
310      break;
311
312    Survivor = Candidates.find_first();
313  }
314  // If we ran off the end, that's where we want to restore.
315  if (MI == ME) RestorePointMI = ME;
316  assert (RestorePointMI != StartMI &&
317          "No available scavenger restore location!");
318
319  // We ran out of candidates, so stop the search.
320  UseMI = RestorePointMI;
321  return Survivor;
322}
323
324unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
325                                        MachineBasicBlock::iterator I,
326                                        int SPAdj) {
327  // Consider all allocatable registers in the register class initially
328  BitVector Candidates =
329    TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
330
331  // Exclude all the registers being used by the instruction.
332  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
333    MachineOperand &MO = I->getOperand(i);
334    if (MO.isReg() && MO.getReg() != 0 &&
335        !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
336      Candidates.reset(MO.getReg());
337  }
338
339  // Try to find a register that's unused if there is one, as then we won't
340  // have to spill. Search explicitly rather than masking out based on
341  // RegsAvailable, as RegsAvailable does not take aliases into account.
342  // That's what getRegsAvailable() is for.
343  BitVector Available = getRegsAvailable(RC);
344
345  if ((Candidates & Available).any())
346     Candidates &= Available;
347
348  // Find the register whose use is furthest away.
349  MachineBasicBlock::iterator UseMI;
350  unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
351
352  // If we found an unused register there is no reason to spill it.
353  if (!isAliasUsed(SReg)) {
354    DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
355    return SReg;
356  }
357
358  assert(ScavengedReg == 0 &&
359         "Scavenger slot is live, unable to scavenge another register!");
360
361  // Avoid infinite regress
362  ScavengedReg = SReg;
363
364  // If the target knows how to save/restore the register, let it do so;
365  // otherwise, use the emergency stack spill slot.
366  if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
367    // Spill the scavenged register before I.
368    assert(ScavengingFrameIndex >= 0 &&
369           "Cannot scavenge register without an emergency spill slot!");
370    TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
371    MachineBasicBlock::iterator II = prior(I);
372    TRI->eliminateFrameIndex(II, SPAdj, this);
373
374    // Restore the scavenged register before its use (or first terminator).
375    TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
376    II = prior(UseMI);
377    TRI->eliminateFrameIndex(II, SPAdj, this);
378  }
379
380  ScavengeRestore = prior(UseMI);
381
382  // Doing this here leads to infinite regress.
383  // ScavengedReg = SReg;
384  ScavengedRC = RC;
385
386  DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
387        "\n");
388
389  return SReg;
390}
391