Physregs may hold multiple stack slot values at the same time. Keep track
[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/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include <algorithm>
32 #include <iostream>
33 using namespace llvm;
34
35 namespace {
36   Statistic<> NumSpills("spiller", "Number of register spills");
37   Statistic<> NumStores("spiller", "Number of stores added");
38   Statistic<> NumLoads ("spiller", "Number of loads added");
39   Statistic<> NumReused("spiller", "Number of values reused");
40   Statistic<> NumDSE   ("spiller", "Number of dead stores elided");
41
42   enum SpillerName { simple, local };
43
44   cl::opt<SpillerName>
45   SpillerOpt("spiller",
46              cl::desc("Spiller to use: (default: local)"),
47              cl::Prefix,
48              cl::values(clEnumVal(simple, "  simple spiller"),
49                         clEnumVal(local,  "  local spiller"),
50                         clEnumValEnd),
51              cl::init(local));
52 }
53
54 //===----------------------------------------------------------------------===//
55 //  VirtRegMap implementation
56 //===----------------------------------------------------------------------===//
57
58 void VirtRegMap::grow() {
59   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
60   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
61 }
62
63 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
64   assert(MRegisterInfo::isVirtualRegister(virtReg));
65   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
66          "attempt to assign stack slot to already spilled register");
67   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
68   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
69                                                         RC->getAlignment());
70   Virt2StackSlotMap[virtReg] = frameIndex;
71   ++NumSpills;
72   return frameIndex;
73 }
74
75 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
76   assert(MRegisterInfo::isVirtualRegister(virtReg));
77   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
78          "attempt to assign stack slot to already spilled register");
79   Virt2StackSlotMap[virtReg] = frameIndex;
80 }
81
82 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
83                             unsigned OpNo, MachineInstr *NewMI) {
84   // Move previous memory references folded to new instruction.
85   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
86   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
87          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
88     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
89     MI2VirtMap.erase(I++);
90   }
91
92   ModRef MRInfo;
93   if (!OldMI->getOperand(OpNo).isDef()) {
94     assert(OldMI->getOperand(OpNo).isUse() && "Operand is not use or def?");
95     MRInfo = isRef;
96   } else {
97     MRInfo = OldMI->getOperand(OpNo).isUse() ? isModRef : isMod;
98   }
99
100   // add new memory reference
101   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
102 }
103
104 void VirtRegMap::print(std::ostream &OS) const {
105   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
106
107   OS << "********** REGISTER MAP **********\n";
108   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
109          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
110     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
111       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
112
113   }
114
115   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
116          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
117     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
118       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
119   OS << '\n';
120 }
121
122 void VirtRegMap::dump() const { print(std::cerr); }
123
124
125 //===----------------------------------------------------------------------===//
126 // Simple Spiller Implementation
127 //===----------------------------------------------------------------------===//
128
129 Spiller::~Spiller() {}
130
131 namespace {
132   struct SimpleSpiller : public Spiller {
133     bool runOnMachineFunction(MachineFunction& mf, const VirtRegMap &VRM);
134   };
135 }
136
137 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF,
138                                          const VirtRegMap &VRM) {
139   DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
140   DEBUG(std::cerr << "********** Function: "
141                   << MF.getFunction()->getName() << '\n');
142   const TargetMachine &TM = MF.getTarget();
143   const MRegisterInfo &MRI = *TM.getRegisterInfo();
144   bool *PhysRegsUsed = MF.getUsedPhysregs();
145
146   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
147   // each vreg once (in the case where a spilled vreg is used by multiple
148   // operands).  This is always smaller than the number of operands to the
149   // current machine instr, so it should be small.
150   std::vector<unsigned> LoadedRegs;
151
152   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
153        MBBI != E; ++MBBI) {
154     DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
155     MachineBasicBlock &MBB = *MBBI;
156     for (MachineBasicBlock::iterator MII = MBB.begin(),
157            E = MBB.end(); MII != E; ++MII) {
158       MachineInstr &MI = *MII;
159       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
160         MachineOperand &MO = MI.getOperand(i);
161         if (MO.isRegister() && MO.getReg())
162           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
163             unsigned VirtReg = MO.getReg();
164             unsigned PhysReg = VRM.getPhys(VirtReg);
165             if (VRM.hasStackSlot(VirtReg)) {
166               int StackSlot = VRM.getStackSlot(VirtReg);
167               const TargetRegisterClass* RC =
168                 MF.getSSARegMap()->getRegClass(VirtReg);
169
170               if (MO.isUse() &&
171                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
172                   == LoadedRegs.end()) {
173                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
174                 LoadedRegs.push_back(VirtReg);
175                 ++NumLoads;
176                 DEBUG(std::cerr << '\t' << *prior(MII));
177               }
178
179               if (MO.isDef()) {
180                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
181                 ++NumStores;
182               }
183             }
184             PhysRegsUsed[PhysReg] = true;
185             MI.SetMachineOperandReg(i, PhysReg);
186           } else {
187             PhysRegsUsed[MO.getReg()] = true;
188           }
189       }
190
191       DEBUG(std::cerr << '\t' << MI);
192       LoadedRegs.clear();
193     }
194   }
195   return true;
196 }
197
198 //===----------------------------------------------------------------------===//
199 //  Local Spiller Implementation
200 //===----------------------------------------------------------------------===//
201
202 namespace {
203   /// LocalSpiller - This spiller does a simple pass over the machine basic
204   /// block to attempt to keep spills in registers as much as possible for
205   /// blocks that have low register pressure (the vreg may be spilled due to
206   /// register pressure in other blocks).
207   class LocalSpiller : public Spiller {
208     const MRegisterInfo *MRI;
209     const TargetInstrInfo *TII;
210   public:
211     bool runOnMachineFunction(MachineFunction &MF, const VirtRegMap &VRM) {
212       MRI = MF.getTarget().getRegisterInfo();
213       TII = MF.getTarget().getInstrInfo();
214       DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
215                       << MF.getFunction()->getName() << "':\n");
216
217       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
218            MBB != E; ++MBB)
219         RewriteMBB(*MBB, VRM);
220       return true;
221     }
222   private:
223     void RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM);
224     void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
225                         std::multimap<unsigned, int> &PhysRegs);
226     void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
227                             std::multimap<unsigned, int> &PhysRegs);
228     void ModifyStackSlot(int Slot, std::map<int, unsigned> &SpillSlots,
229                          std::multimap<unsigned, int> &PhysRegs);
230   };
231 }
232
233 void LocalSpiller::ClobberPhysRegOnly(unsigned PhysReg,
234                                       std::map<int, unsigned> &SpillSlots,
235                               std::multimap<unsigned, int> &PhysRegsAvailable) {
236   std::map<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(PhysReg);
237   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
238     int Slot = I->second;
239     PhysRegsAvailable.erase(I++);
240     assert(SpillSlots[Slot] == PhysReg && "Bidirectional map mismatch!");
241     SpillSlots.erase(Slot);
242     DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
243                     << " clobbered, invalidating SS#" << Slot << "\n");
244
245   }
246 }
247
248 void LocalSpiller::ClobberPhysReg(unsigned PhysReg,
249                                   std::map<int, unsigned> &SpillSlots,
250                               std::multimap<unsigned, int> &PhysRegsAvailable) {
251   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
252     ClobberPhysRegOnly(*AS, SpillSlots, PhysRegsAvailable);
253   ClobberPhysRegOnly(PhysReg, SpillSlots, PhysRegsAvailable);
254 }
255
256 /// ModifyStackSlot - This method is called when the value in a stack slot
257 /// changes.  This removes information about which register the previous value
258 /// for this slot lives in (as the previous value is dead now).
259 void LocalSpiller::ModifyStackSlot(int Slot, std::map<int,unsigned> &SpillSlots,
260                               std::multimap<unsigned, int> &PhysRegsAvailable) {
261   std::map<int, unsigned>::iterator It = SpillSlots.find(Slot);
262   if (It == SpillSlots.end()) return;
263   unsigned Reg = It->second;
264   SpillSlots.erase(It);
265   
266   // This register may hold the value of multiple stack slots, only remove this
267   // stack slot from the set of values the register contains.
268   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
269   for (; ; ++I) {
270     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
271            "Map inverse broken!");
272     if (I->second == Slot) break;
273   }
274   PhysRegsAvailable.erase(I);
275 }
276
277
278
279 // ReusedOp - For each reused operand, we keep track of a bit of information, in
280 // case we need to rollback upon processing a new operand.  See comments below.
281 namespace {
282   struct ReusedOp {
283     // The MachineInstr operand that reused an available value.
284     unsigned Operand;
285
286     // StackSlot - The spill slot of the value being reused.
287     unsigned StackSlot;
288
289     // PhysRegReused - The physical register the value was available in.
290     unsigned PhysRegReused;
291
292     // AssignedPhysReg - The physreg that was assigned for use by the reload.
293     unsigned AssignedPhysReg;
294     
295     // VirtReg - The virtual register itself.
296     unsigned VirtReg;
297
298     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
299              unsigned vreg)
300       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
301       VirtReg(vreg) {}
302   };
303 }
304
305
306 /// rewriteMBB - Keep track of which spills are available even after the
307 /// register allocator is done with them.  If possible, avoid reloading vregs.
308 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM) {
309
310   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
311   // register values that are still available, due to being loaded or stored to,
312   // but not invalidated yet.
313   std::map<int, unsigned> SpillSlotsAvailable;
314
315   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
316   // which stack slot values are currently held by a physreg.  This is used to
317   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
318   std::multimap<unsigned, int> PhysRegsAvailable;
319
320   DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
321
322   std::vector<ReusedOp> ReusedOperands;
323
324   // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
325   // of it.  ".first" is the machine operand index (should always be 0 for now),
326   // and ".second" is the virtual register that is spilled.
327   std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
328
329   // MaybeDeadStores - When we need to write a value back into a stack slot,
330   // keep track of the inserted store.  If the stack slot value is never read
331   // (because the value was used from some available register, for example), and
332   // subsequently stored to, the original store is dead.  This map keeps track
333   // of inserted stores that are not used.  If we see a subsequent store to the
334   // same stack slot, the original store is deleted.
335   std::map<int, MachineInstr*> MaybeDeadStores;
336
337   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
338
339   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
340        MII != E; ) {
341     MachineInstr &MI = *MII;
342     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
343
344     ReusedOperands.clear();
345     DefAndUseVReg.clear();
346
347     // Process all of the spilled uses and all non spilled reg references.
348     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
349       MachineOperand &MO = MI.getOperand(i);
350       if (!MO.isRegister() || MO.getReg() == 0)
351         continue;   // Ignore non-register operands.
352       
353       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
354         // Ignore physregs for spilling, but remember that it is used by this
355         // function.
356         PhysRegsUsed[MO.getReg()] = true;
357         continue;
358       }
359       
360       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
361              "Not a virtual or a physical register?");
362       
363       unsigned VirtReg = MO.getReg();
364       if (!VRM.hasStackSlot(VirtReg)) {
365         // This virtual register was assigned a physreg!
366         unsigned Phys = VRM.getPhys(VirtReg);
367         PhysRegsUsed[Phys] = true;
368         MI.SetMachineOperandReg(i, Phys);
369         continue;
370       }
371       
372       // This virtual register is now known to be a spilled value.
373       if (!MO.isUse())
374         continue;  // Handle defs in the loop below (handle use&def here though)
375
376       // If this is both a def and a use, we need to emit a store to the
377       // stack slot after the instruction.  Keep track of D&U operands
378       // because we are about to change it to a physreg here.
379       if (MO.isDef()) {
380         // Remember that this was a def-and-use operand, and that the
381         // stack slot is live after this instruction executes.
382         DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
383       }
384       
385       int StackSlot = VRM.getStackSlot(VirtReg);
386       unsigned PhysReg;
387
388       // Check to see if this stack slot is available.
389       std::map<int, unsigned>::iterator SSI =
390         SpillSlotsAvailable.find(StackSlot);
391       if (SSI != SpillSlotsAvailable.end()) {
392         DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
393                         << MRI->getName(SSI->second) << " for vreg"
394                         << VirtReg <<" instead of reloading into physreg "
395                         << MRI->getName(VRM.getPhys(VirtReg)) << "\n");
396         // If this stack slot value is already available, reuse it!
397         PhysReg = SSI->second;
398         MI.SetMachineOperandReg(i, PhysReg);
399
400         // The only technical detail we have is that we don't know that
401         // PhysReg won't be clobbered by a reloaded stack slot that occurs
402         // later in the instruction.  In particular, consider 'op V1, V2'.
403         // If V1 is available in physreg R0, we would choose to reuse it
404         // here, instead of reloading it into the register the allocator
405         // indicated (say R1).  However, V2 might have to be reloaded
406         // later, and it might indicate that it needs to live in R0.  When
407         // this occurs, we need to have information available that
408         // indicates it is safe to use R1 for the reload instead of R0.
409         //
410         // To further complicate matters, we might conflict with an alias,
411         // or R0 and R1 might not be compatible with each other.  In this
412         // case, we actually insert a reload for V1 in R1, ensuring that
413         // we can get at R0 or its alias.
414         ReusedOperands.push_back(ReusedOp(i, StackSlot, PhysReg,
415                                           VRM.getPhys(VirtReg), VirtReg));
416         ++NumReused;
417         continue;
418       }
419       
420       // Otherwise, reload it and remember that we have it.
421       PhysReg = VRM.getPhys(VirtReg);
422       assert(PhysReg && "Must map virtreg to physreg!");
423       const TargetRegisterClass* RC =
424         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
425
426     RecheckRegister:
427       // Note that, if we reused a register for a previous operand, the
428       // register we want to reload into might not actually be
429       // available.  If this occurs, use the register indicated by the
430       // reuser.
431       if (!ReusedOperands.empty())   // This is most often empty.
432         for (unsigned ro = 0, e = ReusedOperands.size(); ro != e; ++ro)
433           if (ReusedOperands[ro].PhysRegReused == PhysReg) {
434             // Yup, use the reload register that we didn't use before.
435             PhysReg = ReusedOperands[ro].AssignedPhysReg;
436             goto RecheckRegister;
437           } else {
438             ReusedOp &Op = ReusedOperands[ro];
439             unsigned PRRU = Op.PhysRegReused;
440             if (MRI->areAliases(PRRU, PhysReg)) {
441               // Okay, we found out that an alias of a reused register
442               // was used.  This isn't good because it means we have
443               // to undo a previous reuse.
444               const TargetRegisterClass *AliasRC =
445                 MBB.getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
446               MRI->loadRegFromStackSlot(MBB, &MI, Op.AssignedPhysReg,
447                                         Op.StackSlot, AliasRC);
448               ClobberPhysReg(Op.AssignedPhysReg, SpillSlotsAvailable,
449                              PhysRegsAvailable);
450
451               // Any stores to this stack slot are not dead anymore.
452               MaybeDeadStores.erase(Op.StackSlot);
453
454               MI.SetMachineOperandReg(Op.Operand, Op.AssignedPhysReg);
455               PhysRegsAvailable.insert(std::make_pair(Op.AssignedPhysReg,
456                                                       Op.StackSlot));
457               SpillSlotsAvailable[Op.StackSlot] = Op.AssignedPhysReg;
458               PhysRegsAvailable.erase(Op.PhysRegReused);
459               DEBUG(std::cerr << "Remembering SS#" << Op.StackSlot
460                               << " in physreg "
461                               << MRI->getName(Op.AssignedPhysReg) << "\n");
462               ++NumLoads;
463               DEBUG(std::cerr << '\t' << *prior(MII));
464
465               DEBUG(std::cerr << "Reuse undone!\n");
466               ReusedOperands.erase(ReusedOperands.begin()+ro);
467               --NumReused;
468               goto ContinueReload;
469             }
470           }
471     ContinueReload:
472       PhysRegsUsed[PhysReg] = true;
473       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
474       // This invalidates PhysReg.
475       ClobberPhysReg(PhysReg, SpillSlotsAvailable, PhysRegsAvailable);
476
477       // Any stores to this stack slot are not dead anymore.
478       MaybeDeadStores.erase(StackSlot);
479
480       MI.SetMachineOperandReg(i, PhysReg);
481       PhysRegsAvailable.insert(std::make_pair(PhysReg, StackSlot));
482       SpillSlotsAvailable[StackSlot] = PhysReg;
483       DEBUG(std::cerr << "Remembering SS#" << StackSlot <<" in physreg "
484                       << MRI->getName(PhysReg) << "\n");
485       ++NumLoads;
486       DEBUG(std::cerr << '\t' << *prior(MII));
487     }
488
489     // Loop over all of the implicit defs, clearing them from our available
490     // sets.
491     for (const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
492          *ImpDef; ++ImpDef) {
493       PhysRegsUsed[*ImpDef] = true;
494       ClobberPhysReg(*ImpDef, SpillSlotsAvailable, PhysRegsAvailable);
495     }
496
497     DEBUG(std::cerr << '\t' << MI);
498
499     // If we have folded references to memory operands, make sure we clear all
500     // physical registers that may contain the value of the spilled virtual
501     // register
502     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
503     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
504       DEBUG(std::cerr << "Folded vreg: " << I->second.first << "  MR: "
505                       << I->second.second);
506       unsigned VirtReg = I->second.first;
507       VirtRegMap::ModRef MR = I->second.second;
508       if (!VRM.hasStackSlot(VirtReg)) {
509         DEBUG(std::cerr << ": No stack slot!\n");
510         continue;
511       }
512       int SS = VRM.getStackSlot(VirtReg);
513       DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
514       
515       // If this folded instruction is just a use, check to see if it's a
516       // straight load from the virt reg slot.
517       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
518         int FrameIdx;
519         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
520           // If this spill slot is available, turn it into a copy (or nothing)
521           // instead of leaving it as a load!
522           std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(SS);
523           if (FrameIdx == SS && It != SpillSlotsAvailable.end()) {
524             DEBUG(std::cerr << "Promoted Load To Copy: " << MI);
525             MachineFunction &MF = *MBB.getParent();
526             if (DestReg != It->second) {
527               MRI->copyRegToReg(MBB, &MI, DestReg, It->second,
528                                 MF.getSSARegMap()->getRegClass(VirtReg));
529               // Revisit the copy so we make sure to notice the effects of the
530               // operation on the destreg (either needing to RA it if it's 
531               // virtual or needing to clobber any values if it's physical).
532               NextMII = &MI;
533               --NextMII;  // backtrack to the copy.
534             }
535             MBB.erase(&MI);
536             goto ProcessNextInst;
537           }
538         }
539       }
540
541       // If this reference is not a use, any previous store is now dead.
542       // Otherwise, the store to this stack slot is not dead anymore.
543       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
544       if (MDSI != MaybeDeadStores.end()) {
545         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
546           MaybeDeadStores.erase(MDSI);
547         else {
548           // If we get here, the store is dead, nuke it now.
549           assert(MR == VirtRegMap::isMod && "Can't be modref!");
550           MBB.erase(MDSI->second);
551           MaybeDeadStores.erase(MDSI);
552           ++NumDSE;
553         }
554       }
555
556       // If the spill slot value is available, and this is a new definition of
557       // the value, the value is not available anymore.
558       if (MR & VirtRegMap::isMod) {
559         // Notice that the value in this stack slot has been modified.
560         ModifyStackSlot(SS, SpillSlotsAvailable, PhysRegsAvailable);
561         
562         // If this is *just* a mod of the value, check to see if this is just a
563         // store to the spill slot (i.e. the spill got merged into the copy). If
564         // so, realize that the vreg is available now, and add the store to the
565         // MaybeDeadStore info.
566         int StackSlot;
567         if (!(MR & VirtRegMap::isRef)) {
568           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
569             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
570                    "Src hasn't been allocated yet?");
571             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
572             // this as a potentially dead store in case there is a subsequent
573             // store into the stack slot without a read from it.
574             MaybeDeadStores[StackSlot] = &MI;
575
576             // If the stack slot value was previously available in some other
577             // register, change it now.  Otherwise, make the register available,
578             // in PhysReg.
579             SpillSlotsAvailable[StackSlot] = SrcReg;
580             PhysRegsAvailable.insert(std::make_pair(SrcReg, StackSlot));
581             DEBUG(std::cerr << "Updating SS#" << StackSlot << " in physreg "
582                             << MRI->getName(SrcReg) << " for virtreg #"
583                             << VirtReg << "\n" << MI);
584           }
585         }
586       }
587     }
588
589     // Process all of the spilled defs.
590     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
591       MachineOperand &MO = MI.getOperand(i);
592       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
593         unsigned VirtReg = MO.getReg();
594
595         bool TakenCareOf = false;
596         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
597           // Check to see if this is a def-and-use vreg operand that we do need
598           // to insert a store for.
599           bool OpTakenCareOf = false;
600           if (MO.isUse() && !DefAndUseVReg.empty()) {
601             for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
602               if (DefAndUseVReg[dau].first == i) {
603                 VirtReg = DefAndUseVReg[dau].second;
604                 OpTakenCareOf = true;
605                 break;
606               }
607           }
608
609           if (!OpTakenCareOf) {
610             ClobberPhysReg(VirtReg, SpillSlotsAvailable, PhysRegsAvailable);
611             TakenCareOf = true;
612           }
613         }
614
615         if (!TakenCareOf) {
616           // The only vregs left are stack slot definitions.
617           int StackSlot = VRM.getStackSlot(VirtReg);
618           const TargetRegisterClass *RC =
619             MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
620           unsigned PhysReg;
621
622           // If this is a def&use operand, and we used a different physreg for
623           // it than the one assigned, make sure to execute the store from the
624           // correct physical register.
625           if (MO.getReg() == VirtReg)
626             PhysReg = VRM.getPhys(VirtReg);
627           else
628             PhysReg = MO.getReg();
629
630           PhysRegsUsed[PhysReg] = true;
631           MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
632           DEBUG(std::cerr << "Store:\t" << *next(MII));
633           MI.SetMachineOperandReg(i, PhysReg);
634
635           // If there is a dead store to this stack slot, nuke it now.
636           MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
637           if (LastStore) {
638             DEBUG(std::cerr << " Killed store:\t" << *LastStore);
639             ++NumDSE;
640             MBB.erase(LastStore);
641           }
642           LastStore = next(MII);
643
644           // If the stack slot value was previously available in some other
645           // register, change it now.  Otherwise, make the register available,
646           // in PhysReg.
647           ModifyStackSlot(StackSlot, SpillSlotsAvailable, PhysRegsAvailable);
648           ClobberPhysReg(PhysReg, SpillSlotsAvailable, PhysRegsAvailable);
649
650           PhysRegsAvailable.insert(std::make_pair(PhysReg, StackSlot));
651           SpillSlotsAvailable[StackSlot] = PhysReg;
652           DEBUG(std::cerr << "Updating SS#" << StackSlot <<" in physreg "
653                           << MRI->getName(PhysReg) << " for virtreg #"
654                           << VirtReg << "\n");
655
656           ++NumStores;
657           VirtReg = PhysReg;
658         }
659       }
660     }
661   ProcessNextInst:
662     MII = NextMII;
663   }
664 }
665
666
667
668 llvm::Spiller* llvm::createSpiller() {
669   switch (SpillerOpt) {
670   default: assert(0 && "Unreachable!");
671   case local:
672     return new LocalSpiller();
673   case simple:
674     return new SimpleSpiller();
675   }
676 }