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