LLVM API Documentation

RegisterScavenging.cpp
Go to the documentation of this file.
00001 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the machine register scavenger. It can provide
00011 // information, such as unused registers, at any point in a machine basic block.
00012 // It also provides a mechanism to make registers available by evicting them to
00013 // spill slots.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/CodeGen/RegisterScavenging.h"
00018 #include "llvm/CodeGen/MachineBasicBlock.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstr.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Target/TargetRegisterInfo.h"
00029 #include "llvm/Target/TargetSubtargetInfo.h"
00030 using namespace llvm;
00031 
00032 #define DEBUG_TYPE "reg-scavenging"
00033 
00034 /// setUsed - Set the register units of this register as used.
00035 void RegScavenger::setRegUsed(unsigned Reg) {
00036   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
00037     RegUnitsAvailable.reset(*RUI);
00038 }
00039 
00040 void RegScavenger::initRegState() {
00041   for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
00042          IE = Scavenged.end(); I != IE; ++I) {
00043     I->Reg = 0;
00044     I->Restore = nullptr;
00045   }
00046 
00047   // All register units start out unused.
00048   RegUnitsAvailable.set();
00049 
00050   if (!MBB)
00051     return;
00052 
00053   // Live-in registers are in use.
00054   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
00055          E = MBB->livein_end(); I != E; ++I)
00056     setRegUsed(*I);
00057 
00058   // Pristine CSRs are also unavailable.
00059   BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
00060   for (int I = PR.find_first(); I>0; I = PR.find_next(I))
00061     setRegUsed(I);
00062 }
00063 
00064 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
00065   MachineFunction &MF = *mbb->getParent();
00066   const TargetMachine &TM = MF.getTarget();
00067   TII = TM.getSubtargetImpl()->getInstrInfo();
00068   TRI = TM.getSubtargetImpl()->getRegisterInfo();
00069   MRI = &MF.getRegInfo();
00070 
00071   assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
00072          "Target changed?");
00073 
00074   // It is not possible to use the register scavenger after late optimization
00075   // passes that don't preserve accurate liveness information.
00076   assert(MRI->tracksLiveness() &&
00077          "Cannot use register scavenger with inaccurate liveness");
00078 
00079   // Self-initialize.
00080   if (!MBB) {
00081     NumRegUnits = TRI->getNumRegUnits();
00082     RegUnitsAvailable.resize(NumRegUnits);
00083     KillRegUnits.resize(NumRegUnits);
00084     DefRegUnits.resize(NumRegUnits);
00085     TmpRegUnits.resize(NumRegUnits);
00086   }
00087 
00088   MBB = mbb;
00089   initRegState();
00090 
00091   Tracking = false;
00092 }
00093 
00094 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
00095   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
00096     BV.set(*RUI);
00097 }
00098 
00099 void RegScavenger::determineKillsAndDefs() {
00100   assert(Tracking && "Must be tracking to determine kills and defs");
00101 
00102   MachineInstr *MI = MBBI;
00103   assert(!MI->isDebugValue() && "Debug values have no kills or defs");
00104 
00105   // Find out which registers are early clobbered, killed, defined, and marked
00106   // def-dead in this instruction.
00107   // FIXME: The scavenger is not predication aware. If the instruction is
00108   // predicated, conservatively assume "kill" markers do not actually kill the
00109   // register. Similarly ignores "dead" markers.
00110   bool isPred = TII->isPredicated(MI);
00111   KillRegUnits.reset();
00112   DefRegUnits.reset();
00113   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00114     const MachineOperand &MO = MI->getOperand(i);
00115     if (MO.isRegMask()) {
00116       
00117       TmpRegUnits.clear();
00118       for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
00119         for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
00120           if (MO.clobbersPhysReg(*RURI)) {
00121             TmpRegUnits.set(RU);
00122             break;
00123           }
00124         }
00125       }
00126       
00127       // Apply the mask.
00128       (isPred ? DefRegUnits : KillRegUnits) |= TmpRegUnits;
00129     }
00130     if (!MO.isReg())
00131       continue;
00132     unsigned Reg = MO.getReg();
00133     if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
00134       continue;
00135 
00136     if (MO.isUse()) {
00137       // Ignore undef uses.
00138       if (MO.isUndef())
00139         continue;
00140       if (!isPred && MO.isKill())
00141         addRegUnits(KillRegUnits, Reg);
00142     } else {
00143       assert(MO.isDef());
00144       if (!isPred && MO.isDead())
00145         addRegUnits(KillRegUnits, Reg);
00146       else
00147         addRegUnits(DefRegUnits, Reg);
00148     }
00149   }
00150 }
00151 
00152 void RegScavenger::unprocess() {
00153   assert(Tracking && "Cannot unprocess because we're not tracking");
00154 
00155   MachineInstr *MI = MBBI;
00156   if (!MI->isDebugValue()) {
00157     determineKillsAndDefs();
00158 
00159     // Commit the changes.
00160     setUsed(KillRegUnits);
00161     setUnused(DefRegUnits);
00162   }
00163 
00164   if (MBBI == MBB->begin()) {
00165     MBBI = MachineBasicBlock::iterator(nullptr);
00166     Tracking = false;
00167   } else
00168     --MBBI;
00169 }
00170 
00171 void RegScavenger::forward() {
00172   // Move ptr forward.
00173   if (!Tracking) {
00174     MBBI = MBB->begin();
00175     Tracking = true;
00176   } else {
00177     assert(MBBI != MBB->end() && "Already past the end of the basic block!");
00178     MBBI = std::next(MBBI);
00179   }
00180   assert(MBBI != MBB->end() && "Already at the end of the basic block!");
00181 
00182   MachineInstr *MI = MBBI;
00183 
00184   for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
00185          IE = Scavenged.end(); I != IE; ++I) {
00186     if (I->Restore != MI)
00187       continue;
00188 
00189     I->Reg = 0;
00190     I->Restore = nullptr;
00191   }
00192 
00193   if (MI->isDebugValue())
00194     return;
00195 
00196   determineKillsAndDefs();
00197 
00198   // Verify uses and defs.
00199 #ifndef NDEBUG
00200   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00201     const MachineOperand &MO = MI->getOperand(i);
00202     if (!MO.isReg())
00203       continue;
00204     unsigned Reg = MO.getReg();
00205     if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
00206       continue;
00207     if (MO.isUse()) {
00208       if (MO.isUndef())
00209         continue;
00210       if (!isRegUsed(Reg)) {
00211         // Check if it's partial live: e.g.
00212         // D0 = insert_subreg D0<undef>, S0
00213         // ... D0
00214         // The problem is the insert_subreg could be eliminated. The use of
00215         // D0 is using a partially undef value. This is not *incorrect* since
00216         // S1 is can be freely clobbered.
00217         // Ideally we would like a way to model this, but leaving the
00218         // insert_subreg around causes both correctness and performance issues.
00219         bool SubUsed = false;
00220         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
00221           if (isRegUsed(*SubRegs)) {
00222             SubUsed = true;
00223             break;
00224           }
00225         bool SuperUsed = false;
00226         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
00227           if (isRegUsed(*SR)) {
00228             SuperUsed = true;
00229             break;
00230           }
00231         }
00232         if (!SubUsed && !SuperUsed) {
00233           MBB->getParent()->verify(nullptr, "In Register Scavenger");
00234           llvm_unreachable("Using an undefined register!");
00235         }
00236         (void)SubUsed;
00237         (void)SuperUsed;
00238       }
00239     } else {
00240       assert(MO.isDef());
00241 #if 0
00242       // FIXME: Enable this once we've figured out how to correctly transfer
00243       // implicit kills during codegen passes like the coalescer.
00244       assert((KillRegs.test(Reg) || isUnused(Reg) ||
00245               isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
00246              "Re-defining a live register!");
00247 #endif
00248     }
00249   }
00250 #endif // NDEBUG
00251 
00252   // Commit the changes.
00253   setUnused(KillRegUnits);
00254   setUsed(DefRegUnits);
00255 }
00256 
00257 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
00258   if (includeReserved && isReserved(Reg))
00259     return true;
00260   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
00261     if (!RegUnitsAvailable.test(*RUI))
00262       return true;
00263   return false;
00264 }
00265 
00266 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
00267   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
00268        I != E; ++I)
00269     if (!isRegUsed(*I)) {
00270       DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
00271             "\n");
00272       return *I;
00273     }
00274   return 0;
00275 }
00276 
00277 /// getRegsAvailable - Return all available registers in the register class
00278 /// in Mask.
00279 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
00280   BitVector Mask(TRI->getNumRegs());
00281   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
00282        I != E; ++I)
00283     if (!isRegUsed(*I))
00284       Mask.set(*I);
00285   return Mask;
00286 }
00287 
00288 /// findSurvivorReg - Return the candidate register that is unused for the
00289 /// longest after StartMII. UseMI is set to the instruction where the search
00290 /// stopped.
00291 ///
00292 /// No more than InstrLimit instructions are inspected.
00293 ///
00294 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
00295                                        BitVector &Candidates,
00296                                        unsigned InstrLimit,
00297                                        MachineBasicBlock::iterator &UseMI) {
00298   int Survivor = Candidates.find_first();
00299   assert(Survivor > 0 && "No candidates for scavenging");
00300 
00301   MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
00302   assert(StartMI != ME && "MI already at terminator");
00303   MachineBasicBlock::iterator RestorePointMI = StartMI;
00304   MachineBasicBlock::iterator MI = StartMI;
00305 
00306   bool inVirtLiveRange = false;
00307   for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
00308     if (MI->isDebugValue()) {
00309       ++InstrLimit; // Don't count debug instructions
00310       continue;
00311     }
00312     bool isVirtKillInsn = false;
00313     bool isVirtDefInsn = false;
00314     // Remove any candidates touched by instruction.
00315     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00316       const MachineOperand &MO = MI->getOperand(i);
00317       if (MO.isRegMask())
00318         Candidates.clearBitsNotInMask(MO.getRegMask());
00319       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
00320         continue;
00321       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
00322         if (MO.isDef())
00323           isVirtDefInsn = true;
00324         else if (MO.isKill())
00325           isVirtKillInsn = true;
00326         continue;
00327       }
00328       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
00329         Candidates.reset(*AI);
00330     }
00331     // If we're not in a virtual reg's live range, this is a valid
00332     // restore point.
00333     if (!inVirtLiveRange) RestorePointMI = MI;
00334 
00335     // Update whether we're in the live range of a virtual register
00336     if (isVirtKillInsn) inVirtLiveRange = false;
00337     if (isVirtDefInsn) inVirtLiveRange = true;
00338 
00339     // Was our survivor untouched by this instruction?
00340     if (Candidates.test(Survivor))
00341       continue;
00342 
00343     // All candidates gone?
00344     if (Candidates.none())
00345       break;
00346 
00347     Survivor = Candidates.find_first();
00348   }
00349   // If we ran off the end, that's where we want to restore.
00350   if (MI == ME) RestorePointMI = ME;
00351   assert (RestorePointMI != StartMI &&
00352           "No available scavenger restore location!");
00353 
00354   // We ran out of candidates, so stop the search.
00355   UseMI = RestorePointMI;
00356   return Survivor;
00357 }
00358 
00359 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
00360   unsigned i = 0;
00361   while (!MI->getOperand(i).isFI()) {
00362     ++i;
00363     assert(i < MI->getNumOperands() &&
00364            "Instr doesn't have FrameIndex operand!");
00365   }
00366   return i;
00367 }
00368 
00369 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
00370                                         MachineBasicBlock::iterator I,
00371                                         int SPAdj) {
00372   // Consider all allocatable registers in the register class initially
00373   BitVector Candidates =
00374     TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
00375 
00376   // Exclude all the registers being used by the instruction.
00377   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00378     MachineOperand &MO = I->getOperand(i);
00379     if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
00380         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
00381       Candidates.reset(MO.getReg());
00382   }
00383 
00384   // Try to find a register that's unused if there is one, as then we won't
00385   // have to spill.
00386   BitVector Available = getRegsAvailable(RC);
00387   Available &= Candidates;
00388   if (Available.any())
00389     Candidates = Available;
00390 
00391   // Find the register whose use is furthest away.
00392   MachineBasicBlock::iterator UseMI;
00393   unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
00394 
00395   // If we found an unused register there is no reason to spill it.
00396   if (!isRegUsed(SReg)) {
00397     DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
00398     return SReg;
00399   }
00400 
00401   // Find an available scavenging slot.
00402   unsigned SI;
00403   for (SI = 0; SI < Scavenged.size(); ++SI)
00404     if (Scavenged[SI].Reg == 0)
00405       break;
00406 
00407   if (SI == Scavenged.size()) {
00408     // We need to scavenge a register but have no spill slot, the target
00409     // must know how to do it (if not, we'll assert below).
00410     Scavenged.push_back(ScavengedInfo());
00411   }
00412 
00413   // Avoid infinite regress
00414   Scavenged[SI].Reg = SReg;
00415 
00416   // If the target knows how to save/restore the register, let it do so;
00417   // otherwise, use the emergency stack spill slot.
00418   if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
00419     // Spill the scavenged register before I.
00420     assert(Scavenged[SI].FrameIndex >= 0 &&
00421            "Cannot scavenge register without an emergency spill slot!");
00422     TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
00423                              RC, TRI);
00424     MachineBasicBlock::iterator II = std::prev(I);
00425 
00426     unsigned FIOperandNum = getFrameIndexOperandNum(II);
00427     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
00428 
00429     // Restore the scavenged register before its use (or first terminator).
00430     TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
00431                               RC, TRI);
00432     II = std::prev(UseMI);
00433 
00434     FIOperandNum = getFrameIndexOperandNum(II);
00435     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
00436   }
00437 
00438   Scavenged[SI].Restore = std::prev(UseMI);
00439 
00440   // Doing this here leads to infinite regress.
00441   // Scavenged[SI].Reg = SReg;
00442 
00443   DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
00444         "\n");
00445 
00446   return SReg;
00447 }