VirtRegMap.cpp revision 821b8560e735613dfcf7670866f9142e4845037e
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  /// AddAvailableRegsToLiveIn - Availability information is being kept coming
412  /// into the specified MBB. Add available physical registers as potential
413  /// live-in's. If they are reused in the MBB, they will be added to the
414  /// live-in set to make register scavenger and post-allocation scheduler.
415  void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
416                                std::vector<MachineOperand*> &KillOps);
417};
418}
419
420/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
421/// stackslot register. The register is still available but is no longer
422/// allowed to be modifed.
423void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
424  std::multimap<unsigned, int>::iterator I =
425    PhysRegsAvailable.lower_bound(PhysReg);
426  while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
427    int SlotOrReMat = I->second;
428    I++;
429    assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
430           "Bidirectional map mismatch!");
431    SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
432    DOUT << "PhysReg " << TRI->getName(PhysReg)
433         << " copied, it is available for use but can no longer be modified\n";
434  }
435}
436
437/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
438/// stackslot register and its aliases. The register and its aliases may
439/// still available but is no longer allowed to be modifed.
440void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
441  for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
442    disallowClobberPhysRegOnly(*AS);
443  disallowClobberPhysRegOnly(PhysReg);
444}
445
446/// ClobberPhysRegOnly - This is called when the specified physreg changes
447/// value.  We use this to invalidate any info about stuff we thing lives in it.
448void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
449  std::multimap<unsigned, int>::iterator I =
450    PhysRegsAvailable.lower_bound(PhysReg);
451  while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
452    int SlotOrReMat = I->second;
453    PhysRegsAvailable.erase(I++);
454    assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
455           "Bidirectional map mismatch!");
456    SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
457    DOUT << "PhysReg " << TRI->getName(PhysReg)
458         << " clobbered, invalidating ";
459    if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
460      DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
461    else
462      DOUT << "SS#" << SlotOrReMat << "\n";
463  }
464}
465
466/// ClobberPhysReg - This is called when the specified physreg changes
467/// value.  We use this to invalidate any info about stuff we thing lives in
468/// it and any of its aliases.
469void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
470  for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
471    ClobberPhysRegOnly(*AS);
472  ClobberPhysRegOnly(PhysReg);
473}
474
475/// ModifyStackSlotOrReMat - This method is called when the value in a stack
476/// slot changes.  This removes information about which register the previous
477/// value for this slot lives in (as the previous value is dead now).
478void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
479  std::map<int, unsigned>::iterator It =
480    SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
481  if (It == SpillSlotsOrReMatsAvailable.end()) return;
482  unsigned Reg = It->second >> 1;
483  SpillSlotsOrReMatsAvailable.erase(It);
484
485  // This register may hold the value of multiple stack slots, only remove this
486  // stack slot from the set of values the register contains.
487  std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
488  for (; ; ++I) {
489    assert(I != PhysRegsAvailable.end() && I->first == Reg &&
490           "Map inverse broken!");
491    if (I->second == SlotOrReMat) break;
492  }
493  PhysRegsAvailable.erase(I);
494}
495
496/// InvalidateKill - A MI that defines the specified register is being deleted,
497/// invalidate the register kill information.
498static void InvalidateKill(unsigned Reg, BitVector &RegKills,
499                           std::vector<MachineOperand*> &KillOps) {
500  if (RegKills[Reg]) {
501    KillOps[Reg]->setIsKill(false);
502    KillOps[Reg] = NULL;
503    RegKills.reset(Reg);
504  }
505}
506
507/// AddAvailableRegsToLiveIn - Availability information is being kept coming
508/// into the specified MBB. Add available physical registers as potential
509/// live-in's. If they are reused in the MBB, they will be added to the
510/// live-in set to make register scavenger and post-allocation scheduler.
511void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
512                                        BitVector &RegKills,
513                                        std::vector<MachineOperand*> &KillOps) {
514  std::set<unsigned> NotAvailable;
515  for (std::multimap<unsigned, int>::iterator
516         I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
517       I != E; ++I) {
518    unsigned Reg = I->first;
519    const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
520    // FIXME: A temporary workaround. We can't reuse available value if it's
521    // not safe to move the def of the virtual register's class. e.g.
522    // X86::RFP* register classes. Do not add it as a live-in.
523    if (!TII->isSafeToMoveRegClassDefs(RC))
524      // This is no longer available.
525      NotAvailable.insert(Reg);
526    else {
527      MBB.addLiveIn(Reg);
528      InvalidateKill(Reg, RegKills, KillOps);
529    }
530
531    // Skip over the same register.
532    std::multimap<unsigned, int>::iterator NI = next(I);
533    while (NI != E && NI->first == Reg) {
534      ++I;
535      ++NI;
536    }
537  }
538
539  for (std::set<unsigned>::iterator I = NotAvailable.begin(),
540         E = NotAvailable.end(); I != E; ++I) {
541    ClobberPhysReg(*I);
542    for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
543       *SubRegs; ++SubRegs)
544      ClobberPhysReg(*SubRegs);
545  }
546}
547
548/// findSinglePredSuccessor - Return via reference a vector of machine basic
549/// blocks each of which is a successor of the specified BB and has no other
550/// predecessor.
551static void findSinglePredSuccessor(MachineBasicBlock *MBB,
552                                   SmallVectorImpl<MachineBasicBlock *> &Succs) {
553  for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
554         SE = MBB->succ_end(); SI != SE; ++SI) {
555    MachineBasicBlock *SuccMBB = *SI;
556    if (SuccMBB->pred_size() == 1)
557      Succs.push_back(SuccMBB);
558  }
559}
560
561namespace {
562  /// LocalSpiller - This spiller does a simple pass over the machine basic
563  /// block to attempt to keep spills in registers as much as possible for
564  /// blocks that have low register pressure (the vreg may be spilled due to
565  /// register pressure in other blocks).
566  class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
567    MachineRegisterInfo *RegInfo;
568    const TargetRegisterInfo *TRI;
569    const TargetInstrInfo *TII;
570    DenseMap<MachineInstr*, unsigned> DistanceMap;
571  public:
572    bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
573      RegInfo = &MF.getRegInfo();
574      TRI = MF.getTarget().getRegisterInfo();
575      TII = MF.getTarget().getInstrInfo();
576      DOUT << "\n**** Local spiller rewriting function '"
577           << MF.getFunction()->getName() << "':\n";
578      DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
579              " ****\n";
580      DEBUG(MF.dump());
581
582      // Spills - Keep track of which spilled values are available in physregs
583      // so that we can choose to reuse the physregs instead of emitting
584      // reloads. This is usually refreshed per basic block.
585      AvailableSpills Spills(TRI, TII);
586
587      // Keep track of kill information.
588      BitVector RegKills(TRI->getNumRegs());
589      std::vector<MachineOperand*> KillOps;
590      KillOps.resize(TRI->getNumRegs(), NULL);
591
592      // SingleEntrySuccs - Successor blocks which have a single predecessor.
593      SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
594      SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
595
596      // Traverse the basic blocks depth first.
597      MachineBasicBlock *Entry = MF.begin();
598      SmallPtrSet<MachineBasicBlock*,16> Visited;
599      for (df_ext_iterator<MachineBasicBlock*,
600             SmallPtrSet<MachineBasicBlock*,16> >
601             DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
602           DFI != E; ++DFI) {
603        MachineBasicBlock *MBB = *DFI;
604        if (!EarlyVisited.count(MBB))
605          RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
606
607        // If this MBB is the only predecessor of a successor. Keep the
608        // availability information and visit it next.
609        do {
610          // Keep visiting single predecessor successor as long as possible.
611          SinglePredSuccs.clear();
612          findSinglePredSuccessor(MBB, SinglePredSuccs);
613          if (SinglePredSuccs.empty())
614            MBB = 0;
615          else {
616            // FIXME: More than one successors, each of which has MBB has
617            // the only predecessor.
618            MBB = SinglePredSuccs[0];
619            if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
620              Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
621              RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
622            }
623          }
624        } while (MBB);
625
626        // Clear the availability info.
627        Spills.clear();
628      }
629
630      DOUT << "**** Post Machine Instrs ****\n";
631      DEBUG(MF.dump());
632
633      // Mark unused spill slots.
634      MachineFrameInfo *MFI = MF.getFrameInfo();
635      int SS = VRM.getLowSpillSlot();
636      if (SS != VirtRegMap::NO_STACK_SLOT)
637        for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
638          if (!VRM.isSpillSlotUsed(SS)) {
639            MFI->RemoveStackObject(SS);
640            ++NumDSS;
641          }
642
643      return true;
644    }
645  private:
646    void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
647                          unsigned Reg, BitVector &RegKills,
648                          std::vector<MachineOperand*> &KillOps);
649    bool PrepForUnfoldOpti(MachineBasicBlock &MBB,
650                           MachineBasicBlock::iterator &MII,
651                           std::vector<MachineInstr*> &MaybeDeadStores,
652                           AvailableSpills &Spills, BitVector &RegKills,
653                           std::vector<MachineOperand*> &KillOps,
654                           VirtRegMap &VRM);
655    bool CommuteToFoldReload(MachineBasicBlock &MBB,
656                             MachineBasicBlock::iterator &MII,
657                             unsigned VirtReg, unsigned SrcReg, int SS,
658                             AvailableSpills &Spills,
659                             BitVector &RegKills,
660                             std::vector<MachineOperand*> &KillOps,
661                             const TargetRegisterInfo *TRI,
662                             VirtRegMap &VRM);
663    void SpillRegToStackSlot(MachineBasicBlock &MBB,
664                             MachineBasicBlock::iterator &MII,
665                             int Idx, unsigned PhysReg, int StackSlot,
666                             const TargetRegisterClass *RC,
667                             bool isAvailable, MachineInstr *&LastStore,
668                             AvailableSpills &Spills,
669                             SmallSet<MachineInstr*, 4> &ReMatDefs,
670                             BitVector &RegKills,
671                             std::vector<MachineOperand*> &KillOps,
672                             VirtRegMap &VRM);
673    void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
674                    AvailableSpills &Spills,
675                    BitVector &RegKills, std::vector<MachineOperand*> &KillOps);
676  };
677}
678
679/// InvalidateKills - MI is going to be deleted. If any of its operands are
680/// marked kill, then invalidate the information.
681static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
682                            std::vector<MachineOperand*> &KillOps,
683                            SmallVector<unsigned, 2> *KillRegs = NULL) {
684  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
685    MachineOperand &MO = MI.getOperand(i);
686    if (!MO.isReg() || !MO.isUse() || !MO.isKill())
687      continue;
688    unsigned Reg = MO.getReg();
689    if (TargetRegisterInfo::isVirtualRegister(Reg))
690      continue;
691    if (KillRegs)
692      KillRegs->push_back(Reg);
693    assert(Reg < KillOps.size());
694    if (KillOps[Reg] == &MO) {
695      RegKills.reset(Reg);
696      KillOps[Reg] = NULL;
697    }
698  }
699}
700
701/// InvalidateRegDef - If the def operand of the specified def MI is now dead
702/// (since it's spill instruction is removed), mark it isDead. Also checks if
703/// the def MI has other definition operands that are not dead. Returns it by
704/// reference.
705static bool InvalidateRegDef(MachineBasicBlock::iterator I,
706                             MachineInstr &NewDef, unsigned Reg,
707                             bool &HasLiveDef) {
708  // Due to remat, it's possible this reg isn't being reused. That is,
709  // the def of this reg (by prev MI) is now dead.
710  MachineInstr *DefMI = I;
711  MachineOperand *DefOp = NULL;
712  for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
713    MachineOperand &MO = DefMI->getOperand(i);
714    if (MO.isReg() && MO.isDef()) {
715      if (MO.getReg() == Reg)
716        DefOp = &MO;
717      else if (!MO.isDead())
718        HasLiveDef = true;
719    }
720  }
721  if (!DefOp)
722    return false;
723
724  bool FoundUse = false, Done = false;
725  MachineBasicBlock::iterator E = &NewDef;
726  ++I; ++E;
727  for (; !Done && I != E; ++I) {
728    MachineInstr *NMI = I;
729    for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
730      MachineOperand &MO = NMI->getOperand(j);
731      if (!MO.isReg() || MO.getReg() != Reg)
732        continue;
733      if (MO.isUse())
734        FoundUse = true;
735      Done = true; // Stop after scanning all the operands of this MI.
736    }
737  }
738  if (!FoundUse) {
739    // Def is dead!
740    DefOp->setIsDead();
741    return true;
742  }
743  return false;
744}
745
746/// UpdateKills - Track and update kill info. If a MI reads a register that is
747/// marked kill, then it must be due to register reuse. Transfer the kill info
748/// over.
749static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
750                        std::vector<MachineOperand*> &KillOps,
751                        const TargetRegisterInfo* TRI) {
752  const TargetInstrDesc &TID = MI.getDesc();
753  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
754    MachineOperand &MO = MI.getOperand(i);
755    if (!MO.isReg() || !MO.isUse())
756      continue;
757    unsigned Reg = MO.getReg();
758    if (Reg == 0)
759      continue;
760
761    if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
762      // That can't be right. Register is killed but not re-defined and it's
763      // being reused. Let's fix that.
764      KillOps[Reg]->setIsKill(false);
765      KillOps[Reg] = NULL;
766      RegKills.reset(Reg);
767      if (i < TID.getNumOperands() &&
768          TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
769        // Unless it's a two-address operand, this is the new kill.
770        MO.setIsKill();
771    }
772    if (MO.isKill()) {
773      RegKills.set(Reg);
774      KillOps[Reg] = &MO;
775    }
776  }
777
778  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
779    const MachineOperand &MO = MI.getOperand(i);
780    if (!MO.isReg() || !MO.isDef())
781      continue;
782    unsigned Reg = MO.getReg();
783    RegKills.reset(Reg);
784    KillOps[Reg] = NULL;
785    // It also defines (or partially define) aliases.
786    for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
787      RegKills.reset(*AS);
788      KillOps[*AS] = NULL;
789    }
790  }
791}
792
793/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
794///
795static void ReMaterialize(MachineBasicBlock &MBB,
796                          MachineBasicBlock::iterator &MII,
797                          unsigned DestReg, unsigned Reg,
798                          const TargetInstrInfo *TII,
799                          const TargetRegisterInfo *TRI,
800                          VirtRegMap &VRM) {
801  TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
802  MachineInstr *NewMI = prior(MII);
803  for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
804    MachineOperand &MO = NewMI->getOperand(i);
805    if (!MO.isReg() || MO.getReg() == 0)
806      continue;
807    unsigned VirtReg = MO.getReg();
808    if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
809      continue;
810    assert(MO.isUse());
811    unsigned SubIdx = MO.getSubReg();
812    unsigned Phys = VRM.getPhys(VirtReg);
813    assert(Phys);
814    unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
815    MO.setReg(RReg);
816  }
817  ++NumReMats;
818}
819
820
821// ReusedOp - For each reused operand, we keep track of a bit of information, in
822// case we need to rollback upon processing a new operand.  See comments below.
823namespace {
824  struct ReusedOp {
825    // The MachineInstr operand that reused an available value.
826    unsigned Operand;
827
828    // StackSlotOrReMat - The spill slot or remat id of the value being reused.
829    unsigned StackSlotOrReMat;
830
831    // PhysRegReused - The physical register the value was available in.
832    unsigned PhysRegReused;
833
834    // AssignedPhysReg - The physreg that was assigned for use by the reload.
835    unsigned AssignedPhysReg;
836
837    // VirtReg - The virtual register itself.
838    unsigned VirtReg;
839
840    ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
841             unsigned vreg)
842      : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
843        AssignedPhysReg(apr), VirtReg(vreg) {}
844  };
845
846  /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
847  /// is reused instead of reloaded.
848  class VISIBILITY_HIDDEN ReuseInfo {
849    MachineInstr &MI;
850    std::vector<ReusedOp> Reuses;
851    BitVector PhysRegsClobbered;
852  public:
853    ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
854      PhysRegsClobbered.resize(tri->getNumRegs());
855    }
856
857    bool hasReuses() const {
858      return !Reuses.empty();
859    }
860
861    /// addReuse - If we choose to reuse a virtual register that is already
862    /// available instead of reloading it, remember that we did so.
863    void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
864                  unsigned PhysRegReused, unsigned AssignedPhysReg,
865                  unsigned VirtReg) {
866      // If the reload is to the assigned register anyway, no undo will be
867      // required.
868      if (PhysRegReused == AssignedPhysReg) return;
869
870      // Otherwise, remember this.
871      Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
872                                AssignedPhysReg, VirtReg));
873    }
874
875    void markClobbered(unsigned PhysReg) {
876      PhysRegsClobbered.set(PhysReg);
877    }
878
879    bool isClobbered(unsigned PhysReg) const {
880      return PhysRegsClobbered.test(PhysReg);
881    }
882
883    /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
884    /// is some other operand that is using the specified register, either pick
885    /// a new register to use, or evict the previous reload and use this reg.
886    unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
887                             AvailableSpills &Spills,
888                             std::vector<MachineInstr*> &MaybeDeadStores,
889                             SmallSet<unsigned, 8> &Rejected,
890                             BitVector &RegKills,
891                             std::vector<MachineOperand*> &KillOps,
892                             VirtRegMap &VRM) {
893      const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
894                                   .getInstrInfo();
895
896      if (Reuses.empty()) return PhysReg;  // This is most often empty.
897
898      for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
899        ReusedOp &Op = Reuses[ro];
900        // If we find some other reuse that was supposed to use this register
901        // exactly for its reload, we can change this reload to use ITS reload
902        // register. That is, unless its reload register has already been
903        // considered and subsequently rejected because it has also been reused
904        // by another operand.
905        if (Op.PhysRegReused == PhysReg &&
906            Rejected.count(Op.AssignedPhysReg) == 0) {
907          // Yup, use the reload register that we didn't use before.
908          unsigned NewReg = Op.AssignedPhysReg;
909          Rejected.insert(PhysReg);
910          return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
911                                 RegKills, KillOps, VRM);
912        } else {
913          // Otherwise, we might also have a problem if a previously reused
914          // value aliases the new register.  If so, codegen the previous reload
915          // and use this one.
916          unsigned PRRU = Op.PhysRegReused;
917          const TargetRegisterInfo *TRI = Spills.getRegInfo();
918          if (TRI->areAliases(PRRU, PhysReg)) {
919            // Okay, we found out that an alias of a reused register
920            // was used.  This isn't good because it means we have
921            // to undo a previous reuse.
922            MachineBasicBlock *MBB = MI->getParent();
923            const TargetRegisterClass *AliasRC =
924              MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
925
926            // Copy Op out of the vector and remove it, we're going to insert an
927            // explicit load for it.
928            ReusedOp NewOp = Op;
929            Reuses.erase(Reuses.begin()+ro);
930
931            // Ok, we're going to try to reload the assigned physreg into the
932            // slot that we were supposed to in the first place.  However, that
933            // register could hold a reuse.  Check to see if it conflicts or
934            // would prefer us to use a different register.
935            unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
936                                                  MI, Spills, MaybeDeadStores,
937                                              Rejected, RegKills, KillOps, VRM);
938
939            MachineBasicBlock::iterator MII = MI;
940            if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
941              ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
942            } else {
943              TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
944                                        NewOp.StackSlotOrReMat, AliasRC);
945              MachineInstr *LoadMI = prior(MII);
946              VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
947              // Any stores to this stack slot are not dead anymore.
948              MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
949              ++NumLoads;
950            }
951            Spills.ClobberPhysReg(NewPhysReg);
952            Spills.ClobberPhysReg(NewOp.PhysRegReused);
953
954            unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
955            unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
956            MI->getOperand(NewOp.Operand).setReg(RReg);
957
958            Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
959            --MII;
960            UpdateKills(*MII, RegKills, KillOps, TRI);
961            DOUT << '\t' << *MII;
962
963            DOUT << "Reuse undone!\n";
964            --NumReused;
965
966            // Finally, PhysReg is now available, go ahead and use it.
967            return PhysReg;
968          }
969        }
970      }
971      return PhysReg;
972    }
973
974    /// GetRegForReload - Helper for the above GetRegForReload(). Add a
975    /// 'Rejected' set to remember which registers have been considered and
976    /// rejected for the reload. This avoids infinite looping in case like
977    /// this:
978    /// t1 := op t2, t3
979    /// t2 <- assigned r0 for use by the reload but ended up reuse r1
980    /// t3 <- assigned r1 for use by the reload but ended up reuse r0
981    /// t1 <- desires r1
982    ///       sees r1 is taken by t2, tries t2's reload register r0
983    ///       sees r0 is taken by t3, tries t3's reload register r1
984    ///       sees r1 is taken by t2, tries t2's reload register r0 ...
985    unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
986                             AvailableSpills &Spills,
987                             std::vector<MachineInstr*> &MaybeDeadStores,
988                             BitVector &RegKills,
989                             std::vector<MachineOperand*> &KillOps,
990                             VirtRegMap &VRM) {
991      SmallSet<unsigned, 8> Rejected;
992      return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
993                             RegKills, KillOps, VRM);
994    }
995  };
996}
997
998/// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
999/// instruction. e.g.
1000///     xorl  %edi, %eax
1001///     movl  %eax, -32(%ebp)
1002///     movl  -36(%ebp), %eax
1003///     orl   %eax, -32(%ebp)
1004/// ==>
1005///     xorl  %edi, %eax
1006///     orl   -36(%ebp), %eax
1007///     mov   %eax, -32(%ebp)
1008/// This enables unfolding optimization for a subsequent instruction which will
1009/// also eliminate the newly introduced store instruction.
1010bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
1011                                    MachineBasicBlock::iterator &MII,
1012                                    std::vector<MachineInstr*> &MaybeDeadStores,
1013                                    AvailableSpills &Spills,
1014                                    BitVector &RegKills,
1015                                    std::vector<MachineOperand*> &KillOps,
1016                                    VirtRegMap &VRM) {
1017  MachineFunction &MF = *MBB.getParent();
1018  MachineInstr &MI = *MII;
1019  unsigned UnfoldedOpc = 0;
1020  unsigned UnfoldPR = 0;
1021  unsigned UnfoldVR = 0;
1022  int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1023  VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1024  for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1025    // Only transform a MI that folds a single register.
1026    if (UnfoldedOpc)
1027      return false;
1028    UnfoldVR = I->second.first;
1029    VirtRegMap::ModRef MR = I->second.second;
1030    // MI2VirtMap be can updated which invalidate the iterator.
1031    // Increment the iterator first.
1032    ++I;
1033    if (VRM.isAssignedReg(UnfoldVR))
1034      continue;
1035    // If this reference is not a use, any previous store is now dead.
1036    // Otherwise, the store to this stack slot is not dead anymore.
1037    FoldedSS = VRM.getStackSlot(UnfoldVR);
1038    MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1039    if (DeadStore && (MR & VirtRegMap::isModRef)) {
1040      unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1041      if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1042        continue;
1043      UnfoldPR = PhysReg;
1044      UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1045                                                    false, true);
1046    }
1047  }
1048
1049  if (!UnfoldedOpc)
1050    return false;
1051
1052  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1053    MachineOperand &MO = MI.getOperand(i);
1054    if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1055      continue;
1056    unsigned VirtReg = MO.getReg();
1057    if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1058      continue;
1059    if (VRM.isAssignedReg(VirtReg)) {
1060      unsigned PhysReg = VRM.getPhys(VirtReg);
1061      if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1062        return false;
1063    } else if (VRM.isReMaterialized(VirtReg))
1064      continue;
1065    int SS = VRM.getStackSlot(VirtReg);
1066    unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1067    if (PhysReg) {
1068      if (TRI->regsOverlap(PhysReg, UnfoldPR))
1069        return false;
1070      continue;
1071    }
1072    if (VRM.hasPhys(VirtReg)) {
1073      PhysReg = VRM.getPhys(VirtReg);
1074      if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1075        continue;
1076    }
1077
1078    // Ok, we'll need to reload the value into a register which makes
1079    // it impossible to perform the store unfolding optimization later.
1080    // Let's see if it is possible to fold the load if the store is
1081    // unfolded. This allows us to perform the store unfolding
1082    // optimization.
1083    SmallVector<MachineInstr*, 4> NewMIs;
1084    if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1085      assert(NewMIs.size() == 1);
1086      MachineInstr *NewMI = NewMIs.back();
1087      NewMIs.clear();
1088      int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1089      assert(Idx != -1);
1090      SmallVector<unsigned, 1> Ops;
1091      Ops.push_back(Idx);
1092      MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1093      if (FoldedMI) {
1094        VRM.addSpillSlotUse(SS, FoldedMI);
1095        if (!VRM.hasPhys(UnfoldVR))
1096          VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1097        VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1098        MII = MBB.insert(MII, FoldedMI);
1099        InvalidateKills(MI, RegKills, KillOps);
1100        VRM.RemoveMachineInstrFromMaps(&MI);
1101        MBB.erase(&MI);
1102        MF.DeleteMachineInstr(NewMI);
1103        return true;
1104      }
1105      MF.DeleteMachineInstr(NewMI);
1106    }
1107  }
1108  return false;
1109}
1110
1111/// CommuteToFoldReload -
1112/// Look for
1113/// r1 = load fi#1
1114/// r1 = op r1, r2<kill>
1115/// store r1, fi#1
1116///
1117/// If op is commutable and r2 is killed, then we can xform these to
1118/// r2 = op r2, fi#1
1119/// store r2, fi#1
1120bool LocalSpiller::CommuteToFoldReload(MachineBasicBlock &MBB,
1121                                    MachineBasicBlock::iterator &MII,
1122                                    unsigned VirtReg, unsigned SrcReg, int SS,
1123                                    AvailableSpills &Spills,
1124                                    BitVector &RegKills,
1125                                    std::vector<MachineOperand*> &KillOps,
1126                                    const TargetRegisterInfo *TRI,
1127                                    VirtRegMap &VRM) {
1128  if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1129    return false;
1130
1131  MachineFunction &MF = *MBB.getParent();
1132  MachineInstr &MI = *MII;
1133  MachineBasicBlock::iterator DefMII = prior(MII);
1134  MachineInstr *DefMI = DefMII;
1135  const TargetInstrDesc &TID = DefMI->getDesc();
1136  unsigned NewDstIdx;
1137  if (DefMII != MBB.begin() &&
1138      TID.isCommutable() &&
1139      TII->CommuteChangesDestination(DefMI, NewDstIdx)) {
1140    MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1141    unsigned NewReg = NewDstMO.getReg();
1142    if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1143      return false;
1144    MachineInstr *ReloadMI = prior(DefMII);
1145    int FrameIdx;
1146    unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1147    if (DestReg != SrcReg || FrameIdx != SS)
1148      return false;
1149    int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1150    if (UseIdx == -1)
1151      return false;
1152    int DefIdx = TID.getOperandConstraint(UseIdx, TOI::TIED_TO);
1153    if (DefIdx == -1)
1154      return false;
1155    assert(DefMI->getOperand(DefIdx).isReg() &&
1156           DefMI->getOperand(DefIdx).getReg() == SrcReg);
1157
1158    // Now commute def instruction.
1159    MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1160    if (!CommutedMI)
1161      return false;
1162    SmallVector<unsigned, 1> Ops;
1163    Ops.push_back(NewDstIdx);
1164    MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1165    // Not needed since foldMemoryOperand returns new MI.
1166    MF.DeleteMachineInstr(CommutedMI);
1167    if (!FoldedMI)
1168      return false;
1169
1170    VRM.addSpillSlotUse(SS, FoldedMI);
1171    VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1172    // Insert new def MI and spill MI.
1173    const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
1174    TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1175    MII = prior(MII);
1176    MachineInstr *StoreMI = MII;
1177    VRM.addSpillSlotUse(SS, StoreMI);
1178    VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1179    MII = MBB.insert(MII, FoldedMI);  // Update MII to backtrack.
1180
1181    // Delete all 3 old instructions.
1182    InvalidateKills(*ReloadMI, RegKills, KillOps);
1183    VRM.RemoveMachineInstrFromMaps(ReloadMI);
1184    MBB.erase(ReloadMI);
1185    InvalidateKills(*DefMI, RegKills, KillOps);
1186    VRM.RemoveMachineInstrFromMaps(DefMI);
1187    MBB.erase(DefMI);
1188    InvalidateKills(MI, RegKills, KillOps);
1189    VRM.RemoveMachineInstrFromMaps(&MI);
1190    MBB.erase(&MI);
1191
1192    // If NewReg was previously holding value of some SS, it's now clobbered.
1193    // This has to be done now because it's a physical register. When this
1194    // instruction is re-visited, it's ignored.
1195    Spills.ClobberPhysReg(NewReg);
1196
1197    ++NumCommutes;
1198    return true;
1199  }
1200
1201  return false;
1202}
1203
1204/// findSuperReg - Find the SubReg's super-register of given register class
1205/// where its SubIdx sub-register is SubReg.
1206static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
1207                             unsigned SubIdx, const TargetRegisterInfo *TRI) {
1208  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1209       I != E; ++I) {
1210    unsigned Reg = *I;
1211    if (TRI->getSubReg(Reg, SubIdx) == SubReg)
1212      return Reg;
1213  }
1214  return 0;
1215}
1216
1217/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1218/// the last store to the same slot is now dead. If so, remove the last store.
1219void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
1220                                  MachineBasicBlock::iterator &MII,
1221                                  int Idx, unsigned PhysReg, int StackSlot,
1222                                  const TargetRegisterClass *RC,
1223                                  bool isAvailable, MachineInstr *&LastStore,
1224                                  AvailableSpills &Spills,
1225                                  SmallSet<MachineInstr*, 4> &ReMatDefs,
1226                                  BitVector &RegKills,
1227                                  std::vector<MachineOperand*> &KillOps,
1228                                  VirtRegMap &VRM) {
1229  TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1230  MachineInstr *StoreMI = next(MII);
1231  VRM.addSpillSlotUse(StackSlot, StoreMI);
1232  DOUT << "Store:\t" << *StoreMI;
1233
1234  // If there is a dead store to this stack slot, nuke it now.
1235  if (LastStore) {
1236    DOUT << "Removed dead store:\t" << *LastStore;
1237    ++NumDSE;
1238    SmallVector<unsigned, 2> KillRegs;
1239    InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
1240    MachineBasicBlock::iterator PrevMII = LastStore;
1241    bool CheckDef = PrevMII != MBB.begin();
1242    if (CheckDef)
1243      --PrevMII;
1244    VRM.RemoveMachineInstrFromMaps(LastStore);
1245    MBB.erase(LastStore);
1246    if (CheckDef) {
1247      // Look at defs of killed registers on the store. Mark the defs
1248      // as dead since the store has been deleted and they aren't
1249      // being reused.
1250      for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1251        bool HasOtherDef = false;
1252        if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1253          MachineInstr *DeadDef = PrevMII;
1254          if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1255            // FIXME: This assumes a remat def does not have side
1256            // effects.
1257            VRM.RemoveMachineInstrFromMaps(DeadDef);
1258            MBB.erase(DeadDef);
1259            ++NumDRM;
1260          }
1261        }
1262      }
1263    }
1264  }
1265
1266  LastStore = next(MII);
1267
1268  // If the stack slot value was previously available in some other
1269  // register, change it now.  Otherwise, make the register available,
1270  // in PhysReg.
1271  Spills.ModifyStackSlotOrReMat(StackSlot);
1272  Spills.ClobberPhysReg(PhysReg);
1273  Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1274  ++NumStores;
1275}
1276
1277/// TransferDeadness - A identity copy definition is dead and it's being
1278/// removed. Find the last def or use and mark it as dead / kill.
1279void LocalSpiller::TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1280                                    unsigned Reg, BitVector &RegKills,
1281                                    std::vector<MachineOperand*> &KillOps) {
1282  int LastUDDist = -1;
1283  MachineInstr *LastUDMI = NULL;
1284  for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1285         RE = RegInfo->reg_end(); RI != RE; ++RI) {
1286    MachineInstr *UDMI = &*RI;
1287    if (UDMI->getParent() != MBB)
1288      continue;
1289    DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1290    if (DI == DistanceMap.end() || DI->second > CurDist)
1291      continue;
1292    if ((int)DI->second < LastUDDist)
1293      continue;
1294    LastUDDist = DI->second;
1295    LastUDMI = UDMI;
1296  }
1297
1298  if (LastUDMI) {
1299    const TargetInstrDesc &TID = LastUDMI->getDesc();
1300    MachineOperand *LastUD = NULL;
1301    for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1302      MachineOperand &MO = LastUDMI->getOperand(i);
1303      if (!MO.isReg() || MO.getReg() != Reg)
1304        continue;
1305      if (!LastUD || (LastUD->isUse() && MO.isDef()))
1306        LastUD = &MO;
1307      if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1)
1308        return;
1309    }
1310    if (LastUD->isDef())
1311      LastUD->setIsDead();
1312    else {
1313      LastUD->setIsKill();
1314      RegKills.set(Reg);
1315      KillOps[Reg] = LastUD;
1316    }
1317  }
1318}
1319
1320/// hasLaterNon2AddrUse - If the MI has another use of the specified virtual
1321/// register later and it's not a two-address, return true. That means it's
1322/// safe to mark the current use at 'i' isKill.
1323static bool hasLaterNon2AddrUse(MachineInstr &MI, unsigned i, unsigned VirtReg){
1324  const TargetInstrDesc &TID = MI.getDesc();
1325
1326  ++i;
1327  for (unsigned e = TID.getNumOperands(); i != e; ++i) {
1328    const MachineOperand &MO = MI.getOperand(i);
1329    if (!MO.isReg() || MO.getReg() != VirtReg)
1330      continue;
1331    if (TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
1332      return true;
1333  }
1334  return false;
1335}
1336
1337/// rewriteMBB - Keep track of which spills are available even after the
1338/// register allocator is done with them.  If possible, avid reloading vregs.
1339void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1340                              AvailableSpills &Spills, BitVector &RegKills,
1341                              std::vector<MachineOperand*> &KillOps) {
1342  DOUT << "\n**** Local spiller rewriting MBB '"
1343       << MBB.getBasicBlock()->getName() << ":\n";
1344
1345  MachineFunction &MF = *MBB.getParent();
1346
1347  // MaybeDeadStores - When we need to write a value back into a stack slot,
1348  // keep track of the inserted store.  If the stack slot value is never read
1349  // (because the value was used from some available register, for example), and
1350  // subsequently stored to, the original store is dead.  This map keeps track
1351  // of inserted stores that are not used.  If we see a subsequent store to the
1352  // same stack slot, the original store is deleted.
1353  std::vector<MachineInstr*> MaybeDeadStores;
1354  MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1355
1356  // ReMatDefs - These are rematerializable def MIs which are not deleted.
1357  SmallSet<MachineInstr*, 4> ReMatDefs;
1358
1359  // Clear kill info.
1360  RegKills.reset();
1361  KillOps.clear();
1362  KillOps.resize(TRI->getNumRegs(), NULL);
1363
1364  unsigned Dist = 0;
1365  DistanceMap.clear();
1366  for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1367       MII != E; ) {
1368    MachineBasicBlock::iterator NextMII = MII; ++NextMII;
1369
1370    VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1371    bool Erased = false;
1372    bool BackTracked = false;
1373    if (PrepForUnfoldOpti(MBB, MII,
1374                          MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1375      NextMII = next(MII);
1376
1377    MachineInstr &MI = *MII;
1378    const TargetInstrDesc &TID = MI.getDesc();
1379
1380    if (VRM.hasEmergencySpills(&MI)) {
1381      // Spill physical register(s) in the rare case the allocator has run out
1382      // of registers to allocate.
1383      SmallSet<int, 4> UsedSS;
1384      std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1385      for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1386        unsigned PhysReg = EmSpills[i];
1387        const TargetRegisterClass *RC =
1388          TRI->getPhysicalRegisterRegClass(PhysReg);
1389        assert(RC && "Unable to determine register class!");
1390        int SS = VRM.getEmergencySpillSlot(RC);
1391        if (UsedSS.count(SS))
1392          assert(0 && "Need to spill more than one physical registers!");
1393        UsedSS.insert(SS);
1394        TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1395        MachineInstr *StoreMI = prior(MII);
1396        VRM.addSpillSlotUse(SS, StoreMI);
1397        TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1398        MachineInstr *LoadMI = next(MII);
1399        VRM.addSpillSlotUse(SS, LoadMI);
1400        ++NumPSpills;
1401      }
1402      NextMII = next(MII);
1403    }
1404
1405    // Insert restores here if asked to.
1406    if (VRM.isRestorePt(&MI)) {
1407      std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1408      for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1409        unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1410        if (!VRM.getPreSplitReg(VirtReg))
1411          continue; // Split interval spilled again.
1412        unsigned Phys = VRM.getPhys(VirtReg);
1413        RegInfo->setPhysRegUsed(Phys);
1414
1415        // Check if the value being restored if available. If so, it must be
1416        // from a predecessor BB that fallthrough into this BB. We do not
1417        // expect:
1418        // BB1:
1419        // r1 = load fi#1
1420        // ...
1421        //    = r1<kill>
1422        // ... # r1 not clobbered
1423        // ...
1424        //    = load fi#1
1425        bool DoReMat = VRM.isReMaterialized(VirtReg);
1426        int SSorRMId = DoReMat
1427          ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1428        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1429        unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1430        if (InReg == Phys) {
1431          // If the value is already available in the expected register, save
1432          // a reload / remat.
1433          if (SSorRMId)
1434            DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1435          else
1436            DOUT << "Reusing SS#" << SSorRMId;
1437          DOUT << " from physreg "
1438               << TRI->getName(InReg) << " for vreg"
1439               << VirtReg <<" instead of reloading into physreg "
1440               << TRI->getName(Phys) << "\n";
1441          ++NumOmitted;
1442          continue;
1443        } else if (InReg && InReg != Phys) {
1444          if (SSorRMId)
1445            DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1446          else
1447            DOUT << "Reusing SS#" << SSorRMId;
1448          DOUT << " from physreg "
1449               << TRI->getName(InReg) << " for vreg"
1450               << VirtReg <<" by copying it into physreg "
1451               << TRI->getName(Phys) << "\n";
1452
1453          // If the reloaded / remat value is available in another register,
1454          // copy it to the desired register.
1455          TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1456
1457          // This invalidates Phys.
1458          Spills.ClobberPhysReg(Phys);
1459          // Remember it's available.
1460          Spills.addAvailable(SSorRMId, Phys);
1461
1462          // Mark is killed.
1463          MachineInstr *CopyMI = prior(MII);
1464          MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1465          KillOpnd->setIsKill();
1466          UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1467
1468          DOUT << '\t' << *CopyMI;
1469          ++NumCopified;
1470          continue;
1471        }
1472
1473        if (VRM.isReMaterialized(VirtReg)) {
1474          ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1475        } else {
1476          const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1477          TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1478          MachineInstr *LoadMI = prior(MII);
1479          VRM.addSpillSlotUse(SSorRMId, LoadMI);
1480          ++NumLoads;
1481        }
1482
1483        // This invalidates Phys.
1484        Spills.ClobberPhysReg(Phys);
1485        // Remember it's available.
1486        Spills.addAvailable(SSorRMId, Phys);
1487
1488        UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1489        DOUT << '\t' << *prior(MII);
1490      }
1491    }
1492
1493    // Insert spills here if asked to.
1494    if (VRM.isSpillPt(&MI)) {
1495      std::vector<std::pair<unsigned,bool> > &SpillRegs =
1496        VRM.getSpillPtSpills(&MI);
1497      for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1498        unsigned VirtReg = SpillRegs[i].first;
1499        bool isKill = SpillRegs[i].second;
1500        if (!VRM.getPreSplitReg(VirtReg))
1501          continue; // Split interval spilled again.
1502        const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1503        unsigned Phys = VRM.getPhys(VirtReg);
1504        int StackSlot = VRM.getStackSlot(VirtReg);
1505        TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1506        MachineInstr *StoreMI = next(MII);
1507        VRM.addSpillSlotUse(StackSlot, StoreMI);
1508        DOUT << "Store:\t" << *StoreMI;
1509        VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1510      }
1511      NextMII = next(MII);
1512    }
1513
1514    /// ReusedOperands - Keep track of operand reuse in case we need to undo
1515    /// reuse.
1516    ReuseInfo ReusedOperands(MI, TRI);
1517    SmallVector<unsigned, 4> VirtUseOps;
1518    for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1519      MachineOperand &MO = MI.getOperand(i);
1520      if (!MO.isReg() || MO.getReg() == 0)
1521        continue;   // Ignore non-register operands.
1522
1523      unsigned VirtReg = MO.getReg();
1524      if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1525        // Ignore physregs for spilling, but remember that it is used by this
1526        // function.
1527        RegInfo->setPhysRegUsed(VirtReg);
1528        continue;
1529      }
1530
1531      // We want to process implicit virtual register uses first.
1532      if (MO.isImplicit())
1533        // If the virtual register is implicitly defined, emit a implicit_def
1534        // before so scavenger knows it's "defined".
1535        VirtUseOps.insert(VirtUseOps.begin(), i);
1536      else
1537        VirtUseOps.push_back(i);
1538    }
1539
1540    // Process all of the spilled uses and all non spilled reg references.
1541    SmallVector<int, 2> PotentialDeadStoreSlots;
1542    for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1543      unsigned i = VirtUseOps[j];
1544      MachineOperand &MO = MI.getOperand(i);
1545      unsigned VirtReg = MO.getReg();
1546      assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1547             "Not a virtual register?");
1548
1549      unsigned SubIdx = MO.getSubReg();
1550      if (VRM.isAssignedReg(VirtReg)) {
1551        // This virtual register was assigned a physreg!
1552        unsigned Phys = VRM.getPhys(VirtReg);
1553        RegInfo->setPhysRegUsed(Phys);
1554        if (MO.isDef())
1555          ReusedOperands.markClobbered(Phys);
1556        unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1557        MI.getOperand(i).setReg(RReg);
1558        if (VRM.isImplicitlyDefined(VirtReg))
1559          BuildMI(MBB, &MI, MI.getDebugLoc(),
1560                  TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1561        continue;
1562      }
1563
1564      // This virtual register is now known to be a spilled value.
1565      if (!MO.isUse())
1566        continue;  // Handle defs in the loop below (handle use&def here though)
1567
1568      bool DoReMat = VRM.isReMaterialized(VirtReg);
1569      int SSorRMId = DoReMat
1570        ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1571      int ReuseSlot = SSorRMId;
1572
1573      // Check to see if this stack slot is available.
1574      unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1575
1576      // If this is a sub-register use, make sure the reuse register is in the
1577      // right register class. For example, for x86 not all of the 32-bit
1578      // registers have accessible sub-registers.
1579      // Similarly so for EXTRACT_SUBREG. Consider this:
1580      // EDI = op
1581      // MOV32_mr fi#1, EDI
1582      // ...
1583      //       = EXTRACT_SUBREG fi#1
1584      // fi#1 is available in EDI, but it cannot be reused because it's not in
1585      // the right register file.
1586      if (PhysReg &&
1587          (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1588        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1589        if (!RC->contains(PhysReg))
1590          PhysReg = 0;
1591      }
1592
1593      if (PhysReg) {
1594        // This spilled operand might be part of a two-address operand.  If this
1595        // is the case, then changing it will necessarily require changing the
1596        // def part of the instruction as well.  However, in some cases, we
1597        // aren't allowed to modify the reused register.  If none of these cases
1598        // apply, reuse it.
1599        bool CanReuse = true;
1600        int ti = TID.getOperandConstraint(i, TOI::TIED_TO);
1601        if (ti != -1) {
1602          // Okay, we have a two address operand.  We can reuse this physreg as
1603          // long as we are allowed to clobber the value and there isn't an
1604          // earlier def that has already clobbered the physreg.
1605          CanReuse = Spills.canClobberPhysReg(ReuseSlot) &&
1606            !ReusedOperands.isClobbered(PhysReg);
1607        }
1608
1609        if (CanReuse) {
1610          // If this stack slot value is already available, reuse it!
1611          if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1612            DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1613          else
1614            DOUT << "Reusing SS#" << ReuseSlot;
1615          DOUT << " from physreg "
1616               << TRI->getName(PhysReg) << " for vreg"
1617               << VirtReg <<" instead of reloading into physreg "
1618               << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1619          unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1620          MI.getOperand(i).setReg(RReg);
1621
1622          // The only technical detail we have is that we don't know that
1623          // PhysReg won't be clobbered by a reloaded stack slot that occurs
1624          // later in the instruction.  In particular, consider 'op V1, V2'.
1625          // If V1 is available in physreg R0, we would choose to reuse it
1626          // here, instead of reloading it into the register the allocator
1627          // indicated (say R1).  However, V2 might have to be reloaded
1628          // later, and it might indicate that it needs to live in R0.  When
1629          // this occurs, we need to have information available that
1630          // indicates it is safe to use R1 for the reload instead of R0.
1631          //
1632          // To further complicate matters, we might conflict with an alias,
1633          // or R0 and R1 might not be compatible with each other.  In this
1634          // case, we actually insert a reload for V1 in R1, ensuring that
1635          // we can get at R0 or its alias.
1636          ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1637                                  VRM.getPhys(VirtReg), VirtReg);
1638          if (ti != -1)
1639            // Only mark it clobbered if this is a use&def operand.
1640            ReusedOperands.markClobbered(PhysReg);
1641          ++NumReused;
1642
1643          if (MI.getOperand(i).isKill() &&
1644              ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1645
1646            // The store of this spilled value is potentially dead, but we
1647            // won't know for certain until we've confirmed that the re-use
1648            // above is valid, which means waiting until the other operands
1649            // are processed. For now we just track the spill slot, we'll
1650            // remove it after the other operands are processed if valid.
1651
1652            PotentialDeadStoreSlots.push_back(ReuseSlot);
1653          }
1654
1655          // Mark is isKill if it's there no other uses of the same virtual
1656          // register and it's not a two-address operand. IsKill will be
1657          // unset if reg is reused.
1658          if (ti == -1 && !hasLaterNon2AddrUse(MI, i, VirtReg))
1659            MI.getOperand(i).setIsKill();
1660          continue;
1661        }  // CanReuse
1662
1663        // Otherwise we have a situation where we have a two-address instruction
1664        // whose mod/ref operand needs to be reloaded.  This reload is already
1665        // available in some register "PhysReg", but if we used PhysReg as the
1666        // operand to our 2-addr instruction, the instruction would modify
1667        // PhysReg.  This isn't cool if something later uses PhysReg and expects
1668        // to get its initial value.
1669        //
1670        // To avoid this problem, and to avoid doing a load right after a store,
1671        // we emit a copy from PhysReg into the designated register for this
1672        // operand.
1673        unsigned DesignatedReg = VRM.getPhys(VirtReg);
1674        assert(DesignatedReg && "Must map virtreg to physreg!");
1675
1676        // Note that, if we reused a register for a previous operand, the
1677        // register we want to reload into might not actually be
1678        // available.  If this occurs, use the register indicated by the
1679        // reuser.
1680        if (ReusedOperands.hasReuses())
1681          DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1682                               Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1683
1684        // If the mapped designated register is actually the physreg we have
1685        // incoming, we don't need to inserted a dead copy.
1686        if (DesignatedReg == PhysReg) {
1687          // If this stack slot value is already available, reuse it!
1688          if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1689            DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1690          else
1691            DOUT << "Reusing SS#" << ReuseSlot;
1692          DOUT << " from physreg " << TRI->getName(PhysReg)
1693               << " for vreg" << VirtReg
1694               << " instead of reloading into same physreg.\n";
1695          unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1696          MI.getOperand(i).setReg(RReg);
1697          ReusedOperands.markClobbered(RReg);
1698          ++NumReused;
1699          continue;
1700        }
1701
1702        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1703        RegInfo->setPhysRegUsed(DesignatedReg);
1704        ReusedOperands.markClobbered(DesignatedReg);
1705        TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1706
1707        MachineInstr *CopyMI = prior(MII);
1708        UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1709
1710        // This invalidates DesignatedReg.
1711        Spills.ClobberPhysReg(DesignatedReg);
1712
1713        Spills.addAvailable(ReuseSlot, DesignatedReg);
1714        unsigned RReg =
1715          SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1716        MI.getOperand(i).setReg(RReg);
1717        DOUT << '\t' << *prior(MII);
1718        ++NumReused;
1719        continue;
1720      } // if (PhysReg)
1721
1722      // Otherwise, reload it and remember that we have it.
1723      PhysReg = VRM.getPhys(VirtReg);
1724      assert(PhysReg && "Must map virtreg to physreg!");
1725
1726      // Note that, if we reused a register for a previous operand, the
1727      // register we want to reload into might not actually be
1728      // available.  If this occurs, use the register indicated by the
1729      // reuser.
1730      if (ReusedOperands.hasReuses())
1731        PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1732                               Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1733
1734      RegInfo->setPhysRegUsed(PhysReg);
1735      ReusedOperands.markClobbered(PhysReg);
1736      if (DoReMat) {
1737        ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1738      } else {
1739        const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1740        TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1741        MachineInstr *LoadMI = prior(MII);
1742        VRM.addSpillSlotUse(SSorRMId, LoadMI);
1743        ++NumLoads;
1744      }
1745      // This invalidates PhysReg.
1746      Spills.ClobberPhysReg(PhysReg);
1747
1748      // Any stores to this stack slot are not dead anymore.
1749      if (!DoReMat)
1750        MaybeDeadStores[SSorRMId] = NULL;
1751      Spills.addAvailable(SSorRMId, PhysReg);
1752      // Assumes this is the last use. IsKill will be unset if reg is reused
1753      // unless it's a two-address operand.
1754      if (TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
1755        MI.getOperand(i).setIsKill();
1756      unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1757      MI.getOperand(i).setReg(RReg);
1758      UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1759      DOUT << '\t' << *prior(MII);
1760    }
1761
1762    // Ok - now we can remove stores that have been confirmed dead.
1763    for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1764      // This was the last use and the spilled value is still available
1765      // for reuse. That means the spill was unnecessary!
1766      int PDSSlot = PotentialDeadStoreSlots[j];
1767      MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1768      if (DeadStore) {
1769        DOUT << "Removed dead store:\t" << *DeadStore;
1770        InvalidateKills(*DeadStore, RegKills, KillOps);
1771        VRM.RemoveMachineInstrFromMaps(DeadStore);
1772        MBB.erase(DeadStore);
1773        MaybeDeadStores[PDSSlot] = NULL;
1774        ++NumDSE;
1775      }
1776    }
1777
1778
1779    DOUT << '\t' << MI;
1780
1781
1782    // If we have folded references to memory operands, make sure we clear all
1783    // physical registers that may contain the value of the spilled virtual
1784    // register
1785    SmallSet<int, 2> FoldedSS;
1786    for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1787      unsigned VirtReg = I->second.first;
1788      VirtRegMap::ModRef MR = I->second.second;
1789      DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1790
1791      // MI2VirtMap be can updated which invalidate the iterator.
1792      // Increment the iterator first.
1793      ++I;
1794      int SS = VRM.getStackSlot(VirtReg);
1795      if (SS == VirtRegMap::NO_STACK_SLOT)
1796        continue;
1797      FoldedSS.insert(SS);
1798      DOUT << " - StackSlot: " << SS << "\n";
1799
1800      // If this folded instruction is just a use, check to see if it's a
1801      // straight load from the virt reg slot.
1802      if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1803        int FrameIdx;
1804        unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1805        if (DestReg && FrameIdx == SS) {
1806          // If this spill slot is available, turn it into a copy (or nothing)
1807          // instead of leaving it as a load!
1808          if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1809            DOUT << "Promoted Load To Copy: " << MI;
1810            if (DestReg != InReg) {
1811              const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1812              TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1813              MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1814              unsigned SubIdx = DefMO->getSubReg();
1815              // Revisit the copy so we make sure to notice the effects of the
1816              // operation on the destreg (either needing to RA it if it's
1817              // virtual or needing to clobber any values if it's physical).
1818              NextMII = &MI;
1819              --NextMII;  // backtrack to the copy.
1820              // Propagate the sub-register index over.
1821              if (SubIdx) {
1822                DefMO = NextMII->findRegisterDefOperand(DestReg);
1823                DefMO->setSubReg(SubIdx);
1824              }
1825
1826              // Mark is killed.
1827              MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1828              KillOpnd->setIsKill();
1829
1830              BackTracked = true;
1831            } else {
1832              DOUT << "Removing now-noop copy: " << MI;
1833              // Unset last kill since it's being reused.
1834              InvalidateKill(InReg, RegKills, KillOps);
1835            }
1836
1837            InvalidateKills(MI, RegKills, KillOps);
1838            VRM.RemoveMachineInstrFromMaps(&MI);
1839            MBB.erase(&MI);
1840            Erased = true;
1841            goto ProcessNextInst;
1842          }
1843        } else {
1844          unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1845          SmallVector<MachineInstr*, 4> NewMIs;
1846          if (PhysReg &&
1847              TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1848            MBB.insert(MII, NewMIs[0]);
1849            InvalidateKills(MI, RegKills, KillOps);
1850            VRM.RemoveMachineInstrFromMaps(&MI);
1851            MBB.erase(&MI);
1852            Erased = true;
1853            --NextMII;  // backtrack to the unfolded instruction.
1854            BackTracked = true;
1855            goto ProcessNextInst;
1856          }
1857        }
1858      }
1859
1860      // If this reference is not a use, any previous store is now dead.
1861      // Otherwise, the store to this stack slot is not dead anymore.
1862      MachineInstr* DeadStore = MaybeDeadStores[SS];
1863      if (DeadStore) {
1864        bool isDead = !(MR & VirtRegMap::isRef);
1865        MachineInstr *NewStore = NULL;
1866        if (MR & VirtRegMap::isModRef) {
1867          unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1868          SmallVector<MachineInstr*, 4> NewMIs;
1869          // We can reuse this physreg as long as we are allowed to clobber
1870          // the value and there isn't an earlier def that has already clobbered
1871          // the physreg.
1872          if (PhysReg &&
1873              !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1874            MachineOperand *KillOpnd =
1875              DeadStore->findRegisterUseOperand(PhysReg, true);
1876            // Note, if the store is storing a sub-register, it's possible the
1877            // super-register is needed below.
1878            if (KillOpnd && !KillOpnd->getSubReg() &&
1879                TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1880             MBB.insert(MII, NewMIs[0]);
1881              NewStore = NewMIs[1];
1882              MBB.insert(MII, NewStore);
1883              VRM.addSpillSlotUse(SS, NewStore);
1884              InvalidateKills(MI, RegKills, KillOps);
1885              VRM.RemoveMachineInstrFromMaps(&MI);
1886              MBB.erase(&MI);
1887              Erased = true;
1888              --NextMII;
1889              --NextMII;  // backtrack to the unfolded instruction.
1890              BackTracked = true;
1891              isDead = true;
1892            }
1893          }
1894        }
1895
1896        if (isDead) {  // Previous store is dead.
1897          // If we get here, the store is dead, nuke it now.
1898          DOUT << "Removed dead store:\t" << *DeadStore;
1899          InvalidateKills(*DeadStore, RegKills, KillOps);
1900          VRM.RemoveMachineInstrFromMaps(DeadStore);
1901          MBB.erase(DeadStore);
1902          if (!NewStore)
1903            ++NumDSE;
1904        }
1905
1906        MaybeDeadStores[SS] = NULL;
1907        if (NewStore) {
1908          // Treat this store as a spill merged into a copy. That makes the
1909          // stack slot value available.
1910          VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1911          goto ProcessNextInst;
1912        }
1913      }
1914
1915      // If the spill slot value is available, and this is a new definition of
1916      // the value, the value is not available anymore.
1917      if (MR & VirtRegMap::isMod) {
1918        // Notice that the value in this stack slot has been modified.
1919        Spills.ModifyStackSlotOrReMat(SS);
1920
1921        // If this is *just* a mod of the value, check to see if this is just a
1922        // store to the spill slot (i.e. the spill got merged into the copy). If
1923        // so, realize that the vreg is available now, and add the store to the
1924        // MaybeDeadStore info.
1925        int StackSlot;
1926        if (!(MR & VirtRegMap::isRef)) {
1927          if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1928            assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1929                   "Src hasn't been allocated yet?");
1930
1931            if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
1932                                    Spills, RegKills, KillOps, TRI, VRM)) {
1933              NextMII = next(MII);
1934              BackTracked = true;
1935              goto ProcessNextInst;
1936            }
1937
1938            // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1939            // this as a potentially dead store in case there is a subsequent
1940            // store into the stack slot without a read from it.
1941            MaybeDeadStores[StackSlot] = &MI;
1942
1943            // If the stack slot value was previously available in some other
1944            // register, change it now.  Otherwise, make the register
1945            // available in PhysReg.
1946            Spills.addAvailable(StackSlot, SrcReg, false/*!clobber*/);
1947          }
1948        }
1949      }
1950    }
1951
1952    // Process all of the spilled defs.
1953    for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1954      MachineOperand &MO = MI.getOperand(i);
1955      if (!(MO.isReg() && MO.getReg() && MO.isDef()))
1956        continue;
1957
1958      unsigned VirtReg = MO.getReg();
1959      if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1960        // Check to see if this is a noop copy.  If so, eliminate the
1961        // instruction before considering the dest reg to be changed.
1962        unsigned Src, Dst, SrcSR, DstSR;
1963        if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1964          ++NumDCE;
1965          DOUT << "Removing now-noop copy: " << MI;
1966          SmallVector<unsigned, 2> KillRegs;
1967          InvalidateKills(MI, RegKills, KillOps, &KillRegs);
1968          if (MO.isDead() && !KillRegs.empty()) {
1969            // Source register or an implicit super/sub-register use is killed.
1970            assert(KillRegs[0] == Dst ||
1971                   TRI->isSubRegister(KillRegs[0], Dst) ||
1972                   TRI->isSuperRegister(KillRegs[0], Dst));
1973            // Last def is now dead.
1974            TransferDeadness(&MBB, Dist, Src, RegKills, KillOps);
1975          }
1976          VRM.RemoveMachineInstrFromMaps(&MI);
1977          MBB.erase(&MI);
1978          Erased = true;
1979          Spills.disallowClobberPhysReg(VirtReg);
1980          goto ProcessNextInst;
1981        }
1982
1983        // If it's not a no-op copy, it clobbers the value in the destreg.
1984        Spills.ClobberPhysReg(VirtReg);
1985        ReusedOperands.markClobbered(VirtReg);
1986
1987        // Check to see if this instruction is a load from a stack slot into
1988        // a register.  If so, this provides the stack slot value in the reg.
1989        int FrameIdx;
1990        if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1991          assert(DestReg == VirtReg && "Unknown load situation!");
1992
1993          // If it is a folded reference, then it's not safe to clobber.
1994          bool Folded = FoldedSS.count(FrameIdx);
1995          // Otherwise, if it wasn't available, remember that it is now!
1996          Spills.addAvailable(FrameIdx, DestReg, !Folded);
1997          goto ProcessNextInst;
1998        }
1999
2000        continue;
2001      }
2002
2003      unsigned SubIdx = MO.getSubReg();
2004      bool DoReMat = VRM.isReMaterialized(VirtReg);
2005      if (DoReMat)
2006        ReMatDefs.insert(&MI);
2007
2008      // The only vregs left are stack slot definitions.
2009      int StackSlot = VRM.getStackSlot(VirtReg);
2010      const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2011
2012      // If this def is part of a two-address operand, make sure to execute
2013      // the store from the correct physical register.
2014      unsigned PhysReg;
2015      int TiedOp = MI.getDesc().findTiedToSrcOperand(i);
2016      if (TiedOp != -1) {
2017        PhysReg = MI.getOperand(TiedOp).getReg();
2018        if (SubIdx) {
2019          unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2020          assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2021                 "Can't find corresponding super-register!");
2022          PhysReg = SuperReg;
2023        }
2024      } else {
2025        PhysReg = VRM.getPhys(VirtReg);
2026        if (ReusedOperands.isClobbered(PhysReg)) {
2027          // Another def has taken the assigned physreg. It must have been a
2028          // use&def which got it due to reuse. Undo the reuse!
2029          PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2030                               Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2031        }
2032      }
2033
2034      assert(PhysReg && "VR not assigned a physical register?");
2035      RegInfo->setPhysRegUsed(PhysReg);
2036      unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2037      ReusedOperands.markClobbered(RReg);
2038      MI.getOperand(i).setReg(RReg);
2039
2040      if (!MO.isDead()) {
2041        MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2042        SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2043                          LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2044        NextMII = next(MII);
2045
2046        // Check to see if this is a noop copy.  If so, eliminate the
2047        // instruction before considering the dest reg to be changed.
2048        {
2049          unsigned Src, Dst, SrcSR, DstSR;
2050          if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2051            ++NumDCE;
2052            DOUT << "Removing now-noop copy: " << MI;
2053            InvalidateKills(MI, RegKills, KillOps);
2054            VRM.RemoveMachineInstrFromMaps(&MI);
2055            MBB.erase(&MI);
2056            Erased = true;
2057            UpdateKills(*LastStore, RegKills, KillOps, TRI);
2058            goto ProcessNextInst;
2059          }
2060        }
2061      }
2062    }
2063  ProcessNextInst:
2064    DistanceMap.insert(std::make_pair(&MI, Dist++));
2065    if (!Erased && !BackTracked) {
2066      for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2067        UpdateKills(*II, RegKills, KillOps, TRI);
2068    }
2069    MII = NextMII;
2070  }
2071
2072}
2073
2074llvm::Spiller* llvm::createSpiller() {
2075  switch (SpillerOpt) {
2076  default: assert(0 && "Unreachable!");
2077  case local:
2078    return new LocalSpiller();
2079  case simple:
2080    return new SimpleSpiller();
2081  }
2082}
2083