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