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