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