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