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