LLVM API Documentation

VirtRegMap.cpp

Go to the documentation of this file.
00001 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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 VirtRegMap class.
00011 //
00012 // It also contains implementations of the the Spiller interface, which, given a
00013 // virtual register map and a machine function, eliminates all virtual
00014 // references by replacing them with physical register references - adding spill
00015 // code as necessary.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #define DEBUG_TYPE "spiller"
00020 #include "VirtRegMap.h"
00021 #include "llvm/Function.h"
00022 #include "llvm/CodeGen/MachineFrameInfo.h"
00023 #include "llvm/CodeGen/MachineFunction.h"
00024 #include "llvm/CodeGen/MachineInstrBuilder.h"
00025 #include "llvm/CodeGen/MachineRegisterInfo.h"
00026 #include "llvm/Target/TargetMachine.h"
00027 #include "llvm/Target/TargetInstrInfo.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/Compiler.h"
00031 #include "llvm/ADT/BitVector.h"
00032 #include "llvm/ADT/DenseMap.h"
00033 #include "llvm/ADT/Statistic.h"
00034 #include "llvm/ADT/STLExtras.h"
00035 #include "llvm/ADT/SmallSet.h"
00036 #include <algorithm>
00037 using namespace llvm;
00038 
00039 STATISTIC(NumSpills  , "Number of register spills");
00040 STATISTIC(NumPSpills , "Number of physical register spills");
00041 STATISTIC(NumReMats  , "Number of re-materialization");
00042 STATISTIC(NumDRM     , "Number of re-materializable defs elided");
00043 STATISTIC(NumStores  , "Number of stores added");
00044 STATISTIC(NumLoads   , "Number of loads added");
00045 STATISTIC(NumReused  , "Number of values reused");
00046 STATISTIC(NumDSE     , "Number of dead stores elided");
00047 STATISTIC(NumDCE     , "Number of copies elided");
00048 STATISTIC(NumDSS     , "Number of dead spill slots removed");
00049 STATISTIC(NumCommutes, "Number of instructions commuted");
00050 
00051 namespace {
00052   enum SpillerName { simple, local };
00053 }
00054 
00055 static cl::opt<SpillerName>
00056 SpillerOpt("spiller",
00057            cl::desc("Spiller to use: (default: local)"),
00058            cl::Prefix,
00059            cl::values(clEnumVal(simple, "simple spiller"),
00060                       clEnumVal(local,  "local spiller"),
00061                       clEnumValEnd),
00062            cl::init(local));
00063 
00064 //===----------------------------------------------------------------------===//
00065 //  VirtRegMap implementation
00066 //===----------------------------------------------------------------------===//
00067 
00068 VirtRegMap::VirtRegMap(MachineFunction &mf)
00069   : TII(*mf.getTarget().getInstrInfo()), MF(mf), 
00070     Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
00071     Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
00072     Virt2SplitKillMap(0), ReMatMap(NULL), ReMatId(MAX_STACK_SLOT+1),
00073     LowSpillSlot(NO_STACK_SLOT), HighSpillSlot(NO_STACK_SLOT) {
00074   SpillSlotToUsesMap.resize(8);
00075   ImplicitDefed.resize(MF.getRegInfo().getLastVirtReg()+1-
00076                        TargetRegisterInfo::FirstVirtualRegister);
00077   grow();
00078 }
00079 
00080 void VirtRegMap::grow() {
00081   unsigned LastVirtReg = MF.getRegInfo().getLastVirtReg();
00082   Virt2PhysMap.grow(LastVirtReg);
00083   Virt2StackSlotMap.grow(LastVirtReg);
00084   Virt2ReMatIdMap.grow(LastVirtReg);
00085   Virt2SplitMap.grow(LastVirtReg);
00086   Virt2SplitKillMap.grow(LastVirtReg);
00087   ReMatMap.grow(LastVirtReg);
00088   ImplicitDefed.resize(LastVirtReg-TargetRegisterInfo::FirstVirtualRegister+1);
00089 }
00090 
00091 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
00092   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
00093   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
00094          "attempt to assign stack slot to already spilled register");
00095   const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(virtReg);
00096   int SS = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
00097                                                 RC->getAlignment());
00098   if (LowSpillSlot == NO_STACK_SLOT)
00099     LowSpillSlot = SS;
00100   if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
00101     HighSpillSlot = SS;
00102   unsigned Idx = SS-LowSpillSlot;
00103   while (Idx >= SpillSlotToUsesMap.size())
00104     SpillSlotToUsesMap.resize(SpillSlotToUsesMap.size()*2);
00105   Virt2StackSlotMap[virtReg] = SS;
00106   ++NumSpills;
00107   return SS;
00108 }
00109 
00110 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
00111   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
00112   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
00113          "attempt to assign stack slot to already spilled register");
00114   assert((SS >= 0 ||
00115           (SS >= MF.getFrameInfo()->getObjectIndexBegin())) &&
00116          "illegal fixed frame index");
00117   Virt2StackSlotMap[virtReg] = SS;
00118 }
00119 
00120 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
00121   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
00122   assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
00123          "attempt to assign re-mat id to already spilled register");
00124   Virt2ReMatIdMap[virtReg] = ReMatId;
00125   return ReMatId++;
00126 }
00127 
00128 void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
00129   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
00130   assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
00131          "attempt to assign re-mat id to already spilled register");
00132   Virt2ReMatIdMap[virtReg] = id;
00133 }
00134 
00135 int VirtRegMap::getEmergencySpillSlot(const TargetRegisterClass *RC) {
00136   std::map<const TargetRegisterClass*, int>::iterator I =
00137     EmergencySpillSlots.find(RC);
00138   if (I != EmergencySpillSlots.end())
00139     return I->second;
00140   int SS = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
00141                                                 RC->getAlignment());
00142   if (LowSpillSlot == NO_STACK_SLOT)
00143     LowSpillSlot = SS;
00144   if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
00145     HighSpillSlot = SS;
00146   EmergencySpillSlots[RC] = SS;
00147   return SS;
00148 }
00149 
00150 void VirtRegMap::addSpillSlotUse(int FI, MachineInstr *MI) {
00151   if (!MF.getFrameInfo()->isFixedObjectIndex(FI)) {
00152     // If FI < LowSpillSlot, this stack reference was produced by
00153     // instruction selection and is not a spill
00154     if (FI >= LowSpillSlot) {
00155       assert(FI >= 0 && "Spill slot index should not be negative!");
00156       assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
00157              && "Invalid spill slot");
00158       SpillSlotToUsesMap[FI-LowSpillSlot].insert(MI);
00159     }
00160   }
00161 }
00162 
00163 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
00164                             MachineInstr *NewMI, ModRef MRInfo) {
00165   // Move previous memory references folded to new instruction.
00166   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
00167   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
00168          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
00169     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
00170     MI2VirtMap.erase(I++);
00171   }
00172 
00173   // add new memory reference
00174   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
00175 }
00176 
00177 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
00178   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
00179   MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)));
00180 }
00181 
00182 void VirtRegMap::RemoveMachineInstrFromMaps(MachineInstr *MI) {
00183   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00184     MachineOperand &MO = MI->getOperand(i);
00185     if (!MO.isFI())
00186       continue;
00187     int FI = MO.getIndex();
00188     if (MF.getFrameInfo()->isFixedObjectIndex(FI))
00189       continue;
00190     // This stack reference was produced by instruction selection and
00191     // is not a spill
00192     if (FI < LowSpillSlot)
00193       continue;
00194     assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
00195            && "Invalid spill slot");
00196     SpillSlotToUsesMap[FI-LowSpillSlot].erase(MI);
00197   }
00198   MI2VirtMap.erase(MI);
00199   SpillPt2VirtMap.erase(MI);
00200   RestorePt2VirtMap.erase(MI);
00201   EmergencySpillMap.erase(MI);
00202 }
00203 
00204 void VirtRegMap::print(std::ostream &OS) const {
00205   const TargetRegisterInfo* TRI = MF.getTarget().getRegisterInfo();
00206 
00207   OS << "********** REGISTER MAP **********\n";
00208   for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
00209          e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i) {
00210     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
00211       OS << "[reg" << i << " -> " << TRI->getName(Virt2PhysMap[i])
00212          << "]\n";
00213   }
00214 
00215   for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
00216          e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i)
00217     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
00218       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
00219   OS << '\n';
00220 }
00221 
00222 void VirtRegMap::dump() const {
00223   print(cerr);
00224 }
00225 
00226 
00227 //===----------------------------------------------------------------------===//
00228 // Simple Spiller Implementation
00229 //===----------------------------------------------------------------------===//
00230 
00231 Spiller::~Spiller() {}
00232 
00233 namespace {
00234   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
00235     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
00236   };
00237 }
00238 
00239 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
00240   DOUT << "********** REWRITE MACHINE CODE **********\n";
00241   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
00242   const TargetMachine &TM = MF.getTarget();
00243   const TargetInstrInfo &TII = *TM.getInstrInfo();
00244   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
00245   
00246 
00247   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
00248   // each vreg once (in the case where a spilled vreg is used by multiple
00249   // operands).  This is always smaller than the number of operands to the
00250   // current machine instr, so it should be small.
00251   std::vector<unsigned> LoadedRegs;
00252 
00253   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
00254        MBBI != E; ++MBBI) {
00255     DOUT << MBBI->getBasicBlock()->getName() << ":\n";
00256     MachineBasicBlock &MBB = *MBBI;
00257     for (MachineBasicBlock::iterator MII = MBB.begin(),
00258            E = MBB.end(); MII != E; ++MII) {
00259       MachineInstr &MI = *MII;
00260       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00261         MachineOperand &MO = MI.getOperand(i);
00262         if (MO.isReg() && MO.getReg()) {
00263           if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
00264             unsigned VirtReg = MO.getReg();
00265             unsigned SubIdx = MO.getSubReg();
00266             unsigned PhysReg = VRM.getPhys(VirtReg);
00267             unsigned RReg = SubIdx ? TRI.getSubReg(PhysReg, SubIdx) : PhysReg;
00268             if (!VRM.isAssignedReg(VirtReg)) {
00269               int StackSlot = VRM.getStackSlot(VirtReg);
00270               const TargetRegisterClass* RC =
00271                 MF.getRegInfo().getRegClass(VirtReg);
00272 
00273               if (MO.isUse() &&
00274                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
00275                   == LoadedRegs.end()) {
00276                 TII.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
00277                 MachineInstr *LoadMI = prior(MII);
00278                 VRM.addSpillSlotUse(StackSlot, LoadMI);
00279                 LoadedRegs.push_back(VirtReg);
00280                 ++NumLoads;
00281                 DOUT << '\t' << *LoadMI;
00282               }
00283 
00284               if (MO.isDef()) {
00285                 TII.storeRegToStackSlot(MBB, next(MII), PhysReg, true,
00286                                         StackSlot, RC);
00287                 MachineInstr *StoreMI = next(MII);
00288                 VRM.addSpillSlotUse(StackSlot, StoreMI);
00289                 ++NumStores;
00290               }
00291             }
00292             MF.getRegInfo().setPhysRegUsed(RReg);
00293             MI.getOperand(i).setReg(RReg);
00294           } else {
00295             MF.getRegInfo().setPhysRegUsed(MO.getReg());
00296           }
00297         }
00298       }
00299 
00300       DOUT << '\t' << MI;
00301       LoadedRegs.clear();
00302     }
00303   }
00304   return true;
00305 }
00306 
00307 //===----------------------------------------------------------------------===//
00308 //  Local Spiller Implementation
00309 //===----------------------------------------------------------------------===//
00310 
00311 namespace {
00312   class AvailableSpills;
00313 
00314   /// LocalSpiller - This spiller does a simple pass over the machine basic
00315   /// block to attempt to keep spills in registers as much as possible for
00316   /// blocks that have low register pressure (the vreg may be spilled due to
00317   /// register pressure in other blocks).
00318   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
00319     MachineRegisterInfo *RegInfo;
00320     const TargetRegisterInfo *TRI;
00321     const TargetInstrInfo *TII;
00322     DenseMap<MachineInstr*, unsigned> DistanceMap;
00323   public:
00324     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
00325       RegInfo = &MF.getRegInfo(); 
00326       TRI = MF.getTarget().getRegisterInfo();
00327       TII = MF.getTarget().getInstrInfo();
00328       DOUT << "\n**** Local spiller rewriting function '"
00329            << MF.getFunction()->getName() << "':\n";
00330       DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
00331               " ****\n";
00332       DEBUG(MF.dump());
00333 
00334       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
00335            MBB != E; ++MBB)
00336         RewriteMBB(*MBB, VRM);
00337 
00338       // Mark unused spill slots.
00339       MachineFrameInfo *MFI = MF.getFrameInfo();
00340       int SS = VRM.getLowSpillSlot();
00341       if (SS != VirtRegMap::NO_STACK_SLOT)
00342         for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
00343           if (!VRM.isSpillSlotUsed(SS)) {
00344             MFI->RemoveStackObject(SS);
00345             ++NumDSS;
00346           }
00347 
00348       DOUT << "**** Post Machine Instrs ****\n";
00349       DEBUG(MF.dump());
00350 
00351       return true;
00352     }
00353   private:
00354     void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
00355                           unsigned Reg, BitVector &RegKills,
00356                           std::vector<MachineOperand*> &KillOps);
00357     bool PrepForUnfoldOpti(MachineBasicBlock &MBB,
00358                            MachineBasicBlock::iterator &MII,
00359                            std::vector<MachineInstr*> &MaybeDeadStores,
00360                            AvailableSpills &Spills, BitVector &RegKills,
00361                            std::vector<MachineOperand*> &KillOps,
00362                            VirtRegMap &VRM);
00363     bool CommuteToFoldReload(MachineBasicBlock &MBB,
00364                              MachineBasicBlock::iterator &MII,
00365                              unsigned VirtReg, unsigned SrcReg, int SS,
00366                              BitVector &RegKills,
00367                              std::vector<MachineOperand*> &KillOps,
00368                              const TargetRegisterInfo *TRI,
00369                              VirtRegMap &VRM);
00370     void SpillRegToStackSlot(MachineBasicBlock &MBB,
00371                              MachineBasicBlock::iterator &MII,
00372                              int Idx, unsigned PhysReg, int StackSlot,
00373                              const TargetRegisterClass *RC,
00374                              bool isAvailable, MachineInstr *&LastStore,
00375                              AvailableSpills &Spills,
00376                              SmallSet<MachineInstr*, 4> &ReMatDefs,
00377                              BitVector &RegKills,
00378                              std::vector<MachineOperand*> &KillOps,
00379                              VirtRegMap &VRM);
00380     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
00381   };
00382 }
00383 
00384 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
00385 /// top down, keep track of which spills slots or remat are available in each
00386 /// register.
00387 ///
00388 /// Note that not all physregs are created equal here.  In particular, some
00389 /// physregs are reloads that we are allowed to clobber or ignore at any time.
00390 /// Other physregs are values that the register allocated program is using that
00391 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
00392 /// per-stack-slot / remat id basis as the low bit in the value of the
00393 /// SpillSlotsAvailable entries.  The predicate 'canClobberPhysReg()' checks
00394 /// this bit and addAvailable sets it if.
00395 namespace {
00396 class VISIBILITY_HIDDEN AvailableSpills {
00397   const TargetRegisterInfo *TRI;
00398   const TargetInstrInfo *TII;
00399 
00400   // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
00401   // or remat'ed virtual register values that are still available, due to being
00402   // loaded or stored to, but not invalidated yet.
00403   std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
00404     
00405   // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
00406   // indicating which stack slot values are currently held by a physreg.  This
00407   // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
00408   // physreg is modified.
00409   std::multimap<unsigned, int> PhysRegsAvailable;
00410   
00411   void disallowClobberPhysRegOnly(unsigned PhysReg);
00412 
00413   void ClobberPhysRegOnly(unsigned PhysReg);
00414 public:
00415   AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
00416     : TRI(tri), TII(tii) {
00417   }
00418   
00419   const TargetRegisterInfo *getRegInfo() const { return TRI; }
00420 
00421   /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
00422   /// available in a  physical register, return that PhysReg, otherwise
00423   /// return 0.
00424   unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
00425     std::map<int, unsigned>::const_iterator I =
00426       SpillSlotsOrReMatsAvailable.find(Slot);
00427     if (I != SpillSlotsOrReMatsAvailable.end()) {
00428       return I->second >> 1;  // Remove the CanClobber bit.
00429     }
00430     return 0;
00431   }
00432 
00433   /// addAvailable - Mark that the specified stack slot / remat is available in
00434   /// the specified physreg.  If CanClobber is true, the physreg can be modified
00435   /// at any time without changing the semantics of the program.
00436   void addAvailable(int SlotOrReMat, MachineInstr *MI, unsigned Reg,
00437                     bool CanClobber = true) {
00438     // If this stack slot is thought to be available in some other physreg, 
00439     // remove its record.
00440     ModifyStackSlotOrReMat(SlotOrReMat);
00441     
00442     PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
00443     SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) | (unsigned)CanClobber;
00444   
00445     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
00446       DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
00447     else
00448       DOUT << "Remembering SS#" << SlotOrReMat;
00449     DOUT << " in physreg " << TRI->getName(Reg) << "\n";
00450   }
00451 
00452   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
00453   /// value of the specified stackslot register if it desires.  The specified
00454   /// stack slot must be available in a physreg for this query to make sense.
00455   bool canClobberPhysReg(int SlotOrReMat) const {
00456     assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
00457            "Value not available!");
00458     return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
00459   }
00460 
00461   /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
00462   /// stackslot register. The register is still available but is no longer
00463   /// allowed to be modifed.
00464   void disallowClobberPhysReg(unsigned PhysReg);
00465   
00466   /// ClobberPhysReg - This is called when the specified physreg changes
00467   /// value.  We use this to invalidate any info about stuff that lives in
00468   /// it and any of its aliases.
00469   void ClobberPhysReg(unsigned PhysReg);
00470 
00471   /// ModifyStackSlotOrReMat - This method is called when the value in a stack
00472   /// slot changes.  This removes information about which register the previous
00473   /// value for this slot lives in (as the previous value is dead now).
00474   void ModifyStackSlotOrReMat(int SlotOrReMat);
00475 };
00476 }
00477 
00478 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
00479 /// stackslot register. The register is still available but is no longer
00480 /// allowed to be modifed.
00481 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
00482   std::multimap<unsigned, int>::iterator I =
00483     PhysRegsAvailable.lower_bound(PhysReg);
00484   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
00485     int SlotOrReMat = I->second;
00486     I++;
00487     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
00488            "Bidirectional map mismatch!");
00489     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
00490     DOUT << "PhysReg " << TRI->getName(PhysReg)
00491          << " copied, it is available for use but can no longer be modified\n";
00492   }
00493 }
00494 
00495 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
00496 /// stackslot register and its aliases. The register and its aliases may
00497 /// still available but is no longer allowed to be modifed.
00498 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
00499   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
00500     disallowClobberPhysRegOnly(*AS);
00501   disallowClobberPhysRegOnly(PhysReg);
00502 }
00503 
00504 /// ClobberPhysRegOnly - This is called when the specified physreg changes
00505 /// value.  We use this to invalidate any info about stuff we thing lives in it.
00506 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
00507   std::multimap<unsigned, int>::iterator I =
00508     PhysRegsAvailable.lower_bound(PhysReg);
00509   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
00510     int SlotOrReMat = I->second;
00511     PhysRegsAvailable.erase(I++);
00512     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
00513            "Bidirectional map mismatch!");
00514     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
00515     DOUT << "PhysReg " << TRI->getName(PhysReg)
00516          << " clobbered, invalidating ";
00517     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
00518       DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
00519     else
00520       DOUT << "SS#" << SlotOrReMat << "\n";
00521   }
00522 }
00523 
00524 /// ClobberPhysReg - This is called when the specified physreg changes
00525 /// value.  We use this to invalidate any info about stuff we thing lives in
00526 /// it and any of its aliases.
00527 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
00528   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
00529     ClobberPhysRegOnly(*AS);
00530   ClobberPhysRegOnly(PhysReg);
00531 }
00532 
00533 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
00534 /// slot changes.  This removes information about which register the previous
00535 /// value for this slot lives in (as the previous value is dead now).
00536 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
00537   std::map<int, unsigned>::iterator It =
00538     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
00539   if (It == SpillSlotsOrReMatsAvailable.end()) return;
00540   unsigned Reg = It->second >> 1;
00541   SpillSlotsOrReMatsAvailable.erase(It);
00542   
00543   // This register may hold the value of multiple stack slots, only remove this
00544   // stack slot from the set of values the register contains.
00545   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
00546   for (; ; ++I) {
00547     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
00548            "Map inverse broken!");
00549     if (I->second == SlotOrReMat) break;
00550   }
00551   PhysRegsAvailable.erase(I);
00552 }
00553 
00554 
00555 
00556 /// InvalidateKills - MI is going to be deleted. If any of its operands are
00557 /// marked kill, then invalidate the information.
00558 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
00559                             std::vector<MachineOperand*> &KillOps,
00560                             SmallVector<unsigned, 2> *KillRegs = NULL) {
00561   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00562     MachineOperand &MO = MI.getOperand(i);
00563     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
00564       continue;
00565     unsigned Reg = MO.getReg();
00566     if (TargetRegisterInfo::isVirtualRegister(Reg))
00567       continue;
00568     if (KillRegs)
00569       KillRegs->push_back(Reg);
00570     assert(Reg < KillOps.size());
00571     if (KillOps[Reg] == &MO) {
00572       RegKills.reset(Reg);
00573       KillOps[Reg] = NULL;
00574     }
00575   }
00576 }
00577 
00578 /// InvalidateKill - A MI that defines the specified register is being deleted,
00579 /// invalidate the register kill information.
00580 static void InvalidateKill(unsigned Reg, BitVector &RegKills,
00581                            std::vector<MachineOperand*> &KillOps) {
00582   if (RegKills[Reg]) {
00583     KillOps[Reg]->setIsKill(false);
00584     KillOps[Reg] = NULL;
00585     RegKills.reset(Reg);
00586   }
00587 }
00588 
00589 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
00590 /// (since it's spill instruction is removed), mark it isDead. Also checks if
00591 /// the def MI has other definition operands that are not dead. Returns it by
00592 /// reference.
00593 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
00594                              MachineInstr &NewDef, unsigned Reg,
00595                              bool &HasLiveDef) {
00596   // Due to remat, it's possible this reg isn't being reused. That is,
00597   // the def of this reg (by prev MI) is now dead.
00598   MachineInstr *DefMI = I;
00599   MachineOperand *DefOp = NULL;
00600   for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
00601     MachineOperand &MO = DefMI->getOperand(i);
00602     if (MO.isReg() && MO.isDef()) {
00603       if (MO.getReg() == Reg)
00604         DefOp = &MO;
00605       else if (!MO.isDead())
00606         HasLiveDef = true;
00607     }
00608   }
00609   if (!DefOp)
00610     return false;
00611 
00612   bool FoundUse = false, Done = false;
00613   MachineBasicBlock::iterator E = &NewDef;
00614   ++I; ++E;
00615   for (; !Done && I != E; ++I) {
00616     MachineInstr *NMI = I;
00617     for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
00618       MachineOperand &MO = NMI->getOperand(j);
00619       if (!MO.isReg() || MO.getReg() != Reg)
00620         continue;
00621       if (MO.isUse())
00622         FoundUse = true;
00623       Done = true; // Stop after scanning all the operands of this MI.
00624     }
00625   }
00626   if (!FoundUse) {
00627     // Def is dead!
00628     DefOp->setIsDead();
00629     return true;
00630   }
00631   return false;
00632 }
00633 
00634 /// UpdateKills - Track and update kill info. If a MI reads a register that is
00635 /// marked kill, then it must be due to register reuse. Transfer the kill info
00636 /// over.
00637 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
00638                         std::vector<MachineOperand*> &KillOps,
00639                         const TargetRegisterInfo* TRI) {
00640   const TargetInstrDesc &TID = MI.getDesc();
00641   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00642     MachineOperand &MO = MI.getOperand(i);
00643     if (!MO.isReg() || !MO.isUse())
00644       continue;
00645     unsigned Reg = MO.getReg();
00646     if (Reg == 0)
00647       continue;
00648     
00649     if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
00650       // That can't be right. Register is killed but not re-defined and it's
00651       // being reused. Let's fix that.
00652       KillOps[Reg]->setIsKill(false);
00653       KillOps[Reg] = NULL;
00654       RegKills.reset(Reg);
00655       if (i < TID.getNumOperands() &&
00656           TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
00657         // Unless it's a two-address operand, this is the new kill.
00658         MO.setIsKill();
00659     }
00660     if (MO.isKill()) {
00661       RegKills.set(Reg);
00662       KillOps[Reg] = &MO;
00663     }
00664   }
00665 
00666   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00667     const MachineOperand &MO = MI.getOperand(i);
00668     if (!MO.isReg() || !MO.isDef())
00669       continue;
00670     unsigned Reg = MO.getReg();
00671     RegKills.reset(Reg);
00672     KillOps[Reg] = NULL;
00673     // It also defines (or partially define) aliases.
00674     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
00675       RegKills.reset(*AS);
00676       KillOps[*AS] = NULL;
00677     }
00678   }
00679 }
00680 
00681 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
00682 ///
00683 static void ReMaterialize(MachineBasicBlock &MBB,
00684                           MachineBasicBlock::iterator &MII,
00685                           unsigned DestReg, unsigned Reg,
00686                           const TargetInstrInfo *TII,
00687                           const TargetRegisterInfo *TRI,
00688                           VirtRegMap &VRM) {
00689   TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
00690   MachineInstr *NewMI = prior(MII);
00691   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
00692     MachineOperand &MO = NewMI->getOperand(i);
00693     if (!MO.isReg() || MO.getReg() == 0)
00694       continue;
00695     unsigned VirtReg = MO.getReg();
00696     if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
00697       continue;
00698     assert(MO.isUse());
00699     unsigned SubIdx = MO.getSubReg();
00700     unsigned Phys = VRM.getPhys(VirtReg);
00701     assert(Phys);
00702     unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
00703     MO.setReg(RReg);
00704   }
00705   ++NumReMats;
00706 }
00707 
00708 
00709 // ReusedOp - For each reused operand, we keep track of a bit of information, in
00710 // case we need to rollback upon processing a new operand.  See comments below.
00711 namespace {
00712   struct ReusedOp {
00713     // The MachineInstr operand that reused an available value.
00714     unsigned Operand;
00715 
00716     // StackSlotOrReMat - The spill slot or remat id of the value being reused.
00717     unsigned StackSlotOrReMat;
00718 
00719     // PhysRegReused - The physical register the value was available in.
00720     unsigned PhysRegReused;
00721 
00722     // AssignedPhysReg - The physreg that was assigned for use by the reload.
00723     unsigned AssignedPhysReg;
00724     
00725     // VirtReg - The virtual register itself.
00726     unsigned VirtReg;
00727 
00728     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
00729              unsigned vreg)
00730       : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
00731         AssignedPhysReg(apr), VirtReg(vreg) {}
00732   };
00733   
00734   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
00735   /// is reused instead of reloaded.
00736   class VISIBILITY_HIDDEN ReuseInfo {
00737     MachineInstr &MI;
00738     std::vector<ReusedOp> Reuses;
00739     BitVector PhysRegsClobbered;
00740   public:
00741     ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
00742       PhysRegsClobbered.resize(tri->getNumRegs());
00743     }
00744     
00745     bool hasReuses() const {
00746       return !Reuses.empty();
00747     }
00748     
00749     /// addReuse - If we choose to reuse a virtual register that is already
00750     /// available instead of reloading it, remember that we did so.
00751     void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
00752                   unsigned PhysRegReused, unsigned AssignedPhysReg,
00753                   unsigned VirtReg) {
00754       // If the reload is to the assigned register anyway, no undo will be
00755       // required.
00756       if (PhysRegReused == AssignedPhysReg) return;
00757       
00758       // Otherwise, remember this.
00759       Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused, 
00760                                 AssignedPhysReg, VirtReg));
00761     }
00762 
00763     void markClobbered(unsigned PhysReg) {
00764       PhysRegsClobbered.set(PhysReg);
00765     }
00766 
00767     bool isClobbered(unsigned PhysReg) const {
00768       return PhysRegsClobbered.test(PhysReg);
00769     }
00770     
00771     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
00772     /// is some other operand that is using the specified register, either pick
00773     /// a new register to use, or evict the previous reload and use this reg. 
00774     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
00775                              AvailableSpills &Spills,
00776                              std::vector<MachineInstr*> &MaybeDeadStores,
00777                              SmallSet<unsigned, 8> &Rejected,
00778                              BitVector &RegKills,
00779                              std::vector<MachineOperand*> &KillOps,
00780                              VirtRegMap &VRM) {
00781       const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
00782                                    .getInstrInfo();
00783       
00784       if (Reuses.empty()) return PhysReg;  // This is most often empty.
00785 
00786       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
00787         ReusedOp &Op = Reuses[ro];
00788         // If we find some other reuse that was supposed to use this register
00789         // exactly for its reload, we can change this reload to use ITS reload
00790         // register. That is, unless its reload register has already been
00791         // considered and subsequently rejected because it has also been reused
00792         // by another operand.
00793         if (Op.PhysRegReused == PhysReg &&
00794             Rejected.count(Op.AssignedPhysReg) == 0) {
00795           // Yup, use the reload register that we didn't use before.
00796           unsigned NewReg = Op.AssignedPhysReg;
00797           Rejected.insert(PhysReg);
00798           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
00799                                  RegKills, KillOps, VRM);
00800         } else {
00801           // Otherwise, we might also have a problem if a previously reused
00802           // value aliases the new register.  If so, codegen the previous reload
00803           // and use this one.          
00804           unsigned PRRU = Op.PhysRegReused;
00805           const TargetRegisterInfo *TRI = Spills.getRegInfo();
00806           if (TRI->areAliases(PRRU, PhysReg)) {
00807             // Okay, we found out that an alias of a reused register
00808             // was used.  This isn't good because it means we have
00809             // to undo a previous reuse.
00810             MachineBasicBlock *MBB = MI->getParent();
00811             const TargetRegisterClass *AliasRC =
00812               MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
00813 
00814             // Copy Op out of the vector and remove it, we're going to insert an
00815             // explicit load for it.
00816             ReusedOp NewOp = Op;
00817             Reuses.erase(Reuses.begin()+ro);
00818 
00819             // Ok, we're going to try to reload the assigned physreg into the
00820             // slot that we were supposed to in the first place.  However, that
00821             // register could hold a reuse.  Check to see if it conflicts or
00822             // would prefer us to use a different register.
00823             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
00824                                                   MI, Spills, MaybeDeadStores,
00825                                               Rejected, RegKills, KillOps, VRM);
00826             
00827             MachineBasicBlock::iterator MII = MI;
00828             if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
00829               ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
00830             } else {
00831               TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
00832                                         NewOp.StackSlotOrReMat, AliasRC);
00833               MachineInstr *LoadMI = prior(MII);
00834               VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
00835               // Any stores to this stack slot are not dead anymore.
00836               MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;            
00837               ++NumLoads;
00838             }
00839             Spills.ClobberPhysReg(NewPhysReg);
00840             Spills.ClobberPhysReg(NewOp.PhysRegReused);
00841 
00842             unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
00843             unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
00844             MI->getOperand(NewOp.Operand).setReg(RReg);
00845             
00846             Spills.addAvailable(NewOp.StackSlotOrReMat, MI, NewPhysReg);
00847             --MII;
00848             UpdateKills(*MII, RegKills, KillOps, TRI);
00849             DOUT << '\t' << *MII;
00850             
00851             DOUT << "Reuse undone!\n";
00852             --NumReused;
00853             
00854             // Finally, PhysReg is now available, go ahead and use it.
00855             return PhysReg;
00856           }
00857         }
00858       }
00859       return PhysReg;
00860     }
00861 
00862     /// GetRegForReload - Helper for the above GetRegForReload(). Add a
00863     /// 'Rejected' set to remember which registers have been considered and
00864     /// rejected for the reload. This avoids infinite looping in case like
00865     /// this:
00866     /// t1 := op t2, t3
00867     /// t2 <- assigned r0 for use by the reload but ended up reuse r1
00868     /// t3 <- assigned r1 for use by the reload but ended up reuse r0
00869     /// t1 <- desires r1
00870     ///       sees r1 is taken by t2, tries t2's reload register r0
00871     ///       sees r0 is taken by t3, tries t3's reload register r1
00872     ///       sees r1 is taken by t2, tries t2's reload register r0 ...
00873     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
00874                              AvailableSpills &Spills,
00875                              std::vector<MachineInstr*> &MaybeDeadStores,
00876                              BitVector &RegKills,
00877                              std::vector<MachineOperand*> &KillOps,
00878                              VirtRegMap &VRM) {
00879       SmallSet<unsigned, 8> Rejected;
00880       return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
00881                              RegKills, KillOps, VRM);
00882     }
00883   };
00884 }
00885 
00886 /// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
00887 /// instruction. e.g.
00888 ///     xorl  %edi, %eax
00889 ///     movl  %eax, -32(%ebp)
00890 ///     movl  -36(%ebp), %eax
00891 ///     orl   %eax, -32(%ebp)
00892 /// ==>
00893 ///     xorl  %edi, %eax
00894 ///     orl   -36(%ebp), %eax
00895 ///     mov   %eax, -32(%ebp)
00896 /// This enables unfolding optimization for a subsequent instruction which will
00897 /// also eliminate the newly introduced store instruction.
00898 bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
00899                                     MachineBasicBlock::iterator &MII,
00900                                     std::vector<MachineInstr*> &MaybeDeadStores,
00901                                     AvailableSpills &Spills,
00902                                     BitVector &RegKills,
00903                                     std::vector<MachineOperand*> &KillOps,
00904                                     VirtRegMap &VRM) {
00905   MachineFunction &MF = *MBB.getParent();
00906   MachineInstr &MI = *MII;
00907   unsigned UnfoldedOpc = 0;
00908   unsigned UnfoldPR = 0;
00909   unsigned UnfoldVR = 0;
00910   int FoldedSS = VirtRegMap::NO_STACK_SLOT;
00911   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
00912   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
00913     // Only transform a