For PR1284:
[oota-llvm.git] / lib / CodeGen / VirtRegMap.cpp
1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the VirtRegMap class.
11 //
12 // It also contains implementations of the the Spiller interface, which, given a
13 // virtual register map and a machine function, eliminates all virtual
14 // references by replacing them with physical register references - adding spill
15 // code as necessary.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "spiller"
20 #include "VirtRegMap.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 STATISTIC(NumSpills, "Number of register spills");
38 STATISTIC(NumReMats, "Number of re-materialization");
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41 STATISTIC(NumReused, "Number of values reused");
42 STATISTIC(NumDSE   , "Number of dead stores elided");
43 STATISTIC(NumDCE   , "Number of copies elided");
44
45 namespace {
46   enum SpillerName { simple, local };
47
48   static cl::opt<SpillerName>
49   SpillerOpt("spiller",
50              cl::desc("Spiller to use: (default: local)"),
51              cl::Prefix,
52              cl::values(clEnumVal(simple, "  simple spiller"),
53                         clEnumVal(local,  "  local spiller"),
54                         clEnumValEnd),
55              cl::init(local));
56 }
57
58 //===----------------------------------------------------------------------===//
59 //  VirtRegMap implementation
60 //===----------------------------------------------------------------------===//
61
62 VirtRegMap::VirtRegMap(MachineFunction &mf)
63   : TII(*mf.getTarget().getInstrInfo()), MF(mf), 
64     Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
65     ReMatId(MAX_STACK_SLOT+1) {
66   grow();
67 }
68
69 void VirtRegMap::grow() {
70   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
71   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
72 }
73
74 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
75   assert(MRegisterInfo::isVirtualRegister(virtReg));
76   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
77          "attempt to assign stack slot to already spilled register");
78   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
79   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
80                                                         RC->getAlignment());
81   Virt2StackSlotMap[virtReg] = frameIndex;
82   ++NumSpills;
83   return frameIndex;
84 }
85
86 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
87   assert(MRegisterInfo::isVirtualRegister(virtReg));
88   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
89          "attempt to assign stack slot to already spilled register");
90   assert((frameIndex >= 0 ||
91           (frameIndex >= MF.getFrameInfo()->getObjectIndexBegin())) &&
92          "illegal fixed frame index");
93   Virt2StackSlotMap[virtReg] = frameIndex;
94 }
95
96 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
97   assert(MRegisterInfo::isVirtualRegister(virtReg));
98   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
99          "attempt to assign re-mat id to already spilled register");
100   const MachineInstr *DefMI = getReMaterializedMI(virtReg);
101   int FrameIdx;
102   if (TII.isLoadFromStackSlot((MachineInstr*)DefMI, FrameIdx)) {
103     // Load from stack slot is re-materialize as reload from the stack slot!
104     Virt2StackSlotMap[virtReg] = FrameIdx;
105     return FrameIdx;
106   }
107   Virt2StackSlotMap[virtReg] = ReMatId;
108   return ReMatId++;
109 }
110
111 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
112                             unsigned OpNo, MachineInstr *NewMI) {
113   // Move previous memory references folded to new instruction.
114   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
115   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
116          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
117     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
118     MI2VirtMap.erase(I++);
119   }
120
121   ModRef MRInfo;
122   const TargetInstrDescriptor *TID = OldMI->getInstrDescriptor();
123   if (TID->getOperandConstraint(OpNo, TOI::TIED_TO) != -1 ||
124       TID->findTiedToSrcOperand(OpNo) != -1) {
125     // Folded a two-address operand.
126     MRInfo = isModRef;
127   } else if (OldMI->getOperand(OpNo).isDef()) {
128     MRInfo = isMod;
129   } else {
130     MRInfo = isRef;
131   }
132
133   // add new memory reference
134   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
135 }
136
137 void VirtRegMap::print(std::ostream &OS) const {
138   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
139
140   OS << "********** REGISTER MAP **********\n";
141   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
142          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
143     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
144       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
145
146   }
147
148   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
149          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
150     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
151       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
152   OS << '\n';
153 }
154
155 void VirtRegMap::dump() const {
156   print(DOUT);
157 }
158
159
160 //===----------------------------------------------------------------------===//
161 // Simple Spiller Implementation
162 //===----------------------------------------------------------------------===//
163
164 Spiller::~Spiller() {}
165
166 namespace {
167   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
168     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
169   };
170 }
171
172 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
173   DOUT << "********** REWRITE MACHINE CODE **********\n";
174   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
175   const TargetMachine &TM = MF.getTarget();
176   const MRegisterInfo &MRI = *TM.getRegisterInfo();
177   bool *PhysRegsUsed = MF.getUsedPhysregs();
178
179   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
180   // each vreg once (in the case where a spilled vreg is used by multiple
181   // operands).  This is always smaller than the number of operands to the
182   // current machine instr, so it should be small.
183   std::vector<unsigned> LoadedRegs;
184
185   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
186        MBBI != E; ++MBBI) {
187     DOUT << MBBI->getBasicBlock()->getName() << ":\n";
188     MachineBasicBlock &MBB = *MBBI;
189     for (MachineBasicBlock::iterator MII = MBB.begin(),
190            E = MBB.end(); MII != E; ++MII) {
191       MachineInstr &MI = *MII;
192       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
193         MachineOperand &MO = MI.getOperand(i);
194         if (MO.isRegister() && MO.getReg())
195           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
196             unsigned VirtReg = MO.getReg();
197             unsigned PhysReg = VRM.getPhys(VirtReg);
198             if (VRM.hasStackSlot(VirtReg)) {
199               int StackSlot = VRM.getStackSlot(VirtReg);
200               const TargetRegisterClass* RC =
201                 MF.getSSARegMap()->getRegClass(VirtReg);
202
203               if (MO.isUse() &&
204                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
205                   == LoadedRegs.end()) {
206                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
207                 LoadedRegs.push_back(VirtReg);
208                 ++NumLoads;
209                 DOUT << '\t' << *prior(MII);
210               }
211
212               if (MO.isDef()) {
213                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
214                 ++NumStores;
215               }
216             }
217             PhysRegsUsed[PhysReg] = true;
218             MI.getOperand(i).setReg(PhysReg);
219           } else {
220             PhysRegsUsed[MO.getReg()] = true;
221           }
222       }
223
224       DOUT << '\t' << MI;
225       LoadedRegs.clear();
226     }
227   }
228   return true;
229 }
230
231 //===----------------------------------------------------------------------===//
232 //  Local Spiller Implementation
233 //===----------------------------------------------------------------------===//
234
235 namespace {
236   /// LocalSpiller - This spiller does a simple pass over the machine basic
237   /// block to attempt to keep spills in registers as much as possible for
238   /// blocks that have low register pressure (the vreg may be spilled due to
239   /// register pressure in other blocks).
240   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
241     const MRegisterInfo *MRI;
242     const TargetInstrInfo *TII;
243   public:
244     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
245       MRI = MF.getTarget().getRegisterInfo();
246       TII = MF.getTarget().getInstrInfo();
247       DOUT << "\n**** Local spiller rewriting function '"
248            << MF.getFunction()->getName() << "':\n";
249
250       std::vector<MachineInstr *> ReMatedMIs;
251       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
252            MBB != E; ++MBB)
253         RewriteMBB(*MBB, VRM, ReMatedMIs);
254       for (unsigned i = 0, e = ReMatedMIs.size(); i != e; ++i)
255         delete ReMatedMIs[i];
256       return true;
257     }
258   private:
259     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
260                     std::vector<MachineInstr*> &ReMatedMIs);
261   };
262 }
263
264 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
265 /// top down, keep track of which spills slots are available in each register.
266 ///
267 /// Note that not all physregs are created equal here.  In particular, some
268 /// physregs are reloads that we are allowed to clobber or ignore at any time.
269 /// Other physregs are values that the register allocated program is using that
270 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
271 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
272 /// entries.  The predicate 'canClobberPhysReg()' checks this bit and
273 /// addAvailable sets it if.
274 namespace {
275 class VISIBILITY_HIDDEN AvailableSpills {
276   const MRegisterInfo *MRI;
277   const TargetInstrInfo *TII;
278
279   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
280   // register values that are still available, due to being loaded or stored to,
281   // but not invalidated yet. It also tracks the instructions that defined
282   // or used the register.
283   typedef std::pair<unsigned, std::vector<MachineInstr*> > SSInfo;
284   std::map<int, SSInfo> SpillSlotsAvailable;
285     
286   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
287   // which stack slot values are currently held by a physreg.  This is used to
288   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
289   std::multimap<unsigned, int> PhysRegsAvailable;
290   
291   void disallowClobberPhysRegOnly(unsigned PhysReg);
292
293   void ClobberPhysRegOnly(unsigned PhysReg);
294 public:
295   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
296     : MRI(mri), TII(tii) {
297   }
298   
299   const MRegisterInfo *getRegInfo() const { return MRI; }
300
301   /// getSpillSlotPhysReg - If the specified stack slot is available in a 
302   /// physical register, return that PhysReg, otherwise return 0. It also
303   /// returns by reference the instruction that either defines or last uses
304   /// the register.
305   unsigned getSpillSlotPhysReg(int Slot, MachineInstr *&SSMI) const {
306     std::map<int, SSInfo>::const_iterator I = SpillSlotsAvailable.find(Slot);
307     if (I != SpillSlotsAvailable.end()) {
308       if (!I->second.second.empty())
309         SSMI = I->second.second.back();
310       return I->second.first >> 1;  // Remove the CanClobber bit.
311     }
312     return 0;
313   }
314
315   /// addLastUse - Add the last use information of all stack slots whose
316   /// values are available in the specific register.
317   void addLastUse(unsigned PhysReg, MachineInstr *Use) {
318     std::multimap<unsigned, int>::iterator I =
319       PhysRegsAvailable.lower_bound(PhysReg);
320     while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
321       int Slot = I->second;
322       I++;
323
324       std::map<int, SSInfo>::iterator II = SpillSlotsAvailable.find(Slot);
325       assert(II != SpillSlotsAvailable.end() && "Slot not available!");
326       unsigned Val = II->second.first;
327       assert((Val >> 1) == PhysReg && "Bidirectional map mismatch!");
328       // This can be true if there are multiple uses of the same register.
329       if (II->second.second.back() != Use)
330         II->second.second.push_back(Use);
331     }
332   }
333   
334   /// removeLastUse - Remove the last use information of all stack slots whose
335   /// values are available in the specific register.
336   void removeLastUse(unsigned PhysReg, MachineInstr *Use) {
337     std::multimap<unsigned, int>::iterator I =
338       PhysRegsAvailable.lower_bound(PhysReg);
339     while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
340       int Slot = I->second;
341       I++;
342
343       std::map<int, SSInfo>::iterator II = SpillSlotsAvailable.find(Slot);
344       assert(II != SpillSlotsAvailable.end() && "Slot not available!");
345       unsigned Val = II->second.first;
346       assert((Val >> 1) == PhysReg && "Bidirectional map mismatch!");
347       if (II->second.second.back() == Use)
348         II->second.second.pop_back();
349     }
350   }
351   
352   /// addAvailable - Mark that the specified stack slot is available in the
353   /// specified physreg.  If CanClobber is true, the physreg can be modified at
354   /// any time without changing the semantics of the program.
355   void addAvailable(int Slot, MachineInstr *MI, unsigned Reg,
356                     bool CanClobber = true) {
357     // If this stack slot is thought to be available in some other physreg, 
358     // remove its record.
359     ModifyStackSlot(Slot);
360     
361     PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
362     std::vector<MachineInstr*> DefUses;
363     DefUses.push_back(MI);
364     SpillSlotsAvailable[Slot] =
365       std::make_pair((Reg << 1) | (unsigned)CanClobber, DefUses);
366   
367     if (Slot > VirtRegMap::MAX_STACK_SLOT)
368       DOUT << "Remembering RM#" << Slot-VirtRegMap::MAX_STACK_SLOT-1;
369     else
370       DOUT << "Remembering SS#" << Slot;
371     DOUT << " in physreg " << MRI->getName(Reg) << "\n";
372   }
373
374   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
375   /// value of the specified stackslot register if it desires.  The specified
376   /// stack slot must be available in a physreg for this query to make sense.
377   bool canClobberPhysReg(int Slot) const {
378     assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
379     return SpillSlotsAvailable.find(Slot)->second.first & 1;
380   }
381   
382   /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
383   /// stackslot register. The register is still available but is no longer
384   /// allowed to be modifed.
385   void disallowClobberPhysReg(unsigned PhysReg);
386   
387   /// ClobberPhysReg - This is called when the specified physreg changes
388   /// value.  We use this to invalidate any info about stuff we thing lives in
389   /// it and any of its aliases.
390   void ClobberPhysReg(unsigned PhysReg);
391
392   /// ModifyStackSlot - This method is called when the value in a stack slot
393   /// changes.  This removes information about which register the previous value
394   /// for this slot lives in (as the previous value is dead now).
395   void ModifyStackSlot(int Slot);
396 };
397 }
398
399 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
400 /// stackslot register. The register is still available but is no longer
401 /// allowed to be modifed.
402 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
403   std::multimap<unsigned, int>::iterator I =
404     PhysRegsAvailable.lower_bound(PhysReg);
405   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
406     int Slot = I->second;
407     I++;
408     assert((SpillSlotsAvailable[Slot].first >> 1) == PhysReg &&
409            "Bidirectional map mismatch!");
410     SpillSlotsAvailable[Slot].first &= ~1;
411     DOUT << "PhysReg " << MRI->getName(PhysReg)
412          << " copied, it is available for use but can no longer be modified\n";
413   }
414 }
415
416 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
417 /// stackslot register and its aliases. The register and its aliases may
418 /// still available but is no longer allowed to be modifed.
419 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
420   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
421     disallowClobberPhysRegOnly(*AS);
422   disallowClobberPhysRegOnly(PhysReg);
423 }
424
425 /// ClobberPhysRegOnly - This is called when the specified physreg changes
426 /// value.  We use this to invalidate any info about stuff we thing lives in it.
427 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
428   std::multimap<unsigned, int>::iterator I =
429     PhysRegsAvailable.lower_bound(PhysReg);
430   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
431     int Slot = I->second;
432     PhysRegsAvailable.erase(I++);
433     assert((SpillSlotsAvailable[Slot].first >> 1) == PhysReg &&
434            "Bidirectional map mismatch!");
435     SpillSlotsAvailable.erase(Slot);
436     DOUT << "PhysReg " << MRI->getName(PhysReg)
437          << " clobbered, invalidating ";
438     if (Slot > VirtRegMap::MAX_STACK_SLOT)
439       DOUT << "RM#" << Slot-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
440     else
441       DOUT << "SS#" << Slot << "\n";
442   }
443 }
444
445 /// ClobberPhysReg - This is called when the specified physreg changes
446 /// value.  We use this to invalidate any info about stuff we thing lives in
447 /// it and any of its aliases.
448 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
449   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
450     ClobberPhysRegOnly(*AS);
451   ClobberPhysRegOnly(PhysReg);
452 }
453
454 /// ModifyStackSlot - This method is called when the value in a stack slot
455 /// changes.  This removes information about which register the previous value
456 /// for this slot lives in (as the previous value is dead now).
457 void AvailableSpills::ModifyStackSlot(int Slot) {
458   std::map<int, SSInfo>::iterator It = SpillSlotsAvailable.find(Slot);
459   if (It == SpillSlotsAvailable.end()) return;
460   unsigned Reg = It->second.first >> 1;
461   SpillSlotsAvailable.erase(It);
462   
463   // This register may hold the value of multiple stack slots, only remove this
464   // stack slot from the set of values the register contains.
465   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
466   for (; ; ++I) {
467     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
468            "Map inverse broken!");
469     if (I->second == Slot) break;
470   }
471   PhysRegsAvailable.erase(I);
472 }
473
474
475
476 // ReusedOp - For each reused operand, we keep track of a bit of information, in
477 // case we need to rollback upon processing a new operand.  See comments below.
478 namespace {
479   struct ReusedOp {
480     // The MachineInstr operand that reused an available value.
481     unsigned Operand;
482
483     // StackSlot - The spill slot of the value being reused.
484     unsigned StackSlot;
485
486     // PhysRegReused - The physical register the value was available in.
487     unsigned PhysRegReused;
488
489     // AssignedPhysReg - The physreg that was assigned for use by the reload.
490     unsigned AssignedPhysReg;
491     
492     // VirtReg - The virtual register itself.
493     unsigned VirtReg;
494
495     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
496              unsigned vreg)
497       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
498       VirtReg(vreg) {}
499   };
500   
501   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
502   /// is reused instead of reloaded.
503   class VISIBILITY_HIDDEN ReuseInfo {
504     MachineInstr &MI;
505     std::vector<ReusedOp> Reuses;
506     BitVector PhysRegsClobbered;
507   public:
508     ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
509       PhysRegsClobbered.resize(mri->getNumRegs());
510     }
511     
512     bool hasReuses() const {
513       return !Reuses.empty();
514     }
515     
516     /// addReuse - If we choose to reuse a virtual register that is already
517     /// available instead of reloading it, remember that we did so.
518     void addReuse(unsigned OpNo, unsigned StackSlot,
519                   unsigned PhysRegReused, unsigned AssignedPhysReg,
520                   unsigned VirtReg) {
521       // If the reload is to the assigned register anyway, no undo will be
522       // required.
523       if (PhysRegReused == AssignedPhysReg) return;
524       
525       // Otherwise, remember this.
526       Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused, 
527                                 AssignedPhysReg, VirtReg));
528     }
529
530     void markClobbered(unsigned PhysReg) {
531       PhysRegsClobbered.set(PhysReg);
532     }
533
534     bool isClobbered(unsigned PhysReg) const {
535       return PhysRegsClobbered.test(PhysReg);
536     }
537     
538     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
539     /// is some other operand that is using the specified register, either pick
540     /// a new register to use, or evict the previous reload and use this reg. 
541     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
542                              AvailableSpills &Spills,
543                              std::map<int, MachineInstr*> &MaybeDeadStores,
544                              SmallSet<unsigned, 8> &Rejected) {
545       if (Reuses.empty()) return PhysReg;  // This is most often empty.
546
547       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
548         ReusedOp &Op = Reuses[ro];
549         // If we find some other reuse that was supposed to use this register
550         // exactly for its reload, we can change this reload to use ITS reload
551         // register. That is, unless its reload register has already been
552         // considered and subsequently rejected because it has also been reused
553         // by another operand.
554         if (Op.PhysRegReused == PhysReg &&
555             Rejected.count(Op.AssignedPhysReg) == 0) {
556           // Yup, use the reload register that we didn't use before.
557           unsigned NewReg = Op.AssignedPhysReg;
558           Rejected.insert(PhysReg);
559           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected);
560         } else {
561           // Otherwise, we might also have a problem if a previously reused
562           // value aliases the new register.  If so, codegen the previous reload
563           // and use this one.          
564           unsigned PRRU = Op.PhysRegReused;
565           const MRegisterInfo *MRI = Spills.getRegInfo();
566           if (MRI->areAliases(PRRU, PhysReg)) {
567             // Okay, we found out that an alias of a reused register
568             // was used.  This isn't good because it means we have
569             // to undo a previous reuse.
570             MachineBasicBlock *MBB = MI->getParent();
571             const TargetRegisterClass *AliasRC =
572               MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
573
574             // Copy Op out of the vector and remove it, we're going to insert an
575             // explicit load for it.
576             ReusedOp NewOp = Op;
577             Reuses.erase(Reuses.begin()+ro);
578
579             // Ok, we're going to try to reload the assigned physreg into the
580             // slot that we were supposed to in the first place.  However, that
581             // register could hold a reuse.  Check to see if it conflicts or
582             // would prefer us to use a different register.
583             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
584                                          MI, Spills, MaybeDeadStores, Rejected);
585             
586             MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
587                                       NewOp.StackSlot, AliasRC);
588             Spills.ClobberPhysReg(NewPhysReg);
589             Spills.ClobberPhysReg(NewOp.PhysRegReused);
590             
591             // Any stores to this stack slot are not dead anymore.
592             MaybeDeadStores.erase(NewOp.StackSlot);
593             
594             MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
595             
596             Spills.addAvailable(NewOp.StackSlot, MI, NewPhysReg);
597             ++NumLoads;
598             DEBUG(MachineBasicBlock::iterator MII = MI;
599                   DOUT << '\t' << *prior(MII));
600             
601             DOUT << "Reuse undone!\n";
602             --NumReused;
603             
604             // Finally, PhysReg is now available, go ahead and use it.
605             return PhysReg;
606           }
607         }
608       }
609       return PhysReg;
610     }
611
612     /// GetRegForReload - Helper for the above GetRegForReload(). Add a
613     /// 'Rejected' set to remember which registers have been considered and
614     /// rejected for the reload. This avoids infinite looping in case like
615     /// this:
616     /// t1 := op t2, t3
617     /// t2 <- assigned r0 for use by the reload but ended up reuse r1
618     /// t3 <- assigned r1 for use by the reload but ended up reuse r0
619     /// t1 <- desires r1
620     ///       sees r1 is taken by t2, tries t2's reload register r0
621     ///       sees r0 is taken by t3, tries t3's reload register r1
622     ///       sees r1 is taken by t2, tries t2's reload register r0 ...
623     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
624                              AvailableSpills &Spills,
625                              std::map<int, MachineInstr*> &MaybeDeadStores) {
626       SmallSet<unsigned, 8> Rejected;
627       return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected);
628     }
629   };
630 }
631
632
633 /// rewriteMBB - Keep track of which spills are available even after the
634 /// register allocator is done with them.  If possible, avoid reloading vregs.
635 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
636                               std::vector<MachineInstr*> &ReMatedMIs) {
637   DOUT << MBB.getBasicBlock()->getName() << ":\n";
638
639   // Spills - Keep track of which spilled values are available in physregs so
640   // that we can choose to reuse the physregs instead of emitting reloads.
641   AvailableSpills Spills(MRI, TII);
642   
643   // MaybeDeadStores - When we need to write a value back into a stack slot,
644   // keep track of the inserted store.  If the stack slot value is never read
645   // (because the value was used from some available register, for example), and
646   // subsequently stored to, the original store is dead.  This map keeps track
647   // of inserted stores that are not used.  If we see a subsequent store to the
648   // same stack slot, the original store is deleted.
649   std::map<int, MachineInstr*> MaybeDeadStores;
650
651   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
652
653   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
654        MII != E; ) {
655     MachineInstr &MI = *MII;
656     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
657
658     /// ReusedOperands - Keep track of operand reuse in case we need to undo
659     /// reuse.
660     ReuseInfo ReusedOperands(MI, MRI);
661
662     // Loop over all of the implicit defs, clearing them from our available
663     // sets.
664     const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
665
666     // If this instruction is being rematerialized, just remove it!
667     int FrameIdx;
668     if ((TID->Flags & M_REMATERIALIZIBLE) ||
669         TII->isLoadFromStackSlot(&MI, FrameIdx)) {
670       bool Remove = true;
671       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
672         MachineOperand &MO = MI.getOperand(i);
673         if (!MO.isRegister() || MO.getReg() == 0)
674           continue;   // Ignore non-register operands.
675         if (MO.isDef() && !VRM.isReMaterialized(MO.getReg())) {
676           Remove = false;
677           break;
678         }
679       }
680       if (Remove) {
681         VRM.RemoveFromFoldedVirtMap(&MI);
682         ReMatedMIs.push_back(MI.removeFromParent());
683         MII = NextMII;
684         continue;
685       }
686     }
687
688     const unsigned *ImpDef = TID->ImplicitDefs;
689     if (ImpDef) {
690       for ( ; *ImpDef; ++ImpDef) {
691         PhysRegsUsed[*ImpDef] = true;
692         ReusedOperands.markClobbered(*ImpDef);
693         Spills.ClobberPhysReg(*ImpDef);
694       }
695     }
696
697     // Process all of the spilled uses and all non spilled reg references.
698     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
699       MachineOperand &MO = MI.getOperand(i);
700       if (!MO.isRegister() || MO.getReg() == 0)
701         continue;   // Ignore non-register operands.
702       
703       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
704         // Ignore physregs for spilling, but remember that it is used by this
705         // function.
706         PhysRegsUsed[MO.getReg()] = true;
707         ReusedOperands.markClobbered(MO.getReg());
708         continue;
709       }
710       
711       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
712              "Not a virtual or a physical register?");
713       
714       unsigned VirtReg = MO.getReg();
715       if (!VRM.hasStackSlot(VirtReg)) {
716         // This virtual register was assigned a physreg!
717         unsigned Phys = VRM.getPhys(VirtReg);
718         PhysRegsUsed[Phys] = true;
719         if (MO.isDef())
720           ReusedOperands.markClobbered(Phys);
721         MI.getOperand(i).setReg(Phys);
722         continue;
723       }
724       
725       // This virtual register is now known to be a spilled value.
726       if (!MO.isUse())
727         continue;  // Handle defs in the loop below (handle use&def here though)
728
729       bool doReMat = VRM.isReMaterialized(VirtReg);
730       int StackSlot = VRM.getStackSlot(VirtReg);
731       unsigned PhysReg;
732
733       // Check to see if this stack slot is available.
734       MachineInstr *SSMI = NULL;
735       if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot, SSMI))) {
736         // This spilled operand might be part of a two-address operand.  If this
737         // is the case, then changing it will necessarily require changing the 
738         // def part of the instruction as well.  However, in some cases, we
739         // aren't allowed to modify the reused register.  If none of these cases
740         // apply, reuse it.
741         bool CanReuse = true;
742         int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
743         if (ti != -1 &&
744             MI.getOperand(ti).isReg() && 
745             MI.getOperand(ti).getReg() == VirtReg) {
746           // Okay, we have a two address operand.  We can reuse this physreg as
747           // long as we are allowed to clobber the value and there isn't an
748           // earlier def that has already clobbered the physreg.
749           CanReuse = Spills.canClobberPhysReg(StackSlot) &&
750             !ReusedOperands.isClobbered(PhysReg);
751         }
752         
753         if (CanReuse) {
754           // If this stack slot value is already available, reuse it!
755           if (StackSlot > VirtRegMap::MAX_STACK_SLOT)
756             DOUT << "Reusing RM#" << StackSlot-VirtRegMap::MAX_STACK_SLOT-1;
757           else
758             DOUT << "Reusing SS#" << StackSlot;
759           DOUT << " from physreg "
760                << MRI->getName(PhysReg) << " for vreg"
761                << VirtReg <<" instead of reloading into physreg "
762                << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
763           MI.getOperand(i).setReg(PhysReg);
764
765           // Extend the live range of the MI that last kill the register if
766           // necessary.
767           bool WasKill = false;
768           if (SSMI) {
769             int UIdx = SSMI->findRegisterUseOperand(PhysReg, true);
770             if (UIdx != -1) {
771               MachineOperand &MOK = SSMI->getOperand(UIdx);
772               WasKill = MOK.isKill();
773               MOK.unsetIsKill();
774             }
775           }
776           if (ti == -1) {
777             // Unless it's the use of a two-address code, transfer the kill
778             // of the reused register to this use.
779             if (WasKill)
780               MI.getOperand(i).setIsKill();
781             Spills.addLastUse(PhysReg, &MI);
782           }
783
784           // The only technical detail we have is that we don't know that
785           // PhysReg won't be clobbered by a reloaded stack slot that occurs
786           // later in the instruction.  In particular, consider 'op V1, V2'.
787           // If V1 is available in physreg R0, we would choose to reuse it
788           // here, instead of reloading it into the register the allocator
789           // indicated (say R1).  However, V2 might have to be reloaded
790           // later, and it might indicate that it needs to live in R0.  When
791           // this occurs, we need to have information available that
792           // indicates it is safe to use R1 for the reload instead of R0.
793           //
794           // To further complicate matters, we might conflict with an alias,
795           // or R0 and R1 might not be compatible with each other.  In this
796           // case, we actually insert a reload for V1 in R1, ensuring that
797           // we can get at R0 or its alias.
798           ReusedOperands.addReuse(i, StackSlot, PhysReg,
799                                   VRM.getPhys(VirtReg), VirtReg);
800           if (ti != -1)
801             // Only mark it clobbered if this is a use&def operand.
802             ReusedOperands.markClobbered(PhysReg);
803           ++NumReused;
804           continue;
805         }
806         
807         // Otherwise we have a situation where we have a two-address instruction
808         // whose mod/ref operand needs to be reloaded.  This reload is already
809         // available in some register "PhysReg", but if we used PhysReg as the
810         // operand to our 2-addr instruction, the instruction would modify
811         // PhysReg.  This isn't cool if something later uses PhysReg and expects
812         // to get its initial value.
813         //
814         // To avoid this problem, and to avoid doing a load right after a store,
815         // we emit a copy from PhysReg into the designated register for this
816         // operand.
817         unsigned DesignatedReg = VRM.getPhys(VirtReg);
818         assert(DesignatedReg && "Must map virtreg to physreg!");
819
820         // Note that, if we reused a register for a previous operand, the
821         // register we want to reload into might not actually be
822         // available.  If this occurs, use the register indicated by the
823         // reuser.
824         if (ReusedOperands.hasReuses())
825           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
826                                                       Spills, MaybeDeadStores);
827         
828         // If the mapped designated register is actually the physreg we have
829         // incoming, we don't need to inserted a dead copy.
830         if (DesignatedReg == PhysReg) {
831           // If this stack slot value is already available, reuse it!
832           if (StackSlot > VirtRegMap::MAX_STACK_SLOT)
833             DOUT << "Reusing RM#" << StackSlot-VirtRegMap::MAX_STACK_SLOT-1;
834           else
835             DOUT << "Reusing SS#" << StackSlot;
836           DOUT << " from physreg " << MRI->getName(PhysReg) << " for vreg"
837                << VirtReg
838                << " instead of reloading into same physreg.\n";
839           MI.getOperand(i).setReg(PhysReg);
840           ReusedOperands.markClobbered(PhysReg);
841           ++NumReused;
842           continue;
843         }
844         
845         const TargetRegisterClass* RC =
846           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
847
848         PhysRegsUsed[DesignatedReg] = true;
849         ReusedOperands.markClobbered(DesignatedReg);
850         MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
851
852         // Extend the live range of the MI that last kill the register if
853         // necessary.
854         bool WasKill = false;
855         if (SSMI) {
856           int UIdx = SSMI->findRegisterUseOperand(PhysReg, true);
857           if (UIdx != -1) {
858             MachineOperand &MOK = SSMI->getOperand(UIdx);
859             WasKill = MOK.isKill();
860             MOK.unsetIsKill();
861           }
862         }
863         MachineInstr *CopyMI = prior(MII);
864         if (WasKill) {
865           // Transfer kill to the next use.
866           int UIdx = CopyMI->findRegisterUseOperand(PhysReg);
867           assert(UIdx != -1);
868           MachineOperand &MOU = CopyMI->getOperand(UIdx);
869           MOU.setIsKill();
870         }
871         Spills.addLastUse(PhysReg, CopyMI);
872
873         // This invalidates DesignatedReg.
874         Spills.ClobberPhysReg(DesignatedReg);
875         
876         Spills.addAvailable(StackSlot, &MI, DesignatedReg);
877         MI.getOperand(i).setReg(DesignatedReg);
878         DOUT << '\t' << *prior(MII);
879         ++NumReused;
880         continue;
881       }
882       
883       // Otherwise, reload it and remember that we have it.
884       PhysReg = VRM.getPhys(VirtReg);
885       assert(PhysReg && "Must map virtreg to physreg!");
886       const TargetRegisterClass* RC =
887         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
888
889       // Note that, if we reused a register for a previous operand, the
890       // register we want to reload into might not actually be
891       // available.  If this occurs, use the register indicated by the
892       // reuser.
893       if (ReusedOperands.hasReuses())
894         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
895                                                  Spills, MaybeDeadStores);
896       
897       PhysRegsUsed[PhysReg] = true;
898       ReusedOperands.markClobbered(PhysReg);
899       if (doReMat) {
900         MRI->reMaterialize(MBB, &MI, PhysReg, VRM.getReMaterializedMI(VirtReg));
901         ++NumReMats;
902       } else {
903         MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
904         ++NumLoads;
905       }
906       // This invalidates PhysReg.
907       Spills.ClobberPhysReg(PhysReg);
908
909       // Any stores to this stack slot are not dead anymore.
910       if (!doReMat)
911         MaybeDeadStores.erase(StackSlot);
912       Spills.addAvailable(StackSlot, &MI, PhysReg);
913       // Assumes this is the last use. IsKill will be unset if reg is reused
914       // unless it's a two-address operand.
915       if (TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
916         MI.getOperand(i).setIsKill();
917       MI.getOperand(i).setReg(PhysReg);
918       DOUT << '\t' << *prior(MII);
919     }
920
921     DOUT << '\t' << MI;
922
923     // If we have folded references to memory operands, make sure we clear all
924     // physical registers that may contain the value of the spilled virtual
925     // register
926     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
927     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
928       DOUT << "Folded vreg: " << I->second.first << "  MR: "
929            << I->second.second;
930       unsigned VirtReg = I->second.first;
931       VirtRegMap::ModRef MR = I->second.second;
932       if (!VRM.hasStackSlot(VirtReg)) {
933         DOUT << ": No stack slot!\n";
934         continue;
935       }
936       int SS = VRM.getStackSlot(VirtReg);
937       DOUT << " - StackSlot: " << SS << "\n";
938       
939       // If this folded instruction is just a use, check to see if it's a
940       // straight load from the virt reg slot.
941       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
942         int FrameIdx;
943         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
944           if (FrameIdx == SS) {
945             // If this spill slot is available, turn it into a copy (or nothing)
946             // instead of leaving it as a load!
947             MachineInstr *SSMI = NULL;
948             if (unsigned InReg = Spills.getSpillSlotPhysReg(SS, SSMI)) {
949               DOUT << "Promoted Load To Copy: " << MI;
950               MachineFunction &MF = *MBB.getParent();
951               if (DestReg != InReg) {
952                 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
953                                   MF.getSSARegMap()->getRegClass(VirtReg));
954                 // Revisit the copy so we make sure to notice the effects of the
955                 // operation on the destreg (either needing to RA it if it's 
956                 // virtual or needing to clobber any values if it's physical).
957                 NextMII = &MI;
958                 --NextMII;  // backtrack to the copy.
959               } else
960                 DOUT << "Removing now-noop copy: " << MI;
961
962               // Either way, the live range of the last kill of InReg has been
963               // extended. Remove its kill.
964               bool WasKill = false;
965               if (SSMI) {
966                 int UIdx = SSMI->findRegisterUseOperand(InReg, true);
967                 if (UIdx != -1) {
968                   MachineOperand &MOK = SSMI->getOperand(UIdx);
969                   WasKill = MOK.isKill();
970                   MOK.unsetIsKill();
971                 }
972               }
973               if (NextMII != MBB.end()) {
974                 // If NextMII uses InReg and the use is not a two address
975                 // operand, mark it killed.
976                 int UIdx = NextMII->findRegisterUseOperand(InReg);
977                 if (UIdx != -1) {
978                   MachineOperand &MOU = NextMII->getOperand(UIdx);
979                   if (WasKill) {
980                     const TargetInstrDescriptor *NTID =
981                       NextMII->getInstrDescriptor();
982                     if (UIdx >= NTID->numOperands ||
983                         NTID->getOperandConstraint(UIdx, TOI::TIED_TO) == -1)
984                       MOU.setIsKill();
985                   }
986                   Spills.addLastUse(InReg, &(*NextMII));
987                 }
988               }
989
990               VRM.RemoveFromFoldedVirtMap(&MI);
991               MBB.erase(&MI);
992               goto ProcessNextInst;
993             }
994           }
995         }
996       }
997
998       // If this reference is not a use, any previous store is now dead.
999       // Otherwise, the store to this stack slot is not dead anymore.
1000       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
1001       if (MDSI != MaybeDeadStores.end()) {
1002         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
1003           MaybeDeadStores.erase(MDSI);
1004         else {
1005           // If we get here, the store is dead, nuke it now.
1006           assert(VirtRegMap::isMod && "Can't be modref!");
1007           DOUT << "Removed dead store:\t" << *MDSI->second;
1008           MBB.erase(MDSI->second);
1009           VRM.RemoveFromFoldedVirtMap(MDSI->second);
1010           MaybeDeadStores.erase(MDSI);
1011           ++NumDSE;
1012         }
1013       }
1014
1015       // If the spill slot value is available, and this is a new definition of
1016       // the value, the value is not available anymore.
1017       if (MR & VirtRegMap::isMod) {
1018         // Notice that the value in this stack slot has been modified.
1019         Spills.ModifyStackSlot(SS);
1020         
1021         // If this is *just* a mod of the value, check to see if this is just a
1022         // store to the spill slot (i.e. the spill got merged into the copy). If
1023         // so, realize that the vreg is available now, and add the store to the
1024         // MaybeDeadStore info.
1025         int StackSlot;
1026         if (!(MR & VirtRegMap::isRef)) {
1027           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1028             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
1029                    "Src hasn't been allocated yet?");
1030             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1031             // this as a potentially dead store in case there is a subsequent
1032             // store into the stack slot without a read from it.
1033             MaybeDeadStores[StackSlot] = &MI;
1034
1035             // If the stack slot value was previously available in some other
1036             // register, change it now.  Otherwise, make the register available,
1037             // in PhysReg.
1038             Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
1039           }
1040         }
1041       }
1042     }
1043
1044     // Process all of the spilled defs.
1045     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1046       MachineOperand &MO = MI.getOperand(i);
1047       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
1048         unsigned VirtReg = MO.getReg();
1049
1050         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
1051           // Check to see if this is a noop copy.  If so, eliminate the
1052           // instruction before considering the dest reg to be changed.
1053           unsigned Src, Dst;
1054           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1055             ++NumDCE;
1056             DOUT << "Removing now-noop copy: " << MI;
1057             Spills.removeLastUse(Src, &MI);
1058             MBB.erase(&MI);
1059             VRM.RemoveFromFoldedVirtMap(&MI);
1060             Spills.disallowClobberPhysReg(VirtReg);
1061             goto ProcessNextInst;
1062           }
1063           
1064           // If it's not a no-op copy, it clobbers the value in the destreg.
1065           Spills.ClobberPhysReg(VirtReg);
1066           ReusedOperands.markClobbered(VirtReg);
1067  
1068           // Check to see if this instruction is a load from a stack slot into
1069           // a register.  If so, this provides the stack slot value in the reg.
1070           int FrameIdx;
1071           if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1072             assert(DestReg == VirtReg && "Unknown load situation!");
1073             
1074             // Otherwise, if it wasn't available, remember that it is now!
1075             Spills.addAvailable(FrameIdx, &MI, DestReg);
1076             goto ProcessNextInst;
1077           }
1078             
1079           continue;
1080         }
1081
1082         // The only vregs left are stack slot definitions.
1083         int StackSlot = VRM.getStackSlot(VirtReg);
1084         const TargetRegisterClass *RC =
1085           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
1086
1087         // If this def is part of a two-address operand, make sure to execute
1088         // the store from the correct physical register.
1089         unsigned PhysReg;
1090         int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
1091         if (TiedOp != -1)
1092           PhysReg = MI.getOperand(TiedOp).getReg();
1093         else {
1094           PhysReg = VRM.getPhys(VirtReg);
1095           if (ReusedOperands.isClobbered(PhysReg)) {
1096             // Another def has taken the assigned physreg. It must have been a
1097             // use&def which got it due to reuse. Undo the reuse!
1098             PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1099                                                      Spills, MaybeDeadStores);
1100           }
1101         }
1102
1103         PhysRegsUsed[PhysReg] = true;
1104         ReusedOperands.markClobbered(PhysReg);
1105         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
1106         DOUT << "Store:\t" << *next(MII);
1107         MI.getOperand(i).setReg(PhysReg);
1108
1109         // If there is a dead store to this stack slot, nuke it now.
1110         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1111         if (LastStore) {
1112           DOUT << "Removed dead store:\t" << *LastStore;
1113           ++NumDSE;
1114           MBB.erase(LastStore);
1115           VRM.RemoveFromFoldedVirtMap(LastStore);
1116         }
1117         LastStore = next(MII);
1118
1119         // If the stack slot value was previously available in some other
1120         // register, change it now.  Otherwise, make the register available,
1121         // in PhysReg.
1122         Spills.ModifyStackSlot(StackSlot);
1123         Spills.ClobberPhysReg(PhysReg);
1124         Spills.addAvailable(StackSlot, LastStore, PhysReg);
1125         ++NumStores;
1126
1127         // Check to see if this is a noop copy.  If so, eliminate the
1128         // instruction before considering the dest reg to be changed.
1129         {
1130           unsigned Src, Dst;
1131           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1132             ++NumDCE;
1133             DOUT << "Removing now-noop copy: " << MI;
1134             Spills.removeLastUse(Src, &MI);
1135             MBB.erase(&MI);
1136             VRM.RemoveFromFoldedVirtMap(&MI);
1137             goto ProcessNextInst;
1138           }
1139         }        
1140       }
1141     }
1142   ProcessNextInst:
1143     MII = NextMII;
1144   }
1145 }
1146
1147
1148
1149 llvm::Spiller* llvm::createSpiller() {
1150   switch (SpillerOpt) {
1151   default: assert(0 && "Unreachable!");
1152   case local:
1153     return new LocalSpiller();
1154   case simple:
1155     return new SimpleSpiller();
1156   }
1157 }