Disable this assert for now, it is firing on an llvm-gcc bootstrap. :(
[oota-llvm.git] / lib / CodeGen / VirtRegRewriter.cpp
1 //===-- llvm/CodeGen/Rewriter.cpp -  Rewriter -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "virtregrewriter"
11 #include "VirtRegRewriter.h"
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/ADT/DepthFirstIterator.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include <algorithm>
18 using namespace llvm;
19
20 STATISTIC(NumDSE     , "Number of dead stores elided");
21 STATISTIC(NumDSS     , "Number of dead spill slots removed");
22 STATISTIC(NumCommutes, "Number of instructions commuted");
23 STATISTIC(NumDRM     , "Number of re-materializable defs elided");
24 STATISTIC(NumStores  , "Number of stores added");
25 STATISTIC(NumPSpills , "Number of physical register spills");
26 STATISTIC(NumOmitted , "Number of reloads omited");
27 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
28 STATISTIC(NumCopified, "Number of available reloads turned into copies");
29 STATISTIC(NumReMats  , "Number of re-materialization");
30 STATISTIC(NumLoads   , "Number of loads added");
31 STATISTIC(NumReused  , "Number of values reused");
32 STATISTIC(NumDCE     , "Number of copies elided");
33 STATISTIC(NumSUnfold , "Number of stores unfolded");
34 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
35
36 namespace {
37   enum RewriterName { local, trivial };
38 }
39
40 static cl::opt<RewriterName>
41 RewriterOpt("rewriter",
42             cl::desc("Rewriter to use: (default: local)"),
43             cl::Prefix,
44             cl::values(clEnumVal(local,   "local rewriter"),
45                        clEnumVal(trivial, "trivial rewriter"),
46                        clEnumValEnd),
47             cl::init(local));
48
49 VirtRegRewriter::~VirtRegRewriter() {}
50
51
52  
53 /// This class is intended for use with the new spilling framework only. It
54 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
55 /// spill code.
56 struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
57
58   bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
59                             LiveIntervals* LIs) {
60     DOUT << "********** REWRITE MACHINE CODE **********\n";
61     DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
62     MachineRegisterInfo *mri = &MF.getRegInfo();
63
64     bool changed = false;
65
66     for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
67          liItr != liEnd; ++liItr) {
68
69       if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
70         if (VRM.hasPhys(liItr->first)) {
71           unsigned preg = VRM.getPhys(liItr->first);
72           mri->replaceRegWith(liItr->first, preg);
73           mri->setPhysRegUsed(preg);
74           changed = true;
75         }
76       }
77       else {
78         if (!liItr->second->empty()) {
79           mri->setPhysRegUsed(liItr->first);
80         }
81       }
82     }
83     
84     return changed;
85   }
86
87 };
88
89 // ************************************************************************ //
90
91 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
92 /// from top down, keep track of which spill slots or remat are available in
93 /// each register.
94 ///
95 /// Note that not all physregs are created equal here.  In particular, some
96 /// physregs are reloads that we are allowed to clobber or ignore at any time.
97 /// Other physregs are values that the register allocated program is using
98 /// that we cannot CHANGE, but we can read if we like.  We keep track of this
99 /// on a per-stack-slot / remat id basis as the low bit in the value of the
100 /// SpillSlotsAvailable entries.  The predicate 'canClobberPhysReg()' checks
101 /// this bit and addAvailable sets it if.
102 class VISIBILITY_HIDDEN AvailableSpills {
103   const TargetRegisterInfo *TRI;
104   const TargetInstrInfo *TII;
105
106   // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
107   // or remat'ed virtual register values that are still available, due to
108   // being loaded or stored to, but not invalidated yet.
109   std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
110
111   // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
112   // indicating which stack slot values are currently held by a physreg.  This
113   // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
114   // physreg is modified.
115   std::multimap<unsigned, int> PhysRegsAvailable;
116
117   void disallowClobberPhysRegOnly(unsigned PhysReg);
118
119   void ClobberPhysRegOnly(unsigned PhysReg);
120 public:
121   AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
122     : TRI(tri), TII(tii) {
123   }
124
125   /// clear - Reset the state.
126   void clear() {
127     SpillSlotsOrReMatsAvailable.clear();
128     PhysRegsAvailable.clear();
129   }
130
131   const TargetRegisterInfo *getRegInfo() const { return TRI; }
132
133   /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
134   /// available in a physical register, return that PhysReg, otherwise
135   /// return 0.
136   unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
137     std::map<int, unsigned>::const_iterator I =
138       SpillSlotsOrReMatsAvailable.find(Slot);
139     if (I != SpillSlotsOrReMatsAvailable.end()) {
140       return I->second >> 1;  // Remove the CanClobber bit.
141     }
142     return 0;
143   }
144
145   /// addAvailable - Mark that the specified stack slot / remat is available
146   /// in the specified physreg.  If CanClobber is true, the physreg can be
147   /// modified at any time without changing the semantics of the program.
148   void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
149     // If this stack slot is thought to be available in some other physreg, 
150     // remove its record.
151     ModifyStackSlotOrReMat(SlotOrReMat);
152
153     PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
154     SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
155                                               (unsigned)CanClobber;
156
157     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
158       DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
159     else
160       DOUT << "Remembering SS#" << SlotOrReMat;
161     DOUT << " in physreg " << TRI->getName(Reg) << "\n";
162   }
163
164   /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
165   /// the value of the specified stackslot register if it desires. The
166   /// specified stack slot must be available in a physreg for this query to
167   /// make sense.
168   bool canClobberPhysRegForSS(int SlotOrReMat) const {
169     assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
170            "Value not available!");
171     return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
172   }
173
174   /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
175   /// physical register where values for some stack slot(s) might be
176   /// available.
177   bool canClobberPhysReg(unsigned PhysReg) const {
178     std::multimap<unsigned, int>::const_iterator I =
179       PhysRegsAvailable.lower_bound(PhysReg);
180     while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
181       int SlotOrReMat = I->second;
182       I++;
183       if (!canClobberPhysRegForSS(SlotOrReMat))
184         return false;
185     }
186     return true;
187   }
188
189   /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
190   /// stackslot register. The register is still available but is no longer
191   /// allowed to be modifed.
192   void disallowClobberPhysReg(unsigned PhysReg);
193
194   /// ClobberPhysReg - This is called when the specified physreg changes
195   /// value.  We use this to invalidate any info about stuff that lives in
196   /// it and any of its aliases.
197   void ClobberPhysReg(unsigned PhysReg);
198
199   /// ModifyStackSlotOrReMat - This method is called when the value in a stack
200   /// slot changes.  This removes information about which register the
201   /// previous value for this slot lives in (as the previous value is dead
202   /// now).
203   void ModifyStackSlotOrReMat(int SlotOrReMat);
204
205   /// AddAvailableRegsToLiveIn - Availability information is being kept coming
206   /// into the specified MBB. Add available physical registers as potential
207   /// live-in's. If they are reused in the MBB, they will be added to the
208   /// live-in set to make register scavenger and post-allocation scheduler.
209   void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
210                                 std::vector<MachineOperand*> &KillOps);
211 };
212
213 // ************************************************************************ //
214
215 // ReusedOp - For each reused operand, we keep track of a bit of information,
216 // in case we need to rollback upon processing a new operand.  See comments
217 // below.
218 struct ReusedOp {
219   // The MachineInstr operand that reused an available value.
220   unsigned Operand;
221
222   // StackSlotOrReMat - The spill slot or remat id of the value being reused.
223   unsigned StackSlotOrReMat;
224
225   // PhysRegReused - The physical register the value was available in.
226   unsigned PhysRegReused;
227
228   // AssignedPhysReg - The physreg that was assigned for use by the reload.
229   unsigned AssignedPhysReg;
230   
231   // VirtReg - The virtual register itself.
232   unsigned VirtReg;
233
234   ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
235            unsigned vreg)
236     : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
237       AssignedPhysReg(apr), VirtReg(vreg) {}
238 };
239
240 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
241 /// is reused instead of reloaded.
242 class VISIBILITY_HIDDEN ReuseInfo {
243   MachineInstr &MI;
244   std::vector<ReusedOp> Reuses;
245   BitVector PhysRegsClobbered;
246 public:
247   ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
248     PhysRegsClobbered.resize(tri->getNumRegs());
249   }
250   
251   bool hasReuses() const {
252     return !Reuses.empty();
253   }
254   
255   /// addReuse - If we choose to reuse a virtual register that is already
256   /// available instead of reloading it, remember that we did so.
257   void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
258                 unsigned PhysRegReused, unsigned AssignedPhysReg,
259                 unsigned VirtReg) {
260     // If the reload is to the assigned register anyway, no undo will be
261     // required.
262     if (PhysRegReused == AssignedPhysReg) return;
263     
264     // Otherwise, remember this.
265     Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused, 
266                               AssignedPhysReg, VirtReg));
267   }
268
269   void markClobbered(unsigned PhysReg) {
270     PhysRegsClobbered.set(PhysReg);
271   }
272
273   bool isClobbered(unsigned PhysReg) const {
274     return PhysRegsClobbered.test(PhysReg);
275   }
276   
277   /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
278   /// is some other operand that is using the specified register, either pick
279   /// a new register to use, or evict the previous reload and use this reg. 
280   unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
281                            AvailableSpills &Spills,
282                            std::vector<MachineInstr*> &MaybeDeadStores,
283                            SmallSet<unsigned, 8> &Rejected,
284                            BitVector &RegKills,
285                            std::vector<MachineOperand*> &KillOps,
286                            VirtRegMap &VRM);
287
288   /// GetRegForReload - Helper for the above GetRegForReload(). Add a
289   /// 'Rejected' set to remember which registers have been considered and
290   /// rejected for the reload. This avoids infinite looping in case like
291   /// this:
292   /// t1 := op t2, t3
293   /// t2 <- assigned r0 for use by the reload but ended up reuse r1
294   /// t3 <- assigned r1 for use by the reload but ended up reuse r0
295   /// t1 <- desires r1
296   ///       sees r1 is taken by t2, tries t2's reload register r0
297   ///       sees r0 is taken by t3, tries t3's reload register r1
298   ///       sees r1 is taken by t2, tries t2's reload register r0 ...
299   unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
300                            AvailableSpills &Spills,
301                            std::vector<MachineInstr*> &MaybeDeadStores,
302                            BitVector &RegKills,
303                            std::vector<MachineOperand*> &KillOps,
304                            VirtRegMap &VRM) {
305     SmallSet<unsigned, 8> Rejected;
306     return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
307                            RegKills, KillOps, VRM);
308   }
309 };
310
311
312 // ****************** //
313 // Utility Functions  //
314 // ****************** //
315
316 /// findSinglePredSuccessor - Return via reference a vector of machine basic
317 /// blocks each of which is a successor of the specified BB and has no other
318 /// predecessor.
319 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
320                                    SmallVectorImpl<MachineBasicBlock *> &Succs) {
321   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
322          SE = MBB->succ_end(); SI != SE; ++SI) {
323     MachineBasicBlock *SuccMBB = *SI;
324     if (SuccMBB->pred_size() == 1)
325       Succs.push_back(SuccMBB);
326   }
327 }
328
329 /// InvalidateKill - Invalidate register kill information for a specific
330 /// register. This also unsets the kills marker on the last kill operand.
331 static void InvalidateKill(unsigned Reg,
332                            const TargetRegisterInfo* TRI,
333                            BitVector &RegKills,
334                            std::vector<MachineOperand*> &KillOps) {
335   if (RegKills[Reg]) {
336     KillOps[Reg]->setIsKill(false);
337     // KillOps[Reg] might be a def of a super-register.
338     unsigned KReg = KillOps[Reg]->getReg();
339     KillOps[KReg] = NULL;
340     RegKills.reset(KReg);
341     for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
342       if (RegKills[*SR]) {
343         KillOps[*SR]->setIsKill(false);
344         KillOps[*SR] = NULL;
345         RegKills.reset(*SR);
346       }
347     }
348   }
349 }
350
351 /// InvalidateKills - MI is going to be deleted. If any of its operands are
352 /// marked kill, then invalidate the information.
353 static void InvalidateKills(MachineInstr &MI,
354                             const TargetRegisterInfo* TRI,
355                             BitVector &RegKills,
356                             std::vector<MachineOperand*> &KillOps,
357                             SmallVector<unsigned, 2> *KillRegs = NULL) {
358   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
359     MachineOperand &MO = MI.getOperand(i);
360     if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
361       continue;
362     unsigned Reg = MO.getReg();
363     if (TargetRegisterInfo::isVirtualRegister(Reg))
364       continue;
365     if (KillRegs)
366       KillRegs->push_back(Reg);
367     assert(Reg < KillOps.size());
368     if (KillOps[Reg] == &MO) {
369       KillOps[Reg] = NULL;
370       RegKills.reset(Reg);
371       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
372         if (RegKills[*SR]) {
373           KillOps[*SR] = NULL;
374           RegKills.reset(*SR);
375         }
376       }
377     }
378   }
379 }
380
381 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
382 /// (since it's spill instruction is removed), mark it isDead. Also checks if
383 /// the def MI has other definition operands that are not dead. Returns it by
384 /// reference.
385 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
386                              MachineInstr &NewDef, unsigned Reg,
387                              bool &HasLiveDef) {
388   // Due to remat, it's possible this reg isn't being reused. That is,
389   // the def of this reg (by prev MI) is now dead.
390   MachineInstr *DefMI = I;
391   MachineOperand *DefOp = NULL;
392   for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
393     MachineOperand &MO = DefMI->getOperand(i);
394     if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
395       continue;
396     if (MO.getReg() == Reg)
397       DefOp = &MO;
398     else if (!MO.isDead())
399       HasLiveDef = true;
400   }
401   if (!DefOp)
402     return false;
403
404   bool FoundUse = false, Done = false;
405   MachineBasicBlock::iterator E = &NewDef;
406   ++I; ++E;
407   for (; !Done && I != E; ++I) {
408     MachineInstr *NMI = I;
409     for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
410       MachineOperand &MO = NMI->getOperand(j);
411       if (!MO.isReg() || MO.getReg() != Reg)
412         continue;
413       if (MO.isUse())
414         FoundUse = true;
415       Done = true; // Stop after scanning all the operands of this MI.
416     }
417   }
418   if (!FoundUse) {
419     // Def is dead!
420     DefOp->setIsDead();
421     return true;
422   }
423   return false;
424 }
425
426 /// UpdateKills - Track and update kill info. If a MI reads a register that is
427 /// marked kill, then it must be due to register reuse. Transfer the kill info
428 /// over.
429 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
430                         BitVector &RegKills,
431                         std::vector<MachineOperand*> &KillOps) {
432   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
433     MachineOperand &MO = MI.getOperand(i);
434     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
435       continue;
436     unsigned Reg = MO.getReg();
437     if (Reg == 0)
438       continue;
439     
440     if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
441       // That can't be right. Register is killed but not re-defined and it's
442       // being reused. Let's fix that.
443       KillOps[Reg]->setIsKill(false);
444       // KillOps[Reg] might be a def of a super-register.
445       unsigned KReg = KillOps[Reg]->getReg();
446       KillOps[KReg] = NULL;
447       RegKills.reset(KReg);
448
449       // Must be a def of a super-register. Its other sub-regsters are no
450       // longer killed as well.
451       for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
452         KillOps[*SR] = NULL;
453         RegKills.reset(*SR);
454       }
455
456       if (!MI.isRegTiedToDefOperand(i))
457         // Unless it's a two-address operand, this is the new kill.
458         MO.setIsKill();
459     }
460     if (MO.isKill()) {
461       RegKills.set(Reg);
462       KillOps[Reg] = &MO;
463       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
464         RegKills.set(*SR);
465         KillOps[*SR] = &MO;
466       }
467     }
468   }
469
470   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
471     const MachineOperand &MO = MI.getOperand(i);
472     if (!MO.isReg() || !MO.isDef())
473       continue;
474     unsigned Reg = MO.getReg();
475     RegKills.reset(Reg);
476     KillOps[Reg] = NULL;
477     // It also defines (or partially define) aliases.
478     for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
479       RegKills.reset(*SR);
480       KillOps[*SR] = NULL;
481     }
482   }
483 }
484
485 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
486 ///
487 static void ReMaterialize(MachineBasicBlock &MBB,
488                           MachineBasicBlock::iterator &MII,
489                           unsigned DestReg, unsigned Reg,
490                           const TargetInstrInfo *TII,
491                           const TargetRegisterInfo *TRI,
492                           VirtRegMap &VRM) {
493   MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
494 #if 0
495 #ifndef NDEBUG
496   const TargetInstrDesc &TID = ReMatDefMI->getDesc();
497   assert(TID.getNumDefs() != 1 &&
498          "Don't know how to remat instructions that define > 1 values!");
499 #endif
500 #endif
501   TII->reMaterialize(MBB, MII, DestReg,
502                      ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
503   MachineInstr *NewMI = prior(MII);
504   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
505     MachineOperand &MO = NewMI->getOperand(i);
506     if (!MO.isReg() || MO.getReg() == 0)
507       continue;
508     unsigned VirtReg = MO.getReg();
509     if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
510       continue;
511     assert(MO.isUse());
512     unsigned SubIdx = MO.getSubReg();
513     unsigned Phys = VRM.getPhys(VirtReg);
514     assert(Phys);
515     unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
516     MO.setReg(RReg);
517     MO.setSubReg(0);
518   }
519   ++NumReMats;
520 }
521
522 /// findSuperReg - Find the SubReg's super-register of given register class
523 /// where its SubIdx sub-register is SubReg.
524 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
525                              unsigned SubIdx, const TargetRegisterInfo *TRI) {
526   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
527        I != E; ++I) {
528     unsigned Reg = *I;
529     if (TRI->getSubReg(Reg, SubIdx) == SubReg)
530       return Reg;
531   }
532   return 0;
533 }
534
535 // ******************************** //
536 // Available Spills Implementation  //
537 // ******************************** //
538
539 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
540 /// stackslot register. The register is still available but is no longer
541 /// allowed to be modifed.
542 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
543   std::multimap<unsigned, int>::iterator I =
544     PhysRegsAvailable.lower_bound(PhysReg);
545   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
546     int SlotOrReMat = I->second;
547     I++;
548     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
549            "Bidirectional map mismatch!");
550     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
551     DOUT << "PhysReg " << TRI->getName(PhysReg)
552          << " copied, it is available for use but can no longer be modified\n";
553   }
554 }
555
556 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
557 /// stackslot register and its aliases. The register and its aliases may
558 /// still available but is no longer allowed to be modifed.
559 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
560   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
561     disallowClobberPhysRegOnly(*AS);
562   disallowClobberPhysRegOnly(PhysReg);
563 }
564
565 /// ClobberPhysRegOnly - This is called when the specified physreg changes
566 /// value.  We use this to invalidate any info about stuff we thing lives in it.
567 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
568   std::multimap<unsigned, int>::iterator I =
569     PhysRegsAvailable.lower_bound(PhysReg);
570   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
571     int SlotOrReMat = I->second;
572     PhysRegsAvailable.erase(I++);
573     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
574            "Bidirectional map mismatch!");
575     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
576     DOUT << "PhysReg " << TRI->getName(PhysReg)
577          << " clobbered, invalidating ";
578     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
579       DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
580     else
581       DOUT << "SS#" << SlotOrReMat << "\n";
582   }
583 }
584
585 /// ClobberPhysReg - This is called when the specified physreg changes
586 /// value.  We use this to invalidate any info about stuff we thing lives in
587 /// it and any of its aliases.
588 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
589   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
590     ClobberPhysRegOnly(*AS);
591   ClobberPhysRegOnly(PhysReg);
592 }
593
594 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
595 /// into the specified MBB. Add available physical registers as potential
596 /// live-in's. If they are reused in the MBB, they will be added to the
597 /// live-in set to make register scavenger and post-allocation scheduler.
598 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
599                                         BitVector &RegKills,
600                                         std::vector<MachineOperand*> &KillOps) {
601   std::set<unsigned> NotAvailable;
602   for (std::multimap<unsigned, int>::iterator
603          I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
604        I != E; ++I) {
605     unsigned Reg = I->first;
606     const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
607     // FIXME: A temporary workaround. We can't reuse available value if it's
608     // not safe to move the def of the virtual register's class. e.g.
609     // X86::RFP* register classes. Do not add it as a live-in.
610     if (!TII->isSafeToMoveRegClassDefs(RC))
611       // This is no longer available.
612       NotAvailable.insert(Reg);
613     else {
614       MBB.addLiveIn(Reg);
615       InvalidateKill(Reg, TRI, RegKills, KillOps);
616     }
617
618     // Skip over the same register.
619     std::multimap<unsigned, int>::iterator NI = next(I);
620     while (NI != E && NI->first == Reg) {
621       ++I;
622       ++NI;
623     }
624   }
625
626   for (std::set<unsigned>::iterator I = NotAvailable.begin(),
627          E = NotAvailable.end(); I != E; ++I) {
628     ClobberPhysReg(*I);
629     for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
630        *SubRegs; ++SubRegs)
631       ClobberPhysReg(*SubRegs);
632   }
633 }
634
635 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
636 /// slot changes.  This removes information about which register the previous
637 /// value for this slot lives in (as the previous value is dead now).
638 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
639   std::map<int, unsigned>::iterator It =
640     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
641   if (It == SpillSlotsOrReMatsAvailable.end()) return;
642   unsigned Reg = It->second >> 1;
643   SpillSlotsOrReMatsAvailable.erase(It);
644   
645   // This register may hold the value of multiple stack slots, only remove this
646   // stack slot from the set of values the register contains.
647   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
648   for (; ; ++I) {
649     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
650            "Map inverse broken!");
651     if (I->second == SlotOrReMat) break;
652   }
653   PhysRegsAvailable.erase(I);
654 }
655
656 // ************************** //
657 // Reuse Info Implementation  //
658 // ************************** //
659
660 /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
661 /// is some other operand that is using the specified register, either pick
662 /// a new register to use, or evict the previous reload and use this reg.
663 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
664                          AvailableSpills &Spills,
665                          std::vector<MachineInstr*> &MaybeDeadStores,
666                          SmallSet<unsigned, 8> &Rejected,
667                          BitVector &RegKills,
668                          std::vector<MachineOperand*> &KillOps,
669                          VirtRegMap &VRM) {
670   const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
671                                .getInstrInfo();
672   
673   if (Reuses.empty()) return PhysReg;  // This is most often empty.
674
675   for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
676     ReusedOp &Op = Reuses[ro];
677     // If we find some other reuse that was supposed to use this register
678     // exactly for its reload, we can change this reload to use ITS reload
679     // register. That is, unless its reload register has already been
680     // considered and subsequently rejected because it has also been reused
681     // by another operand.
682     if (Op.PhysRegReused == PhysReg &&
683         Rejected.count(Op.AssignedPhysReg) == 0) {
684       // Yup, use the reload register that we didn't use before.
685       unsigned NewReg = Op.AssignedPhysReg;
686       Rejected.insert(PhysReg);
687       return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
688                              RegKills, KillOps, VRM);
689     } else {
690       // Otherwise, we might also have a problem if a previously reused
691       // value aliases the new register.  If so, codegen the previous reload
692       // and use this one.          
693       unsigned PRRU = Op.PhysRegReused;
694       const TargetRegisterInfo *TRI = Spills.getRegInfo();
695       if (TRI->areAliases(PRRU, PhysReg)) {
696         // Okay, we found out that an alias of a reused register
697         // was used.  This isn't good because it means we have
698         // to undo a previous reuse.
699         MachineBasicBlock *MBB = MI->getParent();
700         const TargetRegisterClass *AliasRC =
701           MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
702
703         // Copy Op out of the vector and remove it, we're going to insert an
704         // explicit load for it.
705         ReusedOp NewOp = Op;
706         Reuses.erase(Reuses.begin()+ro);
707
708         // Ok, we're going to try to reload the assigned physreg into the
709         // slot that we were supposed to in the first place.  However, that
710         // register could hold a reuse.  Check to see if it conflicts or
711         // would prefer us to use a different register.
712         unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
713                                               MI, Spills, MaybeDeadStores,
714                                           Rejected, RegKills, KillOps, VRM);
715         
716         MachineBasicBlock::iterator MII = MI;
717         if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
718           ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
719         } else {
720           TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
721                                     NewOp.StackSlotOrReMat, AliasRC);
722           MachineInstr *LoadMI = prior(MII);
723           VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
724           // Any stores to this stack slot are not dead anymore.
725           MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;            
726           ++NumLoads;
727         }
728         Spills.ClobberPhysReg(NewPhysReg);
729         Spills.ClobberPhysReg(NewOp.PhysRegReused);
730
731         unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
732         unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
733         MI->getOperand(NewOp.Operand).setReg(RReg);
734         MI->getOperand(NewOp.Operand).setSubReg(0);
735
736         Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
737         --MII;
738         UpdateKills(*MII, TRI, RegKills, KillOps);
739         DOUT << '\t' << *MII;
740         
741         DOUT << "Reuse undone!\n";
742         --NumReused;
743         
744         // Finally, PhysReg is now available, go ahead and use it.
745         return PhysReg;
746       }
747     }
748   }
749   return PhysReg;
750 }
751
752 // ************************************************************************ //
753
754 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
755 /// stack slot mod/ref. It also checks if it's possible to unfold the
756 /// instruction by having it define a specified physical register instead.
757 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
758                                  const TargetInstrInfo *TII,
759                                  const TargetRegisterInfo *TRI,
760                                  VirtRegMap &VRM) {
761   if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
762     return false;
763
764   bool Found = false;
765   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
766   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
767     unsigned VirtReg = I->second.first;
768     VirtRegMap::ModRef MR = I->second.second;
769     if (MR & VirtRegMap::isModRef)
770       if (VRM.getStackSlot(VirtReg) == SS) {
771         Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
772         break;
773       }
774   }
775   if (!Found)
776     return false;
777
778   // Does the instruction uses a register that overlaps the scratch register?
779   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
780     MachineOperand &MO = MI.getOperand(i);
781     if (!MO.isReg() || MO.getReg() == 0)
782       continue;
783     unsigned Reg = MO.getReg();
784     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
785       if (!VRM.hasPhys(Reg))
786         continue;
787       Reg = VRM.getPhys(Reg);
788     }
789     if (TRI->regsOverlap(PhysReg, Reg))
790       return false;
791   }
792   return true;
793 }
794
795 /// FindFreeRegister - Find a free register of a given register class by looking
796 /// at (at most) the last two machine instructions.
797 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
798                                  MachineBasicBlock &MBB,
799                                  const TargetRegisterClass *RC,
800                                  const TargetRegisterInfo *TRI,
801                                  BitVector &AllocatableRegs) {
802   BitVector Defs(TRI->getNumRegs());
803   BitVector Uses(TRI->getNumRegs());
804   SmallVector<unsigned, 4> LocalUses;
805   SmallVector<unsigned, 4> Kills;
806
807   // Take a look at 2 instructions at most.
808   for (unsigned Count = 0; Count < 2; ++Count) {
809     if (MII == MBB.begin())
810       break;
811     MachineInstr *PrevMI = prior(MII);
812     for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
813       MachineOperand &MO = PrevMI->getOperand(i);
814       if (!MO.isReg() || MO.getReg() == 0)
815         continue;
816       unsigned Reg = MO.getReg();
817       if (MO.isDef()) {
818         Defs.set(Reg);
819         for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
820           Defs.set(*AS);
821       } else  {
822         LocalUses.push_back(Reg);
823         if (MO.isKill() && AllocatableRegs[Reg])
824           Kills.push_back(Reg);
825       }
826     }
827
828     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
829       unsigned Kill = Kills[i];
830       if (!Defs[Kill] && !Uses[Kill] &&
831           TRI->getPhysicalRegisterRegClass(Kill) == RC)
832         return Kill;
833     }
834     for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
835       unsigned Reg = LocalUses[i];
836       Uses.set(Reg);
837       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
838         Uses.set(*AS);
839     }
840
841     MII = PrevMI;
842   }
843
844   return 0;
845 }
846
847 static
848 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
849   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
850     MachineOperand &MO = MI->getOperand(i);
851     if (MO.isReg() && MO.getReg() == VirtReg)
852       MO.setReg(PhysReg);
853   }
854 }
855
856 namespace {
857   struct RefSorter {
858     bool operator()(const std::pair<MachineInstr*, int> &A,
859                     const std::pair<MachineInstr*, int> &B) {
860       return A.second < B.second;
861     }
862   };
863 }
864
865 // ***************************** //
866 // Local Spiller Implementation  //
867 // ***************************** //
868
869 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
870   MachineRegisterInfo *RegInfo;
871   const TargetRegisterInfo *TRI;
872   const TargetInstrInfo *TII;
873   BitVector AllocatableRegs;
874   DenseMap<MachineInstr*, unsigned> DistanceMap;
875 public:
876
877   bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
878                             LiveIntervals* LIs) {
879     RegInfo = &MF.getRegInfo(); 
880     TRI = MF.getTarget().getRegisterInfo();
881     TII = MF.getTarget().getInstrInfo();
882     AllocatableRegs = TRI->getAllocatableSet(MF);
883     DOUT << "\n**** Local spiller rewriting function '"
884          << MF.getFunction()->getName() << "':\n";
885     DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
886             " ****\n";
887     DEBUG(MF.dump());
888
889     // Spills - Keep track of which spilled values are available in physregs
890     // so that we can choose to reuse the physregs instead of emitting
891     // reloads. This is usually refreshed per basic block.
892     AvailableSpills Spills(TRI, TII);
893
894     // Keep track of kill information.
895     BitVector RegKills(TRI->getNumRegs());
896     std::vector<MachineOperand*> KillOps;
897     KillOps.resize(TRI->getNumRegs(), NULL);
898
899     // SingleEntrySuccs - Successor blocks which have a single predecessor.
900     SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
901     SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
902
903     // Traverse the basic blocks depth first.
904     MachineBasicBlock *Entry = MF.begin();
905     SmallPtrSet<MachineBasicBlock*,16> Visited;
906     for (df_ext_iterator<MachineBasicBlock*,
907            SmallPtrSet<MachineBasicBlock*,16> >
908            DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
909          DFI != E; ++DFI) {
910       MachineBasicBlock *MBB = *DFI;
911       if (!EarlyVisited.count(MBB))
912         RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
913
914       // If this MBB is the only predecessor of a successor. Keep the
915       // availability information and visit it next.
916       do {
917         // Keep visiting single predecessor successor as long as possible.
918         SinglePredSuccs.clear();
919         findSinglePredSuccessor(MBB, SinglePredSuccs);
920         if (SinglePredSuccs.empty())
921           MBB = 0;
922         else {
923           // FIXME: More than one successors, each of which has MBB has
924           // the only predecessor.
925           MBB = SinglePredSuccs[0];
926           if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
927             Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
928             RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
929           }
930         }
931       } while (MBB);
932
933       // Clear the availability info.
934       Spills.clear();
935     }
936
937     DOUT << "**** Post Machine Instrs ****\n";
938     DEBUG(MF.dump());
939
940     // Mark unused spill slots.
941     MachineFrameInfo *MFI = MF.getFrameInfo();
942     int SS = VRM.getLowSpillSlot();
943     if (SS != VirtRegMap::NO_STACK_SLOT)
944       for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
945         if (!VRM.isSpillSlotUsed(SS)) {
946           MFI->RemoveStackObject(SS);
947           ++NumDSS;
948         }
949
950     return true;
951   }
952
953 private:
954
955   /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
956   /// a scratch register is available.
957   ///     xorq  %r12<kill>, %r13
958   ///     addq  %rax, -184(%rbp)
959   ///     addq  %r13, -184(%rbp)
960   /// ==>
961   ///     xorq  %r12<kill>, %r13
962   ///     movq  -184(%rbp), %r12
963   ///     addq  %rax, %r12
964   ///     addq  %r13, %r12
965   ///     movq  %r12, -184(%rbp)
966   bool OptimizeByUnfold2(unsigned VirtReg, int SS,
967                          MachineBasicBlock &MBB,
968                          MachineBasicBlock::iterator &MII,
969                          std::vector<MachineInstr*> &MaybeDeadStores,
970                          AvailableSpills &Spills,
971                          BitVector &RegKills,
972                          std::vector<MachineOperand*> &KillOps,
973                          VirtRegMap &VRM) {
974
975     MachineBasicBlock::iterator NextMII = next(MII);
976     if (NextMII == MBB.end())
977       return false;
978
979     if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
980       return false;
981
982     // Now let's see if the last couple of instructions happens to have freed up
983     // a register.
984     const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
985     unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
986     if (!PhysReg)
987       return false;
988
989     MachineFunction &MF = *MBB.getParent();
990     TRI = MF.getTarget().getRegisterInfo();
991     MachineInstr &MI = *MII;
992     if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
993       return false;
994
995     // If the next instruction also folds the same SS modref and can be unfoled,
996     // then it's worthwhile to issue a load from SS into the free register and
997     // then unfold these instructions.
998     if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
999       return false;
1000
1001     // Load from SS to the spare physical register.
1002     TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1003     // This invalidates Phys.
1004     Spills.ClobberPhysReg(PhysReg);
1005     // Remember it's available.
1006     Spills.addAvailable(SS, PhysReg);
1007     MaybeDeadStores[SS] = NULL;
1008
1009     // Unfold current MI.
1010     SmallVector<MachineInstr*, 4> NewMIs;
1011     if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1012       llvm_unreachable("Unable unfold the load / store folding instruction!");
1013     assert(NewMIs.size() == 1);
1014     AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1015     VRM.transferRestorePts(&MI, NewMIs[0]);
1016     MII = MBB.insert(MII, NewMIs[0]);
1017     InvalidateKills(MI, TRI, RegKills, KillOps);
1018     VRM.RemoveMachineInstrFromMaps(&MI);
1019     MBB.erase(&MI);
1020     ++NumModRefUnfold;
1021
1022     // Unfold next instructions that fold the same SS.
1023     do {
1024       MachineInstr &NextMI = *NextMII;
1025       NextMII = next(NextMII);
1026       NewMIs.clear();
1027       if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1028         llvm_unreachable("Unable unfold the load / store folding instruction!");
1029       assert(NewMIs.size() == 1);
1030       AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1031       VRM.transferRestorePts(&NextMI, NewMIs[0]);
1032       MBB.insert(NextMII, NewMIs[0]);
1033       InvalidateKills(NextMI, TRI, RegKills, KillOps);
1034       VRM.RemoveMachineInstrFromMaps(&NextMI);
1035       MBB.erase(&NextMI);
1036       ++NumModRefUnfold;
1037       if (NextMII == MBB.end())
1038         break;
1039     } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1040
1041     // Store the value back into SS.
1042     TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1043     MachineInstr *StoreMI = prior(NextMII);
1044     VRM.addSpillSlotUse(SS, StoreMI);
1045     VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1046
1047     return true;
1048   }
1049
1050   /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1051   /// instruction. e.g.
1052   ///     xorl  %edi, %eax
1053   ///     movl  %eax, -32(%ebp)
1054   ///     movl  -36(%ebp), %eax
1055   ///     orl   %eax, -32(%ebp)
1056   /// ==>
1057   ///     xorl  %edi, %eax
1058   ///     orl   -36(%ebp), %eax
1059   ///     mov   %eax, -32(%ebp)
1060   /// This enables unfolding optimization for a subsequent instruction which will
1061   /// also eliminate the newly introduced store instruction.
1062   bool OptimizeByUnfold(MachineBasicBlock &MBB,
1063                         MachineBasicBlock::iterator &MII,
1064                         std::vector<MachineInstr*> &MaybeDeadStores,
1065                         AvailableSpills &Spills,
1066                         BitVector &RegKills,
1067                         std::vector<MachineOperand*> &KillOps,
1068                         VirtRegMap &VRM) {
1069     MachineFunction &MF = *MBB.getParent();
1070     MachineInstr &MI = *MII;
1071     unsigned UnfoldedOpc = 0;
1072     unsigned UnfoldPR = 0;
1073     unsigned UnfoldVR = 0;
1074     int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1075     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1076     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1077       // Only transform a MI that folds a single register.
1078       if (UnfoldedOpc)
1079         return false;
1080       UnfoldVR = I->second.first;
1081       VirtRegMap::ModRef MR = I->second.second;
1082       // MI2VirtMap be can updated which invalidate the iterator.
1083       // Increment the iterator first.
1084       ++I; 
1085       if (VRM.isAssignedReg(UnfoldVR))
1086         continue;
1087       // If this reference is not a use, any previous store is now dead.
1088       // Otherwise, the store to this stack slot is not dead anymore.
1089       FoldedSS = VRM.getStackSlot(UnfoldVR);
1090       MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1091       if (DeadStore && (MR & VirtRegMap::isModRef)) {
1092         unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1093         if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1094           continue;
1095         UnfoldPR = PhysReg;
1096         UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1097                                                       false, true);
1098       }
1099     }
1100
1101     if (!UnfoldedOpc) {
1102       if (!UnfoldVR)
1103         return false;
1104
1105       // Look for other unfolding opportunities.
1106       return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1107                                MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1108     }
1109
1110     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1111       MachineOperand &MO = MI.getOperand(i);
1112       if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1113         continue;
1114       unsigned VirtReg = MO.getReg();
1115       if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1116         continue;
1117       if (VRM.isAssignedReg(VirtReg)) {
1118         unsigned PhysReg = VRM.getPhys(VirtReg);
1119         if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1120           return false;
1121       } else if (VRM.isReMaterialized(VirtReg))
1122         continue;
1123       int SS = VRM.getStackSlot(VirtReg);
1124       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1125       if (PhysReg) {
1126         if (TRI->regsOverlap(PhysReg, UnfoldPR))
1127           return false;
1128         continue;
1129       }
1130       if (VRM.hasPhys(VirtReg)) {
1131         PhysReg = VRM.getPhys(VirtReg);
1132         if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1133           continue;
1134       }
1135
1136       // Ok, we'll need to reload the value into a register which makes
1137       // it impossible to perform the store unfolding optimization later.
1138       // Let's see if it is possible to fold the load if the store is
1139       // unfolded. This allows us to perform the store unfolding
1140       // optimization.
1141       SmallVector<MachineInstr*, 4> NewMIs;
1142       if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1143         assert(NewMIs.size() == 1);
1144         MachineInstr *NewMI = NewMIs.back();
1145         NewMIs.clear();
1146         int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1147         assert(Idx != -1);
1148         SmallVector<unsigned, 1> Ops;
1149         Ops.push_back(Idx);
1150         MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1151         if (FoldedMI) {
1152           VRM.addSpillSlotUse(SS, FoldedMI);
1153           if (!VRM.hasPhys(UnfoldVR))
1154             VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1155           VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1156           MII = MBB.insert(MII, FoldedMI);
1157           InvalidateKills(MI, TRI, RegKills, KillOps);
1158           VRM.RemoveMachineInstrFromMaps(&MI);
1159           MBB.erase(&MI);
1160           MF.DeleteMachineInstr(NewMI);
1161           return true;
1162         }
1163         MF.DeleteMachineInstr(NewMI);
1164       }
1165     }
1166
1167     return false;
1168   }
1169
1170   /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1171   /// where SrcReg is r1 and it is tied to r0. Return true if after
1172   /// commuting this instruction it will be r0 = op r2, r1.
1173   static bool CommuteChangesDestination(MachineInstr *DefMI,
1174                                         const TargetInstrDesc &TID,
1175                                         unsigned SrcReg,
1176                                         const TargetInstrInfo *TII,
1177                                         unsigned &DstIdx) {
1178     if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1179       return false;
1180     if (!DefMI->getOperand(1).isReg() ||
1181         DefMI->getOperand(1).getReg() != SrcReg)
1182       return false;
1183     unsigned DefIdx;
1184     if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1185       return false;
1186     unsigned SrcIdx1, SrcIdx2;
1187     if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1188       return false;
1189     if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1190       DstIdx = 2;
1191       return true;
1192     }
1193     return false;
1194   }
1195
1196   /// CommuteToFoldReload -
1197   /// Look for
1198   /// r1 = load fi#1
1199   /// r1 = op r1, r2<kill>
1200   /// store r1, fi#1
1201   ///
1202   /// If op is commutable and r2 is killed, then we can xform these to
1203   /// r2 = op r2, fi#1
1204   /// store r2, fi#1
1205   bool CommuteToFoldReload(MachineBasicBlock &MBB,
1206                            MachineBasicBlock::iterator &MII,
1207                            unsigned VirtReg, unsigned SrcReg, int SS,
1208                            AvailableSpills &Spills,
1209                            BitVector &RegKills,
1210                            std::vector<MachineOperand*> &KillOps,
1211                            const TargetRegisterInfo *TRI,
1212                            VirtRegMap &VRM) {
1213     if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1214       return false;
1215
1216     MachineFunction &MF = *MBB.getParent();
1217     MachineInstr &MI = *MII;
1218     MachineBasicBlock::iterator DefMII = prior(MII);
1219     MachineInstr *DefMI = DefMII;
1220     const TargetInstrDesc &TID = DefMI->getDesc();
1221     unsigned NewDstIdx;
1222     if (DefMII != MBB.begin() &&
1223         TID.isCommutable() &&
1224         CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1225       MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1226       unsigned NewReg = NewDstMO.getReg();
1227       if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1228         return false;
1229       MachineInstr *ReloadMI = prior(DefMII);
1230       int FrameIdx;
1231       unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1232       if (DestReg != SrcReg || FrameIdx != SS)
1233         return false;
1234       int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1235       if (UseIdx == -1)
1236         return false;
1237       unsigned DefIdx;
1238       if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1239         return false;
1240       assert(DefMI->getOperand(DefIdx).isReg() &&
1241              DefMI->getOperand(DefIdx).getReg() == SrcReg);
1242
1243       // Now commute def instruction.
1244       MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1245       if (!CommutedMI)
1246         return false;
1247       SmallVector<unsigned, 1> Ops;
1248       Ops.push_back(NewDstIdx);
1249       MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1250       // Not needed since foldMemoryOperand returns new MI.
1251       MF.DeleteMachineInstr(CommutedMI);
1252       if (!FoldedMI)
1253         return false;
1254
1255       VRM.addSpillSlotUse(SS, FoldedMI);
1256       VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1257       // Insert new def MI and spill MI.
1258       const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1259       TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1260       MII = prior(MII);
1261       MachineInstr *StoreMI = MII;
1262       VRM.addSpillSlotUse(SS, StoreMI);
1263       VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1264       MII = MBB.insert(MII, FoldedMI);  // Update MII to backtrack.
1265
1266       // Delete all 3 old instructions.
1267       InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1268       VRM.RemoveMachineInstrFromMaps(ReloadMI);
1269       MBB.erase(ReloadMI);
1270       InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1271       VRM.RemoveMachineInstrFromMaps(DefMI);
1272       MBB.erase(DefMI);
1273       InvalidateKills(MI, TRI, RegKills, KillOps);
1274       VRM.RemoveMachineInstrFromMaps(&MI);
1275       MBB.erase(&MI);
1276
1277       // If NewReg was previously holding value of some SS, it's now clobbered.
1278       // This has to be done now because it's a physical register. When this
1279       // instruction is re-visited, it's ignored.
1280       Spills.ClobberPhysReg(NewReg);
1281
1282       ++NumCommutes;
1283       return true;
1284     }
1285
1286     return false;
1287   }
1288
1289   /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1290   /// the last store to the same slot is now dead. If so, remove the last store.
1291   void SpillRegToStackSlot(MachineBasicBlock &MBB,
1292                            MachineBasicBlock::iterator &MII,
1293                            int Idx, unsigned PhysReg, int StackSlot,
1294                            const TargetRegisterClass *RC,
1295                            bool isAvailable, MachineInstr *&LastStore,
1296                            AvailableSpills &Spills,
1297                            SmallSet<MachineInstr*, 4> &ReMatDefs,
1298                            BitVector &RegKills,
1299                            std::vector<MachineOperand*> &KillOps,
1300                            VirtRegMap &VRM) {
1301
1302     TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1303     MachineInstr *StoreMI = next(MII);
1304     VRM.addSpillSlotUse(StackSlot, StoreMI);
1305     DOUT << "Store:\t" << *StoreMI;
1306
1307     // If there is a dead store to this stack slot, nuke it now.
1308     if (LastStore) {
1309       DOUT << "Removed dead store:\t" << *LastStore;
1310       ++NumDSE;
1311       SmallVector<unsigned, 2> KillRegs;
1312       InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1313       MachineBasicBlock::iterator PrevMII = LastStore;
1314       bool CheckDef = PrevMII != MBB.begin();
1315       if (CheckDef)
1316         --PrevMII;
1317       VRM.RemoveMachineInstrFromMaps(LastStore);
1318       MBB.erase(LastStore);
1319       if (CheckDef) {
1320         // Look at defs of killed registers on the store. Mark the defs
1321         // as dead since the store has been deleted and they aren't
1322         // being reused.
1323         for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1324           bool HasOtherDef = false;
1325           if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1326             MachineInstr *DeadDef = PrevMII;
1327             if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1328               // FIXME: This assumes a remat def does not have side effects.
1329               VRM.RemoveMachineInstrFromMaps(DeadDef);
1330               MBB.erase(DeadDef);
1331               ++NumDRM;
1332             }
1333           }
1334         }
1335       }
1336     }
1337
1338     LastStore = next(MII);
1339
1340     // If the stack slot value was previously available in some other
1341     // register, change it now.  Otherwise, make the register available,
1342     // in PhysReg.
1343     Spills.ModifyStackSlotOrReMat(StackSlot);
1344     Spills.ClobberPhysReg(PhysReg);
1345     Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1346     ++NumStores;
1347   }
1348
1349   /// TransferDeadness - A identity copy definition is dead and it's being
1350   /// removed. Find the last def or use and mark it as dead / kill.
1351   void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1352                         unsigned Reg, BitVector &RegKills,
1353                         std::vector<MachineOperand*> &KillOps,
1354                         VirtRegMap &VRM) {
1355     SmallPtrSet<MachineInstr*, 4> Seens;
1356     SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1357     for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1358            RE = RegInfo->reg_end(); RI != RE; ++RI) {
1359       MachineInstr *UDMI = &*RI;
1360       if (UDMI->getParent() != MBB)
1361         continue;
1362       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1363       if (DI == DistanceMap.end() || DI->second > CurDist)
1364         continue;
1365       if (Seens.insert(UDMI))
1366         Refs.push_back(std::make_pair(UDMI, DI->second));
1367     }
1368
1369     if (Refs.empty())
1370       return;
1371     std::sort(Refs.begin(), Refs.end(), RefSorter());
1372
1373     while (!Refs.empty()) {
1374       MachineInstr *LastUDMI = Refs.back().first;
1375       Refs.pop_back();
1376
1377       MachineOperand *LastUD = NULL;
1378       for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1379         MachineOperand &MO = LastUDMI->getOperand(i);
1380         if (!MO.isReg() || MO.getReg() != Reg)
1381           continue;
1382         if (!LastUD || (LastUD->isUse() && MO.isDef()))
1383           LastUD = &MO;
1384         if (LastUDMI->isRegTiedToDefOperand(i))
1385           break;
1386       }
1387       if (LastUD->isDef()) {
1388         // If the instruction has no side effect, delete it and propagate
1389         // backward further. Otherwise, mark is dead and we are done.
1390         const TargetInstrDesc &TID = LastUDMI->getDesc();
1391         if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1392             TID.hasUnmodeledSideEffects()) {
1393           LastUD->setIsDead();
1394           break;
1395         }
1396         VRM.RemoveMachineInstrFromMaps(LastUDMI);
1397         MBB->erase(LastUDMI);
1398       } else {
1399         LastUD->setIsKill();
1400         RegKills.set(Reg);
1401         KillOps[Reg] = LastUD;
1402         break;
1403       }
1404     }
1405   }
1406
1407   /// rewriteMBB - Keep track of which spills are available even after the
1408   /// register allocator is done with them.  If possible, avid reloading vregs.
1409   void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1410                   LiveIntervals *LIs,
1411                   AvailableSpills &Spills, BitVector &RegKills,
1412                   std::vector<MachineOperand*> &KillOps) {
1413
1414     DOUT << "\n**** Local spiller rewriting MBB '"
1415          << MBB.getBasicBlock()->getName() << "':\n";
1416
1417     MachineFunction &MF = *MBB.getParent();
1418     
1419     // MaybeDeadStores - When we need to write a value back into a stack slot,
1420     // keep track of the inserted store.  If the stack slot value is never read
1421     // (because the value was used from some available register, for example), and
1422     // subsequently stored to, the original store is dead.  This map keeps track
1423     // of inserted stores that are not used.  If we see a subsequent store to the
1424     // same stack slot, the original store is deleted.
1425     std::vector<MachineInstr*> MaybeDeadStores;
1426     MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1427
1428     // ReMatDefs - These are rematerializable def MIs which are not deleted.
1429     SmallSet<MachineInstr*, 4> ReMatDefs;
1430
1431     // Clear kill info.
1432     SmallSet<unsigned, 2> KilledMIRegs;
1433     RegKills.reset();
1434     KillOps.clear();
1435     KillOps.resize(TRI->getNumRegs(), NULL);
1436
1437     unsigned Dist = 0;
1438     DistanceMap.clear();
1439     for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1440          MII != E; ) {
1441       MachineBasicBlock::iterator NextMII = next(MII);
1442
1443       VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1444       bool Erased = false;
1445       bool BackTracked = false;
1446       if (OptimizeByUnfold(MBB, MII,
1447                            MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1448         NextMII = next(MII);
1449
1450       MachineInstr &MI = *MII;
1451
1452       if (VRM.hasEmergencySpills(&MI)) {
1453         // Spill physical register(s) in the rare case the allocator has run out
1454         // of registers to allocate.
1455         SmallSet<int, 4> UsedSS;
1456         std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1457         for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1458           unsigned PhysReg = EmSpills[i];
1459           const TargetRegisterClass *RC =
1460             TRI->getPhysicalRegisterRegClass(PhysReg);
1461           assert(RC && "Unable to determine register class!");
1462           int SS = VRM.getEmergencySpillSlot(RC);
1463           if (UsedSS.count(SS))
1464             llvm_unreachable("Need to spill more than one physical registers!");
1465           UsedSS.insert(SS);
1466           TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1467           MachineInstr *StoreMI = prior(MII);
1468           VRM.addSpillSlotUse(SS, StoreMI);
1469           TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1470           MachineInstr *LoadMI = next(MII);
1471           VRM.addSpillSlotUse(SS, LoadMI);
1472           ++NumPSpills;
1473         }
1474         NextMII = next(MII);
1475       }
1476
1477       // Insert restores here if asked to.
1478       if (VRM.isRestorePt(&MI)) {
1479         std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1480         for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1481           unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1482           if (!VRM.getPreSplitReg(VirtReg))
1483             continue; // Split interval spilled again.
1484           unsigned Phys = VRM.getPhys(VirtReg);
1485           RegInfo->setPhysRegUsed(Phys);
1486
1487           // Check if the value being restored if available. If so, it must be
1488           // from a predecessor BB that fallthrough into this BB. We do not
1489           // expect:
1490           // BB1:
1491           // r1 = load fi#1
1492           // ...
1493           //    = r1<kill>
1494           // ... # r1 not clobbered
1495           // ...
1496           //    = load fi#1
1497           bool DoReMat = VRM.isReMaterialized(VirtReg);
1498           int SSorRMId = DoReMat
1499             ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1500           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1501           unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1502           if (InReg == Phys) {
1503             // If the value is already available in the expected register, save
1504             // a reload / remat.
1505             if (SSorRMId)
1506               DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1507             else
1508               DOUT << "Reusing SS#" << SSorRMId;
1509             DOUT << " from physreg "
1510                  << TRI->getName(InReg) << " for vreg"
1511                  << VirtReg <<" instead of reloading into physreg "
1512                  << TRI->getName(Phys) << "\n";
1513             ++NumOmitted;
1514             continue;
1515           } else if (InReg && InReg != Phys) {
1516             if (SSorRMId)
1517               DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1518             else
1519               DOUT << "Reusing SS#" << SSorRMId;
1520             DOUT << " from physreg "
1521                  << TRI->getName(InReg) << " for vreg"
1522                  << VirtReg <<" by copying it into physreg "
1523                  << TRI->getName(Phys) << "\n";
1524
1525             // If the reloaded / remat value is available in another register,
1526             // copy it to the desired register.
1527             TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1528
1529             // This invalidates Phys.
1530             Spills.ClobberPhysReg(Phys);
1531             // Remember it's available.
1532             Spills.addAvailable(SSorRMId, Phys);
1533
1534             // Mark is killed.
1535             MachineInstr *CopyMI = prior(MII);
1536             MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1537             KillOpnd->setIsKill();
1538             UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1539
1540             DOUT << '\t' << *CopyMI;
1541             ++NumCopified;
1542             continue;
1543           }
1544
1545           if (VRM.isReMaterialized(VirtReg)) {
1546             ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1547           } else {
1548             const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1549             TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1550             MachineInstr *LoadMI = prior(MII);
1551             VRM.addSpillSlotUse(SSorRMId, LoadMI);
1552             ++NumLoads;
1553           }
1554
1555           // This invalidates Phys.
1556           Spills.ClobberPhysReg(Phys);
1557           // Remember it's available.
1558           Spills.addAvailable(SSorRMId, Phys);
1559
1560           UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1561           DOUT << '\t' << *prior(MII);
1562         }
1563       }
1564
1565       // Insert spills here if asked to.
1566       if (VRM.isSpillPt(&MI)) {
1567         std::vector<std::pair<unsigned,bool> > &SpillRegs =
1568           VRM.getSpillPtSpills(&MI);
1569         for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1570           unsigned VirtReg = SpillRegs[i].first;
1571           bool isKill = SpillRegs[i].second;
1572           if (!VRM.getPreSplitReg(VirtReg))
1573             continue; // Split interval spilled again.
1574           const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1575           unsigned Phys = VRM.getPhys(VirtReg);
1576           int StackSlot = VRM.getStackSlot(VirtReg);
1577           TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1578           MachineInstr *StoreMI = next(MII);
1579           VRM.addSpillSlotUse(StackSlot, StoreMI);
1580           DOUT << "Store:\t" << *StoreMI;
1581           VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1582         }
1583         NextMII = next(MII);
1584       }
1585
1586       /// ReusedOperands - Keep track of operand reuse in case we need to undo
1587       /// reuse.
1588       ReuseInfo ReusedOperands(MI, TRI);
1589       SmallVector<unsigned, 4> VirtUseOps;
1590       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1591         MachineOperand &MO = MI.getOperand(i);
1592         if (!MO.isReg() || MO.getReg() == 0)
1593           continue;   // Ignore non-register operands.
1594         
1595         unsigned VirtReg = MO.getReg();
1596         if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1597           // Ignore physregs for spilling, but remember that it is used by this
1598           // function.
1599           RegInfo->setPhysRegUsed(VirtReg);
1600           continue;
1601         }
1602
1603         // We want to process implicit virtual register uses first.
1604         if (MO.isImplicit())
1605           // If the virtual register is implicitly defined, emit a implicit_def
1606           // before so scavenger knows it's "defined".
1607           // FIXME: This is a horrible hack done the by register allocator to
1608           // remat a definition with virtual register operand.
1609           VirtUseOps.insert(VirtUseOps.begin(), i);
1610         else
1611           VirtUseOps.push_back(i);
1612       }
1613
1614       // Process all of the spilled uses and all non spilled reg references.
1615       SmallVector<int, 2> PotentialDeadStoreSlots;
1616       KilledMIRegs.clear();
1617       for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1618         unsigned i = VirtUseOps[j];
1619         MachineOperand &MO = MI.getOperand(i);
1620         unsigned VirtReg = MO.getReg();
1621         assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1622                "Not a virtual register?");
1623
1624         unsigned SubIdx = MO.getSubReg();
1625         if (VRM.isAssignedReg(VirtReg)) {
1626           // This virtual register was assigned a physreg!
1627           unsigned Phys = VRM.getPhys(VirtReg);
1628           RegInfo->setPhysRegUsed(Phys);
1629           if (MO.isDef())
1630             ReusedOperands.markClobbered(Phys);
1631           unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1632           MI.getOperand(i).setReg(RReg);
1633           MI.getOperand(i).setSubReg(0);
1634           if (VRM.isImplicitlyDefined(VirtReg))
1635             // FIXME: Is this needed?
1636             BuildMI(MBB, &MI, MI.getDebugLoc(),
1637                     TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1638           continue;
1639         }
1640         
1641         // This virtual register is now known to be a spilled value.
1642         if (!MO.isUse())
1643           continue;  // Handle defs in the loop below (handle use&def here though)
1644
1645         bool AvoidReload = MO.isUndef();
1646         // Check if it is defined by an implicit def. It should not be spilled.
1647         // Note, this is for correctness reason. e.g.
1648         // 8   %reg1024<def> = IMPLICIT_DEF
1649         // 12  %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1650         // The live range [12, 14) are not part of the r1024 live interval since
1651         // it's defined by an implicit def. It will not conflicts with live
1652         // interval of r1025. Now suppose both registers are spilled, you can
1653         // easily see a situation where both registers are reloaded before
1654         // the INSERT_SUBREG and both target registers that would overlap.
1655         bool DoReMat = VRM.isReMaterialized(VirtReg);
1656         int SSorRMId = DoReMat
1657           ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1658         int ReuseSlot = SSorRMId;
1659
1660         // Check to see if this stack slot is available.
1661         unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1662
1663         // If this is a sub-register use, make sure the reuse register is in the
1664         // right register class. For example, for x86 not all of the 32-bit
1665         // registers have accessible sub-registers.
1666         // Similarly so for EXTRACT_SUBREG. Consider this:
1667         // EDI = op
1668         // MOV32_mr fi#1, EDI
1669         // ...
1670         //       = EXTRACT_SUBREG fi#1
1671         // fi#1 is available in EDI, but it cannot be reused because it's not in
1672         // the right register file.
1673         if (PhysReg && !AvoidReload &&
1674             (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1675           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1676           if (!RC->contains(PhysReg))
1677             PhysReg = 0;
1678         }
1679
1680         if (PhysReg && !AvoidReload) {
1681           // This spilled operand might be part of a two-address operand.  If this
1682           // is the case, then changing it will necessarily require changing the 
1683           // def part of the instruction as well.  However, in some cases, we
1684           // aren't allowed to modify the reused register.  If none of these cases
1685           // apply, reuse it.
1686           bool CanReuse = true;
1687           bool isTied = MI.isRegTiedToDefOperand(i);
1688           if (isTied) {
1689             // Okay, we have a two address operand.  We can reuse this physreg as
1690             // long as we are allowed to clobber the value and there isn't an
1691             // earlier def that has already clobbered the physreg.
1692             CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1693               Spills.canClobberPhysReg(PhysReg);
1694           }
1695           
1696           if (CanReuse) {
1697             // If this stack slot value is already available, reuse it!
1698             if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1699               DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1700             else
1701               DOUT << "Reusing SS#" << ReuseSlot;
1702             DOUT << " from physreg "
1703                  << TRI->getName(PhysReg) << " for vreg"
1704                  << VirtReg <<" instead of reloading into physreg "
1705                  << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1706             unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1707             MI.getOperand(i).setReg(RReg);
1708             MI.getOperand(i).setSubReg(0);
1709
1710             // The only technical detail we have is that we don't know that
1711             // PhysReg won't be clobbered by a reloaded stack slot that occurs
1712             // later in the instruction.  In particular, consider 'op V1, V2'.
1713             // If V1 is available in physreg R0, we would choose to reuse it
1714             // here, instead of reloading it into the register the allocator
1715             // indicated (say R1).  However, V2 might have to be reloaded
1716             // later, and it might indicate that it needs to live in R0.  When
1717             // this occurs, we need to have information available that
1718             // indicates it is safe to use R1 for the reload instead of R0.
1719             //
1720             // To further complicate matters, we might conflict with an alias,
1721             // or R0 and R1 might not be compatible with each other.  In this
1722             // case, we actually insert a reload for V1 in R1, ensuring that
1723             // we can get at R0 or its alias.
1724             ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1725                                     VRM.getPhys(VirtReg), VirtReg);
1726             if (isTied)
1727               // Only mark it clobbered if this is a use&def operand.
1728               ReusedOperands.markClobbered(PhysReg);
1729             ++NumReused;
1730
1731             if (MI.getOperand(i).isKill() &&
1732                 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1733
1734               // The store of this spilled value is potentially dead, but we
1735               // won't know for certain until we've confirmed that the re-use
1736               // above is valid, which means waiting until the other operands
1737               // are processed. For now we just track the spill slot, we'll
1738               // remove it after the other operands are processed if valid.
1739
1740               PotentialDeadStoreSlots.push_back(ReuseSlot);
1741             }
1742
1743             // Mark is isKill if it's there no other uses of the same virtual
1744             // register and it's not a two-address operand. IsKill will be
1745             // unset if reg is reused.
1746             if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1747               MI.getOperand(i).setIsKill();
1748               KilledMIRegs.insert(VirtReg);
1749             }
1750
1751             continue;
1752           }  // CanReuse
1753           
1754           // Otherwise we have a situation where we have a two-address instruction
1755           // whose mod/ref operand needs to be reloaded.  This reload is already
1756           // available in some register "PhysReg", but if we used PhysReg as the
1757           // operand to our 2-addr instruction, the instruction would modify
1758           // PhysReg.  This isn't cool if something later uses PhysReg and expects
1759           // to get its initial value.
1760           //
1761           // To avoid this problem, and to avoid doing a load right after a store,
1762           // we emit a copy from PhysReg into the designated register for this
1763           // operand.
1764           unsigned DesignatedReg = VRM.getPhys(VirtReg);
1765           assert(DesignatedReg && "Must map virtreg to physreg!");
1766
1767           // Note that, if we reused a register for a previous operand, the
1768           // register we want to reload into might not actually be
1769           // available.  If this occurs, use the register indicated by the
1770           // reuser.
1771           if (ReusedOperands.hasReuses())
1772             DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
1773                                  Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1774           
1775           // If the mapped designated register is actually the physreg we have
1776           // incoming, we don't need to inserted a dead copy.
1777           if (DesignatedReg == PhysReg) {
1778             // If this stack slot value is already available, reuse it!
1779             if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1780               DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1781             else
1782               DOUT << "Reusing SS#" << ReuseSlot;
1783             DOUT << " from physreg " << TRI->getName(PhysReg)
1784                  << " for vreg" << VirtReg
1785                  << " instead of reloading into same physreg.\n";
1786             unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1787             MI.getOperand(i).setReg(RReg);
1788             MI.getOperand(i).setSubReg(0);
1789             ReusedOperands.markClobbered(RReg);
1790             ++NumReused;
1791             continue;
1792           }
1793           
1794           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1795           RegInfo->setPhysRegUsed(DesignatedReg);
1796           ReusedOperands.markClobbered(DesignatedReg);
1797           TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1798
1799           MachineInstr *CopyMI = prior(MII);
1800           UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1801
1802           // This invalidates DesignatedReg.
1803           Spills.ClobberPhysReg(DesignatedReg);
1804           
1805           Spills.addAvailable(ReuseSlot, DesignatedReg);
1806           unsigned RReg =
1807             SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1808           MI.getOperand(i).setReg(RReg);
1809           MI.getOperand(i).setSubReg(0);
1810           DOUT << '\t' << *prior(MII);
1811           ++NumReused;
1812           continue;
1813         } // if (PhysReg)
1814         
1815         // Otherwise, reload it and remember that we have it.
1816         PhysReg = VRM.getPhys(VirtReg);
1817         assert(PhysReg && "Must map virtreg to physreg!");
1818
1819         // Note that, if we reused a register for a previous operand, the
1820         // register we want to reload into might not actually be
1821         // available.  If this occurs, use the register indicated by the
1822         // reuser.
1823         if (ReusedOperands.hasReuses())
1824           PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1825                                  Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1826         
1827         RegInfo->setPhysRegUsed(PhysReg);
1828         ReusedOperands.markClobbered(PhysReg);
1829         if (AvoidReload)
1830           ++NumAvoided;
1831         else {
1832           if (DoReMat) {
1833             ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1834           } else {
1835             const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1836             TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1837             MachineInstr *LoadMI = prior(MII);
1838             VRM.addSpillSlotUse(SSorRMId, LoadMI);
1839             ++NumLoads;
1840           }
1841           // This invalidates PhysReg.
1842           Spills.ClobberPhysReg(PhysReg);
1843
1844           // Any stores to this stack slot are not dead anymore.
1845           if (!DoReMat)
1846             MaybeDeadStores[SSorRMId] = NULL;
1847           Spills.addAvailable(SSorRMId, PhysReg);
1848           // Assumes this is the last use. IsKill will be unset if reg is reused
1849           // unless it's a two-address operand.
1850           if (!MI.isRegTiedToDefOperand(i) &&
1851               KilledMIRegs.count(VirtReg) == 0) {
1852             MI.getOperand(i).setIsKill();
1853             KilledMIRegs.insert(VirtReg);
1854           }
1855
1856           UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1857           DOUT << '\t' << *prior(MII);
1858         }
1859         unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1860         MI.getOperand(i).setReg(RReg);
1861         MI.getOperand(i).setSubReg(0);
1862       }
1863
1864       // Ok - now we can remove stores that have been confirmed dead.
1865       for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1866         // This was the last use and the spilled value is still available
1867         // for reuse. That means the spill was unnecessary!
1868         int PDSSlot = PotentialDeadStoreSlots[j];
1869         MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1870         if (DeadStore) {
1871           DOUT << "Removed dead store:\t" << *DeadStore;
1872           InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1873           VRM.RemoveMachineInstrFromMaps(DeadStore);
1874           MBB.erase(DeadStore);
1875           MaybeDeadStores[PDSSlot] = NULL;
1876           ++NumDSE;
1877         }
1878       }
1879
1880
1881       DOUT << '\t' << MI;
1882
1883
1884       // If we have folded references to memory operands, make sure we clear all
1885       // physical registers that may contain the value of the spilled virtual
1886       // register
1887       SmallSet<int, 2> FoldedSS;
1888       for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1889         unsigned VirtReg = I->second.first;
1890         VirtRegMap::ModRef MR = I->second.second;
1891         DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1892
1893         // MI2VirtMap be can updated which invalidate the iterator.
1894         // Increment the iterator first.
1895         ++I;
1896         int SS = VRM.getStackSlot(VirtReg);
1897         if (SS == VirtRegMap::NO_STACK_SLOT)
1898           continue;
1899         FoldedSS.insert(SS);
1900         DOUT << " - StackSlot: " << SS << "\n";
1901         
1902         // If this folded instruction is just a use, check to see if it's a
1903         // straight load from the virt reg slot.
1904         if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1905           int FrameIdx;
1906           unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1907           if (DestReg && FrameIdx == SS) {
1908             // If this spill slot is available, turn it into a copy (or nothing)
1909             // instead of leaving it as a load!
1910             if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1911               DOUT << "Promoted Load To Copy: " << MI;
1912               if (DestReg != InReg) {
1913                 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1914                 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1915                 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1916                 unsigned SubIdx = DefMO->getSubReg();
1917                 // Revisit the copy so we make sure to notice the effects of the
1918                 // operation on the destreg (either needing to RA it if it's 
1919                 // virtual or needing to clobber any values if it's physical).
1920                 NextMII = &MI;
1921                 --NextMII;  // backtrack to the copy.
1922                 // Propagate the sub-register index over.
1923                 if (SubIdx) {
1924                   DefMO = NextMII->findRegisterDefOperand(DestReg);
1925                   DefMO->setSubReg(SubIdx);
1926                 }
1927
1928                 // Mark is killed.
1929                 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1930                 KillOpnd->setIsKill();
1931
1932                 BackTracked = true;
1933               } else {
1934                 DOUT << "Removing now-noop copy: " << MI;
1935                 // Unset last kill since it's being reused.
1936                 InvalidateKill(InReg, TRI, RegKills, KillOps);
1937                 Spills.disallowClobberPhysReg(InReg);
1938               }
1939
1940               InvalidateKills(MI, TRI, RegKills, KillOps);
1941               VRM.RemoveMachineInstrFromMaps(&MI);
1942               MBB.erase(&MI);
1943               Erased = true;
1944               goto ProcessNextInst;
1945             }
1946           } else {
1947             unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1948             SmallVector<MachineInstr*, 4> NewMIs;
1949             if (PhysReg &&
1950                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1951               MBB.insert(MII, NewMIs[0]);
1952               InvalidateKills(MI, TRI, RegKills, KillOps);
1953               VRM.RemoveMachineInstrFromMaps(&MI);
1954               MBB.erase(&MI);
1955               Erased = true;
1956               --NextMII;  // backtrack to the unfolded instruction.
1957               BackTracked = true;
1958               goto ProcessNextInst;
1959             }
1960           }
1961         }
1962
1963         // If this reference is not a use, any previous store is now dead.
1964         // Otherwise, the store to this stack slot is not dead anymore.
1965         MachineInstr* DeadStore = MaybeDeadStores[SS];
1966         if (DeadStore) {
1967           bool isDead = !(MR & VirtRegMap::isRef);
1968           MachineInstr *NewStore = NULL;
1969           if (MR & VirtRegMap::isModRef) {
1970             unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1971             SmallVector<MachineInstr*, 4> NewMIs;
1972             // We can reuse this physreg as long as we are allowed to clobber
1973             // the value and there isn't an earlier def that has already clobbered
1974             // the physreg.
1975             if (PhysReg &&
1976                 !ReusedOperands.isClobbered(PhysReg) &&
1977                 Spills.canClobberPhysReg(PhysReg) &&
1978                 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1979               MachineOperand *KillOpnd =
1980                 DeadStore->findRegisterUseOperand(PhysReg, true);
1981               // Note, if the store is storing a sub-register, it's possible the
1982               // super-register is needed below.
1983               if (KillOpnd && !KillOpnd->getSubReg() &&
1984                   TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1985                 MBB.insert(MII, NewMIs[0]);
1986                 NewStore = NewMIs[1];
1987                 MBB.insert(MII, NewStore);
1988                 VRM.addSpillSlotUse(SS, NewStore);
1989                 InvalidateKills(MI, TRI, RegKills, KillOps);
1990                 VRM.RemoveMachineInstrFromMaps(&MI);
1991                 MBB.erase(&MI);
1992                 Erased = true;
1993                 --NextMII;
1994                 --NextMII;  // backtrack to the unfolded instruction.
1995                 BackTracked = true;
1996                 isDead = true;
1997                 ++NumSUnfold;
1998               }
1999             }
2000           }
2001
2002           if (isDead) {  // Previous store is dead.
2003             // If we get here, the store is dead, nuke it now.
2004             DOUT << "Removed dead store:\t" << *DeadStore;
2005             InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2006             VRM.RemoveMachineInstrFromMaps(DeadStore);
2007             MBB.erase(DeadStore);
2008             if (!NewStore)
2009               ++NumDSE;
2010           }
2011
2012           MaybeDeadStores[SS] = NULL;
2013           if (NewStore) {
2014             // Treat this store as a spill merged into a copy. That makes the
2015             // stack slot value available.
2016             VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2017             goto ProcessNextInst;
2018           }
2019         }
2020
2021         // If the spill slot value is available, and this is a new definition of
2022         // the value, the value is not available anymore.
2023         if (MR & VirtRegMap::isMod) {
2024           // Notice that the value in this stack slot has been modified.
2025           Spills.ModifyStackSlotOrReMat(SS);
2026           
2027           // If this is *just* a mod of the value, check to see if this is just a
2028           // store to the spill slot (i.e. the spill got merged into the copy). If
2029           // so, realize that the vreg is available now, and add the store to the
2030           // MaybeDeadStore info.
2031           int StackSlot;
2032           if (!(MR & VirtRegMap::isRef)) {
2033             if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2034               assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2035                      "Src hasn't been allocated yet?");
2036
2037               if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2038                                       Spills, RegKills, KillOps, TRI, VRM)) {
2039                 NextMII = next(MII);
2040                 BackTracked = true;
2041                 goto ProcessNextInst;
2042               }
2043
2044               // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
2045               // this as a potentially dead store in case there is a subsequent
2046               // store into the stack slot without a read from it.
2047               MaybeDeadStores[StackSlot] = &MI;
2048
2049               // If the stack slot value was previously available in some other
2050               // register, change it now.  Otherwise, make the register
2051               // available in PhysReg.
2052               Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2053             }
2054           }
2055         }
2056       }
2057
2058       // Process all of the spilled defs.
2059       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2060         MachineOperand &MO = MI.getOperand(i);
2061         if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2062           continue;
2063
2064         unsigned VirtReg = MO.getReg();
2065         if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2066           // Check to see if this is a noop copy.  If so, eliminate the
2067           // instruction before considering the dest reg to be changed.
2068           // Also check if it's copying from an "undef", if so, we can't
2069           // eliminate this or else the undef marker is lost and it will
2070           // confuses the scavenger. This is extremely rare.
2071           unsigned Src, Dst, SrcSR, DstSR;
2072           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2073               !MI.findRegisterUseOperand(Src)->isUndef()) {
2074             ++NumDCE;
2075             DOUT << "Removing now-noop copy: " << MI;
2076             SmallVector<unsigned, 2> KillRegs;
2077             InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2078             if (MO.isDead() && !KillRegs.empty()) {
2079               // Source register or an implicit super/sub-register use is killed.
2080               assert(KillRegs[0] == Dst ||
2081                      TRI->isSubRegister(KillRegs[0], Dst) ||
2082                      TRI->isSuperRegister(KillRegs[0], Dst));
2083               // Last def is now dead.
2084               TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2085             }
2086             VRM.RemoveMachineInstrFromMaps(&MI);
2087             MBB.erase(&MI);
2088             Erased = true;
2089             Spills.disallowClobberPhysReg(VirtReg);
2090             goto ProcessNextInst;
2091           }
2092
2093           // If it's not a no-op copy, it clobbers the value in the destreg.
2094           Spills.ClobberPhysReg(VirtReg);
2095           ReusedOperands.markClobbered(VirtReg);
2096    
2097           // Check to see if this instruction is a load from a stack slot into
2098           // a register.  If so, this provides the stack slot value in the reg.
2099           int FrameIdx;
2100           if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2101             assert(DestReg == VirtReg && "Unknown load situation!");
2102
2103             // If it is a folded reference, then it's not safe to clobber.
2104             bool Folded = FoldedSS.count(FrameIdx);
2105             // Otherwise, if it wasn't available, remember that it is now!
2106             Spills.addAvailable(FrameIdx, DestReg, !Folded);
2107             goto ProcessNextInst;
2108           }
2109               
2110           continue;
2111         }
2112
2113         unsigned SubIdx = MO.getSubReg();
2114         bool DoReMat = VRM.isReMaterialized(VirtReg);
2115         if (DoReMat)
2116           ReMatDefs.insert(&MI);
2117
2118         // The only vregs left are stack slot definitions.
2119         int StackSlot = VRM.getStackSlot(VirtReg);
2120         const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2121
2122         // If this def is part of a two-address operand, make sure to execute
2123         // the store from the correct physical register.
2124         unsigned PhysReg;
2125         unsigned TiedOp;
2126         if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2127           PhysReg = MI.getOperand(TiedOp).getReg();
2128           if (SubIdx) {
2129             unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2130             assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2131                    "Can't find corresponding super-register!");
2132             PhysReg = SuperReg;
2133           }
2134         } else {
2135           PhysReg = VRM.getPhys(VirtReg);
2136           if (ReusedOperands.isClobbered(PhysReg)) {
2137             // Another def has taken the assigned physreg. It must have been a
2138             // use&def which got it due to reuse. Undo the reuse!
2139             PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
2140                                  Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2141           }
2142         }
2143
2144         assert(PhysReg && "VR not assigned a physical register?");
2145         RegInfo->setPhysRegUsed(PhysReg);
2146         unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2147         ReusedOperands.markClobbered(RReg);
2148         MI.getOperand(i).setReg(RReg);
2149         MI.getOperand(i).setSubReg(0);
2150
2151         if (!MO.isDead()) {
2152           MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2153           SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2154                             LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2155           NextMII = next(MII);
2156
2157           // Check to see if this is a noop copy.  If so, eliminate the
2158           // instruction before considering the dest reg to be changed.
2159           {
2160             unsigned Src, Dst, SrcSR, DstSR;
2161             if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2162               ++NumDCE;
2163               DOUT << "Removing now-noop copy: " << MI;
2164               InvalidateKills(MI, TRI, RegKills, KillOps);
2165               VRM.RemoveMachineInstrFromMaps(&MI);
2166               MBB.erase(&MI);
2167               Erased = true;
2168               UpdateKills(*LastStore, TRI, RegKills, KillOps);
2169               goto ProcessNextInst;
2170             }
2171           }
2172         }    
2173       }
2174     ProcessNextInst:
2175       DistanceMap.insert(std::make_pair(&MI, Dist++));
2176       if (!Erased && !BackTracked) {
2177         for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2178           UpdateKills(*II, TRI, RegKills, KillOps);
2179       }
2180       MII = NextMII;
2181     }
2182
2183   }
2184
2185 };
2186
2187 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2188   switch (RewriterOpt) {
2189   default: llvm_unreachable("Unreachable!");
2190   case local:
2191     return new LocalRewriter();
2192   case trivial:
2193     return new TrivialRewriter();
2194   }
2195 }