Spiller.cpp revision 9a77a92859b609a767d65b91ac7eb86a1a3ae680
1//===-- llvm/CodeGen/Spiller.cpp -  Spiller -------------------------------===//
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 "spiller"
11#include "Spiller.h"
12#include "llvm/Support/Compiler.h"
13#include "llvm/ADT/DepthFirstIterator.h"
14#include "llvm/ADT/Statistic.h"
15#include "llvm/ADT/STLExtras.h"
16#include <algorithm>
17using namespace llvm;
18
19STATISTIC(NumDSE     , "Number of dead stores elided");
20STATISTIC(NumDSS     , "Number of dead spill slots removed");
21STATISTIC(NumCommutes, "Number of instructions commuted");
22STATISTIC(NumDRM     , "Number of re-materializable defs elided");
23STATISTIC(NumStores  , "Number of stores added");
24STATISTIC(NumPSpills , "Number of physical register spills");
25STATISTIC(NumOmitted , "Number of reloads omited");
26STATISTIC(NumCopified, "Number of available reloads turned into copies");
27STATISTIC(NumReMats  , "Number of re-materialization");
28STATISTIC(NumLoads   , "Number of loads added");
29STATISTIC(NumReused  , "Number of values reused");
30STATISTIC(NumDCE     , "Number of copies elided");
31STATISTIC(NumSUnfold , "Number of stores unfolded");
32
33namespace {
34  enum SpillerName { simple, local };
35}
36
37static cl::opt<SpillerName>
38SpillerOpt("spiller",
39           cl::desc("Spiller to use: (default: local)"),
40           cl::Prefix,
41           cl::values(clEnumVal(simple, "simple spiller"),
42                      clEnumVal(local,  "local spiller"),
43                      clEnumValEnd),
44           cl::init(local));
45
46// ****************************** //
47// Simple Spiller Implementation  //
48// ****************************** //
49
50Spiller::~Spiller() {}
51
52bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
53  DOUT << "********** REWRITE MACHINE CODE **********\n";
54  DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
55  const TargetMachine &TM = MF.getTarget();
56  const TargetInstrInfo &TII = *TM.getInstrInfo();
57  const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
58
59
60  // LoadedRegs - Keep track of which vregs are loaded, so that we only load
61  // each vreg once (in the case where a spilled vreg is used by multiple
62  // operands).  This is always smaller than the number of operands to the
63  // current machine instr, so it should be small.
64  std::vector<unsigned> LoadedRegs;
65
66  for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
67       MBBI != E; ++MBBI) {
68    DOUT << MBBI->getBasicBlock()->getName() << ":\n";
69    MachineBasicBlock &MBB = *MBBI;
70    for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
71         MII != E; ++MII) {
72      MachineInstr &MI = *MII;
73      for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
74        MachineOperand &MO = MI.getOperand(i);
75        if (MO.isReg() && MO.getReg()) {
76          if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
77            unsigned VirtReg = MO.getReg();
78            unsigned SubIdx = MO.getSubReg();
79            unsigned PhysReg = VRM.getPhys(VirtReg);
80            unsigned RReg = SubIdx ? TRI.getSubReg(PhysReg, SubIdx) : PhysReg;
81            if (!VRM.isAssignedReg(VirtReg)) {
82              int StackSlot = VRM.getStackSlot(VirtReg);
83              const TargetRegisterClass* RC =
84                                           MF.getRegInfo().getRegClass(VirtReg);
85
86              if (MO.isUse() &&
87                  std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
88                           == LoadedRegs.end()) {
89                TII.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
90                MachineInstr *LoadMI = prior(MII);
91                VRM.addSpillSlotUse(StackSlot, LoadMI);
92                LoadedRegs.push_back(VirtReg);
93                ++NumLoads;
94                DOUT << '\t' << *LoadMI;
95              }
96
97              if (MO.isDef()) {
98                TII.storeRegToStackSlot(MBB, next(MII), PhysReg, true,
99                                        StackSlot, RC);
100                MachineInstr *StoreMI = next(MII);
101                VRM.addSpillSlotUse(StackSlot, StoreMI);
102                ++NumStores;
103              }
104            }
105            MF.getRegInfo().setPhysRegUsed(RReg);
106            MI.getOperand(i).setReg(RReg);
107            MI.getOperand(i).setSubReg(0);
108          } else {
109            MF.getRegInfo().setPhysRegUsed(MO.getReg());
110          }
111        }
112      }
113
114      DOUT << '\t' << MI;
115      LoadedRegs.clear();
116    }
117  }
118  return true;
119}
120
121// ****************** //
122// Utility Functions  //
123// ****************** //
124
125/// InvalidateKill - A MI that defines the specified register is being deleted,
126/// invalidate the register kill information.
127static void InvalidateKill(unsigned Reg, BitVector &RegKills,
128                           std::vector<MachineOperand*> &KillOps) {
129  if (RegKills[Reg]) {
130    KillOps[Reg]->setIsKill(false);
131    KillOps[Reg] = NULL;
132    RegKills.reset(Reg);
133  }
134}
135
136/// findSinglePredSuccessor - Return via reference a vector of machine basic
137/// blocks each of which is a successor of the specified BB and has no other
138/// predecessor.
139static void findSinglePredSuccessor(MachineBasicBlock *MBB,
140                                   SmallVectorImpl<MachineBasicBlock *> &Succs) {
141  for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
142         SE = MBB->succ_end(); SI != SE; ++SI) {
143    MachineBasicBlock *SuccMBB = *SI;
144    if (SuccMBB->pred_size() == 1)
145      Succs.push_back(SuccMBB);
146  }
147}
148
149/// InvalidateKills - MI is going to be deleted. If any of its operands are
150/// marked kill, then invalidate the information.
151static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
152                            std::vector<MachineOperand*> &KillOps,
153                            SmallVector<unsigned, 2> *KillRegs = NULL) {
154  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
155    MachineOperand &MO = MI.getOperand(i);
156    if (!MO.isReg() || !MO.isUse() || !MO.isKill())
157      continue;
158    unsigned Reg = MO.getReg();
159    if (TargetRegisterInfo::isVirtualRegister(Reg))
160      continue;
161    if (KillRegs)
162      KillRegs->push_back(Reg);
163    assert(Reg < KillOps.size());
164    if (KillOps[Reg] == &MO) {
165      RegKills.reset(Reg);
166      KillOps[Reg] = NULL;
167    }
168  }
169}
170
171/// InvalidateRegDef - If the def operand of the specified def MI is now dead
172/// (since it's spill instruction is removed), mark it isDead. Also checks if
173/// the def MI has other definition operands that are not dead. Returns it by
174/// reference.
175static bool InvalidateRegDef(MachineBasicBlock::iterator I,
176                             MachineInstr &NewDef, unsigned Reg,
177                             bool &HasLiveDef) {
178  // Due to remat, it's possible this reg isn't being reused. That is,
179  // the def of this reg (by prev MI) is now dead.
180  MachineInstr *DefMI = I;
181  MachineOperand *DefOp = NULL;
182  for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
183    MachineOperand &MO = DefMI->getOperand(i);
184    if (MO.isReg() && MO.isDef()) {
185      if (MO.getReg() == Reg)
186        DefOp = &MO;
187      else if (!MO.isDead())
188        HasLiveDef = true;
189    }
190  }
191  if (!DefOp)
192    return false;
193
194  bool FoundUse = false, Done = false;
195  MachineBasicBlock::iterator E = &NewDef;
196  ++I; ++E;
197  for (; !Done && I != E; ++I) {
198    MachineInstr *NMI = I;
199    for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
200      MachineOperand &MO = NMI->getOperand(j);
201      if (!MO.isReg() || MO.getReg() != Reg)
202        continue;
203      if (MO.isUse())
204        FoundUse = true;
205      Done = true; // Stop after scanning all the operands of this MI.
206    }
207  }
208  if (!FoundUse) {
209    // Def is dead!
210    DefOp->setIsDead();
211    return true;
212  }
213  return false;
214}
215
216/// UpdateKills - Track and update kill info. If a MI reads a register that is
217/// marked kill, then it must be due to register reuse. Transfer the kill info
218/// over.
219static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
220                        std::vector<MachineOperand*> &KillOps,
221                        const TargetRegisterInfo* TRI) {
222  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
223    MachineOperand &MO = MI.getOperand(i);
224    if (!MO.isReg() || !MO.isUse())
225      continue;
226    unsigned Reg = MO.getReg();
227    if (Reg == 0)
228      continue;
229
230    if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
231      // That can't be right. Register is killed but not re-defined and it's
232      // being reused. Let's fix that.
233      KillOps[Reg]->setIsKill(false);
234      KillOps[Reg] = NULL;
235      RegKills.reset(Reg);
236      if (!MI.isRegTiedToDefOperand(i))
237        // Unless it's a two-address operand, this is the new kill.
238        MO.setIsKill();
239    }
240    if (MO.isKill()) {
241      RegKills.set(Reg);
242      KillOps[Reg] = &MO;
243    }
244  }
245
246  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
247    const MachineOperand &MO = MI.getOperand(i);
248    if (!MO.isReg() || !MO.isDef())
249      continue;
250    unsigned Reg = MO.getReg();
251    RegKills.reset(Reg);
252    KillOps[Reg] = NULL;
253    // It also defines (or partially define) aliases.
254    for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
255      RegKills.reset(*AS);
256      KillOps[*AS] = NULL;
257    }
258  }
259}
260
261/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
262///
263static void ReMaterialize(MachineBasicBlock &MBB,
264                          MachineBasicBlock::iterator &MII,
265                          unsigned DestReg, unsigned Reg,
266                          const TargetInstrInfo *TII,
267                          const TargetRegisterInfo *TRI,
268                          VirtRegMap &VRM) {
269  TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
270  MachineInstr *NewMI = prior(MII);
271  for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
272    MachineOperand &MO = NewMI->getOperand(i);
273    if (!MO.isReg() || MO.getReg() == 0)
274      continue;
275    unsigned VirtReg = MO.getReg();
276    if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
277      continue;
278    assert(MO.isUse());
279    unsigned SubIdx = MO.getSubReg();
280    unsigned Phys = VRM.getPhys(VirtReg);
281    assert(Phys);
282    unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
283    MO.setReg(RReg);
284    MO.setSubReg(0);
285  }
286  ++NumReMats;
287}
288
289/// findSuperReg - Find the SubReg's super-register of given register class
290/// where its SubIdx sub-register is SubReg.
291static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
292                             unsigned SubIdx, const TargetRegisterInfo *TRI) {
293  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
294       I != E; ++I) {
295    unsigned Reg = *I;
296    if (TRI->getSubReg(Reg, SubIdx) == SubReg)
297      return Reg;
298  }
299  return 0;
300}
301
302// ******************************** //
303// Available Spills Implementation  //
304// ******************************** //
305
306/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
307/// stackslot register. The register is still available but is no longer
308/// allowed to be modifed.
309void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
310  std::multimap<unsigned, int>::iterator I =
311    PhysRegsAvailable.lower_bound(PhysReg);
312  while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
313    int SlotOrReMat = I->second;
314    I++;
315    assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
316           "Bidirectional map mismatch!");
317    SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
318    DOUT << "PhysReg " << TRI->getName(PhysReg)
319         << " copied, it is available for use but can no longer be modified\n";
320  }
321}
322
323/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
324/// stackslot register and its aliases. The register and its aliases may
325/// still available but is no longer allowed to be modifed.
326void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
327  for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
328    disallowClobberPhysRegOnly(*AS);
329  disallowClobberPhysRegOnly(PhysReg);
330}
331
332/// ClobberPhysRegOnly - This is called when the specified physreg changes
333/// value.  We use this to invalidate any info about stuff we thing lives in it.
334void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
335  std::multimap<unsigned, int>::iterator I =
336    PhysRegsAvailable.lower_bound(PhysReg);
337  while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
338    int SlotOrReMat = I->second;
339    PhysRegsAvailable.erase(I++);
340    assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
341           "Bidirectional map mismatch!");
342    SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
343    DOUT << "PhysReg " << TRI->getName(PhysReg)
344         << " clobbered, invalidating ";
345    if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
346      DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
347    else
348      DOUT << "SS#" << SlotOrReMat << "\n";
349  }
350}
351
352/// ClobberPhysReg - This is called when the specified physreg changes
353/// value.  We use this to invalidate any info about stuff we thing lives in
354/// it and any of its aliases.
355void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
356  for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
357    ClobberPhysRegOnly(*AS);
358  ClobberPhysRegOnly(PhysReg);
359}
360
361/// AddAvailableRegsToLiveIn - Availability information is being kept coming
362/// into the specified MBB. Add available physical registers as potential
363/// live-in's. If they are reused in the MBB, they will be added to the
364/// live-in set to make register scavenger and post-allocation scheduler.
365void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
366                                        BitVector &RegKills,
367                                        std::vector<MachineOperand*> &KillOps) {
368  std::set<unsigned> NotAvailable;
369  for (std::multimap<unsigned, int>::iterator
370         I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
371       I != E; ++I) {
372    unsigned Reg = I->first;
373    const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
374    // FIXME: A temporary workaround. We can't reuse available value if it's
375    // not safe to move the def of the virtual register's class. e.g.
376    // X86::RFP* register classes. Do not add it as a live-in.
377    if (!TII->isSafeToMoveRegClassDefs(RC))
378      // This is no longer available.
379      NotAvailable.insert(Reg);
380    else {
381      MBB.addLiveIn(Reg);
382      InvalidateKill(Reg, RegKills, KillOps);
383    }
384
385    // Skip over the same register.
386    std::multimap<unsigned, int>::iterator NI = next(I);
387    while (NI != E && NI->first == Reg) {
388      ++I;
389      ++NI;
390    }
391  }
392
393  for (std::set<unsigned>::iterator I = NotAvailable.begin(),
394         E = NotAvailable.end(); I != E; ++I) {
395    ClobberPhysReg(*I);
396    for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
397       *SubRegs; ++SubRegs)
398      ClobberPhysReg(*SubRegs);
399  }
400}
401
402/// ModifyStackSlotOrReMat - This method is called when the value in a stack
403/// slot changes.  This removes information about which register the previous
404/// value for this slot lives in (as the previous value is dead now).
405void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
406  std::map<int, unsigned>::iterator It =
407    SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
408  if (It == SpillSlotsOrReMatsAvailable.end()) return;
409  unsigned Reg = It->second >> 1;
410  SpillSlotsOrReMatsAvailable.erase(It);
411
412  // This register may hold the value of multiple stack slots, only remove this
413  // stack slot from the set of values the register contains.
414  std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
415  for (; ; ++I) {
416    assert(I != PhysRegsAvailable.end() && I->first == Reg &&
417           "Map inverse broken!");
418    if (I->second == SlotOrReMat) break;
419  }
420  PhysRegsAvailable.erase(I);
421}
422
423// ************************** //
424// Reuse Info Implementation  //
425// ************************** //
426
427/// GetRegForReload - We are about to emit a reload into PhysReg.  If there
428/// is some other operand that is using the specified register, either pick
429/// a new register to use, or evict the previous reload and use this reg.
430unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
431                         AvailableSpills &Spills,
432                         std::vector<MachineInstr*> &MaybeDeadStores,
433                         SmallSet<unsigned, 8> &Rejected,
434                         BitVector &RegKills,
435                         std::vector<MachineOperand*> &KillOps,
436                         VirtRegMap &VRM) {
437  const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
438                               .getInstrInfo();
439
440  if (Reuses.empty()) return PhysReg;  // This is most often empty.
441
442  for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
443    ReusedOp &Op = Reuses[ro];
444    // If we find some other reuse that was supposed to use this register
445    // exactly for its reload, we can change this reload to use ITS reload
446    // register. That is, unless its reload register has already been
447    // considered and subsequently rejected because it has also been reused
448    // by another operand.
449    if (Op.PhysRegReused == PhysReg &&
450        Rejected.count(Op.AssignedPhysReg) == 0) {
451      // Yup, use the reload register that we didn't use before.
452      unsigned NewReg = Op.AssignedPhysReg;
453      Rejected.insert(PhysReg);
454      return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
455                             RegKills, KillOps, VRM);
456    } else {
457      // Otherwise, we might also have a problem if a previously reused
458      // value aliases the new register.  If so, codegen the previous reload
459      // and use this one.
460      unsigned PRRU = Op.PhysRegReused;
461      const TargetRegisterInfo *TRI = Spills.getRegInfo();
462      if (TRI->areAliases(PRRU, PhysReg)) {
463        // Okay, we found out that an alias of a reused register
464        // was used.  This isn't good because it means we have
465        // to undo a previous reuse.
466        MachineBasicBlock *MBB = MI->getParent();
467        const TargetRegisterClass *AliasRC =
468          MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
469
470        // Copy Op out of the vector and remove it, we're going to insert an
471        // explicit load for it.
472        ReusedOp NewOp = Op;
473        Reuses.erase(Reuses.begin()+ro);
474
475        // Ok, we're going to try to reload the assigned physreg into the
476        // slot that we were supposed to in the first place.  However, that
477        // register could hold a reuse.  Check to see if it conflicts or
478        // would prefer us to use a different register.
479        unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
480                                              MI, Spills, MaybeDeadStores,
481                                          Rejected, RegKills, KillOps, VRM);
482
483        MachineBasicBlock::iterator MII = MI;
484        if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
485          ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
486        } else {
487          TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
488                                    NewOp.StackSlotOrReMat, AliasRC);
489          MachineInstr *LoadMI = prior(MII);
490          VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
491          // Any stores to this stack slot are not dead anymore.
492          MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
493          ++NumLoads;
494        }
495        Spills.ClobberPhysReg(NewPhysReg);
496        Spills.ClobberPhysReg(NewOp.PhysRegReused);
497
498        unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
499        unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
500        MI->getOperand(NewOp.Operand).setReg(RReg);
501        MI->getOperand(NewOp.Operand).setSubReg(0);
502
503        Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
504        --MII;
505        UpdateKills(*MII, RegKills, KillOps, TRI);
506        DOUT << '\t' << *MII;
507
508        DOUT << "Reuse undone!\n";
509        --NumReused;
510
511        // Finally, PhysReg is now available, go ahead and use it.
512        return PhysReg;
513      }
514    }
515  }
516  return PhysReg;
517}
518
519// ***************************** //
520// Local Spiller Implementation  //
521// ***************************** //
522
523bool LocalSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
524  RegInfo = &MF.getRegInfo();
525  TRI = MF.getTarget().getRegisterInfo();
526  TII = MF.getTarget().getInstrInfo();
527  DOUT << "\n**** Local spiller rewriting function '"
528       << MF.getFunction()->getName() << "':\n";
529  DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
530          " ****\n";
531  DEBUG(MF.dump());
532
533  // Spills - Keep track of which spilled values are available in physregs
534  // so that we can choose to reuse the physregs instead of emitting
535  // reloads. This is usually refreshed per basic block.
536  AvailableSpills Spills(TRI, TII);
537
538  // Keep track of kill information.
539  BitVector RegKills(TRI->getNumRegs());
540  std::vector<MachineOperand*> KillOps;
541  KillOps.resize(TRI->getNumRegs(), NULL);
542
543  // SingleEntrySuccs - Successor blocks which have a single predecessor.
544  SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
545  SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
546
547  // Traverse the basic blocks depth first.
548  MachineBasicBlock *Entry = MF.begin();
549  SmallPtrSet<MachineBasicBlock*,16> Visited;
550  for (df_ext_iterator<MachineBasicBlock*,
551         SmallPtrSet<MachineBasicBlock*,16> >
552         DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
553       DFI != E; ++DFI) {
554    MachineBasicBlock *MBB = *DFI;
555    if (!EarlyVisited.count(MBB))
556      RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
557
558    // If this MBB is the only predecessor of a successor. Keep the
559    // availability information and visit it next.
560    do {
561      // Keep visiting single predecessor successor as long as possible.
562      SinglePredSuccs.clear();
563      findSinglePredSuccessor(MBB, SinglePredSuccs);
564      if (SinglePredSuccs.empty())
565        MBB = 0;
566      else {
567        // FIXME: More than one successors, each of which has MBB has
568        // the only predecessor.
569        MBB = SinglePredSuccs[0];
570        if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
571          Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
572          RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
573        }
574      }
575    } while (MBB);
576
577    // Clear the availability info.
578    Spills.clear();
579  }
580
581  DOUT << "**** Post Machine Instrs ****\n";
582  DEBUG(MF.dump());
583
584  // Mark unused spill slots.
585  MachineFrameInfo *MFI = MF.getFrameInfo();
586  int SS = VRM.getLowSpillSlot();
587  if (SS != VirtRegMap::NO_STACK_SLOT)
588    for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
589      if (!VRM.isSpillSlotUsed(SS)) {
590        MFI->RemoveStackObject(SS);
591        ++NumDSS;
592      }
593
594  return true;
595}
596
597
598/// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
599/// instruction. e.g.
600///     xorl  %edi, %eax
601///     movl  %eax, -32(%ebp)
602///     movl  -36(%ebp), %eax
603///     orl   %eax, -32(%ebp)
604/// ==>
605///     xorl  %edi, %eax
606///     orl   -36(%ebp), %eax
607///     mov   %eax, -32(%ebp)
608/// This enables unfolding optimization for a subsequent instruction which will
609/// also eliminate the newly introduced store instruction.
610bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
611                                    MachineBasicBlock::iterator &MII,
612                                    std::vector<MachineInstr*> &MaybeDeadStores,
613                                    AvailableSpills &Spills,
614                                    BitVector &RegKills,
615                                    std::vector<MachineOperand*> &KillOps,
616                                    VirtRegMap &VRM) {
617  MachineFunction &MF = *MBB.getParent();
618  MachineInstr &MI = *MII;
619  unsigned UnfoldedOpc = 0;
620  unsigned UnfoldPR = 0;
621  unsigned UnfoldVR = 0;
622  int FoldedSS = VirtRegMap::NO_STACK_SLOT;
623  VirtRegMap::MI2VirtMapTy::const_iterator I, End;
624  for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
625    // Only transform a MI that folds a single register.
626    if (UnfoldedOpc)
627      return false;
628    UnfoldVR = I->second.first;
629    VirtRegMap::ModRef MR = I->second.second;
630    // MI2VirtMap be can updated which invalidate the iterator.
631    // Increment the iterator first.
632    ++I;
633    if (VRM.isAssignedReg(UnfoldVR))
634      continue;
635    // If this reference is not a use, any previous store is now dead.
636    // Otherwise, the store to this stack slot is not dead anymore.
637    FoldedSS = VRM.getStackSlot(UnfoldVR);
638    MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
639    if (DeadStore && (MR & VirtRegMap::isModRef)) {
640      unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
641      if (!PhysReg || !DeadStore->readsRegister(PhysReg))
642        continue;
643      UnfoldPR = PhysReg;
644      UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
645                                                    false, true);
646    }
647  }
648
649  if (!UnfoldedOpc)
650    return false;
651
652  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
653    MachineOperand &MO = MI.getOperand(i);
654    if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
655      continue;
656    unsigned VirtReg = MO.getReg();
657    if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
658      continue;
659    if (VRM.isAssignedReg(VirtReg)) {
660      unsigned PhysReg = VRM.getPhys(VirtReg);
661      if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
662        return false;
663    } else if (VRM.isReMaterialized(VirtReg))
664      continue;
665    int SS = VRM.getStackSlot(VirtReg);
666    unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
667    if (PhysReg) {
668      if (TRI->regsOverlap(PhysReg, UnfoldPR))
669        return false;
670      continue;
671    }
672    if (VRM.hasPhys(VirtReg)) {
673      PhysReg = VRM.getPhys(VirtReg);
674      if (!TRI->regsOverlap(PhysReg, UnfoldPR))
675        continue;
676    }
677
678    // Ok, we'll need to reload the value into a register which makes
679    // it impossible to perform the store unfolding optimization later.
680    // Let's see if it is possible to fold the load if the store is
681    // unfolded. This allows us to perform the store unfolding
682    // optimization.
683    SmallVector<MachineInstr*, 4> NewMIs;
684    if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
685      assert(NewMIs.size() == 1);
686      MachineInstr *NewMI = NewMIs.back();
687      NewMIs.clear();
688      int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
689      assert(Idx != -1);
690      SmallVector<unsigned, 1> Ops;
691      Ops.push_back(Idx);
692      MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
693      if (FoldedMI) {
694        VRM.addSpillSlotUse(SS, FoldedMI);
695        if (!VRM.hasPhys(UnfoldVR))
696          VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
697        VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
698        MII = MBB.insert(MII, FoldedMI);
699        InvalidateKills(MI, RegKills, KillOps);
700        VRM.RemoveMachineInstrFromMaps(&MI);
701        MBB.erase(&MI);
702        MF.DeleteMachineInstr(NewMI);
703        return true;
704      }
705      MF.DeleteMachineInstr(NewMI);
706    }
707  }
708  return false;
709}
710
711/// CommuteToFoldReload -
712/// Look for
713/// r1 = load fi#1
714/// r1 = op r1, r2<kill>
715/// store r1, fi#1
716///
717/// If op is commutable and r2 is killed, then we can xform these to
718/// r2 = op r2, fi#1
719/// store r2, fi#1
720bool LocalSpiller::CommuteToFoldReload(MachineBasicBlock &MBB,
721                                    MachineBasicBlock::iterator &MII,
722                                    unsigned VirtReg, unsigned SrcReg, int SS,
723                                    AvailableSpills &Spills,
724                                    BitVector &RegKills,
725                                    std::vector<MachineOperand*> &KillOps,
726                                    const TargetRegisterInfo *TRI,
727                                    VirtRegMap &VRM) {
728  if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
729    return false;
730
731  MachineFunction &MF = *MBB.getParent();
732  MachineInstr &MI = *MII;
733  MachineBasicBlock::iterator DefMII = prior(MII);
734  MachineInstr *DefMI = DefMII;
735  const TargetInstrDesc &TID = DefMI->getDesc();
736  unsigned NewDstIdx;
737  if (DefMII != MBB.begin() &&
738      TID.isCommutable() &&
739      TII->CommuteChangesDestination(DefMI, NewDstIdx)) {
740    MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
741    unsigned NewReg = NewDstMO.getReg();
742    if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
743      return false;
744    MachineInstr *ReloadMI = prior(DefMII);
745    int FrameIdx;
746    unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
747    if (DestReg != SrcReg || FrameIdx != SS)
748      return false;
749    int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
750    if (UseIdx == -1)
751      return false;
752    unsigned DefIdx;
753    if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
754      return false;
755    assert(DefMI->getOperand(DefIdx).isReg() &&
756           DefMI->getOperand(DefIdx).getReg() == SrcReg);
757
758    // Now commute def instruction.
759    MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
760    if (!CommutedMI)
761      return false;
762    SmallVector<unsigned, 1> Ops;
763    Ops.push_back(NewDstIdx);
764    MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
765    // Not needed since foldMemoryOperand returns new MI.
766    MF.DeleteMachineInstr(CommutedMI);
767    if (!FoldedMI)
768      return false;
769
770    VRM.addSpillSlotUse(SS, FoldedMI);
771    VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
772    // Insert new def MI and spill MI.
773    const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
774    TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
775    MII = prior(MII);
776    MachineInstr *StoreMI = MII;
777    VRM.addSpillSlotUse(SS, StoreMI);
778    VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
779    MII = MBB.insert(MII, FoldedMI);  // Update MII to backtrack.
780
781    // Delete all 3 old instructions.
782    InvalidateKills(*ReloadMI, RegKills, KillOps);
783    VRM.RemoveMachineInstrFromMaps(ReloadMI);
784    MBB.erase(ReloadMI);
785    InvalidateKills(*DefMI, RegKills, KillOps);
786    VRM.RemoveMachineInstrFromMaps(DefMI);
787    MBB.erase(DefMI);
788    InvalidateKills(MI, RegKills, KillOps);
789    VRM.RemoveMachineInstrFromMaps(&MI);
790    MBB.erase(&MI);
791
792    // If NewReg was previously holding value of some SS, it's now clobbered.
793    // This has to be done now because it's a physical register. When this
794    // instruction is re-visited, it's ignored.
795    Spills.ClobberPhysReg(NewReg);
796
797    ++NumCommutes;
798    return true;
799  }
800
801  return false;
802}
803
804/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
805/// the last store to the same slot is now dead. If so, remove the last store.
806void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
807                                  MachineBasicBlock::iterator &MII,
808                                  int Idx, unsigned PhysReg, int StackSlot,
809                                  const TargetRegisterClass *RC,
810                                  bool isAvailable, MachineInstr *&LastStore,
811                                  AvailableSpills &Spills,
812                                  SmallSet<MachineInstr*, 4> &ReMatDefs,
813                                  BitVector &RegKills,
814                                  std::vector<MachineOperand*> &KillOps,
815                                  VirtRegMap &VRM) {
816  TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
817  MachineInstr *StoreMI = next(MII);
818  VRM.addSpillSlotUse(StackSlot, StoreMI);
819  DOUT << "Store:\t" << *StoreMI;
820
821  // If there is a dead store to this stack slot, nuke it now.
822  if (LastStore) {
823    DOUT << "Removed dead store:\t" << *LastStore;
824    ++NumDSE;
825    SmallVector<unsigned, 2> KillRegs;
826    InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
827    MachineBasicBlock::iterator PrevMII = LastStore;
828    bool CheckDef = PrevMII != MBB.begin();
829    if (CheckDef)
830      --PrevMII;
831    VRM.RemoveMachineInstrFromMaps(LastStore);
832    MBB.erase(LastStore);
833    if (CheckDef) {
834      // Look at defs of killed registers on the store. Mark the defs
835      // as dead since the store has been deleted and they aren't
836      // being reused.
837      for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
838        bool HasOtherDef = false;
839        if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
840          MachineInstr *DeadDef = PrevMII;
841          if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
842            // FIXME: This assumes a remat def does not have side
843            // effects.
844            VRM.RemoveMachineInstrFromMaps(DeadDef);
845            MBB.erase(DeadDef);
846            ++NumDRM;
847          }
848        }
849      }
850    }
851  }
852
853  LastStore = next(MII);
854
855  // If the stack slot value was previously available in some other
856  // register, change it now.  Otherwise, make the register available,
857  // in PhysReg.
858  Spills.ModifyStackSlotOrReMat(StackSlot);
859  Spills.ClobberPhysReg(PhysReg);
860  Spills.addAvailable(StackSlot, PhysReg, isAvailable);
861  ++NumStores;
862}
863
864/// TransferDeadness - A identity copy definition is dead and it's being
865/// removed. Find the last def or use and mark it as dead / kill.
866void LocalSpiller::TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
867                                    unsigned Reg, BitVector &RegKills,
868                                    std::vector<MachineOperand*> &KillOps) {
869  int LastUDDist = -1;
870  MachineInstr *LastUDMI = NULL;
871  for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
872         RE = RegInfo->reg_end(); RI != RE; ++RI) {
873    MachineInstr *UDMI = &*RI;
874    if (UDMI->getParent() != MBB)
875      continue;
876    DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
877    if (DI == DistanceMap.end() || DI->second > CurDist)
878      continue;
879    if ((int)DI->second < LastUDDist)
880      continue;
881    LastUDDist = DI->second;
882    LastUDMI = UDMI;
883  }
884
885  if (LastUDMI) {
886    MachineOperand *LastUD = NULL;
887    for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
888      MachineOperand &MO = LastUDMI->getOperand(i);
889      if (!MO.isReg() || MO.getReg() != Reg)
890        continue;
891      if (!LastUD || (LastUD->isUse() && MO.isDef()))
892        LastUD = &MO;
893      if (LastUDMI->isRegTiedToDefOperand(i))
894        return;
895    }
896    if (LastUD->isDef())
897      LastUD->setIsDead();
898    else {
899      LastUD->setIsKill();
900      RegKills.set(Reg);
901      KillOps[Reg] = LastUD;
902    }
903  }
904}
905
906/// rewriteMBB - Keep track of which spills are available even after the
907/// register allocator is done with them.  If possible, avid reloading vregs.
908void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
909                              AvailableSpills &Spills, BitVector &RegKills,
910                              std::vector<MachineOperand*> &KillOps) {
911  DOUT << "\n**** Local spiller rewriting MBB '"
912       << MBB.getBasicBlock()->getName() << "':\n";
913
914  MachineFunction &MF = *MBB.getParent();
915
916  // MaybeDeadStores - When we need to write a value back into a stack slot,
917  // keep track of the inserted store.  If the stack slot value is never read
918  // (because the value was used from some available register, for example), and
919  // subsequently stored to, the original store is dead.  This map keeps track
920  // of inserted stores that are not used.  If we see a subsequent store to the
921  // same stack slot, the original store is deleted.
922  std::vector<MachineInstr*> MaybeDeadStores;
923  MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
924
925  // ReMatDefs - These are rematerializable def MIs which are not deleted.
926  SmallSet<MachineInstr*, 4> ReMatDefs;
927
928  // Clear kill info.
929  SmallSet<unsigned, 2> KilledMIRegs;
930  RegKills.reset();
931  KillOps.clear();
932  KillOps.resize(TRI->getNumRegs(), NULL);
933
934  unsigned Dist = 0;
935  DistanceMap.clear();
936  for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
937       MII != E; ) {
938    MachineBasicBlock::iterator NextMII = MII; ++NextMII;
939
940    VirtRegMap::MI2VirtMapTy::const_iterator I, End;
941    bool Erased = false;
942    bool BackTracked = false;
943    if (PrepForUnfoldOpti(MBB, MII,
944                          MaybeDeadStores, Spills, RegKills, KillOps, VRM))
945      NextMII = next(MII);
946
947    MachineInstr &MI = *MII;
948
949    if (VRM.hasEmergencySpills(&MI)) {
950      // Spill physical register(s) in the rare case the allocator has run out
951      // of registers to allocate.
952      SmallSet<int, 4> UsedSS;
953      std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
954      for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
955        unsigned PhysReg = EmSpills[i];
956        const TargetRegisterClass *RC =
957          TRI->getPhysicalRegisterRegClass(PhysReg);
958        assert(RC && "Unable to determine register class!");
959        int SS = VRM.getEmergencySpillSlot(RC);
960        if (UsedSS.count(SS))
961          assert(0 && "Need to spill more than one physical registers!");
962        UsedSS.insert(SS);
963        TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
964        MachineInstr *StoreMI = prior(MII);
965        VRM.addSpillSlotUse(SS, StoreMI);
966        TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
967        MachineInstr *LoadMI = next(MII);
968        VRM.addSpillSlotUse(SS, LoadMI);
969        ++NumPSpills;
970      }
971      NextMII = next(MII);
972    }
973
974    // Insert restores here if asked to.
975    if (VRM.isRestorePt(&MI)) {
976      std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
977      for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
978        unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
979        if (!VRM.getPreSplitReg(VirtReg))
980          continue; // Split interval spilled again.
981        unsigned Phys = VRM.getPhys(VirtReg);
982        RegInfo->setPhysRegUsed(Phys);
983
984        // Check if the value being restored if available. If so, it must be
985        // from a predecessor BB that fallthrough into this BB. We do not
986        // expect:
987        // BB1:
988        // r1 = load fi#1
989        // ...
990        //    = r1<kill>
991        // ... # r1 not clobbered
992        // ...
993        //    = load fi#1
994        bool DoReMat = VRM.isReMaterialized(VirtReg);
995        int SSorRMId = DoReMat
996          ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
997        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
998        unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
999        if (InReg == Phys) {
1000          // If the value is already available in the expected register, save
1001          // a reload / remat.
1002          if (SSorRMId)
1003            DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1004          else
1005            DOUT << "Reusing SS#" << SSorRMId;
1006          DOUT << " from physreg "
1007               << TRI->getName(InReg) << " for vreg"
1008               << VirtReg <<" instead of reloading into physreg "
1009               << TRI->getName(Phys) << "\n";
1010          ++NumOmitted;
1011          continue;
1012        } else if (InReg && InReg != Phys) {
1013          if (SSorRMId)
1014            DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1015          else
1016            DOUT << "Reusing SS#" << SSorRMId;
1017          DOUT << " from physreg "
1018               << TRI->getName(InReg) << " for vreg"
1019               << VirtReg <<" by copying it into physreg "
1020               << TRI->getName(Phys) << "\n";
1021
1022          // If the reloaded / remat value is available in another register,
1023          // copy it to the desired register.
1024          TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1025
1026          // This invalidates Phys.
1027          Spills.ClobberPhysReg(Phys);
1028          // Remember it's available.
1029          Spills.addAvailable(SSorRMId, Phys);
1030
1031          // Mark is killed.
1032          MachineInstr *CopyMI = prior(MII);
1033          MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1034          KillOpnd->setIsKill();
1035          UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1036
1037          DOUT << '\t' << *CopyMI;
1038          ++NumCopified;
1039          continue;
1040        }
1041
1042        if (VRM.isReMaterialized(VirtReg)) {
1043          ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1044        } else {
1045          const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1046          TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1047          MachineInstr *LoadMI = prior(MII);
1048          VRM.addSpillSlotUse(SSorRMId, LoadMI);
1049          ++NumLoads;
1050        }
1051
1052        // This invalidates Phys.
1053        Spills.ClobberPhysReg(Phys);
1054        // Remember it's available.
1055        Spills.addAvailable(SSorRMId, Phys);
1056
1057        UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1058        DOUT << '\t' << *prior(MII);
1059      }
1060    }
1061
1062    // Insert spills here if asked to.
1063    if (VRM.isSpillPt(&MI)) {
1064      std::vector<std::pair<unsigned,bool> > &SpillRegs =
1065        VRM.getSpillPtSpills(&MI);
1066      for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1067        unsigned VirtReg = SpillRegs[i].first;
1068        bool isKill = SpillRegs[i].second;
1069        if (!VRM.getPreSplitReg(VirtReg))
1070          continue; // Split interval spilled again.
1071        const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1072        unsigned Phys = VRM.getPhys(VirtReg);
1073        int StackSlot = VRM.getStackSlot(VirtReg);
1074        TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1075        MachineInstr *StoreMI = next(MII);
1076        VRM.addSpillSlotUse(StackSlot, StoreMI);
1077        DOUT << "Store:\t" << *StoreMI;
1078        VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1079      }
1080      NextMII = next(MII);
1081    }
1082
1083    /// ReusedOperands - Keep track of operand reuse in case we need to undo
1084    /// reuse.
1085    ReuseInfo ReusedOperands(MI, TRI);
1086    SmallVector<unsigned, 4> VirtUseOps;
1087    for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1088      MachineOperand &MO = MI.getOperand(i);
1089      if (!MO.isReg() || MO.getReg() == 0)
1090        continue;   // Ignore non-register operands.
1091
1092      unsigned VirtReg = MO.getReg();
1093      if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1094        // Ignore physregs for spilling, but remember that it is used by this
1095        // function.
1096        RegInfo->setPhysRegUsed(VirtReg);
1097        continue;
1098      }
1099
1100      // We want to process implicit virtual register uses first.
1101      if (MO.isImplicit())
1102        // If the virtual register is implicitly defined, emit a implicit_def
1103        // before so scavenger knows it's "defined".
1104        VirtUseOps.insert(VirtUseOps.begin(), i);
1105      else
1106        VirtUseOps.push_back(i);
1107    }
1108
1109    // Process all of the spilled uses and all non spilled reg references.
1110    SmallVector<int, 2> PotentialDeadStoreSlots;
1111    KilledMIRegs.clear();
1112    for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1113      unsigned i = VirtUseOps[j];
1114      MachineOperand &MO = MI.getOperand(i);
1115      unsigned VirtReg = MO.getReg();
1116      assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1117             "Not a virtual register?");
1118
1119      unsigned SubIdx = MO.getSubReg();
1120      if (VRM.isAssignedReg(VirtReg)) {
1121        // This virtual register was assigned a physreg!
1122        unsigned Phys = VRM.getPhys(VirtReg);
1123        RegInfo->setPhysRegUsed(Phys);
1124        if (MO.isDef())
1125          ReusedOperands.markClobbered(Phys);
1126        unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1127        MI.getOperand(i).setReg(RReg);
1128        MI.getOperand(i).setSubReg(0);
1129        if (VRM.isImplicitlyDefined(VirtReg))
1130          BuildMI(MBB, &MI, MI.getDebugLoc(),
1131                  TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1132        continue;
1133      }
1134
1135      // This virtual register is now known to be a spilled value.
1136      if (!MO.isUse())
1137        continue;  // Handle defs in the loop below (handle use&def here though)
1138
1139      bool DoReMat = VRM.isReMaterialized(VirtReg);
1140      int SSorRMId = DoReMat
1141        ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1142      int ReuseSlot = SSorRMId;
1143
1144      // Check to see if this stack slot is available.
1145      unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1146
1147      // If this is a sub-register use, make sure the reuse register is in the
1148      // right register class. For example, for x86 not all of the 32-bit
1149      // registers have accessible sub-registers.
1150      // Similarly so for EXTRACT_SUBREG. Consider this:
1151      // EDI = op
1152      // MOV32_mr fi#1, EDI
1153      // ...
1154      //       = EXTRACT_SUBREG fi#1
1155      // fi#1 is available in EDI, but it cannot be reused because it's not in
1156      // the right register file.
1157      if (PhysReg &&
1158          (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1159        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1160        if (!RC->contains(PhysReg))
1161          PhysReg = 0;
1162      }
1163
1164      if (PhysReg) {
1165        // This spilled operand might be part of a two-address operand.  If this
1166        // is the case, then changing it will necessarily require changing the
1167        // def part of the instruction as well.  However, in some cases, we
1168        // aren't allowed to modify the reused register.  If none of these cases
1169        // apply, reuse it.
1170        bool CanReuse = true;
1171        bool isTied = MI.isRegTiedToDefOperand(i);
1172        if (isTied) {
1173          // Okay, we have a two address operand.  We can reuse this physreg as
1174          // long as we are allowed to clobber the value and there isn't an
1175          // earlier def that has already clobbered the physreg.
1176          CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1177            Spills.canClobberPhysReg(PhysReg);
1178        }
1179
1180        if (CanReuse) {
1181          // If this stack slot value is already available, reuse it!
1182          if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1183            DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1184          else
1185            DOUT << "Reusing SS#" << ReuseSlot;
1186          DOUT << " from physreg "
1187               << TRI->getName(PhysReg) << " for vreg"
1188               << VirtReg <<" instead of reloading into physreg "
1189               << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1190          unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1191          MI.getOperand(i).setReg(RReg);
1192          MI.getOperand(i).setSubReg(0);
1193
1194          // The only technical detail we have is that we don't know that
1195          // PhysReg won't be clobbered by a reloaded stack slot that occurs
1196          // later in the instruction.  In particular, consider 'op V1, V2'.
1197          // If V1 is available in physreg R0, we would choose to reuse it
1198          // here, instead of reloading it into the register the allocator
1199          // indicated (say R1).  However, V2 might have to be reloaded
1200          // later, and it might indicate that it needs to live in R0.  When
1201          // this occurs, we need to have information available that
1202          // indicates it is safe to use R1 for the reload instead of R0.
1203          //
1204          // To further complicate matters, we might conflict with an alias,
1205          // or R0 and R1 might not be compatible with each other.  In this
1206          // case, we actually insert a reload for V1 in R1, ensuring that
1207          // we can get at R0 or its alias.
1208          ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1209                                  VRM.getPhys(VirtReg), VirtReg);
1210          if (isTied)
1211            // Only mark it clobbered if this is a use&def operand.
1212            ReusedOperands.markClobbered(PhysReg);
1213          ++NumReused;
1214
1215          if (MI.getOperand(i).isKill() &&
1216              ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1217
1218            // The store of this spilled value is potentially dead, but we
1219            // won't know for certain until we've confirmed that the re-use
1220            // above is valid, which means waiting until the other operands
1221            // are processed. For now we just track the spill slot, we'll
1222            // remove it after the other operands are processed if valid.
1223
1224            PotentialDeadStoreSlots.push_back(ReuseSlot);
1225          }
1226
1227          // Mark is isKill if it's there no other uses of the same virtual
1228          // register and it's not a two-address operand. IsKill will be
1229          // unset if reg is reused.
1230          if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1231            MI.getOperand(i).setIsKill();
1232            KilledMIRegs.insert(VirtReg);
1233          }
1234
1235          continue;
1236        }  // CanReuse
1237
1238        // Otherwise we have a situation where we have a two-address instruction
1239        // whose mod/ref operand needs to be reloaded.  This reload is already
1240        // available in some register "PhysReg", but if we used PhysReg as the
1241        // operand to our 2-addr instruction, the instruction would modify
1242        // PhysReg.  This isn't cool if something later uses PhysReg and expects
1243        // to get its initial value.
1244        //
1245        // To avoid this problem, and to avoid doing a load right after a store,
1246        // we emit a copy from PhysReg into the designated register for this
1247        // operand.
1248        unsigned DesignatedReg = VRM.getPhys(VirtReg);
1249        assert(DesignatedReg && "Must map virtreg to physreg!");
1250
1251        // Note that, if we reused a register for a previous operand, the
1252        // register we want to reload into might not actually be
1253        // available.  If this occurs, use the register indicated by the
1254        // reuser.
1255        if (ReusedOperands.hasReuses())
1256          DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1257                               Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1258
1259        // If the mapped designated register is actually the physreg we have
1260        // incoming, we don't need to inserted a dead copy.
1261        if (DesignatedReg == PhysReg) {
1262          // If this stack slot value is already available, reuse it!
1263          if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1264            DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1265          else
1266            DOUT << "Reusing SS#" << ReuseSlot;
1267          DOUT << " from physreg " << TRI->getName(PhysReg)
1268               << " for vreg" << VirtReg
1269               << " instead of reloading into same physreg.\n";
1270          unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1271          MI.getOperand(i).setReg(RReg);
1272          MI.getOperand(i).setSubReg(0);
1273          ReusedOperands.markClobbered(RReg);
1274          ++NumReused;
1275          continue;
1276        }
1277
1278        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1279        RegInfo->setPhysRegUsed(DesignatedReg);
1280        ReusedOperands.markClobbered(DesignatedReg);
1281        TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1282
1283        MachineInstr *CopyMI = prior(MII);
1284        UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1285
1286        // This invalidates DesignatedReg.
1287        Spills.ClobberPhysReg(DesignatedReg);
1288
1289        Spills.addAvailable(ReuseSlot, DesignatedReg);
1290        unsigned RReg =
1291          SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1292        MI.getOperand(i).setReg(RReg);
1293        MI.getOperand(i).setSubReg(0);
1294        DOUT << '\t' << *prior(MII);
1295        ++NumReused;
1296        continue;
1297      } // if (PhysReg)
1298
1299      // Otherwise, reload it and remember that we have it.
1300      PhysReg = VRM.getPhys(VirtReg);
1301      assert(PhysReg && "Must map virtreg to physreg!");
1302
1303      // Note that, if we reused a register for a previous operand, the
1304      // register we want to reload into might not actually be
1305      // available.  If this occurs, use the register indicated by the
1306      // reuser.
1307      if (ReusedOperands.hasReuses())
1308        PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1309                               Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1310
1311      RegInfo->setPhysRegUsed(PhysReg);
1312      ReusedOperands.markClobbered(PhysReg);
1313      if (DoReMat) {
1314        ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1315      } else {
1316        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1317        TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1318        MachineInstr *LoadMI = prior(MII);
1319        VRM.addSpillSlotUse(SSorRMId, LoadMI);
1320        ++NumLoads;
1321      }
1322      // This invalidates PhysReg.
1323      Spills.ClobberPhysReg(PhysReg);
1324
1325      // Any stores to this stack slot are not dead anymore.
1326      if (!DoReMat)
1327        MaybeDeadStores[SSorRMId] = NULL;
1328      Spills.addAvailable(SSorRMId, PhysReg);
1329      // Assumes this is the last use. IsKill will be unset if reg is reused
1330      // unless it's a two-address operand.
1331      if (!MI.isRegTiedToDefOperand(i) &&
1332          KilledMIRegs.count(VirtReg) == 0) {
1333        MI.getOperand(i).setIsKill();
1334        KilledMIRegs.insert(VirtReg);
1335      }
1336      unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1337      MI.getOperand(i).setReg(RReg);
1338      MI.getOperand(i).setSubReg(0);
1339      UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1340      DOUT << '\t' << *prior(MII);
1341    }
1342
1343    // Ok - now we can remove stores that have been confirmed dead.
1344    for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1345      // This was the last use and the spilled value is still available
1346      // for reuse. That means the spill was unnecessary!
1347      int PDSSlot = PotentialDeadStoreSlots[j];
1348      MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1349      if (DeadStore) {
1350        DOUT << "Removed dead store:\t" << *DeadStore;
1351        InvalidateKills(*DeadStore, RegKills, KillOps);
1352        VRM.RemoveMachineInstrFromMaps(DeadStore);
1353        MBB.erase(DeadStore);
1354        MaybeDeadStores[PDSSlot] = NULL;
1355        ++NumDSE;
1356      }
1357    }
1358
1359
1360    DOUT << '\t' << MI;
1361
1362
1363    // If we have folded references to memory operands, make sure we clear all
1364    // physical registers that may contain the value of the spilled virtual
1365    // register
1366    SmallSet<int, 2> FoldedSS;
1367    for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1368      unsigned VirtReg = I->second.first;
1369      VirtRegMap::ModRef MR = I->second.second;
1370      DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1371
1372      // MI2VirtMap be can updated which invalidate the iterator.
1373      // Increment the iterator first.
1374      ++I;
1375      int SS = VRM.getStackSlot(VirtReg);
1376      if (SS == VirtRegMap::NO_STACK_SLOT)
1377        continue;
1378      FoldedSS.insert(SS);
1379      DOUT << " - StackSlot: " << SS << "\n";
1380
1381      // If this folded instruction is just a use, check to see if it's a
1382      // straight load from the virt reg slot.
1383      if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1384        int FrameIdx;
1385        unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1386        if (DestReg && FrameIdx == SS) {
1387          // If this spill slot is available, turn it into a copy (or nothing)
1388          // instead of leaving it as a load!
1389          if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1390            DOUT << "Promoted Load To Copy: " << MI;
1391            if (DestReg != InReg) {
1392              const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1393              TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1394              MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1395              unsigned SubIdx = DefMO->getSubReg();
1396              // Revisit the copy so we make sure to notice the effects of the
1397              // operation on the destreg (either needing to RA it if it's
1398              // virtual or needing to clobber any values if it's physical).
1399              NextMII = &MI;
1400              --NextMII;  // backtrack to the copy.
1401              // Propagate the sub-register index over.
1402              if (SubIdx) {
1403                DefMO = NextMII->findRegisterDefOperand(DestReg);
1404                DefMO->setSubReg(SubIdx);
1405              }
1406
1407              // Mark is killed.
1408              MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1409              KillOpnd->setIsKill();
1410
1411              BackTracked = true;
1412            } else {
1413              DOUT << "Removing now-noop copy: " << MI;
1414              // Unset last kill since it's being reused.
1415              InvalidateKill(InReg, RegKills, KillOps);
1416              Spills.disallowClobberPhysReg(InReg);
1417            }
1418
1419            InvalidateKills(MI, RegKills, KillOps);
1420            VRM.RemoveMachineInstrFromMaps(&MI);
1421            MBB.erase(&MI);
1422            Erased = true;
1423            goto ProcessNextInst;
1424          }
1425        } else {
1426          unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1427          SmallVector<MachineInstr*, 4> NewMIs;
1428          if (PhysReg &&
1429              TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1430            MBB.insert(MII, NewMIs[0]);
1431            InvalidateKills(MI, RegKills, KillOps);
1432            VRM.RemoveMachineInstrFromMaps(&MI);
1433            MBB.erase(&MI);
1434            Erased = true;
1435            --NextMII;  // backtrack to the unfolded instruction.
1436            BackTracked = true;
1437            goto ProcessNextInst;
1438          }
1439        }
1440      }
1441
1442      // If this reference is not a use, any previous store is now dead.
1443      // Otherwise, the store to this stack slot is not dead anymore.
1444      MachineInstr* DeadStore = MaybeDeadStores[SS];
1445      if (DeadStore) {
1446        bool isDead = !(MR & VirtRegMap::isRef);
1447        MachineInstr *NewStore = NULL;
1448        if (MR & VirtRegMap::isModRef) {
1449          unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1450          SmallVector<MachineInstr*, 4> NewMIs;
1451          // We can reuse this physreg as long as we are allowed to clobber
1452          // the value and there isn't an earlier def that has already clobbered
1453          // the physreg.
1454          if (PhysReg &&
1455              !ReusedOperands.isClobbered(PhysReg) &&
1456              Spills.canClobberPhysReg(PhysReg) &&
1457              !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1458            MachineOperand *KillOpnd =
1459              DeadStore->findRegisterUseOperand(PhysReg, true);
1460            // Note, if the store is storing a sub-register, it's possible the
1461            // super-register is needed below.
1462            if (KillOpnd && !KillOpnd->getSubReg() &&
1463                TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1464              MBB.insert(MII, NewMIs[0]);
1465              NewStore = NewMIs[1];
1466              MBB.insert(MII, NewStore);
1467              VRM.addSpillSlotUse(SS, NewStore);
1468              InvalidateKills(MI, RegKills, KillOps);
1469              VRM.RemoveMachineInstrFromMaps(&MI);
1470              MBB.erase(&MI);
1471              Erased = true;
1472              --NextMII;
1473              --NextMII;  // backtrack to the unfolded instruction.
1474              BackTracked = true;
1475              isDead = true;
1476              ++NumSUnfold;
1477            }
1478          }
1479        }
1480
1481        if (isDead) {  // Previous store is dead.
1482          // If we get here, the store is dead, nuke it now.
1483          DOUT << "Removed dead store:\t" << *DeadStore;
1484          InvalidateKills(*DeadStore, RegKills, KillOps);
1485          VRM.RemoveMachineInstrFromMaps(DeadStore);
1486          MBB.erase(DeadStore);
1487          if (!NewStore)
1488            ++NumDSE;
1489        }
1490
1491        MaybeDeadStores[SS] = NULL;
1492        if (NewStore) {
1493          // Treat this store as a spill merged into a copy. That makes the
1494          // stack slot value available.
1495          VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1496          goto ProcessNextInst;
1497        }
1498      }
1499
1500      // If the spill slot value is available, and this is a new definition of
1501      // the value, the value is not available anymore.
1502      if (MR & VirtRegMap::isMod) {
1503        // Notice that the value in this stack slot has been modified.
1504        Spills.ModifyStackSlotOrReMat(SS);
1505
1506        // If this is *just* a mod of the value, check to see if this is just a
1507        // store to the spill slot (i.e. the spill got merged into the copy). If
1508        // so, realize that the vreg is available now, and add the store to the
1509        // MaybeDeadStore info.
1510        int StackSlot;
1511        if (!(MR & VirtRegMap::isRef)) {
1512          if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1513            assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1514                   "Src hasn't been allocated yet?");
1515
1516            if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
1517                                    Spills, RegKills, KillOps, TRI, VRM)) {
1518              NextMII = next(MII);
1519              BackTracked = true;
1520              goto ProcessNextInst;
1521            }
1522
1523            // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1524            // this as a potentially dead store in case there is a subsequent
1525            // store into the stack slot without a read from it.
1526            MaybeDeadStores[StackSlot] = &MI;
1527
1528            // If the stack slot value was previously available in some other
1529            // register, change it now.  Otherwise, make the register
1530            // available in PhysReg.
1531            Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
1532          }
1533        }
1534      }
1535    }
1536
1537    // Process all of the spilled defs.
1538    for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1539      MachineOperand &MO = MI.getOperand(i);
1540      if (!(MO.isReg() && MO.getReg() && MO.isDef()))
1541        continue;
1542
1543      unsigned VirtReg = MO.getReg();
1544      if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1545        // Check to see if this is a noop copy.  If so, eliminate the
1546        // instruction before considering the dest reg to be changed.
1547        unsigned Src, Dst, SrcSR, DstSR;
1548        if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1549          ++NumDCE;
1550          DOUT << "Removing now-noop copy: " << MI;
1551          SmallVector<unsigned, 2> KillRegs;
1552          InvalidateKills(MI, RegKills, KillOps, &KillRegs);
1553          if (MO.isDead() && !KillRegs.empty()) {
1554            // Source register or an implicit super/sub-register use is killed.
1555            assert(KillRegs[0] == Dst ||
1556                   TRI->isSubRegister(KillRegs[0], Dst) ||
1557                   TRI->isSuperRegister(KillRegs[0], Dst));
1558            // Last def is now dead.
1559            TransferDeadness(&MBB, Dist, Src, RegKills, KillOps);
1560          }
1561          VRM.RemoveMachineInstrFromMaps(&MI);
1562          MBB.erase(&MI);
1563          Erased = true;
1564          Spills.disallowClobberPhysReg(VirtReg);
1565          goto ProcessNextInst;
1566        }
1567
1568        // If it's not a no-op copy, it clobbers the value in the destreg.
1569        Spills.ClobberPhysReg(VirtReg);
1570        ReusedOperands.markClobbered(VirtReg);
1571
1572        // Check to see if this instruction is a load from a stack slot into
1573        // a register.  If so, this provides the stack slot value in the reg.
1574        int FrameIdx;
1575        if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1576          assert(DestReg == VirtReg && "Unknown load situation!");
1577
1578          // If it is a folded reference, then it's not safe to clobber.
1579          bool Folded = FoldedSS.count(FrameIdx);
1580          // Otherwise, if it wasn't available, remember that it is now!
1581          Spills.addAvailable(FrameIdx, DestReg, !Folded);
1582          goto ProcessNextInst;
1583        }
1584
1585        continue;
1586      }
1587
1588      unsigned SubIdx = MO.getSubReg();
1589      bool DoReMat = VRM.isReMaterialized(VirtReg);
1590      if (DoReMat)
1591        ReMatDefs.insert(&MI);
1592
1593      // The only vregs left are stack slot definitions.
1594      int StackSlot = VRM.getStackSlot(VirtReg);
1595      const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1596
1597      // If this def is part of a two-address operand, make sure to execute
1598      // the store from the correct physical register.
1599      unsigned PhysReg;
1600      unsigned TiedOp;
1601      if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
1602        PhysReg = MI.getOperand(TiedOp).getReg();
1603        if (SubIdx) {
1604          unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
1605          assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
1606                 "Can't find corresponding super-register!");
1607          PhysReg = SuperReg;
1608        }
1609      } else {
1610        PhysReg = VRM.getPhys(VirtReg);
1611        if (ReusedOperands.isClobbered(PhysReg)) {
1612          // Another def has taken the assigned physreg. It must have been a
1613          // use&def which got it due to reuse. Undo the reuse!
1614          PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1615                               Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1616        }
1617      }
1618
1619      assert(PhysReg && "VR not assigned a physical register?");
1620      RegInfo->setPhysRegUsed(PhysReg);
1621      unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1622      ReusedOperands.markClobbered(RReg);
1623      MI.getOperand(i).setReg(RReg);
1624      MI.getOperand(i).setSubReg(0);
1625
1626      if (!MO.isDead()) {
1627        MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1628        SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
1629                          LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
1630        NextMII = next(MII);
1631
1632        // Check to see if this is a noop copy.  If so, eliminate the
1633        // instruction before considering the dest reg to be changed.
1634        {
1635          unsigned Src, Dst, SrcSR, DstSR;
1636          if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1637            ++NumDCE;
1638            DOUT << "Removing now-noop copy: " << MI;
1639            InvalidateKills(MI, RegKills, KillOps);
1640            VRM.RemoveMachineInstrFromMaps(&MI);
1641            MBB.erase(&MI);
1642            Erased = true;
1643            UpdateKills(*LastStore, RegKills, KillOps, TRI);
1644            goto ProcessNextInst;
1645          }
1646        }
1647      }
1648    }
1649  ProcessNextInst:
1650    DistanceMap.insert(std::make_pair(&MI, Dist++));
1651    if (!Erased && !BackTracked) {
1652      for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
1653        UpdateKills(*II, RegKills, KillOps, TRI);
1654    }
1655    MII = NextMII;
1656  }
1657
1658}
1659
1660llvm::Spiller* llvm::createSpiller() {
1661  switch (SpillerOpt) {
1662  default: assert(0 && "Unreachable!");
1663  case local:
1664    return new LocalSpiller();
1665  case simple:
1666    return new SimpleSpiller();
1667  }
1668}
1669