don't add nodes to the now-dead nodes list multiple times, this
[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   // These do not affect kill info at all.
576   if (MI.isDebugValue())
577     return;
578   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
579     MachineOperand &MO = MI.getOperand(i);
580     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
581       continue;
582     unsigned Reg = MO.getReg();
583     if (Reg == 0)
584       continue;
585
586     if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
587       // That can't be right. Register is killed but not re-defined and it's
588       // being reused. Let's fix that.
589       KillOps[Reg]->setIsKill(false);
590       // KillOps[Reg] might be a def of a super-register.
591       unsigned KReg = KillOps[Reg]->getReg();
592       KillOps[KReg] = NULL;
593       RegKills.reset(KReg);
594
595       // Must be a def of a super-register. Its other sub-regsters are no
596       // longer killed as well.
597       for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
598         KillOps[*SR] = NULL;
599         RegKills.reset(*SR);
600       }
601     } else {
602       // Check for subreg kills as well.
603       // d4 =
604       // store d4, fi#0
605       // ...
606       //    = s8<kill>
607       // ...
608       //    = d4  <avoiding reload>
609       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
610         unsigned SReg = *SR;
611         if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
612           KillOps[SReg]->setIsKill(false);
613           unsigned KReg = KillOps[SReg]->getReg();
614           KillOps[KReg] = NULL;
615           RegKills.reset(KReg);
616
617           for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
618             KillOps[*SSR] = NULL;
619             RegKills.reset(*SSR);
620           }
621         }
622       }
623     }
624
625     if (MO.isKill()) {
626       RegKills.set(Reg);
627       KillOps[Reg] = &MO;
628       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
629         RegKills.set(*SR);
630         KillOps[*SR] = &MO;
631       }
632     }
633   }
634
635   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
636     const MachineOperand &MO = MI.getOperand(i);
637     if (!MO.isReg() || !MO.getReg() || !MO.isDef())
638       continue;
639     unsigned Reg = MO.getReg();
640     RegKills.reset(Reg);
641     KillOps[Reg] = NULL;
642     // It also defines (or partially define) aliases.
643     for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
644       RegKills.reset(*SR);
645       KillOps[*SR] = NULL;
646     }
647     for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
648       RegKills.reset(*SR);
649       KillOps[*SR] = NULL;
650     }
651   }
652 }
653
654 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
655 ///
656 static void ReMaterialize(MachineBasicBlock &MBB,
657                           MachineBasicBlock::iterator &MII,
658                           unsigned DestReg, unsigned Reg,
659                           const TargetInstrInfo *TII,
660                           const TargetRegisterInfo *TRI,
661                           VirtRegMap &VRM) {
662   MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
663 #ifndef NDEBUG
664   const TargetInstrDesc &TID = ReMatDefMI->getDesc();
665   assert(TID.getNumDefs() == 1 &&
666          "Don't know how to remat instructions that define > 1 values!");
667 #endif
668   TII->reMaterialize(MBB, MII, DestReg,
669                      ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
670   MachineInstr *NewMI = prior(MII);
671   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
672     MachineOperand &MO = NewMI->getOperand(i);
673     if (!MO.isReg() || MO.getReg() == 0)
674       continue;
675     unsigned VirtReg = MO.getReg();
676     if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
677       continue;
678     assert(MO.isUse());
679     unsigned Phys = VRM.getPhys(VirtReg);
680     assert(Phys && "Virtual register is not assigned a register?");
681     substitutePhysReg(MO, Phys, *TRI);
682   }
683   ++NumReMats;
684 }
685
686 /// findSuperReg - Find the SubReg's super-register of given register class
687 /// where its SubIdx sub-register is SubReg.
688 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
689                              unsigned SubIdx, const TargetRegisterInfo *TRI) {
690   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
691        I != E; ++I) {
692     unsigned Reg = *I;
693     if (TRI->getSubReg(Reg, SubIdx) == SubReg)
694       return Reg;
695   }
696   return 0;
697 }
698
699 // ******************************** //
700 // Available Spills Implementation  //
701 // ******************************** //
702
703 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
704 /// stackslot register. The register is still available but is no longer
705 /// allowed to be modifed.
706 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
707   std::multimap<unsigned, int>::iterator I =
708     PhysRegsAvailable.lower_bound(PhysReg);
709   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
710     int SlotOrReMat = I->second;
711     I++;
712     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
713            "Bidirectional map mismatch!");
714     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
715     DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
716          << " copied, it is available for use but can no longer be modified\n");
717   }
718 }
719
720 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
721 /// stackslot register and its aliases. The register and its aliases may
722 /// still available but is no longer allowed to be modifed.
723 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
724   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
725     disallowClobberPhysRegOnly(*AS);
726   disallowClobberPhysRegOnly(PhysReg);
727 }
728
729 /// ClobberPhysRegOnly - This is called when the specified physreg changes
730 /// value.  We use this to invalidate any info about stuff we thing lives in it.
731 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
732   std::multimap<unsigned, int>::iterator I =
733     PhysRegsAvailable.lower_bound(PhysReg);
734   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
735     int SlotOrReMat = I->second;
736     PhysRegsAvailable.erase(I++);
737     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
738            "Bidirectional map mismatch!");
739     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
740     DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
741           << " clobbered, invalidating ");
742     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
743       DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
744     else
745       DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
746   }
747 }
748
749 /// ClobberPhysReg - This is called when the specified physreg changes
750 /// value.  We use this to invalidate any info about stuff we thing lives in
751 /// it and any of its aliases.
752 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
753   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
754     ClobberPhysRegOnly(*AS);
755   ClobberPhysRegOnly(PhysReg);
756 }
757
758 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
759 /// into the specified MBB. Add available physical registers as potential
760 /// live-in's. If they are reused in the MBB, they will be added to the
761 /// live-in set to make register scavenger and post-allocation scheduler.
762 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
763                                         BitVector &RegKills,
764                                         std::vector<MachineOperand*> &KillOps) {
765   std::set<unsigned> NotAvailable;
766   for (std::multimap<unsigned, int>::iterator
767          I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
768        I != E; ++I) {
769     unsigned Reg = I->first;
770     const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
771     // FIXME: A temporary workaround. We can't reuse available value if it's
772     // not safe to move the def of the virtual register's class. e.g.
773     // X86::RFP* register classes. Do not add it as a live-in.
774     if (!TII->isSafeToMoveRegClassDefs(RC))
775       // This is no longer available.
776       NotAvailable.insert(Reg);
777     else {
778       MBB.addLiveIn(Reg);
779       InvalidateKill(Reg, TRI, RegKills, KillOps);
780     }
781
782     // Skip over the same register.
783     std::multimap<unsigned, int>::iterator NI = llvm::next(I);
784     while (NI != E && NI->first == Reg) {
785       ++I;
786       ++NI;
787     }
788   }
789
790   for (std::set<unsigned>::iterator I = NotAvailable.begin(),
791          E = NotAvailable.end(); I != E; ++I) {
792     ClobberPhysReg(*I);
793     for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
794        *SubRegs; ++SubRegs)
795       ClobberPhysReg(*SubRegs);
796   }
797 }
798
799 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
800 /// slot changes.  This removes information about which register the previous
801 /// value for this slot lives in (as the previous value is dead now).
802 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
803   std::map<int, unsigned>::iterator It =
804     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
805   if (It == SpillSlotsOrReMatsAvailable.end()) return;
806   unsigned Reg = It->second >> 1;
807   SpillSlotsOrReMatsAvailable.erase(It);
808
809   // This register may hold the value of multiple stack slots, only remove this
810   // stack slot from the set of values the register contains.
811   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
812   for (; ; ++I) {
813     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
814            "Map inverse broken!");
815     if (I->second == SlotOrReMat) break;
816   }
817   PhysRegsAvailable.erase(I);
818 }
819
820 // ************************** //
821 // Reuse Info Implementation  //
822 // ************************** //
823
824 /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
825 /// is some other operand that is using the specified register, either pick
826 /// a new register to use, or evict the previous reload and use this reg.
827 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
828                          unsigned PhysReg,
829                          MachineFunction &MF,
830                          MachineInstr *MI, AvailableSpills &Spills,
831                          std::vector<MachineInstr*> &MaybeDeadStores,
832                          SmallSet<unsigned, 8> &Rejected,
833                          BitVector &RegKills,
834                          std::vector<MachineOperand*> &KillOps,
835                          VirtRegMap &VRM) {
836   const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
837   const TargetRegisterInfo *TRI = Spills.getRegInfo();
838
839   if (Reuses.empty()) return PhysReg;  // This is most often empty.
840
841   for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
842     ReusedOp &Op = Reuses[ro];
843     // If we find some other reuse that was supposed to use this register
844     // exactly for its reload, we can change this reload to use ITS reload
845     // register. That is, unless its reload register has already been
846     // considered and subsequently rejected because it has also been reused
847     // by another operand.
848     if (Op.PhysRegReused == PhysReg &&
849         Rejected.count(Op.AssignedPhysReg) == 0 &&
850         RC->contains(Op.AssignedPhysReg)) {
851       // Yup, use the reload register that we didn't use before.
852       unsigned NewReg = Op.AssignedPhysReg;
853       Rejected.insert(PhysReg);
854       return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
855                              RegKills, KillOps, VRM);
856     } else {
857       // Otherwise, we might also have a problem if a previously reused
858       // value aliases the new register. If so, codegen the previous reload
859       // and use this one.
860       unsigned PRRU = Op.PhysRegReused;
861       if (TRI->regsOverlap(PRRU, PhysReg)) {
862         // Okay, we found out that an alias of a reused register
863         // was used.  This isn't good because it means we have
864         // to undo a previous reuse.
865         MachineBasicBlock *MBB = MI->getParent();
866         const TargetRegisterClass *AliasRC =
867           MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
868
869         // Copy Op out of the vector and remove it, we're going to insert an
870         // explicit load for it.
871         ReusedOp NewOp = Op;
872         Reuses.erase(Reuses.begin()+ro);
873
874         // MI may be using only a sub-register of PhysRegUsed.
875         unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
876         unsigned SubIdx = 0;
877         assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
878                "A reuse cannot be a virtual register");
879         if (PRRU != RealPhysRegUsed) {
880           // What was the sub-register index?
881           SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
882           assert(SubIdx &&
883                  "Operand physreg is not a sub-register of PhysRegUsed");
884         }
885
886         // Ok, we're going to try to reload the assigned physreg into the
887         // slot that we were supposed to in the first place.  However, that
888         // register could hold a reuse.  Check to see if it conflicts or
889         // would prefer us to use a different register.
890         unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
891                                               MF, MI, Spills, MaybeDeadStores,
892                                               Rejected, RegKills, KillOps, VRM);
893
894         bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
895         int SSorRMId = DoReMat
896           ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
897
898         // Back-schedule reloads and remats.
899         MachineBasicBlock::iterator InsertLoc =
900           ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
901                            DoReMat, SSorRMId, TII, MF);
902
903         if (DoReMat) {
904           ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
905                         TRI, VRM);
906         } else {
907           TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
908                                     NewOp.StackSlotOrReMat, AliasRC);
909           MachineInstr *LoadMI = prior(InsertLoc);
910           VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
911           // Any stores to this stack slot are not dead anymore.
912           MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
913           ++NumLoads;
914         }
915         Spills.ClobberPhysReg(NewPhysReg);
916         Spills.ClobberPhysReg(NewOp.PhysRegReused);
917
918         unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
919         MI->getOperand(NewOp.Operand).setReg(RReg);
920         MI->getOperand(NewOp.Operand).setSubReg(0);
921
922         Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
923         UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
924         DEBUG(dbgs() << '\t' << *prior(InsertLoc));
925
926         DEBUG(dbgs() << "Reuse undone!\n");
927         --NumReused;
928
929         // Finally, PhysReg is now available, go ahead and use it.
930         return PhysReg;
931       }
932     }
933   }
934   return PhysReg;
935 }
936
937 // ************************************************************************ //
938
939 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
940 /// stack slot mod/ref. It also checks if it's possible to unfold the
941 /// instruction by having it define a specified physical register instead.
942 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
943                                  const TargetInstrInfo *TII,
944                                  const TargetRegisterInfo *TRI,
945                                  VirtRegMap &VRM) {
946   if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
947     return false;
948
949   bool Found = false;
950   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
951   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
952     unsigned VirtReg = I->second.first;
953     VirtRegMap::ModRef MR = I->second.second;
954     if (MR & VirtRegMap::isModRef)
955       if (VRM.getStackSlot(VirtReg) == SS) {
956         Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
957         break;
958       }
959   }
960   if (!Found)
961     return false;
962
963   // Does the instruction uses a register that overlaps the scratch register?
964   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
965     MachineOperand &MO = MI.getOperand(i);
966     if (!MO.isReg() || MO.getReg() == 0)
967       continue;
968     unsigned Reg = MO.getReg();
969     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
970       if (!VRM.hasPhys(Reg))
971         continue;
972       Reg = VRM.getPhys(Reg);
973     }
974     if (TRI->regsOverlap(PhysReg, Reg))
975       return false;
976   }
977   return true;
978 }
979
980 /// FindFreeRegister - Find a free register of a given register class by looking
981 /// at (at most) the last two machine instructions.
982 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
983                                  MachineBasicBlock &MBB,
984                                  const TargetRegisterClass *RC,
985                                  const TargetRegisterInfo *TRI,
986                                  BitVector &AllocatableRegs) {
987   BitVector Defs(TRI->getNumRegs());
988   BitVector Uses(TRI->getNumRegs());
989   SmallVector<unsigned, 4> LocalUses;
990   SmallVector<unsigned, 4> Kills;
991
992   // Take a look at 2 instructions at most.
993   for (unsigned Count = 0; Count < 2; ++Count) {
994     if (MII == MBB.begin())
995       break;
996     MachineInstr *PrevMI = prior(MII);
997     for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
998       MachineOperand &MO = PrevMI->getOperand(i);
999       if (!MO.isReg() || MO.getReg() == 0)
1000         continue;
1001       unsigned Reg = MO.getReg();
1002       if (MO.isDef()) {
1003         Defs.set(Reg);
1004         for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1005           Defs.set(*AS);
1006       } else  {
1007         LocalUses.push_back(Reg);
1008         if (MO.isKill() && AllocatableRegs[Reg])
1009           Kills.push_back(Reg);
1010       }
1011     }
1012
1013     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1014       unsigned Kill = Kills[i];
1015       if (!Defs[Kill] && !Uses[Kill] &&
1016           TRI->getPhysicalRegisterRegClass(Kill) == RC)
1017         return Kill;
1018     }
1019     for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1020       unsigned Reg = LocalUses[i];
1021       Uses.set(Reg);
1022       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1023         Uses.set(*AS);
1024     }
1025
1026     MII = PrevMI;
1027   }
1028
1029   return 0;
1030 }
1031
1032 static
1033 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1034                          const TargetRegisterInfo &TRI) {
1035   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1036     MachineOperand &MO = MI->getOperand(i);
1037     if (MO.isReg() && MO.getReg() == VirtReg)
1038       substitutePhysReg(MO, PhysReg, TRI);
1039   }
1040 }
1041
1042 namespace {
1043
1044 struct RefSorter {
1045   bool operator()(const std::pair<MachineInstr*, int> &A,
1046                   const std::pair<MachineInstr*, int> &B) {
1047     return A.second < B.second;
1048   }
1049 };
1050
1051 // ***************************** //
1052 // Local Spiller Implementation  //
1053 // ***************************** //
1054
1055 class LocalRewriter : public VirtRegRewriter {
1056   MachineRegisterInfo *MRI;
1057   const TargetRegisterInfo *TRI;
1058   const TargetInstrInfo *TII;
1059   VirtRegMap *VRM;
1060   BitVector AllocatableRegs;
1061   DenseMap<MachineInstr*, unsigned> DistanceMap;
1062
1063   MachineBasicBlock *MBB;       // Basic block currently being processed.
1064
1065 public:
1066
1067   bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1068                             LiveIntervals* LIs);
1069
1070 private:
1071
1072   bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1073                          MachineBasicBlock::iterator &MII,
1074                          std::vector<MachineInstr*> &MaybeDeadStores,
1075                          AvailableSpills &Spills,
1076                          BitVector &RegKills,
1077                          std::vector<MachineOperand*> &KillOps);
1078
1079   bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1080                         std::vector<MachineInstr*> &MaybeDeadStores,
1081                         AvailableSpills &Spills,
1082                         BitVector &RegKills,
1083                         std::vector<MachineOperand*> &KillOps);
1084
1085   bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1086                            unsigned VirtReg, unsigned SrcReg, int SS,
1087                            AvailableSpills &Spills,
1088                            BitVector &RegKills,
1089                            std::vector<MachineOperand*> &KillOps,
1090                            const TargetRegisterInfo *TRI);
1091
1092   void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1093                            int Idx, unsigned PhysReg, int StackSlot,
1094                            const TargetRegisterClass *RC,
1095                            bool isAvailable, MachineInstr *&LastStore,
1096                            AvailableSpills &Spills,
1097                            SmallSet<MachineInstr*, 4> &ReMatDefs,
1098                            BitVector &RegKills,
1099                            std::vector<MachineOperand*> &KillOps);
1100
1101   void TransferDeadness(unsigned Reg, BitVector &RegKills,
1102                         std::vector<MachineOperand*> &KillOps);
1103
1104   bool InsertEmergencySpills(MachineInstr *MI);
1105
1106   bool InsertRestores(MachineInstr *MI,
1107                       AvailableSpills &Spills,
1108                       BitVector &RegKills,
1109                       std::vector<MachineOperand*> &KillOps);
1110
1111   bool InsertSpills(MachineInstr *MI);
1112
1113   void RewriteMBB(LiveIntervals *LIs,
1114                   AvailableSpills &Spills, BitVector &RegKills,
1115                   std::vector<MachineOperand*> &KillOps);
1116 };
1117 }
1118
1119 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1120                                          LiveIntervals* LIs) {
1121   MRI = &MF.getRegInfo();
1122   TRI = MF.getTarget().getRegisterInfo();
1123   TII = MF.getTarget().getInstrInfo();
1124   VRM = &vrm;
1125   AllocatableRegs = TRI->getAllocatableSet(MF);
1126   DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1127         << MF.getFunction()->getName() << "':\n");
1128   DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1129         " reloads!) ****\n");
1130   DEBUG(MF.dump());
1131
1132   // Spills - Keep track of which spilled values are available in physregs
1133   // so that we can choose to reuse the physregs instead of emitting
1134   // reloads. This is usually refreshed per basic block.
1135   AvailableSpills Spills(TRI, TII);
1136
1137   // Keep track of kill information.
1138   BitVector RegKills(TRI->getNumRegs());
1139   std::vector<MachineOperand*> KillOps;
1140   KillOps.resize(TRI->getNumRegs(), NULL);
1141
1142   // SingleEntrySuccs - Successor blocks which have a single predecessor.
1143   SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1144   SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1145
1146   // Traverse the basic blocks depth first.
1147   MachineBasicBlock *Entry = MF.begin();
1148   SmallPtrSet<MachineBasicBlock*,16> Visited;
1149   for (df_ext_iterator<MachineBasicBlock*,
1150          SmallPtrSet<MachineBasicBlock*,16> >
1151          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1152        DFI != E; ++DFI) {
1153     MBB = *DFI;
1154     if (!EarlyVisited.count(MBB))
1155       RewriteMBB(LIs, Spills, RegKills, KillOps);
1156
1157     // If this MBB is the only predecessor of a successor. Keep the
1158     // availability information and visit it next.
1159     do {
1160       // Keep visiting single predecessor successor as long as possible.
1161       SinglePredSuccs.clear();
1162       findSinglePredSuccessor(MBB, SinglePredSuccs);
1163       if (SinglePredSuccs.empty())
1164         MBB = 0;
1165       else {
1166         // FIXME: More than one successors, each of which has MBB has
1167         // the only predecessor.
1168         MBB = SinglePredSuccs[0];
1169         if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1170           Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1171           RewriteMBB(LIs, Spills, RegKills, KillOps);
1172         }
1173       }
1174     } while (MBB);
1175
1176     // Clear the availability info.
1177     Spills.clear();
1178   }
1179
1180   DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1181   DEBUG(MF.dump());
1182
1183   // Mark unused spill slots.
1184   MachineFrameInfo *MFI = MF.getFrameInfo();
1185   int SS = VRM->getLowSpillSlot();
1186   if (SS != VirtRegMap::NO_STACK_SLOT)
1187     for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS)
1188       if (!VRM->isSpillSlotUsed(SS)) {
1189         MFI->RemoveStackObject(SS);
1190         ++NumDSS;
1191       }
1192
1193   return true;
1194 }
1195
1196 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1197 /// a scratch register is available.
1198 ///     xorq  %r12<kill>, %r13
1199 ///     addq  %rax, -184(%rbp)
1200 ///     addq  %r13, -184(%rbp)
1201 /// ==>
1202 ///     xorq  %r12<kill>, %r13
1203 ///     movq  -184(%rbp), %r12
1204 ///     addq  %rax, %r12
1205 ///     addq  %r13, %r12
1206 ///     movq  %r12, -184(%rbp)
1207 bool LocalRewriter::
1208 OptimizeByUnfold2(unsigned VirtReg, int SS,
1209                   MachineBasicBlock::iterator &MII,
1210                   std::vector<MachineInstr*> &MaybeDeadStores,
1211                   AvailableSpills &Spills,
1212                   BitVector &RegKills,
1213                   std::vector<MachineOperand*> &KillOps) {
1214
1215   MachineBasicBlock::iterator NextMII = llvm::next(MII);
1216   if (NextMII == MBB->end())
1217     return false;
1218
1219   if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1220     return false;
1221
1222   // Now let's see if the last couple of instructions happens to have freed up
1223   // a register.
1224   const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1225   unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1226   if (!PhysReg)
1227     return false;
1228
1229   MachineFunction &MF = *MBB->getParent();
1230   TRI = MF.getTarget().getRegisterInfo();
1231   MachineInstr &MI = *MII;
1232   if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1233     return false;
1234
1235   // If the next instruction also folds the same SS modref and can be unfoled,
1236   // then it's worthwhile to issue a load from SS into the free register and
1237   // then unfold these instructions.
1238   if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1239     return false;
1240
1241   // Back-schedule reloads and remats.
1242   ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1243
1244   // Load from SS to the spare physical register.
1245   TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC);
1246   // This invalidates Phys.
1247   Spills.ClobberPhysReg(PhysReg);
1248   // Remember it's available.
1249   Spills.addAvailable(SS, PhysReg);
1250   MaybeDeadStores[SS] = NULL;
1251
1252   // Unfold current MI.
1253   SmallVector<MachineInstr*, 4> NewMIs;
1254   if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1255     llvm_unreachable("Unable unfold the load / store folding instruction!");
1256   assert(NewMIs.size() == 1);
1257   AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1258   VRM->transferRestorePts(&MI, NewMIs[0]);
1259   MII = MBB->insert(MII, NewMIs[0]);
1260   InvalidateKills(MI, TRI, RegKills, KillOps);
1261   VRM->RemoveMachineInstrFromMaps(&MI);
1262   MBB->erase(&MI);
1263   ++NumModRefUnfold;
1264
1265   // Unfold next instructions that fold the same SS.
1266   do {
1267     MachineInstr &NextMI = *NextMII;
1268     NextMII = llvm::next(NextMII);
1269     NewMIs.clear();
1270     if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1271       llvm_unreachable("Unable unfold the load / store folding instruction!");
1272     assert(NewMIs.size() == 1);
1273     AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1274     VRM->transferRestorePts(&NextMI, NewMIs[0]);
1275     MBB->insert(NextMII, NewMIs[0]);
1276     InvalidateKills(NextMI, TRI, RegKills, KillOps);
1277     VRM->RemoveMachineInstrFromMaps(&NextMI);
1278     MBB->erase(&NextMI);
1279     ++NumModRefUnfold;
1280     if (NextMII == MBB->end())
1281       break;
1282   } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1283
1284   // Store the value back into SS.
1285   TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC);
1286   MachineInstr *StoreMI = prior(NextMII);
1287   VRM->addSpillSlotUse(SS, StoreMI);
1288   VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1289
1290   return true;
1291 }
1292
1293 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1294 /// instruction. e.g.
1295 ///     xorl  %edi, %eax
1296 ///     movl  %eax, -32(%ebp)
1297 ///     movl  -36(%ebp), %eax
1298 ///     orl   %eax, -32(%ebp)
1299 /// ==>
1300 ///     xorl  %edi, %eax
1301 ///     orl   -36(%ebp), %eax
1302 ///     mov   %eax, -32(%ebp)
1303 /// This enables unfolding optimization for a subsequent instruction which will
1304 /// also eliminate the newly introduced store instruction.
1305 bool LocalRewriter::
1306 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1307                  std::vector<MachineInstr*> &MaybeDeadStores,
1308                  AvailableSpills &Spills,
1309                  BitVector &RegKills,
1310                  std::vector<MachineOperand*> &KillOps) {
1311   MachineFunction &MF = *MBB->getParent();
1312   MachineInstr &MI = *MII;
1313   unsigned UnfoldedOpc = 0;
1314   unsigned UnfoldPR = 0;
1315   unsigned UnfoldVR = 0;
1316   int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1317   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1318   for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1319     // Only transform a MI that folds a single register.
1320     if (UnfoldedOpc)
1321       return false;
1322     UnfoldVR = I->second.first;
1323     VirtRegMap::ModRef MR = I->second.second;
1324     // MI2VirtMap be can updated which invalidate the iterator.
1325     // Increment the iterator first.
1326     ++I;
1327     if (VRM->isAssignedReg(UnfoldVR))
1328       continue;
1329     // If this reference is not a use, any previous store is now dead.
1330     // Otherwise, the store to this stack slot is not dead anymore.
1331     FoldedSS = VRM->getStackSlot(UnfoldVR);
1332     MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1333     if (DeadStore && (MR & VirtRegMap::isModRef)) {
1334       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1335       if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1336         continue;
1337       UnfoldPR = PhysReg;
1338       UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1339                                                     false, true);
1340     }
1341   }
1342
1343   if (!UnfoldedOpc) {
1344     if (!UnfoldVR)
1345       return false;
1346
1347     // Look for other unfolding opportunities.
1348     return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1349                              RegKills, KillOps);
1350   }
1351
1352   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1353     MachineOperand &MO = MI.getOperand(i);
1354     if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1355       continue;
1356     unsigned VirtReg = MO.getReg();
1357     if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1358       continue;
1359     if (VRM->isAssignedReg(VirtReg)) {
1360       unsigned PhysReg = VRM->getPhys(VirtReg);
1361       if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1362         return false;
1363     } else if (VRM->isReMaterialized(VirtReg))
1364       continue;
1365     int SS = VRM->getStackSlot(VirtReg);
1366     unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1367     if (PhysReg) {
1368       if (TRI->regsOverlap(PhysReg, UnfoldPR))
1369         return false;
1370       continue;
1371     }
1372     if (VRM->hasPhys(VirtReg)) {
1373       PhysReg = VRM->getPhys(VirtReg);
1374       if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1375         continue;
1376     }
1377
1378     // Ok, we'll need to reload the value into a register which makes
1379     // it impossible to perform the store unfolding optimization later.
1380     // Let's see if it is possible to fold the load if the store is
1381     // unfolded. This allows us to perform the store unfolding
1382     // optimization.
1383     SmallVector<MachineInstr*, 4> NewMIs;
1384     if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1385       assert(NewMIs.size() == 1);
1386       MachineInstr *NewMI = NewMIs.back();
1387       NewMIs.clear();
1388       int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1389       assert(Idx != -1);
1390       SmallVector<unsigned, 1> Ops;
1391       Ops.push_back(Idx);
1392       MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1393       if (FoldedMI) {
1394         VRM->addSpillSlotUse(SS, FoldedMI);
1395         if (!VRM->hasPhys(UnfoldVR))
1396           VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1397         VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1398         MII = MBB->insert(MII, FoldedMI);
1399         InvalidateKills(MI, TRI, RegKills, KillOps);
1400         VRM->RemoveMachineInstrFromMaps(&MI);
1401         MBB->erase(&MI);
1402         MF.DeleteMachineInstr(NewMI);
1403         return true;
1404       }
1405       MF.DeleteMachineInstr(NewMI);
1406     }
1407   }
1408
1409   return false;
1410 }
1411
1412 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1413 /// where SrcReg is r1 and it is tied to r0. Return true if after
1414 /// commuting this instruction it will be r0 = op r2, r1.
1415 static bool CommuteChangesDestination(MachineInstr *DefMI,
1416                                       const TargetInstrDesc &TID,
1417                                       unsigned SrcReg,
1418                                       const TargetInstrInfo *TII,
1419                                       unsigned &DstIdx) {
1420   if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1421     return false;
1422   if (!DefMI->getOperand(1).isReg() ||
1423       DefMI->getOperand(1).getReg() != SrcReg)
1424     return false;
1425   unsigned DefIdx;
1426   if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1427     return false;
1428   unsigned SrcIdx1, SrcIdx2;
1429   if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1430     return false;
1431   if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1432     DstIdx = 2;
1433     return true;
1434   }
1435   return false;
1436 }
1437
1438 /// CommuteToFoldReload -
1439 /// Look for
1440 /// r1 = load fi#1
1441 /// r1 = op r1, r2<kill>
1442 /// store r1, fi#1
1443 ///
1444 /// If op is commutable and r2 is killed, then we can xform these to
1445 /// r2 = op r2, fi#1
1446 /// store r2, fi#1
1447 bool LocalRewriter::
1448 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1449                     unsigned VirtReg, unsigned SrcReg, int SS,
1450                     AvailableSpills &Spills,
1451                     BitVector &RegKills,
1452                     std::vector<MachineOperand*> &KillOps,
1453                     const TargetRegisterInfo *TRI) {
1454   if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1455     return false;
1456
1457   MachineFunction &MF = *MBB->getParent();
1458   MachineInstr &MI = *MII;
1459   MachineBasicBlock::iterator DefMII = prior(MII);
1460   MachineInstr *DefMI = DefMII;
1461   const TargetInstrDesc &TID = DefMI->getDesc();
1462   unsigned NewDstIdx;
1463   if (DefMII != MBB->begin() &&
1464       TID.isCommutable() &&
1465       CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1466     MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1467     unsigned NewReg = NewDstMO.getReg();
1468     if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1469       return false;
1470     MachineInstr *ReloadMI = prior(DefMII);
1471     int FrameIdx;
1472     unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1473     if (DestReg != SrcReg || FrameIdx != SS)
1474       return false;
1475     int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1476     if (UseIdx == -1)
1477       return false;
1478     unsigned DefIdx;
1479     if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1480       return false;
1481     assert(DefMI->getOperand(DefIdx).isReg() &&
1482            DefMI->getOperand(DefIdx).getReg() == SrcReg);
1483
1484     // Now commute def instruction.
1485     MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1486     if (!CommutedMI)
1487       return false;
1488     SmallVector<unsigned, 1> Ops;
1489     Ops.push_back(NewDstIdx);
1490     MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1491     // Not needed since foldMemoryOperand returns new MI.
1492     MF.DeleteMachineInstr(CommutedMI);
1493     if (!FoldedMI)
1494       return false;
1495
1496     VRM->addSpillSlotUse(SS, FoldedMI);
1497     VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1498     // Insert new def MI and spill MI.
1499     const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1500     TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC);
1501     MII = prior(MII);
1502     MachineInstr *StoreMI = MII;
1503     VRM->addSpillSlotUse(SS, StoreMI);
1504     VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1505     MII = MBB->insert(MII, FoldedMI);  // Update MII to backtrack.
1506
1507     // Delete all 3 old instructions.
1508     InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1509     VRM->RemoveMachineInstrFromMaps(ReloadMI);
1510     MBB->erase(ReloadMI);
1511     InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1512     VRM->RemoveMachineInstrFromMaps(DefMI);
1513     MBB->erase(DefMI);
1514     InvalidateKills(MI, TRI, RegKills, KillOps);
1515     VRM->RemoveMachineInstrFromMaps(&MI);
1516     MBB->erase(&MI);
1517
1518     // If NewReg was previously holding value of some SS, it's now clobbered.
1519     // This has to be done now because it's a physical register. When this
1520     // instruction is re-visited, it's ignored.
1521     Spills.ClobberPhysReg(NewReg);
1522
1523     ++NumCommutes;
1524     return true;
1525   }
1526
1527   return false;
1528 }
1529
1530 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1531 /// the last store to the same slot is now dead. If so, remove the last store.
1532 void LocalRewriter::
1533 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1534                     int Idx, unsigned PhysReg, int StackSlot,
1535                     const TargetRegisterClass *RC,
1536                     bool isAvailable, MachineInstr *&LastStore,
1537                     AvailableSpills &Spills,
1538                     SmallSet<MachineInstr*, 4> &ReMatDefs,
1539                     BitVector &RegKills,
1540                     std::vector<MachineOperand*> &KillOps) {
1541
1542   MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1543   TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC);
1544   MachineInstr *StoreMI = prior(oldNextMII);
1545   VRM->addSpillSlotUse(StackSlot, StoreMI);
1546   DEBUG(dbgs() << "Store:\t" << *StoreMI);
1547
1548   // If there is a dead store to this stack slot, nuke it now.
1549   if (LastStore) {
1550     DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1551     ++NumDSE;
1552     SmallVector<unsigned, 2> KillRegs;
1553     InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1554     MachineBasicBlock::iterator PrevMII = LastStore;
1555     bool CheckDef = PrevMII != MBB->begin();
1556     if (CheckDef)
1557       --PrevMII;
1558     VRM->RemoveMachineInstrFromMaps(LastStore);
1559     MBB->erase(LastStore);
1560     if (CheckDef) {
1561       // Look at defs of killed registers on the store. Mark the defs
1562       // as dead since the store has been deleted and they aren't
1563       // being reused.
1564       for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1565         bool HasOtherDef = false;
1566         if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1567           MachineInstr *DeadDef = PrevMII;
1568           if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1569             // FIXME: This assumes a remat def does not have side effects.
1570             VRM->RemoveMachineInstrFromMaps(DeadDef);
1571             MBB->erase(DeadDef);
1572             ++NumDRM;
1573           }
1574         }
1575       }
1576     }
1577   }
1578
1579   // Allow for multi-instruction spill sequences, as on PPC Altivec.  Presume
1580   // the last of multiple instructions is the actual store.
1581   LastStore = prior(oldNextMII);
1582
1583   // If the stack slot value was previously available in some other
1584   // register, change it now.  Otherwise, make the register available,
1585   // in PhysReg.
1586   Spills.ModifyStackSlotOrReMat(StackSlot);
1587   Spills.ClobberPhysReg(PhysReg);
1588   Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1589   ++NumStores;
1590 }
1591
1592 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1593 /// effect and all of its defs are dead.
1594 static bool isSafeToDelete(MachineInstr &MI) {
1595   const TargetInstrDesc &TID = MI.getDesc();
1596   if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1597       TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1598       TID.hasUnmodeledSideEffects())
1599     return false;
1600   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1601     MachineOperand &MO = MI.getOperand(i);
1602     if (!MO.isReg() || !MO.getReg())
1603       continue;
1604     if (MO.isDef() && !MO.isDead())
1605       return false;
1606     if (MO.isUse() && MO.isKill())
1607       // FIXME: We can't remove kill markers or else the scavenger will assert.
1608       // An alternative is to add a ADD pseudo instruction to replace kill
1609       // markers.
1610       return false;
1611   }
1612   return true;
1613 }
1614
1615 /// TransferDeadness - A identity copy definition is dead and it's being
1616 /// removed. Find the last def or use and mark it as dead / kill.
1617 void LocalRewriter::
1618 TransferDeadness(unsigned Reg, BitVector &RegKills,
1619                  std::vector<MachineOperand*> &KillOps) {
1620   SmallPtrSet<MachineInstr*, 4> Seens;
1621   SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1622   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1623          RE = MRI->reg_end(); RI != RE; ++RI) {
1624     MachineInstr *UDMI = &*RI;
1625     if (UDMI->getParent() != MBB)
1626       continue;
1627     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1628     if (DI == DistanceMap.end())
1629       continue;
1630     if (Seens.insert(UDMI))
1631       Refs.push_back(std::make_pair(UDMI, DI->second));
1632   }
1633
1634   if (Refs.empty())
1635     return;
1636   std::sort(Refs.begin(), Refs.end(), RefSorter());
1637
1638   while (!Refs.empty()) {
1639     MachineInstr *LastUDMI = Refs.back().first;
1640     Refs.pop_back();
1641
1642     MachineOperand *LastUD = NULL;
1643     for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1644       MachineOperand &MO = LastUDMI->getOperand(i);
1645       if (!MO.isReg() || MO.getReg() != Reg)
1646         continue;
1647       if (!LastUD || (LastUD->isUse() && MO.isDef()))
1648         LastUD = &MO;
1649       if (LastUDMI->isRegTiedToDefOperand(i))
1650         break;
1651     }
1652     if (LastUD->isDef()) {
1653       // If the instruction has no side effect, delete it and propagate
1654       // backward further. Otherwise, mark is dead and we are done.
1655       if (!isSafeToDelete(*LastUDMI)) {
1656         LastUD->setIsDead();
1657         break;
1658       }
1659       VRM->RemoveMachineInstrFromMaps(LastUDMI);
1660       MBB->erase(LastUDMI);
1661     } else {
1662       LastUD->setIsKill();
1663       RegKills.set(Reg);
1664       KillOps[Reg] = LastUD;
1665       break;
1666     }
1667   }
1668 }
1669
1670 /// InsertEmergencySpills - Insert emergency spills before MI if requested by
1671 /// VRM. Return true if spills were inserted.
1672 bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1673   if (!VRM->hasEmergencySpills(MI))
1674     return false;
1675   MachineBasicBlock::iterator MII = MI;
1676   SmallSet<int, 4> UsedSS;
1677   std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1678   for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1679     unsigned PhysReg = EmSpills[i];
1680     const TargetRegisterClass *RC = TRI->getPhysicalRegisterRegClass(PhysReg);
1681     assert(RC && "Unable to determine register class!");
1682     int SS = VRM->getEmergencySpillSlot(RC);
1683     if (UsedSS.count(SS))
1684       llvm_unreachable("Need to spill more than one physical registers!");
1685     UsedSS.insert(SS);
1686     TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC);
1687     MachineInstr *StoreMI = prior(MII);
1688     VRM->addSpillSlotUse(SS, StoreMI);
1689
1690     // Back-schedule reloads and remats.
1691     MachineBasicBlock::iterator InsertLoc =
1692       ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1693                        TII, *MBB->getParent());
1694
1695     TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC);
1696
1697     MachineInstr *LoadMI = prior(InsertLoc);
1698     VRM->addSpillSlotUse(SS, LoadMI);
1699     ++NumPSpills;
1700     DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1701   }
1702   return true;
1703 }
1704
1705 /// InsertRestores - Restore registers before MI is requested by VRM. Return
1706 /// true is any instructions were inserted.
1707 bool LocalRewriter::InsertRestores(MachineInstr *MI,
1708                                    AvailableSpills &Spills,
1709                                    BitVector &RegKills,
1710                                    std::vector<MachineOperand*> &KillOps) {
1711   if (!VRM->isRestorePt(MI))
1712     return false;
1713   MachineBasicBlock::iterator MII = MI;
1714   std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1715   for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1716     unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1717     if (!VRM->getPreSplitReg(VirtReg))
1718       continue; // Split interval spilled again.
1719     unsigned Phys = VRM->getPhys(VirtReg);
1720     MRI->setPhysRegUsed(Phys);
1721
1722     // Check if the value being restored if available. If so, it must be
1723     // from a predecessor BB that fallthrough into this BB. We do not
1724     // expect:
1725     // BB1:
1726     // r1 = load fi#1
1727     // ...
1728     //    = r1<kill>
1729     // ... # r1 not clobbered
1730     // ...
1731     //    = load fi#1
1732     bool DoReMat = VRM->isReMaterialized(VirtReg);
1733     int SSorRMId = DoReMat
1734       ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1735     const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1736     unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1737     if (InReg == Phys) {
1738       // If the value is already available in the expected register, save
1739       // a reload / remat.
1740       if (SSorRMId)
1741         DEBUG(dbgs() << "Reusing RM#"
1742                      << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1743       else
1744         DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1745       DEBUG(dbgs() << " from physreg "
1746                    << TRI->getName(InReg) << " for vreg"
1747                    << VirtReg <<" instead of reloading into physreg "
1748                    << TRI->getName(Phys) << '\n');
1749       ++NumOmitted;
1750       continue;
1751     } else if (InReg && InReg != Phys) {
1752       if (SSorRMId)
1753         DEBUG(dbgs() << "Reusing RM#"
1754                      << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1755       else
1756         DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1757       DEBUG(dbgs() << " from physreg "
1758                    << TRI->getName(InReg) << " for vreg"
1759                    << VirtReg <<" by copying it into physreg "
1760                    << TRI->getName(Phys) << '\n');
1761
1762       // If the reloaded / remat value is available in another register,
1763       // copy it to the desired register.
1764
1765       // Back-schedule reloads and remats.
1766       MachineBasicBlock::iterator InsertLoc =
1767         ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1768                          *MBB->getParent());
1769
1770       TII->copyRegToReg(*MBB, InsertLoc, Phys, InReg, RC, RC);
1771
1772       // This invalidates Phys.
1773       Spills.ClobberPhysReg(Phys);
1774       // Remember it's available.
1775       Spills.addAvailable(SSorRMId, Phys);
1776
1777       // Mark is killed.
1778       MachineInstr *CopyMI = prior(InsertLoc);
1779       CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1780       MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1781       KillOpnd->setIsKill();
1782       UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1783
1784       DEBUG(dbgs() << '\t' << *CopyMI);
1785       ++NumCopified;
1786       continue;
1787     }
1788
1789     // Back-schedule reloads and remats.
1790     MachineBasicBlock::iterator InsertLoc =
1791       ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1792                        *MBB->getParent());
1793
1794     if (VRM->isReMaterialized(VirtReg)) {
1795       ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1796     } else {
1797       const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1798       TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC);
1799       MachineInstr *LoadMI = prior(InsertLoc);
1800       VRM->addSpillSlotUse(SSorRMId, LoadMI);
1801       ++NumLoads;
1802       DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1803     }
1804
1805     // This invalidates Phys.
1806     Spills.ClobberPhysReg(Phys);
1807     // Remember it's available.
1808     Spills.addAvailable(SSorRMId, Phys);
1809
1810     UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1811     DEBUG(dbgs() << '\t' << *prior(MII));
1812   }
1813   return true;
1814 }
1815
1816 /// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1817 /// true if spills were inserted.
1818 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1819   if (!VRM->isSpillPt(MI))
1820     return false;
1821   MachineBasicBlock::iterator MII = MI;
1822   std::vector<std::pair<unsigned,bool> > &SpillRegs =
1823     VRM->getSpillPtSpills(MI);
1824   for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1825     unsigned VirtReg = SpillRegs[i].first;
1826     bool isKill = SpillRegs[i].second;
1827     if (!VRM->getPreSplitReg(VirtReg))
1828       continue; // Split interval spilled again.
1829     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1830     unsigned Phys = VRM->getPhys(VirtReg);
1831     int StackSlot = VRM->getStackSlot(VirtReg);
1832     MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1833     TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1834                              RC);
1835     MachineInstr *StoreMI = prior(oldNextMII);
1836     VRM->addSpillSlotUse(StackSlot, StoreMI);
1837     DEBUG(dbgs() << "Store:\t" << *StoreMI);
1838     VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1839   }
1840   return true;
1841 }
1842
1843
1844 /// rewriteMBB - Keep track of which spills are available even after the
1845 /// register allocator is done with them.  If possible, avid reloading vregs.
1846 void
1847 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1848                           AvailableSpills &Spills, BitVector &RegKills,
1849                           std::vector<MachineOperand*> &KillOps) {
1850
1851   DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1852                << MBB->getName() << "':\n");
1853
1854   MachineFunction &MF = *MBB->getParent();
1855
1856   // MaybeDeadStores - When we need to write a value back into a stack slot,
1857   // keep track of the inserted store.  If the stack slot value is never read
1858   // (because the value was used from some available register, for example), and
1859   // subsequently stored to, the original store is dead.  This map keeps track
1860   // of inserted stores that are not used.  If we see a subsequent store to the
1861   // same stack slot, the original store is deleted.
1862   std::vector<MachineInstr*> MaybeDeadStores;
1863   MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1864
1865   // ReMatDefs - These are rematerializable def MIs which are not deleted.
1866   SmallSet<MachineInstr*, 4> ReMatDefs;
1867
1868   // Clear kill info.
1869   SmallSet<unsigned, 2> KilledMIRegs;
1870   RegKills.reset();
1871   KillOps.clear();
1872   KillOps.resize(TRI->getNumRegs(), NULL);
1873
1874   DistanceMap.clear();
1875   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1876        MII != E; ) {
1877     MachineBasicBlock::iterator NextMII = llvm::next(MII);
1878
1879     if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1880       NextMII = llvm::next(MII);
1881
1882     if (InsertEmergencySpills(MII))
1883       NextMII = llvm::next(MII);
1884
1885     InsertRestores(MII, Spills, RegKills, KillOps);
1886
1887     if (InsertSpills(MII))
1888       NextMII = llvm::next(MII);
1889
1890     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1891     bool Erased = false;
1892     bool BackTracked = false;
1893     MachineInstr &MI = *MII;
1894
1895     /// ReusedOperands - Keep track of operand reuse in case we need to undo
1896     /// reuse.
1897     ReuseInfo ReusedOperands(MI, TRI);
1898     SmallVector<unsigned, 4> VirtUseOps;
1899     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1900       MachineOperand &MO = MI.getOperand(i);
1901       if (!MO.isReg() || MO.getReg() == 0)
1902         continue;   // Ignore non-register operands.
1903
1904       unsigned VirtReg = MO.getReg();
1905       if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1906         // Ignore physregs for spilling, but remember that it is used by this
1907         // function.
1908         MRI->setPhysRegUsed(VirtReg);
1909         continue;
1910       }
1911
1912       // We want to process implicit virtual register uses first.
1913       if (MO.isImplicit())
1914         // If the virtual register is implicitly defined, emit a implicit_def
1915         // before so scavenger knows it's "defined".
1916         // FIXME: This is a horrible hack done the by register allocator to
1917         // remat a definition with virtual register operand.
1918         VirtUseOps.insert(VirtUseOps.begin(), i);
1919       else
1920         VirtUseOps.push_back(i);
1921     }
1922
1923     // Process all of the spilled uses and all non spilled reg references.
1924     SmallVector<int, 2> PotentialDeadStoreSlots;
1925     KilledMIRegs.clear();
1926     for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1927       unsigned i = VirtUseOps[j];
1928       unsigned VirtReg = MI.getOperand(i).getReg();
1929       assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1930              "Not a virtual register?");
1931
1932       unsigned SubIdx = MI.getOperand(i).getSubReg();
1933       if (VRM->isAssignedReg(VirtReg)) {
1934         // This virtual register was assigned a physreg!
1935         unsigned Phys = VRM->getPhys(VirtReg);
1936         MRI->setPhysRegUsed(Phys);
1937         if (MI.getOperand(i).isDef())
1938           ReusedOperands.markClobbered(Phys);
1939         substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1940         if (VRM->isImplicitlyDefined(VirtReg))
1941           // FIXME: Is this needed?
1942           BuildMI(*MBB, &MI, MI.getDebugLoc(),
1943                   TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1944         continue;
1945       }
1946
1947       // This virtual register is now known to be a spilled value.
1948       if (!MI.getOperand(i).isUse())
1949         continue;  // Handle defs in the loop below (handle use&def here though)
1950
1951       bool AvoidReload = MI.getOperand(i).isUndef();
1952       // Check if it is defined by an implicit def. It should not be spilled.
1953       // Note, this is for correctness reason. e.g.
1954       // 8   %reg1024<def> = IMPLICIT_DEF
1955       // 12  %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1956       // The live range [12, 14) are not part of the r1024 live interval since
1957       // it's defined by an implicit def. It will not conflicts with live
1958       // interval of r1025. Now suppose both registers are spilled, you can
1959       // easily see a situation where both registers are reloaded before
1960       // the INSERT_SUBREG and both target registers that would overlap.
1961       bool DoReMat = VRM->isReMaterialized(VirtReg);
1962       int SSorRMId = DoReMat
1963         ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1964       int ReuseSlot = SSorRMId;
1965
1966       // Check to see if this stack slot is available.
1967       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1968
1969       // If this is a sub-register use, make sure the reuse register is in the
1970       // right register class. For example, for x86 not all of the 32-bit
1971       // registers have accessible sub-registers.
1972       // Similarly so for EXTRACT_SUBREG. Consider this:
1973       // EDI = op
1974       // MOV32_mr fi#1, EDI
1975       // ...
1976       //       = EXTRACT_SUBREG fi#1
1977       // fi#1 is available in EDI, but it cannot be reused because it's not in
1978       // the right register file.
1979       if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
1980         const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1981         if (!RC->contains(PhysReg))
1982           PhysReg = 0;
1983       }
1984
1985       if (PhysReg && !AvoidReload) {
1986         // This spilled operand might be part of a two-address operand.  If this
1987         // is the case, then changing it will necessarily require changing the
1988         // def part of the instruction as well.  However, in some cases, we
1989         // aren't allowed to modify the reused register.  If none of these cases
1990         // apply, reuse it.
1991         bool CanReuse = true;
1992         bool isTied = MI.isRegTiedToDefOperand(i);
1993         if (isTied) {
1994           // Okay, we have a two address operand.  We can reuse this physreg as
1995           // long as we are allowed to clobber the value and there isn't an
1996           // earlier def that has already clobbered the physreg.
1997           CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1998             Spills.canClobberPhysReg(PhysReg);
1999         }
2000
2001         if (CanReuse) {
2002           // If this stack slot value is already available, reuse it!
2003           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2004             DEBUG(dbgs() << "Reusing RM#"
2005                   << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2006           else
2007             DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2008           DEBUG(dbgs() << " from physreg "
2009                 << TRI->getName(PhysReg) << " for vreg"
2010                 << VirtReg <<" instead of reloading into physreg "
2011                 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2012           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2013           MI.getOperand(i).setReg(RReg);
2014           MI.getOperand(i).setSubReg(0);
2015
2016           // The only technical detail we have is that we don't know that
2017           // PhysReg won't be clobbered by a reloaded stack slot that occurs
2018           // later in the instruction.  In particular, consider 'op V1, V2'.
2019           // If V1 is available in physreg R0, we would choose to reuse it
2020           // here, instead of reloading it into the register the allocator
2021           // indicated (say R1).  However, V2 might have to be reloaded
2022           // later, and it might indicate that it needs to live in R0.  When
2023           // this occurs, we need to have information available that
2024           // indicates it is safe to use R1 for the reload instead of R0.
2025           //
2026           // To further complicate matters, we might conflict with an alias,
2027           // or R0 and R1 might not be compatible with each other.  In this
2028           // case, we actually insert a reload for V1 in R1, ensuring that
2029           // we can get at R0 or its alias.
2030           ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2031                                   VRM->getPhys(VirtReg), VirtReg);
2032           if (isTied)
2033             // Only mark it clobbered if this is a use&def operand.
2034             ReusedOperands.markClobbered(PhysReg);
2035           ++NumReused;
2036
2037           if (MI.getOperand(i).isKill() &&
2038               ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2039
2040             // The store of this spilled value is potentially dead, but we
2041             // won't know for certain until we've confirmed that the re-use
2042             // above is valid, which means waiting until the other operands
2043             // are processed. For now we just track the spill slot, we'll
2044             // remove it after the other operands are processed if valid.
2045
2046             PotentialDeadStoreSlots.push_back(ReuseSlot);
2047           }
2048
2049           // Mark is isKill if it's there no other uses of the same virtual
2050           // register and it's not a two-address operand. IsKill will be
2051           // unset if reg is reused.
2052           if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2053             MI.getOperand(i).setIsKill();
2054             KilledMIRegs.insert(VirtReg);
2055           }
2056
2057           continue;
2058         }  // CanReuse
2059
2060         // Otherwise we have a situation where we have a two-address instruction
2061         // whose mod/ref operand needs to be reloaded.  This reload is already
2062         // available in some register "PhysReg", but if we used PhysReg as the
2063         // operand to our 2-addr instruction, the instruction would modify
2064         // PhysReg.  This isn't cool if something later uses PhysReg and expects
2065         // to get its initial value.
2066         //
2067         // To avoid this problem, and to avoid doing a load right after a store,
2068         // we emit a copy from PhysReg into the designated register for this
2069         // operand.
2070         unsigned DesignatedReg = VRM->getPhys(VirtReg);
2071         assert(DesignatedReg && "Must map virtreg to physreg!");
2072
2073         // Note that, if we reused a register for a previous operand, the
2074         // register we want to reload into might not actually be
2075         // available.  If this occurs, use the register indicated by the
2076         // reuser.
2077         if (ReusedOperands.hasReuses())
2078           DesignatedReg = ReusedOperands.
2079             GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2080                             MaybeDeadStores, RegKills, KillOps, *VRM);
2081
2082         // If the mapped designated register is actually the physreg we have
2083         // incoming, we don't need to inserted a dead copy.
2084         if (DesignatedReg == PhysReg) {
2085           // If this stack slot value is already available, reuse it!
2086           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2087             DEBUG(dbgs() << "Reusing RM#"
2088                   << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2089           else
2090             DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2091           DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2092                 << " for vreg" << VirtReg
2093                 << " instead of reloading into same physreg.\n");
2094           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2095           MI.getOperand(i).setReg(RReg);
2096           MI.getOperand(i).setSubReg(0);
2097           ReusedOperands.markClobbered(RReg);
2098           ++NumReused;
2099           continue;
2100         }
2101
2102         const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2103         MRI->setPhysRegUsed(DesignatedReg);
2104         ReusedOperands.markClobbered(DesignatedReg);
2105
2106         // Back-schedule reloads and remats.
2107         MachineBasicBlock::iterator InsertLoc =
2108           ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2109                            SSorRMId, TII, MF);
2110
2111         TII->copyRegToReg(*MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2112
2113         MachineInstr *CopyMI = prior(InsertLoc);
2114         CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2115         UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2116
2117         // This invalidates DesignatedReg.
2118         Spills.ClobberPhysReg(DesignatedReg);
2119
2120         Spills.addAvailable(ReuseSlot, DesignatedReg);
2121         unsigned RReg =
2122           SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2123         MI.getOperand(i).setReg(RReg);
2124         MI.getOperand(i).setSubReg(0);
2125         DEBUG(dbgs() << '\t' << *prior(MII));
2126         ++NumReused;
2127         continue;
2128       } // if (PhysReg)
2129
2130         // Otherwise, reload it and remember that we have it.
2131       PhysReg = VRM->getPhys(VirtReg);
2132       assert(PhysReg && "Must map virtreg to physreg!");
2133
2134       // Note that, if we reused a register for a previous operand, the
2135       // register we want to reload into might not actually be
2136       // available.  If this occurs, use the register indicated by the
2137       // reuser.
2138       if (ReusedOperands.hasReuses())
2139         PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2140                     Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2141
2142       MRI->setPhysRegUsed(PhysReg);
2143       ReusedOperands.markClobbered(PhysReg);
2144       if (AvoidReload)
2145         ++NumAvoided;
2146       else {
2147         // Back-schedule reloads and remats.
2148         MachineBasicBlock::iterator InsertLoc =
2149           ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2150                            SSorRMId, TII, MF);
2151
2152         if (DoReMat) {
2153           ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2154         } else {
2155           const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2156           TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC);
2157           MachineInstr *LoadMI = prior(InsertLoc);
2158           VRM->addSpillSlotUse(SSorRMId, LoadMI);
2159           ++NumLoads;
2160           DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2161         }
2162         // This invalidates PhysReg.
2163         Spills.ClobberPhysReg(PhysReg);
2164
2165         // Any stores to this stack slot are not dead anymore.
2166         if (!DoReMat)
2167           MaybeDeadStores[SSorRMId] = NULL;
2168         Spills.addAvailable(SSorRMId, PhysReg);
2169         // Assumes this is the last use. IsKill will be unset if reg is reused
2170         // unless it's a two-address operand.
2171         if (!MI.isRegTiedToDefOperand(i) &&
2172             KilledMIRegs.count(VirtReg) == 0) {
2173           MI.getOperand(i).setIsKill();
2174           KilledMIRegs.insert(VirtReg);
2175         }
2176
2177         UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2178         DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2179       }
2180       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2181       MI.getOperand(i).setReg(RReg);
2182       MI.getOperand(i).setSubReg(0);
2183     }
2184
2185     // Ok - now we can remove stores that have been confirmed dead.
2186     for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2187       // This was the last use and the spilled value is still available
2188       // for reuse. That means the spill was unnecessary!
2189       int PDSSlot = PotentialDeadStoreSlots[j];
2190       MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2191       if (DeadStore) {
2192         DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2193         InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2194         VRM->RemoveMachineInstrFromMaps(DeadStore);
2195         MBB->erase(DeadStore);
2196         MaybeDeadStores[PDSSlot] = NULL;
2197         ++NumDSE;
2198       }
2199     }
2200
2201
2202     DEBUG(dbgs() << '\t' << MI);
2203
2204
2205     // If we have folded references to memory operands, make sure we clear all
2206     // physical registers that may contain the value of the spilled virtual
2207     // register
2208     SmallSet<int, 2> FoldedSS;
2209     for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
2210       unsigned VirtReg = I->second.first;
2211       VirtRegMap::ModRef MR = I->second.second;
2212       DEBUG(dbgs() << "Folded vreg: " << VirtReg << "  MR: " << MR);
2213
2214       // MI2VirtMap be can updated which invalidate the iterator.
2215       // Increment the iterator first.
2216       ++I;
2217       int SS = VRM->getStackSlot(VirtReg);
2218       if (SS == VirtRegMap::NO_STACK_SLOT)
2219         continue;
2220       FoldedSS.insert(SS);
2221       DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2222
2223       // If this folded instruction is just a use, check to see if it's a
2224       // straight load from the virt reg slot.
2225       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2226         int FrameIdx;
2227         unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2228         if (DestReg && FrameIdx == SS) {
2229           // If this spill slot is available, turn it into a copy (or nothing)
2230           // instead of leaving it as a load!
2231           if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2232             DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2233             if (DestReg != InReg) {
2234               const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2235               TII->copyRegToReg(*MBB, &MI, DestReg, InReg, RC, RC);
2236               MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2237               unsigned SubIdx = DefMO->getSubReg();
2238               // Revisit the copy so we make sure to notice the effects of the
2239               // operation on the destreg (either needing to RA it if it's
2240               // virtual or needing to clobber any values if it's physical).
2241               NextMII = &MI;
2242               --NextMII;  // backtrack to the copy.
2243               NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2244               // Propagate the sub-register index over.
2245               if (SubIdx) {
2246                 DefMO = NextMII->findRegisterDefOperand(DestReg);
2247                 DefMO->setSubReg(SubIdx);
2248               }
2249
2250               // Mark is killed.
2251               MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2252               KillOpnd->setIsKill();
2253
2254               BackTracked = true;
2255             } else {
2256               DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2257               // Unset last kill since it's being reused.
2258               InvalidateKill(InReg, TRI, RegKills, KillOps);
2259               Spills.disallowClobberPhysReg(InReg);
2260             }
2261
2262             InvalidateKills(MI, TRI, RegKills, KillOps);
2263             VRM->RemoveMachineInstrFromMaps(&MI);
2264             MBB->erase(&MI);
2265             Erased = true;
2266             goto ProcessNextInst;
2267           }
2268         } else {
2269           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2270           SmallVector<MachineInstr*, 4> NewMIs;
2271           if (PhysReg &&
2272               TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2273             MBB->insert(MII, NewMIs[0]);
2274             InvalidateKills(MI, TRI, RegKills, KillOps);
2275             VRM->RemoveMachineInstrFromMaps(&MI);
2276             MBB->erase(&MI);
2277             Erased = true;
2278             --NextMII;  // backtrack to the unfolded instruction.
2279             BackTracked = true;
2280             goto ProcessNextInst;
2281           }
2282         }
2283       }
2284
2285       // If this reference is not a use, any previous store is now dead.
2286       // Otherwise, the store to this stack slot is not dead anymore.
2287       MachineInstr* DeadStore = MaybeDeadStores[SS];
2288       if (DeadStore) {
2289         bool isDead = !(MR & VirtRegMap::isRef);
2290         MachineInstr *NewStore = NULL;
2291         if (MR & VirtRegMap::isModRef) {
2292           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2293           SmallVector<MachineInstr*, 4> NewMIs;
2294           // We can reuse this physreg as long as we are allowed to clobber
2295           // the value and there isn't an earlier def that has already clobbered
2296           // the physreg.
2297           if (PhysReg &&
2298               !ReusedOperands.isClobbered(PhysReg) &&
2299               Spills.canClobberPhysReg(PhysReg) &&
2300               !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2301             MachineOperand *KillOpnd =
2302               DeadStore->findRegisterUseOperand(PhysReg, true);
2303             // Note, if the store is storing a sub-register, it's possible the
2304             // super-register is needed below.
2305             if (KillOpnd && !KillOpnd->getSubReg() &&
2306                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2307               MBB->insert(MII, NewMIs[0]);
2308               NewStore = NewMIs[1];
2309               MBB->insert(MII, NewStore);
2310               VRM->addSpillSlotUse(SS, NewStore);
2311               InvalidateKills(MI, TRI, RegKills, KillOps);
2312               VRM->RemoveMachineInstrFromMaps(&MI);
2313               MBB->erase(&MI);
2314               Erased = true;
2315               --NextMII;
2316               --NextMII;  // backtrack to the unfolded instruction.
2317               BackTracked = true;
2318               isDead = true;
2319               ++NumSUnfold;
2320             }
2321           }
2322         }
2323
2324         if (isDead) {  // Previous store is dead.
2325           // If we get here, the store is dead, nuke it now.
2326           DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2327           InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2328           VRM->RemoveMachineInstrFromMaps(DeadStore);
2329           MBB->erase(DeadStore);
2330           if (!NewStore)
2331             ++NumDSE;
2332         }
2333
2334         MaybeDeadStores[SS] = NULL;
2335         if (NewStore) {
2336           // Treat this store as a spill merged into a copy. That makes the
2337           // stack slot value available.
2338           VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2339           goto ProcessNextInst;
2340         }
2341       }
2342
2343       // If the spill slot value is available, and this is a new definition of
2344       // the value, the value is not available anymore.
2345       if (MR & VirtRegMap::isMod) {
2346         // Notice that the value in this stack slot has been modified.
2347         Spills.ModifyStackSlotOrReMat(SS);
2348
2349         // If this is *just* a mod of the value, check to see if this is just a
2350         // store to the spill slot (i.e. the spill got merged into the copy). If
2351         // so, realize that the vreg is available now, and add the store to the
2352         // MaybeDeadStore info.
2353         int StackSlot;
2354         if (!(MR & VirtRegMap::isRef)) {
2355           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2356             assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2357                    "Src hasn't been allocated yet?");
2358
2359             if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2360                                     Spills, RegKills, KillOps, TRI)) {
2361               NextMII = llvm::next(MII);
2362               BackTracked = true;
2363               goto ProcessNextInst;
2364             }
2365
2366             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
2367             // this as a potentially dead store in case there is a subsequent
2368             // store into the stack slot without a read from it.
2369             MaybeDeadStores[StackSlot] = &MI;
2370
2371             // If the stack slot value was previously available in some other
2372             // register, change it now.  Otherwise, make the register
2373             // available in PhysReg.
2374             Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2375           }
2376         }
2377       }
2378     }
2379
2380     // Process all of the spilled defs.
2381     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2382       MachineOperand &MO = MI.getOperand(i);
2383       if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2384         continue;
2385
2386       unsigned VirtReg = MO.getReg();
2387       if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2388         // Check to see if this is a noop copy.  If so, eliminate the
2389         // instruction before considering the dest reg to be changed.
2390         // Also check if it's copying from an "undef", if so, we can't
2391         // eliminate this or else the undef marker is lost and it will
2392         // confuses the scavenger. This is extremely rare.
2393         unsigned Src, Dst, SrcSR, DstSR;
2394         if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2395             !MI.findRegisterUseOperand(Src)->isUndef()) {
2396           ++NumDCE;
2397           DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2398           SmallVector<unsigned, 2> KillRegs;
2399           InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2400           if (MO.isDead() && !KillRegs.empty()) {
2401             // Source register or an implicit super/sub-register use is killed.
2402             assert(KillRegs[0] == Dst ||
2403                    TRI->isSubRegister(KillRegs[0], Dst) ||
2404                    TRI->isSuperRegister(KillRegs[0], Dst));
2405             // Last def is now dead.
2406             TransferDeadness(Src, RegKills, KillOps);
2407           }
2408           VRM->RemoveMachineInstrFromMaps(&MI);
2409           MBB->erase(&MI);
2410           Erased = true;
2411           Spills.disallowClobberPhysReg(VirtReg);
2412           goto ProcessNextInst;
2413         }
2414
2415         // If it's not a no-op copy, it clobbers the value in the destreg.
2416         Spills.ClobberPhysReg(VirtReg);
2417         ReusedOperands.markClobbered(VirtReg);
2418
2419         // Check to see if this instruction is a load from a stack slot into
2420         // a register.  If so, this provides the stack slot value in the reg.
2421         int FrameIdx;
2422         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2423           assert(DestReg == VirtReg && "Unknown load situation!");
2424
2425           // If it is a folded reference, then it's not safe to clobber.
2426           bool Folded = FoldedSS.count(FrameIdx);
2427           // Otherwise, if it wasn't available, remember that it is now!
2428           Spills.addAvailable(FrameIdx, DestReg, !Folded);
2429           goto ProcessNextInst;
2430         }
2431
2432         continue;
2433       }
2434
2435       unsigned SubIdx = MO.getSubReg();
2436       bool DoReMat = VRM->isReMaterialized(VirtReg);
2437       if (DoReMat)
2438         ReMatDefs.insert(&MI);
2439
2440       // The only vregs left are stack slot definitions.
2441       int StackSlot = VRM->getStackSlot(VirtReg);
2442       const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2443
2444       // If this def is part of a two-address operand, make sure to execute
2445       // the store from the correct physical register.
2446       unsigned PhysReg;
2447       unsigned TiedOp;
2448       if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2449         PhysReg = MI.getOperand(TiedOp).getReg();
2450         if (SubIdx) {
2451           unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2452           assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2453                  "Can't find corresponding super-register!");
2454           PhysReg = SuperReg;
2455         }
2456       } else {
2457         PhysReg = VRM->getPhys(VirtReg);
2458         if (ReusedOperands.isClobbered(PhysReg)) {
2459           // Another def has taken the assigned physreg. It must have been a
2460           // use&def which got it due to reuse. Undo the reuse!
2461           PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2462                       Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2463         }
2464       }
2465
2466       assert(PhysReg && "VR not assigned a physical register?");
2467       MRI->setPhysRegUsed(PhysReg);
2468       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2469       ReusedOperands.markClobbered(RReg);
2470       MI.getOperand(i).setReg(RReg);
2471       MI.getOperand(i).setSubReg(0);
2472
2473       if (!MO.isDead()) {
2474         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2475         SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2476           LastStore, Spills, ReMatDefs, RegKills, KillOps);
2477         NextMII = llvm::next(MII);
2478
2479         // Check to see if this is a noop copy.  If so, eliminate the
2480         // instruction before considering the dest reg to be changed.
2481         {
2482           unsigned Src, Dst, SrcSR, DstSR;
2483           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2484             ++NumDCE;
2485             DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2486             InvalidateKills(MI, TRI, RegKills, KillOps);
2487             VRM->RemoveMachineInstrFromMaps(&MI);
2488             MBB->erase(&MI);
2489             Erased = true;
2490             UpdateKills(*LastStore, TRI, RegKills, KillOps);
2491             goto ProcessNextInst;
2492           }
2493         }
2494       }
2495     }
2496     ProcessNextInst:
2497     // Delete dead instructions without side effects.
2498     if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2499       InvalidateKills(MI, TRI, RegKills, KillOps);
2500       VRM->RemoveMachineInstrFromMaps(&MI);
2501       MBB->erase(&MI);
2502       Erased = true;
2503     }
2504     if (!Erased)
2505       DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2506     if (!Erased && !BackTracked) {
2507       for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2508         UpdateKills(*II, TRI, RegKills, KillOps);
2509     }
2510     MII = NextMII;
2511   }
2512
2513 }
2514
2515 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2516   switch (RewriterOpt) {
2517   default: llvm_unreachable("Unreachable!");
2518   case local:
2519     return new LocalRewriter();
2520   case trivial:
2521     return new TrivialRewriter();
2522   }
2523 }