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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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/SSARegMap.h"
00025 #include "llvm/Target/TargetMachine.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/Visibility.h"
00030 #include "llvm/ADT/Statistic.h"
00031 #include "llvm/ADT/STLExtras.h"
00032 #include <algorithm>
00033 #include <iostream>
00034 using namespace llvm;
00035 
00036 namespace {
00037   static Statistic<> NumSpills("spiller", "Number of register spills");
00038   static Statistic<> NumStores("spiller", "Number of stores added");
00039   static Statistic<> NumLoads ("spiller", "Number of loads added");
00040   static Statistic<> NumReused("spiller", "Number of values reused");
00041   static Statistic<> NumDSE   ("spiller", "Number of dead stores elided");
00042   static Statistic<> NumDCE   ("spiller", "Number of copies elided");
00043 
00044   enum SpillerName { simple, local };
00045 
00046   static cl::opt<SpillerName>
00047   SpillerOpt("spiller",
00048              cl::desc("Spiller to use: (default: local)"),
00049              cl::Prefix,
00050              cl::values(clEnumVal(simple, "  simple spiller"),
00051                         clEnumVal(local,  "  local spiller"),
00052                         clEnumValEnd),
00053              cl::init(local));
00054 }
00055 
00056 //===----------------------------------------------------------------------===//
00057 //  VirtRegMap implementation
00058 //===----------------------------------------------------------------------===//
00059 
00060 void VirtRegMap::grow() {
00061   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
00062   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
00063 }
00064 
00065 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
00066   assert(MRegisterInfo::isVirtualRegister(virtReg));
00067   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
00068          "attempt to assign stack slot to already spilled register");
00069   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
00070   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
00071                                                         RC->getAlignment());
00072   Virt2StackSlotMap[virtReg] = frameIndex;
00073   ++NumSpills;
00074   return frameIndex;
00075 }
00076 
00077 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
00078   assert(MRegisterInfo::isVirtualRegister(virtReg));
00079   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
00080          "attempt to assign stack slot to already spilled register");
00081   Virt2StackSlotMap[virtReg] = frameIndex;
00082 }
00083 
00084 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
00085                             unsigned OpNo, MachineInstr *NewMI) {
00086   // Move previous memory references folded to new instruction.
00087   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
00088   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
00089          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
00090     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
00091     MI2VirtMap.erase(I++);
00092   }
00093 
00094   ModRef MRInfo;
00095   if (!OldMI->getOperand(OpNo).isDef()) {
00096     assert(OldMI->getOperand(OpNo).isUse() && "Operand is not use or def?");
00097     MRInfo = isRef;
00098   } else {
00099     MRInfo = OldMI->getOperand(OpNo).isUse() ? isModRef : isMod;
00100   }
00101 
00102   // add new memory reference
00103   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
00104 }
00105 
00106 void VirtRegMap::print(std::ostream &OS) const {
00107   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
00108 
00109   OS << "********** REGISTER MAP **********\n";
00110   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
00111          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
00112     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
00113       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
00114 
00115   }
00116 
00117   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
00118          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
00119     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
00120       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
00121   OS << '\n';
00122 }
00123 
00124 void VirtRegMap::dump() const { print(std::cerr); }
00125 
00126 
00127 //===----------------------------------------------------------------------===//
00128 // Simple Spiller Implementation
00129 //===----------------------------------------------------------------------===//
00130 
00131 Spiller::~Spiller() {}
00132 
00133 namespace {
00134   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
00135     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
00136   };
00137 }
00138 
00139 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
00140   DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
00141   DEBUG(std::cerr << "********** Function: "
00142                   << MF.getFunction()->getName() << '\n');
00143   const TargetMachine &TM = MF.getTarget();
00144   const MRegisterInfo &MRI = *TM.getRegisterInfo();
00145   bool *PhysRegsUsed = MF.getUsedPhysregs();
00146 
00147   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
00148   // each vreg once (in the case where a spilled vreg is used by multiple
00149   // operands).  This is always smaller than the number of operands to the
00150   // current machine instr, so it should be small.
00151   std::vector<unsigned> LoadedRegs;
00152 
00153   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
00154        MBBI != E; ++MBBI) {
00155     DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
00156     MachineBasicBlock &MBB = *MBBI;
00157     for (MachineBasicBlock::iterator MII = MBB.begin(),
00158            E = MBB.end(); MII != E; ++MII) {
00159       MachineInstr &MI = *MII;
00160       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00161         MachineOperand &MO = MI.getOperand(i);
00162         if (MO.isRegister() && MO.getReg())
00163           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
00164             unsigned VirtReg = MO.getReg();
00165             unsigned PhysReg = VRM.getPhys(VirtReg);
00166             if (VRM.hasStackSlot(VirtReg)) {
00167               int StackSlot = VRM.getStackSlot(VirtReg);
00168               const TargetRegisterClass* RC =
00169                 MF.getSSARegMap()->getRegClass(VirtReg);
00170 
00171               if (MO.isUse() &&
00172                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
00173                   == LoadedRegs.end()) {
00174                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
00175                 LoadedRegs.push_back(VirtReg);
00176                 ++NumLoads;
00177                 DEBUG(std::cerr << '\t' << *prior(MII));
00178               }
00179 
00180               if (MO.isDef()) {
00181                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
00182                 ++NumStores;
00183               }
00184             }
00185             PhysRegsUsed[PhysReg] = true;
00186             MI.getOperand(i).setReg(PhysReg);
00187           } else {
00188             PhysRegsUsed[MO.getReg()] = true;
00189           }
00190       }
00191 
00192       DEBUG(std::cerr << '\t' << MI);
00193       LoadedRegs.clear();
00194     }
00195   }
00196   return true;
00197 }
00198 
00199 //===----------------------------------------------------------------------===//
00200 //  Local Spiller Implementation
00201 //===----------------------------------------------------------------------===//
00202 
00203 namespace {
00204   /// LocalSpiller - This spiller does a simple pass over the machine basic
00205   /// block to attempt to keep spills in registers as much as possible for
00206   /// blocks that have low register pressure (the vreg may be spilled due to
00207   /// register pressure in other blocks).
00208   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
00209     const MRegisterInfo *MRI;
00210     const TargetInstrInfo *TII;
00211   public:
00212     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
00213       MRI = MF.getTarget().getRegisterInfo();
00214       TII = MF.getTarget().getInstrInfo();
00215       DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
00216                       << MF.getFunction()->getName() << "':\n");
00217 
00218       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
00219            MBB != E; ++MBB)
00220         RewriteMBB(*MBB, VRM);
00221       return true;
00222     }
00223   private:
00224     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
00225     void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
00226                         std::multimap<unsigned, int> &PhysRegs);
00227     void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
00228                             std::multimap<unsigned, int> &PhysRegs);
00229     void ModifyStackSlot(int Slot, std::map<int, unsigned> &SpillSlots,
00230                          std::multimap<unsigned, int> &PhysRegs);
00231   };
00232 }
00233 
00234 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
00235 /// top down, keep track of which spills slots are available in each register.
00236 ///
00237 /// Note that not all physregs are created equal here.  In particular, some
00238 /// physregs are reloads that we are allowed to clobber or ignore at any time.
00239 /// Other physregs are values that the register allocated program is using that
00240 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
00241 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
00242 /// entries.  The predicate 'canClobberPhysReg()' checks this bit and
00243 /// addAvailable sets it if.
00244 namespace {
00245 class VISIBILITY_HIDDEN AvailableSpills {
00246   const MRegisterInfo *MRI;
00247   const TargetInstrInfo *TII;
00248 
00249   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
00250   // register values that are still available, due to being loaded or stored to,
00251   // but not invalidated yet.
00252   std::map<int, unsigned> SpillSlotsAvailable;
00253     
00254   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
00255   // which stack slot values are currently held by a physreg.  This is used to
00256   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
00257   std::multimap<unsigned, int> PhysRegsAvailable;
00258   
00259   void ClobberPhysRegOnly(unsigned PhysReg);
00260 public:
00261   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
00262     : MRI(mri), TII(tii) {
00263   }
00264   
00265   /// getSpillSlotPhysReg - If the specified stack slot is available in a 
00266   /// physical register, return that PhysReg, otherwise return 0.
00267   unsigned getSpillSlotPhysReg(int Slot) const {
00268     std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
00269     if (I != SpillSlotsAvailable.end())
00270       return I->second >> 1;  // Remove the CanClobber bit.
00271     return 0;
00272   }
00273   
00274   const MRegisterInfo *getRegInfo() const { return MRI; }
00275 
00276   /// addAvailable - Mark that the specified stack slot is available in the
00277   /// specified physreg.  If CanClobber is true, the physreg can be modified at
00278   /// any time without changing the semantics of the program.
00279   void addAvailable(int Slot, unsigned Reg, bool CanClobber = true) {
00280     // If this stack slot is thought to be available in some other physreg, 
00281     // remove its record.
00282     ModifyStackSlot(Slot);
00283     
00284     PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
00285     SpillSlotsAvailable[Slot] = (Reg << 1) | (unsigned)CanClobber;
00286   
00287     DEBUG(std::cerr << "Remembering SS#" << Slot << " in physreg "
00288                     << MRI->getName(Reg) << "\n");
00289   }
00290   
00291   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
00292   /// value of the specified stackslot register if it desires.  The specified
00293   /// stack slot must be available in a physreg for this query to make sense.
00294   bool canClobberPhysReg(int Slot) const {
00295     assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
00296     return SpillSlotsAvailable.find(Slot)->second & 1;
00297   }
00298   
00299   /// ClobberPhysReg - This is called when the specified physreg changes
00300   /// value.  We use this to invalidate any info about stuff we thing lives in
00301   /// it and any of its aliases.
00302   void ClobberPhysReg(unsigned PhysReg);
00303 
00304   /// ModifyStackSlot - This method is called when the value in a stack slot
00305   /// changes.  This removes information about which register the previous value
00306   /// for this slot lives in (as the previous value is dead now).
00307   void ModifyStackSlot(int Slot);
00308 };
00309 }
00310 
00311 /// ClobberPhysRegOnly - This is called when the specified physreg changes
00312 /// value.  We use this to invalidate any info about stuff we thing lives in it.
00313 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
00314   std::multimap<unsigned, int>::iterator I =
00315     PhysRegsAvailable.lower_bound(PhysReg);
00316   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
00317     int Slot = I->second;
00318     PhysRegsAvailable.erase(I++);
00319     assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
00320            "Bidirectional map mismatch!");
00321     SpillSlotsAvailable.erase(Slot);
00322     DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
00323                     << " clobbered, invalidating SS#" << Slot << "\n");
00324   }
00325 }
00326 
00327 /// ClobberPhysReg - This is called when the specified physreg changes
00328 /// value.  We use this to invalidate any info about stuff we thing lives in
00329 /// it and any of its aliases.
00330 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
00331   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
00332     ClobberPhysRegOnly(*AS);
00333   ClobberPhysRegOnly(PhysReg);
00334 }
00335 
00336 /// ModifyStackSlot - This method is called when the value in a stack slot
00337 /// changes.  This removes information about which register the previous value
00338 /// for this slot lives in (as the previous value is dead now).
00339 void AvailableSpills::ModifyStackSlot(int Slot) {
00340   std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
00341   if (It == SpillSlotsAvailable.end()) return;
00342   unsigned Reg = It->second >> 1;
00343   SpillSlotsAvailable.erase(It);
00344   
00345   // This register may hold the value of multiple stack slots, only remove this
00346   // stack slot from the set of values the register contains.
00347   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
00348   for (; ; ++I) {
00349     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
00350            "Map inverse broken!");
00351     if (I->second == Slot) break;
00352   }
00353   PhysRegsAvailable.erase(I);
00354 }
00355 
00356 
00357 
00358 // ReusedOp - For each reused operand, we keep track of a bit of information, in
00359 // case we need to rollback upon processing a new operand.  See comments below.
00360 namespace {
00361   struct ReusedOp {
00362     // The MachineInstr operand that reused an available value.
00363     unsigned Operand;
00364 
00365     // StackSlot - The spill slot of the value being reused.
00366     unsigned StackSlot;
00367 
00368     // PhysRegReused - The physical register the value was available in.
00369     unsigned PhysRegReused;
00370 
00371     // AssignedPhysReg - The physreg that was assigned for use by the reload.
00372     unsigned AssignedPhysReg;
00373     
00374     // VirtReg - The virtual register itself.
00375     unsigned VirtReg;
00376 
00377     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
00378              unsigned vreg)
00379       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
00380       VirtReg(vreg) {}
00381   };
00382   
00383   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
00384   /// is reused instead of reloaded.
00385   class VISIBILITY_HIDDEN ReuseInfo {
00386     MachineInstr &MI;
00387     std::vector<ReusedOp> Reuses;
00388   public:
00389     ReuseInfo(MachineInstr &mi) : MI(mi) {}
00390     
00391     bool hasReuses() const {
00392       return !Reuses.empty();
00393     }
00394     
00395     /// addReuse - If we choose to reuse a virtual register that is already
00396     /// available instead of reloading it, remember that we did so.
00397     void addReuse(unsigned OpNo, unsigned StackSlot,
00398                   unsigned PhysRegReused, unsigned AssignedPhysReg,
00399                   unsigned VirtReg) {
00400       // If the reload is to the assigned register anyway, no undo will be
00401       // required.
00402       if (PhysRegReused == AssignedPhysReg) return;
00403       
00404       // Otherwise, remember this.
00405       Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused, 
00406                                 AssignedPhysReg, VirtReg));
00407     }
00408     
00409     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
00410     /// is some other operand that is using the specified register, either pick
00411     /// a new register to use, or evict the previous reload and use this reg. 
00412     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
00413                              AvailableSpills &Spills,
00414                              std::map<int, MachineInstr*> &MaybeDeadStores) {
00415       if (Reuses.empty()) return PhysReg;  // This is most often empty.
00416 
00417       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
00418         ReusedOp &Op = Reuses[ro];
00419         // If we find some other reuse that was supposed to use this register
00420         // exactly for its reload, we can change this reload to use ITS reload
00421         // register.
00422         if (Op.PhysRegReused == PhysReg) {
00423           // Yup, use the reload register that we didn't use before.
00424           unsigned NewReg = Op.AssignedPhysReg;
00425           
00426           // Remove the record for the previous reuse.  We know it can never be
00427           // invalidated now.
00428           Reuses.erase(Reuses.begin()+ro);
00429           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores);
00430         } else {
00431           // Otherwise, we might also have a problem if a previously reused
00432           // value aliases the new register.  If so, codegen the previous reload
00433           // and use this one.          
00434           unsigned PRRU = Op.PhysRegReused;
00435           const MRegisterInfo *MRI = Spills.getRegInfo();
00436           if (MRI->areAliases(PRRU, PhysReg)) {
00437             // Okay, we found out that an alias of a reused register
00438             // was used.  This isn't good because it means we have
00439             // to undo a previous reuse.
00440             MachineBasicBlock *MBB = MI->getParent();
00441             const TargetRegisterClass *AliasRC =
00442               MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
00443 
00444             // Copy Op out of the vector and remove it, we're going to insert an
00445             // explicit load for it.
00446             ReusedOp NewOp = Op;
00447             Reuses.erase(Reuses.begin()+ro);
00448 
00449             // Ok, we're going to try to reload the assigned physreg into the
00450             // slot that we were supposed to in the first place.  However, that
00451             // register could hold a reuse.  Check to see if it conflicts or
00452             // would prefer us to use a different register.
00453             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
00454                                                   MI, Spills, MaybeDeadStores);
00455             
00456             MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
00457                                       NewOp.StackSlot, AliasRC);
00458             Spills.ClobberPhysReg(NewPhysReg);
00459             Spills.ClobberPhysReg(NewOp.PhysRegReused);
00460             
00461             // Any stores to this stack slot are not dead anymore.
00462             MaybeDeadStores.erase(NewOp.StackSlot);
00463             
00464             MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
00465             
00466             Spills.addAvailable(NewOp.StackSlot, NewPhysReg);
00467             ++NumLoads;
00468             DEBUG(MachineBasicBlock::iterator MII = MI;
00469                   std::cerr << '\t' << *prior(MII));
00470             
00471             DEBUG(std::cerr << "Reuse undone!\n");
00472             --NumReused;
00473             
00474             // Finally, PhysReg is now available, go ahead and use it.
00475             return PhysReg;
00476           }
00477         }
00478       }
00479       return PhysReg;
00480     }
00481   };
00482 }
00483 
00484 
00485 /// rewriteMBB - Keep track of which spills are available even after the
00486 /// register allocator is done with them.  If possible, avoid reloading vregs.
00487 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
00488 
00489   DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
00490 
00491   // Spills - Keep track of which spilled values are available in physregs so
00492   // that we can choose to reuse the physregs instead of emitting reloads.
00493   AvailableSpills Spills(MRI, TII);
00494   
00495   // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
00496   // of it.  ".first" is the machine operand index (should always be 0 for now),
00497   // and ".second" is the virtual register that is spilled.
00498   std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
00499 
00500   // MaybeDeadStores - When we need to write a value back into a stack slot,
00501   // keep track of the inserted store.  If the stack slot value is never read
00502   // (because the value was used from some available register, for example), and
00503   // subsequently stored to, the original store is dead.  This map keeps track
00504   // of inserted stores that are not used.  If we see a subsequent store to the
00505   // same stack slot, the original store is deleted.
00506   std::map<int, MachineInstr*> MaybeDeadStores;
00507 
00508   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
00509 
00510   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
00511        MII != E; ) {
00512     MachineInstr &MI = *MII;
00513     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
00514 
00515     /// ReusedOperands - Keep track of operand reuse in case we need to undo
00516     /// reuse.
00517     ReuseInfo ReusedOperands(MI);
00518     
00519     DefAndUseVReg.clear();
00520 
00521     // Process all of the spilled uses and all non spilled reg references.
00522     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00523       MachineOperand &MO = MI.getOperand(i);
00524       if (!MO.isRegister() || MO.getReg() == 0)
00525         continue;   // Ignore non-register operands.
00526       
00527       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
00528         // Ignore physregs for spilling, but remember that it is used by this
00529         // function.
00530         PhysRegsUsed[MO.getReg()] = true;
00531         continue;
00532       }
00533       
00534       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
00535              "Not a virtual or a physical register?");
00536       
00537       unsigned VirtReg = MO.getReg();
00538       if (!VRM.hasStackSlot(VirtReg)) {
00539         // This virtual register was assigned a physreg!
00540         unsigned Phys = VRM.getPhys(VirtReg);
00541         PhysRegsUsed[Phys] = true;
00542         MI.getOperand(i).setReg(Phys);
00543         continue;
00544       }
00545       
00546       // This virtual register is now known to be a spilled value.
00547       if (!MO.isUse())
00548         continue;  // Handle defs in the loop below (handle use&def here though)
00549 
00550       // If this is both a def and a use, we need to emit a store to the
00551       // stack slot after the instruction.  Keep track of D&U operands
00552       // because we are about to change it to a physreg here.
00553       if (MO.isDef()) {
00554         // Remember that this was a def-and-use operand, and that the
00555         // stack slot is live after this instruction executes.
00556         DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
00557       }
00558       
00559       int StackSlot = VRM.getStackSlot(VirtReg);
00560       unsigned PhysReg;
00561 
00562       // Check to see if this stack slot is available.
00563       if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot))) {
00564 
00565         // Don't reuse it for a def&use operand if we aren't allowed to change
00566         // the physreg!
00567         if (!MO.isDef() || Spills.canClobberPhysReg(StackSlot)) {
00568           // If this stack slot value is already available, reuse it!
00569           DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
00570                           << MRI->getName(PhysReg) << " for vreg"
00571                           << VirtReg <<" instead of reloading into physreg "
00572                           << MRI->getName(VRM.getPhys(VirtReg)) << "\n");
00573           MI.getOperand(i).setReg(PhysReg);
00574 
00575           // The only technical detail we have is that we don't know that
00576           // PhysReg won't be clobbered by a reloaded stack slot that occurs
00577           // later in the instruction.  In particular, consider 'op V1, V2'.
00578           // If V1 is available in physreg R0, we would choose to reuse it
00579           // here, instead of reloading it into the register the allocator
00580           // indicated (say R1).  However, V2 might have to be reloaded
00581           // later, and it might indicate that it needs to live in R0.  When
00582           // this occurs, we need to have information available that
00583           // indicates it is safe to use R1 for the reload instead of R0.
00584           //
00585           // To further complicate matters, we might conflict with an alias,
00586           // or R0 and R1 might not be compatible with each other.  In this
00587           // case, we actually insert a reload for V1 in R1, ensuring that
00588           // we can get at R0 or its alias.
00589           ReusedOperands.addReuse(i, StackSlot, PhysReg,
00590                                   VRM.getPhys(VirtReg), VirtReg);
00591           ++NumReused;
00592           continue;
00593         }
00594         
00595         // Otherwise we have a situation where we have a two-address instruction
00596         // whose mod/ref operand needs to be reloaded.  This reload is already
00597         // available in some register "PhysReg", but if we used PhysReg as the
00598         // operand to our 2-addr instruction, the instruction would modify
00599         // PhysReg.  This isn't cool if something later uses PhysReg and expects
00600         // to get its initial value.
00601         //
00602         // To avoid this problem, and to avoid doing a load right after a store,
00603         // we emit a copy from PhysReg into the designated register for this
00604         // operand.
00605         unsigned DesignatedReg = VRM.getPhys(VirtReg);
00606         assert(DesignatedReg && "Must map virtreg to physreg!");
00607 
00608         // Note that, if we reused a register for a previous operand, the
00609         // register we want to reload into might not actually be
00610         // available.  If this occurs, use the register indicated by the
00611         // reuser.
00612         if (ReusedOperands.hasReuses())
00613           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
00614                                                       Spills, MaybeDeadStores);
00615         
00616         // If the mapped designated register is actually the physreg we have
00617         // incoming, we don't need to inserted a dead copy.
00618         if (DesignatedReg == PhysReg) {
00619           // If this stack slot value is already available, reuse it!
00620           DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
00621                           << MRI->getName(PhysReg) << " for vreg"
00622                           << VirtReg
00623                           << " instead of reloading into same physreg.\n");
00624           MI.getOperand(i).setReg(PhysReg);
00625           ++NumReused;
00626           continue;
00627         }
00628         
00629         const TargetRegisterClass* RC =
00630           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
00631 
00632         PhysRegsUsed[DesignatedReg] = true;
00633         MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
00634         
00635         // This invalidates DesignatedReg.
00636         Spills.ClobberPhysReg(DesignatedReg);
00637         
00638         Spills.addAvailable(StackSlot, DesignatedReg);
00639         MI.getOperand(i).setReg(DesignatedReg);
00640         DEBUG(std::cerr << '\t' << *prior(MII));
00641         ++NumReused;
00642         continue;
00643       }
00644       
00645       // Otherwise, reload it and remember that we have it.
00646       PhysReg = VRM.getPhys(VirtReg);
00647       assert(PhysReg && "Must map virtreg to physreg!");
00648       const TargetRegisterClass* RC =
00649         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
00650 
00651       // Note that, if we reused a register for a previous operand, the
00652       // register we want to reload into might not actually be
00653       // available.  If this occurs, use the register indicated by the
00654       // reuser.
00655       if (ReusedOperands.hasReuses())
00656         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
00657                                                  Spills, MaybeDeadStores);
00658       
00659       PhysRegsUsed[PhysReg] = true;
00660       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
00661       // This invalidates PhysReg.
00662       Spills.ClobberPhysReg(PhysReg);
00663 
00664       // Any stores to this stack slot are not dead anymore.
00665       MaybeDeadStores.erase(StackSlot);
00666       Spills.addAvailable(StackSlot, PhysReg);
00667       ++NumLoads;
00668       MI.getOperand(i).setReg(PhysReg);
00669       DEBUG(std::cerr << '\t' << *prior(MII));
00670     }
00671 
00672     // Loop over all of the implicit defs, clearing them from our available
00673     // sets.
00674     const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
00675     if (ImpDef) {
00676       for ( ; *ImpDef; ++ImpDef) {
00677         PhysRegsUsed[*ImpDef] = true;
00678         Spills.ClobberPhysReg(*ImpDef);
00679       }
00680     }
00681 
00682     DEBUG(std::cerr << '\t' << MI);
00683 
00684     // If we have folded references to memory operands, make sure we clear all
00685     // physical registers that may contain the value of the spilled virtual
00686     // register
00687     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
00688     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
00689       DEBUG(std::cerr << "Folded vreg: " << I->second.first << "  MR: "
00690                       << I->second.second);
00691       unsigned VirtReg = I->second.first;
00692       VirtRegMap::ModRef MR = I->second.second;
00693       if (!VRM.hasStackSlot(VirtReg)) {
00694         DEBUG(std::cerr << ": No stack slot!\n");
00695         continue;
00696       }
00697       int SS = VRM.getStackSlot(VirtReg);
00698       DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
00699       
00700       // If this folded instruction is just a use, check to see if it's a
00701       // straight load from the virt reg slot.
00702       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
00703         int FrameIdx;
00704         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
00705           // If this spill slot is available, turn it into a copy (or nothing)
00706           // instead of leaving it as a load!
00707           unsigned InReg;
00708           if (FrameIdx == SS && (InReg = Spills.getSpillSlotPhysReg(SS))) {
00709             DEBUG(std::cerr << "Promoted Load To Copy: " << MI);
00710             MachineFunction &MF = *MBB.getParent();
00711             if (DestReg != InReg) {
00712               MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
00713                                 MF.getSSARegMap()->getRegClass(VirtReg));
00714               // Revisit the copy so we make sure to notice the effects of the
00715               // operation on the destreg (either needing to RA it if it's 
00716               // virtual or needing to clobber any values if it's physical).
00717               NextMII = &MI;
00718               --NextMII;  // backtrack to the copy.
00719             }
00720             VRM.RemoveFromFoldedVirtMap(&MI);
00721             MBB.erase(&MI);
00722             goto ProcessNextInst;
00723           }
00724         }
00725       }
00726 
00727       // If this reference is not a use, any previous store is now dead.
00728       // Otherwise, the store to this stack slot is not dead anymore.
00729       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
00730       if (MDSI != MaybeDeadStores.end()) {
00731         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
00732           MaybeDeadStores.erase(MDSI);
00733         else {
00734           // If we get here, the store is dead, nuke it now.
00735           assert(VirtRegMap::isMod && "Can't be modref!");
00736           DEBUG(std::cerr << "Removed dead store:\t" << *MDSI->second);
00737           MBB.erase(MDSI->second);
00738           VRM.RemoveFromFoldedVirtMap(MDSI->second);
00739           MaybeDeadStores.erase(MDSI);
00740           ++NumDSE;
00741         }
00742       }
00743 
00744       // If the spill slot value is available, and this is a new definition of
00745       // the value, the value is not available anymore.
00746       if (MR & VirtRegMap::isMod) {
00747         // Notice that the value in this stack slot has been modified.
00748         Spills.ModifyStackSlot(SS);
00749         
00750         // If this is *just* a mod of the value, check to see if this is just a
00751         // store to the spill slot (i.e. the spill got merged into the copy). If
00752         // so, realize that the vreg is available now, and add the store to the
00753         // MaybeDeadStore info.
00754         int StackSlot;
00755         if (!(MR & VirtRegMap::isRef)) {
00756           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
00757             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
00758                    "Src hasn't been allocated yet?");
00759             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
00760             // this as a potentially dead store in case there is a subsequent
00761             // store into the stack slot without a read from it.
00762             MaybeDeadStores[StackSlot] = &MI;
00763 
00764             // If the stack slot value was previously available in some other
00765             // register, change it now.  Otherwise, make the register available,
00766             // in PhysReg.
00767             Spills.addAvailable(StackSlot, SrcReg, false /*don't clobber*/);
00768           }
00769         }
00770       }
00771     }
00772 
00773     // Process all of the spilled defs.
00774     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00775       MachineOperand &MO = MI.getOperand(i);
00776       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
00777         unsigned VirtReg = MO.getReg();
00778 
00779         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
00780           // Check to see if this is a def-and-use vreg operand that we do need
00781           // to insert a store for.
00782           bool OpTakenCareOf = false;
00783           if (MO.isUse() && !DefAndUseVReg.empty()) {
00784             for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
00785               if (DefAndUseVReg[dau].first == i) {
00786                 VirtReg = DefAndUseVReg[dau].second;
00787                 OpTakenCareOf = true;
00788                 break;
00789               }
00790           }
00791 
00792           if (!OpTakenCareOf) {
00793             // Check to see if this is a noop copy.  If so, eliminate the
00794             // instruction before considering the dest reg to be changed.
00795             unsigned Src, Dst;
00796             if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
00797               ++NumDCE;
00798               DEBUG(std::cerr << "Removing now-noop copy: " << MI);
00799               MBB.erase(&MI);
00800               VRM.RemoveFromFoldedVirtMap(&MI);
00801               goto ProcessNextInst;
00802             }
00803             Spills.ClobberPhysReg(VirtReg);
00804             continue;
00805           }
00806         }
00807 
00808         // The only vregs left are stack slot definitions.
00809         int StackSlot = VRM.getStackSlot(VirtReg);
00810         const TargetRegisterClass *RC =
00811           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
00812         unsigned PhysReg;
00813 
00814         // If this is a def&use operand, and we used a different physreg for
00815         // it than the one assigned, make sure to execute the store from the
00816         // correct physical register.
00817         if (MO.getReg() == VirtReg)
00818           PhysReg = VRM.getPhys(VirtReg);
00819         else
00820           PhysReg = MO.getReg();
00821 
00822         PhysRegsUsed[PhysReg] = true;
00823         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
00824         DEBUG(std::cerr << "Store:\t" << *next(MII));
00825         MI.getOperand(i).setReg(PhysReg);
00826 
00827         // Check to see if this is a noop copy.  If so, eliminate the
00828         // instruction before considering the dest reg to be changed.
00829         {
00830           unsigned Src, Dst;
00831           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
00832             ++NumDCE;
00833             DEBUG(std::cerr << "Removing now-noop copy: " << MI);
00834             MBB.erase(&MI);
00835             VRM.RemoveFromFoldedVirtMap(&MI);
00836             goto ProcessNextInst;
00837           }
00838         }
00839         
00840         // If there is a dead store to this stack slot, nuke it now.
00841         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
00842         if (LastStore) {
00843           DEBUG(std::cerr << "Removed dead store:\t" << *LastStore);
00844           ++NumDSE;
00845           MBB.erase(LastStore);
00846           VRM.RemoveFromFoldedVirtMap(LastStore);
00847         }
00848         LastStore = next(MII);
00849 
00850         // If the stack slot value was previously available in some other
00851         // register, change it now.  Otherwise, make the register available,
00852         // in PhysReg.
00853         Spills.ModifyStackSlot(StackSlot);
00854         Spills.ClobberPhysReg(PhysReg);
00855         Spills.addAvailable(StackSlot, PhysReg);
00856         ++NumStores;
00857       }
00858     }
00859   ProcessNextInst:
00860     MII = NextMII;
00861   }
00862 }
00863 
00864 
00865 
00866 llvm::Spiller* llvm::createSpiller() {
00867   switch (SpillerOpt) {
00868   default: assert(0 && "Unreachable!");
00869   case local:
00870     return new LocalSpiller();
00871   case simple:
00872     return new SimpleSpiller();
00873   }
00874 }