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