More removal of std::cerr and DEBUG, replacing with DOUT instead.
[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/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 namespace {
36   static Statistic<> NumSpills("spiller", "Number of register spills");
37   static Statistic<> NumStores("spiller", "Number of stores added");
38   static Statistic<> NumLoads ("spiller", "Number of loads added");
39   static Statistic<> NumReused("spiller", "Number of values reused");
40   static Statistic<> NumDSE   ("spiller", "Number of dead stores elided");
41   static Statistic<> NumDCE   ("spiller", "Number of copies elided");
42
43   enum SpillerName { simple, local };
44
45   static cl::opt<SpillerName>
46   SpillerOpt("spiller",
47              cl::desc("Spiller to use: (default: local)"),
48              cl::Prefix,
49              cl::values(clEnumVal(simple, "  simple spiller"),
50                         clEnumVal(local,  "  local spiller"),
51                         clEnumValEnd),
52              cl::init(local));
53 }
54
55 //===----------------------------------------------------------------------===//
56 //  VirtRegMap implementation
57 //===----------------------------------------------------------------------===//
58
59 VirtRegMap::VirtRegMap(MachineFunction &mf)
60   : TII(*mf.getTarget().getInstrInfo()), MF(mf), 
61     Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT) {
62   grow();
63 }
64
65 void VirtRegMap::grow() {
66   Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
67   Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
68 }
69
70 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
71   assert(MRegisterInfo::isVirtualRegister(virtReg));
72   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
73          "attempt to assign stack slot to already spilled register");
74   const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
75   int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
76                                                         RC->getAlignment());
77   Virt2StackSlotMap[virtReg] = frameIndex;
78   ++NumSpills;
79   return frameIndex;
80 }
81
82 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
83   assert(MRegisterInfo::isVirtualRegister(virtReg));
84   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
85          "attempt to assign stack slot to already spilled register");
86   Virt2StackSlotMap[virtReg] = frameIndex;
87 }
88
89 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
90                             unsigned OpNo, MachineInstr *NewMI) {
91   // Move previous memory references folded to new instruction.
92   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
93   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
94          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
95     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
96     MI2VirtMap.erase(I++);
97   }
98
99   ModRef MRInfo;
100   if (TII.getOperandConstraint(OldMI->getOpcode(), OpNo,
101                                TargetInstrInfo::TIED_TO)) {
102     // Folded a two-address operand.
103     MRInfo = isModRef;
104   } else if (OldMI->getOperand(OpNo).isDef()) {
105     MRInfo = isMod;
106   } else {
107     MRInfo = isRef;
108   }
109
110   // add new memory reference
111   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
112 }
113
114 void VirtRegMap::print(std::ostream &OS) const {
115   llvm_ostream LOS(OS);
116   print(LOS);
117 }
118
119 void VirtRegMap::print(llvm_ostream &OS) const {
120   const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
121
122   OS << "********** REGISTER MAP **********\n";
123   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
124          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
125     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
126       OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
127
128   }
129
130   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
131          e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
132     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
133       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
134   OS << '\n';
135 }
136
137 void VirtRegMap::dump() const {
138   llvm_ostream OS = DOUT;
139   print(OS);
140 }
141
142
143 //===----------------------------------------------------------------------===//
144 // Simple Spiller Implementation
145 //===----------------------------------------------------------------------===//
146
147 Spiller::~Spiller() {}
148
149 namespace {
150   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
151     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
152   };
153 }
154
155 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
156   DOUT << "********** REWRITE MACHINE CODE **********\n";
157   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
158   const TargetMachine &TM = MF.getTarget();
159   const MRegisterInfo &MRI = *TM.getRegisterInfo();
160   bool *PhysRegsUsed = MF.getUsedPhysregs();
161
162   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
163   // each vreg once (in the case where a spilled vreg is used by multiple
164   // operands).  This is always smaller than the number of operands to the
165   // current machine instr, so it should be small.
166   std::vector<unsigned> LoadedRegs;
167
168   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
169        MBBI != E; ++MBBI) {
170     DOUT << MBBI->getBasicBlock()->getName() << ":\n";
171     MachineBasicBlock &MBB = *MBBI;
172     for (MachineBasicBlock::iterator MII = MBB.begin(),
173            E = MBB.end(); MII != E; ++MII) {
174       MachineInstr &MI = *MII;
175       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
176         MachineOperand &MO = MI.getOperand(i);
177         if (MO.isRegister() && MO.getReg())
178           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
179             unsigned VirtReg = MO.getReg();
180             unsigned PhysReg = VRM.getPhys(VirtReg);
181             if (VRM.hasStackSlot(VirtReg)) {
182               int StackSlot = VRM.getStackSlot(VirtReg);
183               const TargetRegisterClass* RC =
184                 MF.getSSARegMap()->getRegClass(VirtReg);
185
186               if (MO.isUse() &&
187                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
188                   == LoadedRegs.end()) {
189                 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
190                 LoadedRegs.push_back(VirtReg);
191                 ++NumLoads;
192                 DOUT << '\t' << *prior(MII);
193               }
194
195               if (MO.isDef()) {
196                 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
197                 ++NumStores;
198               }
199             }
200             PhysRegsUsed[PhysReg] = true;
201             MI.getOperand(i).setReg(PhysReg);
202           } else {
203             PhysRegsUsed[MO.getReg()] = true;
204           }
205       }
206
207       DOUT << '\t' << MI;
208       LoadedRegs.clear();
209     }
210   }
211   return true;
212 }
213
214 //===----------------------------------------------------------------------===//
215 //  Local Spiller Implementation
216 //===----------------------------------------------------------------------===//
217
218 namespace {
219   /// LocalSpiller - This spiller does a simple pass over the machine basic
220   /// block to attempt to keep spills in registers as much as possible for
221   /// blocks that have low register pressure (the vreg may be spilled due to
222   /// register pressure in other blocks).
223   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
224     const MRegisterInfo *MRI;
225     const TargetInstrInfo *TII;
226   public:
227     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
228       MRI = MF.getTarget().getRegisterInfo();
229       TII = MF.getTarget().getInstrInfo();
230       DOUT << "\n**** Local spiller rewriting function '"
231            << MF.getFunction()->getName() << "':\n";
232
233       for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
234            MBB != E; ++MBB)
235         RewriteMBB(*MBB, VRM);
236       return true;
237     }
238   private:
239     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
240     void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
241                         std::multimap<unsigned, int> &PhysRegs);
242     void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
243                             std::multimap<unsigned, int> &PhysRegs);
244     void ModifyStackSlot(int Slot, std::map<int, unsigned> &SpillSlots,
245                          std::multimap<unsigned, int> &PhysRegs);
246   };
247 }
248
249 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
250 /// top down, keep track of which spills slots are available in each register.
251 ///
252 /// Note that not all physregs are created equal here.  In particular, some
253 /// physregs are reloads that we are allowed to clobber or ignore at any time.
254 /// Other physregs are values that the register allocated program is using that
255 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
256 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
257 /// entries.  The predicate 'canClobberPhysReg()' checks this bit and
258 /// addAvailable sets it if.
259 namespace {
260 class VISIBILITY_HIDDEN AvailableSpills {
261   const MRegisterInfo *MRI;
262   const TargetInstrInfo *TII;
263
264   // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
265   // register values that are still available, due to being loaded or stored to,
266   // but not invalidated yet.
267   std::map<int, unsigned> SpillSlotsAvailable;
268     
269   // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
270   // which stack slot values are currently held by a physreg.  This is used to
271   // invalidate entries in SpillSlotsAvailable when a physreg is modified.
272   std::multimap<unsigned, int> PhysRegsAvailable;
273   
274   void ClobberPhysRegOnly(unsigned PhysReg);
275 public:
276   AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
277     : MRI(mri), TII(tii) {
278   }
279   
280   /// getSpillSlotPhysReg - If the specified stack slot is available in a 
281   /// physical register, return that PhysReg, otherwise return 0.
282   unsigned getSpillSlotPhysReg(int Slot) const {
283     std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
284     if (I != SpillSlotsAvailable.end())
285       return I->second >> 1;  // Remove the CanClobber bit.
286     return 0;
287   }
288   
289   const MRegisterInfo *getRegInfo() const { return MRI; }
290
291   /// addAvailable - Mark that the specified stack slot is available in the
292   /// specified physreg.  If CanClobber is true, the physreg can be modified at
293   /// any time without changing the semantics of the program.
294   void addAvailable(int Slot, unsigned Reg, bool CanClobber = true) {
295     // If this stack slot is thought to be available in some other physreg, 
296     // remove its record.
297     ModifyStackSlot(Slot);
298     
299     PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
300     SpillSlotsAvailable[Slot] = (Reg << 1) | (unsigned)CanClobber;
301   
302     DOUT << "Remembering SS#" << Slot << " in physreg "
303          << MRI->getName(Reg) << "\n";
304   }
305   
306   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
307   /// value of the specified stackslot register if it desires.  The specified
308   /// stack slot must be available in a physreg for this query to make sense.
309   bool canClobberPhysReg(int Slot) const {
310     assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
311     return SpillSlotsAvailable.find(Slot)->second & 1;
312   }
313   
314   /// ClobberPhysReg - This is called when the specified physreg changes
315   /// value.  We use this to invalidate any info about stuff we thing lives in
316   /// it and any of its aliases.
317   void ClobberPhysReg(unsigned PhysReg);
318
319   /// ModifyStackSlot - This method is called when the value in a stack slot
320   /// changes.  This removes information about which register the previous value
321   /// for this slot lives in (as the previous value is dead now).
322   void ModifyStackSlot(int Slot);
323 };
324 }
325
326 /// ClobberPhysRegOnly - This is called when the specified physreg changes
327 /// value.  We use this to invalidate any info about stuff we thing lives in it.
328 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
329   std::multimap<unsigned, int>::iterator I =
330     PhysRegsAvailable.lower_bound(PhysReg);
331   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
332     int Slot = I->second;
333     PhysRegsAvailable.erase(I++);
334     assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
335            "Bidirectional map mismatch!");
336     SpillSlotsAvailable.erase(Slot);
337     DOUT << "PhysReg " << MRI->getName(PhysReg)
338          << " clobbered, invalidating SS#" << Slot << "\n";
339   }
340 }
341
342 /// ClobberPhysReg - This is called when the specified physreg changes
343 /// value.  We use this to invalidate any info about stuff we thing lives in
344 /// it and any of its aliases.
345 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
346   for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
347     ClobberPhysRegOnly(*AS);
348   ClobberPhysRegOnly(PhysReg);
349 }
350
351 /// ModifyStackSlot - This method is called when the value in a stack slot
352 /// changes.  This removes information about which register the previous value
353 /// for this slot lives in (as the previous value is dead now).
354 void AvailableSpills::ModifyStackSlot(int Slot) {
355   std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
356   if (It == SpillSlotsAvailable.end()) return;
357   unsigned Reg = It->second >> 1;
358   SpillSlotsAvailable.erase(It);
359   
360   // This register may hold the value of multiple stack slots, only remove this
361   // stack slot from the set of values the register contains.
362   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
363   for (; ; ++I) {
364     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
365            "Map inverse broken!");
366     if (I->second == Slot) break;
367   }
368   PhysRegsAvailable.erase(I);
369 }
370
371
372
373 // ReusedOp - For each reused operand, we keep track of a bit of information, in
374 // case we need to rollback upon processing a new operand.  See comments below.
375 namespace {
376   struct ReusedOp {
377     // The MachineInstr operand that reused an available value.
378     unsigned Operand;
379
380     // StackSlot - The spill slot of the value being reused.
381     unsigned StackSlot;
382
383     // PhysRegReused - The physical register the value was available in.
384     unsigned PhysRegReused;
385
386     // AssignedPhysReg - The physreg that was assigned for use by the reload.
387     unsigned AssignedPhysReg;
388     
389     // VirtReg - The virtual register itself.
390     unsigned VirtReg;
391
392     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
393              unsigned vreg)
394       : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
395       VirtReg(vreg) {}
396   };
397   
398   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
399   /// is reused instead of reloaded.
400   class VISIBILITY_HIDDEN ReuseInfo {
401     MachineInstr &MI;
402     std::vector<ReusedOp> Reuses;
403     bool *PhysRegsClobbered;
404   public:
405     ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
406       PhysRegsClobbered = new bool[mri->getNumRegs()];
407       std::fill(PhysRegsClobbered, PhysRegsClobbered+mri->getNumRegs(), false);
408     }
409     ~ReuseInfo() {
410       delete[] PhysRegsClobbered;
411     }
412     
413     bool hasReuses() const {
414       return !Reuses.empty();
415     }
416     
417     /// addReuse - If we choose to reuse a virtual register that is already
418     /// available instead of reloading it, remember that we did so.
419     void addReuse(unsigned OpNo, unsigned StackSlot,
420                   unsigned PhysRegReused, unsigned AssignedPhysReg,
421                   unsigned VirtReg) {
422       // If the reload is to the assigned register anyway, no undo will be
423       // required.
424       if (PhysRegReused == AssignedPhysReg) return;
425       
426       // Otherwise, remember this.
427       Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused, 
428                                 AssignedPhysReg, VirtReg));
429     }
430
431     void markClobbered(unsigned PhysReg) {
432       PhysRegsClobbered[PhysReg] = true;
433     }
434
435     bool isClobbered(unsigned PhysReg) const {
436       return PhysRegsClobbered[PhysReg];
437     }
438     
439     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
440     /// is some other operand that is using the specified register, either pick
441     /// a new register to use, or evict the previous reload and use this reg. 
442     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
443                              AvailableSpills &Spills,
444                              std::map<int, MachineInstr*> &MaybeDeadStores) {
445       if (Reuses.empty()) return PhysReg;  // This is most often empty.
446
447       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
448         ReusedOp &Op = Reuses[ro];
449         // If we find some other reuse that was supposed to use this register
450         // exactly for its reload, we can change this reload to use ITS reload
451         // register.
452         if (Op.PhysRegReused == PhysReg) {
453           // Yup, use the reload register that we didn't use before.
454           unsigned NewReg = Op.AssignedPhysReg;          
455           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores);
456         } else {
457           // Otherwise, we might also have a problem if a previously reused
458           // value aliases the new register.  If so, codegen the previous reload
459           // and use this one.          
460           unsigned PRRU = Op.PhysRegReused;
461           const MRegisterInfo *MRI = Spills.getRegInfo();
462           if (MRI->areAliases(PRRU, PhysReg)) {
463             // Okay, we found out that an alias of a reused register
464             // was used.  This isn't good because it means we have
465             // to undo a previous reuse.
466             MachineBasicBlock *MBB = MI->getParent();
467             const TargetRegisterClass *AliasRC =
468               MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
469
470             // Copy Op out of the vector and remove it, we're going to insert an
471             // explicit load for it.
472             ReusedOp NewOp = Op;
473             Reuses.erase(Reuses.begin()+ro);
474
475             // Ok, we're going to try to reload the assigned physreg into the
476             // slot that we were supposed to in the first place.  However, that
477             // register could hold a reuse.  Check to see if it conflicts or
478             // would prefer us to use a different register.
479             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
480                                                   MI, Spills, MaybeDeadStores);
481             
482             MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
483                                       NewOp.StackSlot, AliasRC);
484             Spills.ClobberPhysReg(NewPhysReg);
485             Spills.ClobberPhysReg(NewOp.PhysRegReused);
486             
487             // Any stores to this stack slot are not dead anymore.
488             MaybeDeadStores.erase(NewOp.StackSlot);
489             
490             MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
491             
492             Spills.addAvailable(NewOp.StackSlot, NewPhysReg);
493             ++NumLoads;
494             DEBUG(MachineBasicBlock::iterator MII = MI;
495                   DOUT << '\t' << *prior(MII));
496             
497             DOUT << "Reuse undone!\n";
498             --NumReused;
499             
500             // Finally, PhysReg is now available, go ahead and use it.
501             return PhysReg;
502           }
503         }
504       }
505       return PhysReg;
506     }
507   };
508 }
509
510
511 /// rewriteMBB - Keep track of which spills are available even after the
512 /// register allocator is done with them.  If possible, avoid reloading vregs.
513 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
514
515   DOUT << MBB.getBasicBlock()->getName() << ":\n";
516
517   // Spills - Keep track of which spilled values are available in physregs so
518   // that we can choose to reuse the physregs instead of emitting reloads.
519   AvailableSpills Spills(MRI, TII);
520   
521   // MaybeDeadStores - When we need to write a value back into a stack slot,
522   // keep track of the inserted store.  If the stack slot value is never read
523   // (because the value was used from some available register, for example), and
524   // subsequently stored to, the original store is dead.  This map keeps track
525   // of inserted stores that are not used.  If we see a subsequent store to the
526   // same stack slot, the original store is deleted.
527   std::map<int, MachineInstr*> MaybeDeadStores;
528
529   bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
530
531   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
532        MII != E; ) {
533     MachineInstr &MI = *MII;
534     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
535
536     /// ReusedOperands - Keep track of operand reuse in case we need to undo
537     /// reuse.
538     ReuseInfo ReusedOperands(MI, MRI);
539
540     // Loop over all of the implicit defs, clearing them from our available
541     // sets.
542     const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
543     if (ImpDef) {
544       for ( ; *ImpDef; ++ImpDef) {
545         PhysRegsUsed[*ImpDef] = true;
546         ReusedOperands.markClobbered(*ImpDef);
547         Spills.ClobberPhysReg(*ImpDef);
548       }
549     }
550
551     // Process all of the spilled uses and all non spilled reg references.
552     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
553       MachineOperand &MO = MI.getOperand(i);
554       if (!MO.isRegister() || MO.getReg() == 0)
555         continue;   // Ignore non-register operands.
556       
557       if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
558         // Ignore physregs for spilling, but remember that it is used by this
559         // function.
560         PhysRegsUsed[MO.getReg()] = true;
561         ReusedOperands.markClobbered(MO.getReg());
562         continue;
563       }
564       
565       assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
566              "Not a virtual or a physical register?");
567       
568       unsigned VirtReg = MO.getReg();
569       if (!VRM.hasStackSlot(VirtReg)) {
570         // This virtual register was assigned a physreg!
571         unsigned Phys = VRM.getPhys(VirtReg);
572         PhysRegsUsed[Phys] = true;
573         if (MO.isDef())
574           ReusedOperands.markClobbered(Phys);
575         MI.getOperand(i).setReg(Phys);
576         continue;
577       }
578       
579       // This virtual register is now known to be a spilled value.
580       if (!MO.isUse())
581         continue;  // Handle defs in the loop below (handle use&def here though)
582
583       int StackSlot = VRM.getStackSlot(VirtReg);
584       unsigned PhysReg;
585
586       // Check to see if this stack slot is available.
587       if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot))) {
588
589         // This spilled operand might be part of a two-address operand.  If this
590         // is the case, then changing it will necessarily require changing the 
591         // def part of the instruction as well.  However, in some cases, we
592         // aren't allowed to modify the reused register.  If none of these cases
593         // apply, reuse it.
594         bool CanReuse = true;
595         int ti = TII->getOperandConstraint(MI.getOpcode(), i,
596                                            TargetInstrInfo::TIED_TO);
597         if (ti != -1 &&
598             MI.getOperand(ti).isReg() && 
599             MI.getOperand(ti).getReg() == VirtReg) {
600           // Okay, we have a two address operand.  We can reuse this physreg as
601           // long as we are allowed to clobber the value and there is an earlier
602           // def that has already clobbered the physreg.
603           CanReuse = Spills.canClobberPhysReg(StackSlot) &&
604             !ReusedOperands.isClobbered(PhysReg);
605         }
606         
607         if (CanReuse) {
608           // If this stack slot value is already available, reuse it!
609           DOUT << "Reusing SS#" << StackSlot << " from physreg "
610                << MRI->getName(PhysReg) << " for vreg"
611                << VirtReg <<" instead of reloading into physreg "
612                << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
613           MI.getOperand(i).setReg(PhysReg);
614
615           // The only technical detail we have is that we don't know that
616           // PhysReg won't be clobbered by a reloaded stack slot that occurs
617           // later in the instruction.  In particular, consider 'op V1, V2'.
618           // If V1 is available in physreg R0, we would choose to reuse it
619           // here, instead of reloading it into the register the allocator
620           // indicated (say R1).  However, V2 might have to be reloaded
621           // later, and it might indicate that it needs to live in R0.  When
622           // this occurs, we need to have information available that
623           // indicates it is safe to use R1 for the reload instead of R0.
624           //
625           // To further complicate matters, we might conflict with an alias,
626           // or R0 and R1 might not be compatible with each other.  In this
627           // case, we actually insert a reload for V1 in R1, ensuring that
628           // we can get at R0 or its alias.
629           ReusedOperands.addReuse(i, StackSlot, PhysReg,
630                                   VRM.getPhys(VirtReg), VirtReg);
631           if (ti != -1)
632             // Only mark it clobbered if this is a use&def operand.
633             ReusedOperands.markClobbered(PhysReg);
634           ++NumReused;
635           continue;
636         }
637         
638         // Otherwise we have a situation where we have a two-address instruction
639         // whose mod/ref operand needs to be reloaded.  This reload is already
640         // available in some register "PhysReg", but if we used PhysReg as the
641         // operand to our 2-addr instruction, the instruction would modify
642         // PhysReg.  This isn't cool if something later uses PhysReg and expects
643         // to get its initial value.
644         //
645         // To avoid this problem, and to avoid doing a load right after a store,
646         // we emit a copy from PhysReg into the designated register for this
647         // operand.
648         unsigned DesignatedReg = VRM.getPhys(VirtReg);
649         assert(DesignatedReg && "Must map virtreg to physreg!");
650
651         // Note that, if we reused a register for a previous operand, the
652         // register we want to reload into might not actually be
653         // available.  If this occurs, use the register indicated by the
654         // reuser.
655         if (ReusedOperands.hasReuses())
656           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
657                                                       Spills, MaybeDeadStores);
658         
659         // If the mapped designated register is actually the physreg we have
660         // incoming, we don't need to inserted a dead copy.
661         if (DesignatedReg == PhysReg) {
662           // If this stack slot value is already available, reuse it!
663           DOUT << "Reusing SS#" << StackSlot << " from physreg "
664                << MRI->getName(PhysReg) << " for vreg"
665                << VirtReg
666                << " instead of reloading into same physreg.\n";
667           MI.getOperand(i).setReg(PhysReg);
668           ReusedOperands.markClobbered(PhysReg);
669           ++NumReused;
670           continue;
671         }
672         
673         const TargetRegisterClass* RC =
674           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
675
676         PhysRegsUsed[DesignatedReg] = true;
677         ReusedOperands.markClobbered(DesignatedReg);
678         MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
679         
680         // This invalidates DesignatedReg.
681         Spills.ClobberPhysReg(DesignatedReg);
682         
683         Spills.addAvailable(StackSlot, DesignatedReg);
684         MI.getOperand(i).setReg(DesignatedReg);
685         DOUT << '\t' << *prior(MII);
686         ++NumReused;
687         continue;
688       }
689       
690       // Otherwise, reload it and remember that we have it.
691       PhysReg = VRM.getPhys(VirtReg);
692       assert(PhysReg && "Must map virtreg to physreg!");
693       const TargetRegisterClass* RC =
694         MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
695
696       // Note that, if we reused a register for a previous operand, the
697       // register we want to reload into might not actually be
698       // available.  If this occurs, use the register indicated by the
699       // reuser.
700       if (ReusedOperands.hasReuses())
701         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
702                                                  Spills, MaybeDeadStores);
703       
704       PhysRegsUsed[PhysReg] = true;
705       ReusedOperands.markClobbered(PhysReg);
706       MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
707       // This invalidates PhysReg.
708       Spills.ClobberPhysReg(PhysReg);
709
710       // Any stores to this stack slot are not dead anymore.
711       MaybeDeadStores.erase(StackSlot);
712       Spills.addAvailable(StackSlot, PhysReg);
713       ++NumLoads;
714       MI.getOperand(i).setReg(PhysReg);
715       DOUT << '\t' << *prior(MII);
716     }
717
718     DOUT << '\t' << MI;
719
720     // If we have folded references to memory operands, make sure we clear all
721     // physical registers that may contain the value of the spilled virtual
722     // register
723     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
724     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
725       DOUT << "Folded vreg: " << I->second.first << "  MR: "
726            << I->second.second;
727       unsigned VirtReg = I->second.first;
728       VirtRegMap::ModRef MR = I->second.second;
729       if (!VRM.hasStackSlot(VirtReg)) {
730         DOUT << ": No stack slot!\n";
731         continue;
732       }
733       int SS = VRM.getStackSlot(VirtReg);
734       DOUT << " - StackSlot: " << SS << "\n";
735       
736       // If this folded instruction is just a use, check to see if it's a
737       // straight load from the virt reg slot.
738       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
739         int FrameIdx;
740         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
741           if (FrameIdx == SS) {
742             // If this spill slot is available, turn it into a copy (or nothing)
743             // instead of leaving it as a load!
744             if (unsigned InReg = Spills.getSpillSlotPhysReg(SS)) {
745               DOUT << "Promoted Load To Copy: " << MI;
746               MachineFunction &MF = *MBB.getParent();
747               if (DestReg != InReg) {
748                 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
749                                   MF.getSSARegMap()->getRegClass(VirtReg));
750                 // Revisit the copy so we make sure to notice the effects of the
751                 // operation on the destreg (either needing to RA it if it's 
752                 // virtual or needing to clobber any values if it's physical).
753                 NextMII = &MI;
754                 --NextMII;  // backtrack to the copy.
755               }
756               VRM.RemoveFromFoldedVirtMap(&MI);
757               MBB.erase(&MI);
758               goto ProcessNextInst;
759             }
760           }
761         }
762       }
763
764       // If this reference is not a use, any previous store is now dead.
765       // Otherwise, the store to this stack slot is not dead anymore.
766       std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
767       if (MDSI != MaybeDeadStores.end()) {
768         if (MR & VirtRegMap::isRef)   // Previous store is not dead.
769           MaybeDeadStores.erase(MDSI);
770         else {
771           // If we get here, the store is dead, nuke it now.
772           assert(VirtRegMap::isMod && "Can't be modref!");
773           DOUT << "Removed dead store:\t" << *MDSI->second;
774           MBB.erase(MDSI->second);
775           VRM.RemoveFromFoldedVirtMap(MDSI->second);
776           MaybeDeadStores.erase(MDSI);
777           ++NumDSE;
778         }
779       }
780
781       // If the spill slot value is available, and this is a new definition of
782       // the value, the value is not available anymore.
783       if (MR & VirtRegMap::isMod) {
784         // Notice that the value in this stack slot has been modified.
785         Spills.ModifyStackSlot(SS);
786         
787         // If this is *just* a mod of the value, check to see if this is just a
788         // store to the spill slot (i.e. the spill got merged into the copy). If
789         // so, realize that the vreg is available now, and add the store to the
790         // MaybeDeadStore info.
791         int StackSlot;
792         if (!(MR & VirtRegMap::isRef)) {
793           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
794             assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
795                    "Src hasn't been allocated yet?");
796             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
797             // this as a potentially dead store in case there is a subsequent
798             // store into the stack slot without a read from it.
799             MaybeDeadStores[StackSlot] = &MI;
800
801             // If the stack slot value was previously available in some other
802             // register, change it now.  Otherwise, make the register available,
803             // in PhysReg.
804             Spills.addAvailable(StackSlot, SrcReg, false /*don't clobber*/);
805           }
806         }
807       }
808     }
809
810     // Process all of the spilled defs.
811     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
812       MachineOperand &MO = MI.getOperand(i);
813       if (MO.isRegister() && MO.getReg() && MO.isDef()) {
814         unsigned VirtReg = MO.getReg();
815
816         if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
817           // Check to see if this is a noop copy.  If so, eliminate the
818           // instruction before considering the dest reg to be changed.
819           unsigned Src, Dst;
820           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
821             ++NumDCE;
822             DOUT << "Removing now-noop copy: " << MI;
823             MBB.erase(&MI);
824             VRM.RemoveFromFoldedVirtMap(&MI);
825             goto ProcessNextInst;
826           }
827           
828           // If it's not a no-op copy, it clobbers the value in the destreg.
829           Spills.ClobberPhysReg(VirtReg);
830           ReusedOperands.markClobbered(VirtReg);
831  
832           // Check to see if this instruction is a load from a stack slot into
833           // a register.  If so, this provides the stack slot value in the reg.
834           int FrameIdx;
835           if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
836             assert(DestReg == VirtReg && "Unknown load situation!");
837             
838             // Otherwise, if it wasn't available, remember that it is now!
839             Spills.addAvailable(FrameIdx, DestReg);
840             goto ProcessNextInst;
841           }
842             
843           continue;
844         }
845
846         // The only vregs left are stack slot definitions.
847         int StackSlot = VRM.getStackSlot(VirtReg);
848         const TargetRegisterClass *RC =
849           MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
850
851         // If this def is part of a two-address operand, make sure to execute
852         // the store from the correct physical register.
853         unsigned PhysReg;
854         int TiedOp = TII->findTiedToSrcOperand(MI.getOpcode(), i);
855         if (TiedOp != -1)
856           PhysReg = MI.getOperand(TiedOp).getReg();
857         else {
858           PhysReg = VRM.getPhys(VirtReg);
859           if (ReusedOperands.isClobbered(PhysReg)) {
860             // Another def has taken the assigned physreg. It must have been a
861             // use&def which got it due to reuse. Undo the reuse!
862             PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
863                                                      Spills, MaybeDeadStores);
864           }
865         }
866
867         PhysRegsUsed[PhysReg] = true;
868         ReusedOperands.markClobbered(PhysReg);
869         MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
870         DOUT << "Store:\t" << *next(MII);
871         MI.getOperand(i).setReg(PhysReg);
872
873         // Check to see if this is a noop copy.  If so, eliminate the
874         // instruction before considering the dest reg to be changed.
875         {
876           unsigned Src, Dst;
877           if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
878             ++NumDCE;
879             DOUT << "Removing now-noop copy: " << MI;
880             MBB.erase(&MI);
881             VRM.RemoveFromFoldedVirtMap(&MI);
882             goto ProcessNextInst;
883           }
884         }
885         
886         // If there is a dead store to this stack slot, nuke it now.
887         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
888         if (LastStore) {
889           DOUT << "Removed dead store:\t" << *LastStore;
890           ++NumDSE;
891           MBB.erase(LastStore);
892           VRM.RemoveFromFoldedVirtMap(LastStore);
893         }
894         LastStore = next(MII);
895
896         // If the stack slot value was previously available in some other
897         // register, change it now.  Otherwise, make the register available,
898         // in PhysReg.
899         Spills.ModifyStackSlot(StackSlot);
900         Spills.ClobberPhysReg(PhysReg);
901         Spills.addAvailable(StackSlot, PhysReg);
902         ++NumStores;
903       }
904     }
905   ProcessNextInst:
906     MII = NextMII;
907   }
908 }
909
910
911
912 llvm::Spiller* llvm::createSpiller() {
913   switch (SpillerOpt) {
914   default: assert(0 && "Unreachable!");
915   case local:
916     return new LocalSpiller();
917   case simple:
918     return new SimpleSpiller();
919   }
920 }