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