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