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