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