Yet another case where the spiller marked two uses of the same register on the same...
[oota-llvm.git] / lib / CodeGen / VirtRegMap.cpp
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>
38 using namespace llvm;
39
40 STATISTIC(NumSpills  , "Number of register spills");
41 STATISTIC(NumPSpills , "Number of physical register spills");
42 STATISTIC(NumReMats  , "Number of re-materialization");
43 STATISTIC(NumDRM     , "Number of re-materializable defs elided");
44 STATISTIC(NumStores  , "Number of stores added");
45 STATISTIC(NumLoads   , "Number of loads added");
46 STATISTIC(NumReused  , "Number of values reused");
47 STATISTIC(NumDSE     , "Number of dead stores elided");
48 STATISTIC(NumDCE     , "Number of copies elided");
49 STATISTIC(NumDSS     , "Number of dead spill slots removed");
50 STATISTIC(NumCommutes, "Number of instructions commuted");
51 STATISTIC(NumOmitted , "Number of reloads omited");
52 STATISTIC(NumCopified, "Number of available reloads turned into copies");
53
54 namespace {
55   enum SpillerName { simple, local };
56 }
57
58 static cl::opt<SpillerName>
59 SpillerOpt("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
71 VirtRegMap::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
83 void 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
94 int 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
113 void 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
123 int 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
131 void 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
138 int 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
153 void 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
166 void 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
180 void 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
185 void 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
207 void 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
225 void VirtRegMap::dump() const {
226   print(cerr);
227 }
228
229
230 //===----------------------------------------------------------------------===//
231 // Simple Spiller Implementation
232 //===----------------------------------------------------------------------===//
233
234 Spiller::~Spiller() {}
235
236 namespace {
237   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
238     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
239   };
240 }
241
242 bool 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.
325 namespace {
326 class 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);
344 public:
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.
423 void 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.
440 void 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.
448 void 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.
469 void 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).
478 void 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.
498 static 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.
511 void 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.
551 static 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
561 namespace {
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.
681 static 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.
705 static 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.
749 static 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 ///
795 static 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.
823 namespace {
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.
1010 bool 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
1120 bool 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.
1206 static 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.
1219 void 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.
1279 void 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 /// rewriteMBB - Keep track of which spills are available even after the
1321 /// register allocator is done with them.  If possible, avid reloading vregs.
1322 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1323                               AvailableSpills &Spills, BitVector &RegKills,
1324                               std::vector<MachineOperand*> &KillOps) {
1325   DOUT << "\n**** Local spiller rewriting MBB '"
1326        << MBB.getBasicBlock()->getName() << ":\n";
1327
1328   MachineFunction &MF = *MBB.getParent();
1329   
1330   // MaybeDeadStores - When we need to write a value back into a stack slot,
1331   // keep track of the inserted store.  If the stack slot value is never read
1332   // (because the value was used from some available register, for example), and
1333   // subsequently stored to, the original store is dead.  This map keeps track
1334   // of inserted stores that are not used.  If we see a subsequent store to the
1335   // same stack slot, the original store is deleted.
1336   std::vector<MachineInstr*> MaybeDeadStores;
1337   MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1338
1339   // ReMatDefs - These are rematerializable def MIs which are not deleted.
1340   SmallSet<MachineInstr*, 4> ReMatDefs;
1341
1342   // Clear kill info.
1343   SmallSet<unsigned, 2> KilledMIRegs;
1344   RegKills.reset();
1345   KillOps.clear();
1346   KillOps.resize(TRI->getNumRegs(), NULL);
1347
1348   unsigned Dist = 0;
1349   DistanceMap.clear();
1350   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1351        MII != E; ) {
1352     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
1353
1354     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1355     bool Erased = false;
1356     bool BackTracked = false;
1357     if (PrepForUnfoldOpti(MBB, MII,
1358                           MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1359       NextMII = next(MII);
1360
1361     MachineInstr &MI = *MII;
1362     const TargetInstrDesc &TID = MI.getDesc();
1363
1364     if (VRM.hasEmergencySpills(&MI)) {
1365       // Spill physical register(s) in the rare case the allocator has run out
1366       // of registers to allocate.
1367       SmallSet<int, 4> UsedSS;
1368       std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1369       for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1370         unsigned PhysReg = EmSpills[i];
1371         const TargetRegisterClass *RC =
1372           TRI->getPhysicalRegisterRegClass(PhysReg);
1373         assert(RC && "Unable to determine register class!");
1374         int SS = VRM.getEmergencySpillSlot(RC);
1375         if (UsedSS.count(SS))
1376           assert(0 && "Need to spill more than one physical registers!");
1377         UsedSS.insert(SS);
1378         TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1379         MachineInstr *StoreMI = prior(MII);
1380         VRM.addSpillSlotUse(SS, StoreMI);
1381         TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1382         MachineInstr *LoadMI = next(MII);
1383         VRM.addSpillSlotUse(SS, LoadMI);
1384         ++NumPSpills;
1385       }
1386       NextMII = next(MII);
1387     }
1388
1389     // Insert restores here if asked to.
1390     if (VRM.isRestorePt(&MI)) {
1391       std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1392       for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1393         unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1394         if (!VRM.getPreSplitReg(VirtReg))
1395           continue; // Split interval spilled again.
1396         unsigned Phys = VRM.getPhys(VirtReg);
1397         RegInfo->setPhysRegUsed(Phys);
1398
1399         // Check if the value being restored if available. If so, it must be
1400         // from a predecessor BB that fallthrough into this BB. We do not
1401         // expect:
1402         // BB1:
1403         // r1 = load fi#1
1404         // ...
1405         //    = r1<kill>
1406         // ... # r1 not clobbered
1407         // ...
1408         //    = load fi#1
1409         bool DoReMat = VRM.isReMaterialized(VirtReg);
1410         int SSorRMId = DoReMat
1411           ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1412         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1413         unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1414         if (InReg == Phys) {
1415           // If the value is already available in the expected register, save
1416           // a reload / remat.
1417           if (SSorRMId)
1418             DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1419           else
1420             DOUT << "Reusing SS#" << SSorRMId;
1421           DOUT << " from physreg "
1422                << TRI->getName(InReg) << " for vreg"
1423                << VirtReg <<" instead of reloading into physreg "
1424                << TRI->getName(Phys) << "\n";
1425           ++NumOmitted;
1426           continue;
1427         } else if (InReg && InReg != Phys) {
1428           if (SSorRMId)
1429             DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1430           else
1431             DOUT << "Reusing SS#" << SSorRMId;
1432           DOUT << " from physreg "
1433                << TRI->getName(InReg) << " for vreg"
1434                << VirtReg <<" by copying it into physreg "
1435                << TRI->getName(Phys) << "\n";
1436
1437           // If the reloaded / remat value is available in another register,
1438           // copy it to the desired register.
1439           TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1440
1441           // This invalidates Phys.
1442           Spills.ClobberPhysReg(Phys);
1443           // Remember it's available.
1444           Spills.addAvailable(SSorRMId, Phys);
1445
1446           // Mark is killed.
1447           MachineInstr *CopyMI = prior(MII);
1448           MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1449           KillOpnd->setIsKill();
1450           UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1451
1452           DOUT << '\t' << *CopyMI;
1453           ++NumCopified;
1454           continue;
1455         }
1456
1457         if (VRM.isReMaterialized(VirtReg)) {
1458           ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1459         } else {
1460           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1461           TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1462           MachineInstr *LoadMI = prior(MII);
1463           VRM.addSpillSlotUse(SSorRMId, LoadMI);
1464           ++NumLoads;
1465         }
1466
1467         // This invalidates Phys.
1468         Spills.ClobberPhysReg(Phys);
1469         // Remember it's available.
1470         Spills.addAvailable(SSorRMId, Phys);
1471
1472         UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1473         DOUT << '\t' << *prior(MII);
1474       }
1475     }
1476
1477     // Insert spills here if asked to.
1478     if (VRM.isSpillPt(&MI)) {
1479       std::vector<std::pair<unsigned,bool> > &SpillRegs =
1480         VRM.getSpillPtSpills(&MI);
1481       for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1482         unsigned VirtReg = SpillRegs[i].first;
1483         bool isKill = SpillRegs[i].second;
1484         if (!VRM.getPreSplitReg(VirtReg))
1485           continue; // Split interval spilled again.
1486         const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1487         unsigned Phys = VRM.getPhys(VirtReg);
1488         int StackSlot = VRM.getStackSlot(VirtReg);
1489         TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1490         MachineInstr *StoreMI = next(MII);
1491         VRM.addSpillSlotUse(StackSlot, StoreMI);
1492         DOUT << "Store:\t" << *StoreMI;
1493         VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1494       }
1495       NextMII = next(MII);
1496     }
1497
1498     /// ReusedOperands - Keep track of operand reuse in case we need to undo
1499     /// reuse.
1500     ReuseInfo ReusedOperands(MI, TRI);
1501     SmallVector<unsigned, 4> VirtUseOps;
1502     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1503       MachineOperand &MO = MI.getOperand(i);
1504       if (!MO.isReg() || MO.getReg() == 0)
1505         continue;   // Ignore non-register operands.
1506       
1507       unsigned VirtReg = MO.getReg();
1508       if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1509         // Ignore physregs for spilling, but remember that it is used by this
1510         // function.
1511         RegInfo->setPhysRegUsed(VirtReg);
1512         continue;
1513       }
1514
1515       // We want to process implicit virtual register uses first.
1516       if (MO.isImplicit())
1517         // If the virtual register is implicitly defined, emit a implicit_def
1518         // before so scavenger knows it's "defined".
1519         VirtUseOps.insert(VirtUseOps.begin(), i);
1520       else
1521         VirtUseOps.push_back(i);
1522     }
1523
1524     // Process all of the spilled uses and all non spilled reg references.
1525     SmallVector<int, 2> PotentialDeadStoreSlots;
1526     KilledMIRegs.clear();
1527     for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1528       unsigned i = VirtUseOps[j];
1529       MachineOperand &MO = MI.getOperand(i);
1530       unsigned VirtReg = MO.getReg();
1531       assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1532              "Not a virtual register?");
1533
1534       unsigned SubIdx = MO.getSubReg();
1535       if (VRM.isAssignedReg(VirtReg)) {
1536         // This virtual register was assigned a physreg!
1537         unsigned Phys = VRM.getPhys(VirtReg);
1538         RegInfo->setPhysRegUsed(Phys);
1539         if (MO.isDef())
1540           ReusedOperands.markClobbered(Phys);
1541         unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1542         MI.getOperand(i).setReg(RReg);
1543         if (VRM.isImplicitlyDefined(VirtReg))
1544           BuildMI(MBB, &MI, MI.getDebugLoc(),
1545                   TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1546         continue;
1547       }
1548       
1549       // This virtual register is now known to be a spilled value.
1550       if (!MO.isUse())
1551         continue;  // Handle defs in the loop below (handle use&def here though)
1552
1553       bool DoReMat = VRM.isReMaterialized(VirtReg);
1554       int SSorRMId = DoReMat
1555         ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1556       int ReuseSlot = SSorRMId;
1557
1558       // Check to see if this stack slot is available.
1559       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1560
1561       // If this is a sub-register use, make sure the reuse register is in the
1562       // right register class. For example, for x86 not all of the 32-bit
1563       // registers have accessible sub-registers.
1564       // Similarly so for EXTRACT_SUBREG. Consider this:
1565       // EDI = op
1566       // MOV32_mr fi#1, EDI
1567       // ...
1568       //       = EXTRACT_SUBREG fi#1
1569       // fi#1 is available in EDI, but it cannot be reused because it's not in
1570       // the right register file.
1571       if (PhysReg &&
1572           (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1573         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1574         if (!RC->contains(PhysReg))
1575           PhysReg = 0;
1576       }
1577
1578       if (PhysReg) {
1579         // This spilled operand might be part of a two-address operand.  If this
1580         // is the case, then changing it will necessarily require changing the 
1581         // def part of the instruction as well.  However, in some cases, we
1582         // aren't allowed to modify the reused register.  If none of these cases
1583         // apply, reuse it.
1584         bool CanReuse = true;
1585         int ti = TID.getOperandConstraint(i, TOI::TIED_TO);
1586         if (ti != -1) {
1587           // Okay, we have a two address operand.  We can reuse this physreg as
1588           // long as we are allowed to clobber the value and there isn't an
1589           // earlier def that has already clobbered the physreg.
1590           CanReuse = Spills.canClobberPhysReg(ReuseSlot) &&
1591             !ReusedOperands.isClobbered(PhysReg);
1592         }
1593         
1594         if (CanReuse) {
1595           // If this stack slot value is already available, reuse it!
1596           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1597             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1598           else
1599             DOUT << "Reusing SS#" << ReuseSlot;
1600           DOUT << " from physreg "
1601                << TRI->getName(PhysReg) << " for vreg"
1602                << VirtReg <<" instead of reloading into physreg "
1603                << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1604           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1605           MI.getOperand(i).setReg(RReg);
1606
1607           // The only technical detail we have is that we don't know that
1608           // PhysReg won't be clobbered by a reloaded stack slot that occurs
1609           // later in the instruction.  In particular, consider 'op V1, V2'.
1610           // If V1 is available in physreg R0, we would choose to reuse it
1611           // here, instead of reloading it into the register the allocator
1612           // indicated (say R1).  However, V2 might have to be reloaded
1613           // later, and it might indicate that it needs to live in R0.  When
1614           // this occurs, we need to have information available that
1615           // indicates it is safe to use R1 for the reload instead of R0.
1616           //
1617           // To further complicate matters, we might conflict with an alias,
1618           // or R0 and R1 might not be compatible with each other.  In this
1619           // case, we actually insert a reload for V1 in R1, ensuring that
1620           // we can get at R0 or its alias.
1621           ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1622                                   VRM.getPhys(VirtReg), VirtReg);
1623           if (ti != -1)
1624             // Only mark it clobbered if this is a use&def operand.
1625             ReusedOperands.markClobbered(PhysReg);
1626           ++NumReused;
1627
1628           if (MI.getOperand(i).isKill() &&
1629               ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1630
1631             // The store of this spilled value is potentially dead, but we
1632             // won't know for certain until we've confirmed that the re-use
1633             // above is valid, which means waiting until the other operands
1634             // are processed. For now we just track the spill slot, we'll
1635             // remove it after the other operands are processed if valid.
1636
1637             PotentialDeadStoreSlots.push_back(ReuseSlot);
1638           }
1639
1640           // Mark is isKill if it's there no other uses of the same virtual
1641           // register and it's not a two-address operand. IsKill will be
1642           // unset if reg is reused.
1643           if (ti == -1 && KilledMIRegs.count(VirtReg) == 0) {
1644             MI.getOperand(i).setIsKill();
1645             KilledMIRegs.insert(VirtReg);
1646           }
1647
1648           continue;
1649         }  // CanReuse
1650         
1651         // Otherwise we have a situation where we have a two-address instruction
1652         // whose mod/ref operand needs to be reloaded.  This reload is already
1653         // available in some register "PhysReg", but if we used PhysReg as the
1654         // operand to our 2-addr instruction, the instruction would modify
1655         // PhysReg.  This isn't cool if something later uses PhysReg and expects
1656         // to get its initial value.
1657         //
1658         // To avoid this problem, and to avoid doing a load right after a store,
1659         // we emit a copy from PhysReg into the designated register for this
1660         // operand.
1661         unsigned DesignatedReg = VRM.getPhys(VirtReg);
1662         assert(DesignatedReg && "Must map virtreg to physreg!");
1663
1664         // Note that, if we reused a register for a previous operand, the
1665         // register we want to reload into might not actually be
1666         // available.  If this occurs, use the register indicated by the
1667         // reuser.
1668         if (ReusedOperands.hasReuses())
1669           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
1670                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1671         
1672         // If the mapped designated register is actually the physreg we have
1673         // incoming, we don't need to inserted a dead copy.
1674         if (DesignatedReg == PhysReg) {
1675           // If this stack slot value is already available, reuse it!
1676           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1677             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1678           else
1679             DOUT << "Reusing SS#" << ReuseSlot;
1680           DOUT << " from physreg " << TRI->getName(PhysReg)
1681                << " for vreg" << VirtReg
1682                << " instead of reloading into same physreg.\n";
1683           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1684           MI.getOperand(i).setReg(RReg);
1685           ReusedOperands.markClobbered(RReg);
1686           ++NumReused;
1687           continue;
1688         }
1689         
1690         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1691         RegInfo->setPhysRegUsed(DesignatedReg);
1692         ReusedOperands.markClobbered(DesignatedReg);
1693         TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1694
1695         MachineInstr *CopyMI = prior(MII);
1696         UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1697
1698         // This invalidates DesignatedReg.
1699         Spills.ClobberPhysReg(DesignatedReg);
1700         
1701         Spills.addAvailable(ReuseSlot, DesignatedReg);
1702         unsigned RReg =
1703           SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1704         MI.getOperand(i).setReg(RReg);
1705         DOUT << '\t' << *prior(MII);
1706         ++NumReused;
1707         continue;
1708       } // if (PhysReg)
1709       
1710       // Otherwise, reload it and remember that we have it.
1711       PhysReg = VRM.getPhys(VirtReg);
1712       assert(PhysReg && "Must map virtreg to physreg!");
1713
1714       // Note that, if we reused a register for a previous operand, the
1715       // register we want to reload into might not actually be
1716       // available.  If this occurs, use the register indicated by the
1717       // reuser.
1718       if (ReusedOperands.hasReuses())
1719         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1720                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1721       
1722       RegInfo->setPhysRegUsed(PhysReg);
1723       ReusedOperands.markClobbered(PhysReg);
1724       if (DoReMat) {
1725         ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1726       } else {
1727         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1728         TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1729         MachineInstr *LoadMI = prior(MII);
1730         VRM.addSpillSlotUse(SSorRMId, LoadMI);
1731         ++NumLoads;
1732       }
1733       // This invalidates PhysReg.
1734       Spills.ClobberPhysReg(PhysReg);
1735
1736       // Any stores to this stack slot are not dead anymore.
1737       if (!DoReMat)
1738         MaybeDeadStores[SSorRMId] = NULL;
1739       Spills.addAvailable(SSorRMId, PhysReg);
1740       // Assumes this is the last use. IsKill will be unset if reg is reused
1741       // unless it's a two-address operand.
1742       if (TID.getOperandConstraint(i, TOI::TIED_TO) == -1 &&
1743           KilledMIRegs.count(VirtReg) == 0) {
1744         MI.getOperand(i).setIsKill();
1745         KilledMIRegs.insert(VirtReg);
1746       }
1747       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1748       MI.getOperand(i).setReg(RReg);
1749       UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1750       DOUT << '\t' << *prior(MII);
1751     }
1752
1753     // Ok - now we can remove stores that have been confirmed dead.
1754     for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1755       // This was the last use and the spilled value is still available
1756       // for reuse. That means the spill was unnecessary!
1757       int PDSSlot = PotentialDeadStoreSlots[j];
1758       MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1759       if (DeadStore) {
1760         DOUT << "Removed dead store:\t" << *DeadStore;
1761         InvalidateKills(*DeadStore, RegKills, KillOps);
1762         VRM.RemoveMachineInstrFromMaps(DeadStore);
1763         MBB.erase(DeadStore);
1764         MaybeDeadStores[PDSSlot] = NULL;
1765         ++NumDSE;
1766       }
1767     }
1768
1769
1770     DOUT << '\t' << MI;
1771
1772
1773     // If we have folded references to memory operands, make sure we clear all
1774     // physical registers that may contain the value of the spilled virtual
1775     // register
1776     SmallSet<int, 2> FoldedSS;
1777     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1778       unsigned VirtReg = I->second.first;
1779       VirtRegMap::ModRef MR = I->second.second;
1780       DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1781
1782       // MI2VirtMap be can updated which invalidate the iterator.
1783       // Increment the iterator first.
1784       ++I;
1785       int SS = VRM.getStackSlot(VirtReg);
1786       if (SS == VirtRegMap::NO_STACK_SLOT)
1787         continue;
1788       FoldedSS.insert(SS);
1789       DOUT << " - StackSlot: " << SS << "\n";
1790       
1791       // If this folded instruction is just a use, check to see if it's a
1792       // straight load from the virt reg slot.
1793       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1794         int FrameIdx;
1795         unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1796         if (DestReg && FrameIdx == SS) {
1797           // If this spill slot is available, turn it into a copy (or nothing)
1798           // instead of leaving it as a load!
1799           if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1800             DOUT << "Promoted Load To Copy: " << MI;
1801             if (DestReg != InReg) {
1802               const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1803               TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1804               MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1805               unsigned SubIdx = DefMO->getSubReg();
1806               // Revisit the copy so we make sure to notice the effects of the
1807               // operation on the destreg (either needing to RA it if it's 
1808               // virtual or needing to clobber any values if it's physical).
1809               NextMII = &MI;
1810               --NextMII;  // backtrack to the copy.
1811               // Propagate the sub-register index over.
1812               if (SubIdx) {
1813                 DefMO = NextMII->findRegisterDefOperand(DestReg);
1814                 DefMO->setSubReg(SubIdx);
1815               }
1816
1817               // Mark is killed.
1818               MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1819               KillOpnd->setIsKill();
1820
1821               BackTracked = true;
1822             } else {
1823               DOUT << "Removing now-noop copy: " << MI;
1824               // Unset last kill since it's being reused.
1825               InvalidateKill(InReg, RegKills, KillOps);
1826             }
1827
1828             InvalidateKills(MI, RegKills, KillOps);
1829             VRM.RemoveMachineInstrFromMaps(&MI);
1830             MBB.erase(&MI);
1831             Erased = true;
1832             goto ProcessNextInst;
1833           }
1834         } else {
1835           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1836           SmallVector<MachineInstr*, 4> NewMIs;
1837           if (PhysReg &&
1838               TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1839             MBB.insert(MII, NewMIs[0]);
1840             InvalidateKills(MI, RegKills, KillOps);
1841             VRM.RemoveMachineInstrFromMaps(&MI);
1842             MBB.erase(&MI);
1843             Erased = true;
1844             --NextMII;  // backtrack to the unfolded instruction.
1845             BackTracked = true;
1846             goto ProcessNextInst;
1847           }
1848         }
1849       }
1850
1851       // If this reference is not a use, any previous store is now dead.
1852       // Otherwise, the store to this stack slot is not dead anymore.
1853       MachineInstr* DeadStore = MaybeDeadStores[SS];
1854       if (DeadStore) {
1855         bool isDead = !(MR & VirtRegMap::isRef);
1856         MachineInstr *NewStore = NULL;
1857         if (MR & VirtRegMap::isModRef) {
1858           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1859           SmallVector<MachineInstr*, 4> NewMIs;
1860           // We can reuse this physreg as long as we are allowed to clobber
1861           // the value and there isn't an earlier def that has already clobbered
1862           // the physreg.
1863           if (PhysReg &&
1864               !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1865             MachineOperand *KillOpnd =
1866               DeadStore->findRegisterUseOperand(PhysReg, true);
1867             // Note, if the store is storing a sub-register, it's possible the
1868             // super-register is needed below.
1869             if (KillOpnd && !KillOpnd->getSubReg() &&
1870                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1871              MBB.insert(MII, NewMIs[0]);
1872               NewStore = NewMIs[1];
1873               MBB.insert(MII, NewStore);
1874               VRM.addSpillSlotUse(SS, NewStore);
1875               InvalidateKills(MI, RegKills, KillOps);
1876               VRM.RemoveMachineInstrFromMaps(&MI);
1877               MBB.erase(&MI);
1878               Erased = true;
1879               --NextMII;
1880               --NextMII;  // backtrack to the unfolded instruction.
1881               BackTracked = true;
1882               isDead = true;
1883             }
1884           }
1885         }
1886
1887         if (isDead) {  // Previous store is dead.
1888           // If we get here, the store is dead, nuke it now.
1889           DOUT << "Removed dead store:\t" << *DeadStore;
1890           InvalidateKills(*DeadStore, RegKills, KillOps);
1891           VRM.RemoveMachineInstrFromMaps(DeadStore);
1892           MBB.erase(DeadStore);
1893           if (!NewStore)
1894             ++NumDSE;
1895         }
1896
1897         MaybeDeadStores[SS] = NULL;
1898         if (NewStore) {
1899           // Treat this store as a spill merged into a copy. That makes the
1900           // stack slot value available.
1901           VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1902           goto ProcessNextInst;
1903         }
1904       }
1905
1906       // If the spill slot value is available, and this is a new definition of
1907       // the value, the value is not available anymore.
1908       if (MR & VirtRegMap::isMod) {
1909         // Notice that the value in this stack slot has been modified.
1910         Spills.ModifyStackSlotOrReMat(SS);
1911         
1912         // If this is *just* a mod of the value, check to see if this is just a
1913         // store to the spill slot (i.e. the spill got merged into the copy). If
1914         // so, realize that the vreg is available now, and add the store to the
1915         // MaybeDeadStore info.
1916         int StackSlot;
1917         if (!(MR & VirtRegMap::isRef)) {
1918           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1919             assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1920                    "Src hasn't been allocated yet?");
1921
1922             if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
1923                                     Spills, RegKills, KillOps, TRI, VRM)) {
1924               NextMII = next(MII);
1925               BackTracked = true;
1926               goto ProcessNextInst;
1927             }
1928
1929             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1930             // this as a potentially dead store in case there is a subsequent
1931             // store into the stack slot without a read from it.
1932             MaybeDeadStores[StackSlot] = &MI;
1933
1934             // If the stack slot value was previously available in some other
1935             // register, change it now.  Otherwise, make the register
1936             // available in PhysReg.
1937             Spills.addAvailable(StackSlot, SrcReg, false/*!clobber*/);
1938           }
1939         }
1940       }
1941     }
1942
1943     // Process all of the spilled defs.
1944     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1945       MachineOperand &MO = MI.getOperand(i);
1946       if (!(MO.isReg() && MO.getReg() && MO.isDef()))
1947         continue;
1948
1949       unsigned VirtReg = MO.getReg();
1950       if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1951         // Check to see if this is a noop copy.  If so, eliminate the
1952         // instruction before considering the dest reg to be changed.
1953         unsigned Src, Dst, SrcSR, DstSR;
1954         if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1955           ++NumDCE;
1956           DOUT << "Removing now-noop copy: " << MI;
1957           SmallVector<unsigned, 2> KillRegs;
1958           InvalidateKills(MI, RegKills, KillOps, &KillRegs);
1959           if (MO.isDead() && !KillRegs.empty()) {
1960             // Source register or an implicit super/sub-register use is killed.
1961             assert(KillRegs[0] == Dst ||
1962                    TRI->isSubRegister(KillRegs[0], Dst) ||
1963                    TRI->isSuperRegister(KillRegs[0], Dst));
1964             // Last def is now dead.
1965             TransferDeadness(&MBB, Dist, Src, RegKills, KillOps);
1966           }
1967           VRM.RemoveMachineInstrFromMaps(&MI);
1968           MBB.erase(&MI);
1969           Erased = true;
1970           Spills.disallowClobberPhysReg(VirtReg);
1971           goto ProcessNextInst;
1972         }
1973           
1974         // If it's not a no-op copy, it clobbers the value in the destreg.
1975         Spills.ClobberPhysReg(VirtReg);
1976         ReusedOperands.markClobbered(VirtReg);
1977  
1978         // Check to see if this instruction is a load from a stack slot into
1979         // a register.  If so, this provides the stack slot value in the reg.
1980         int FrameIdx;
1981         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1982           assert(DestReg == VirtReg && "Unknown load situation!");
1983
1984           // If it is a folded reference, then it's not safe to clobber.
1985           bool Folded = FoldedSS.count(FrameIdx);
1986           // Otherwise, if it wasn't available, remember that it is now!
1987           Spills.addAvailable(FrameIdx, DestReg, !Folded);
1988           goto ProcessNextInst;
1989         }
1990             
1991         continue;
1992       }
1993
1994       unsigned SubIdx = MO.getSubReg();
1995       bool DoReMat = VRM.isReMaterialized(VirtReg);
1996       if (DoReMat)
1997         ReMatDefs.insert(&MI);
1998
1999       // The only vregs left are stack slot definitions.
2000       int StackSlot = VRM.getStackSlot(VirtReg);
2001       const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2002
2003       // If this def is part of a two-address operand, make sure to execute
2004       // the store from the correct physical register.
2005       unsigned PhysReg;
2006       int TiedOp = MI.getDesc().findTiedToSrcOperand(i);
2007       if (TiedOp != -1) {
2008         PhysReg = MI.getOperand(TiedOp).getReg();
2009         if (SubIdx) {
2010           unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2011           assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2012                  "Can't find corresponding super-register!");
2013           PhysReg = SuperReg;
2014         }
2015       } else {
2016         PhysReg = VRM.getPhys(VirtReg);
2017         if (ReusedOperands.isClobbered(PhysReg)) {
2018           // Another def has taken the assigned physreg. It must have been a
2019           // use&def which got it due to reuse. Undo the reuse!
2020           PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
2021                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2022         }
2023       }
2024
2025       assert(PhysReg && "VR not assigned a physical register?");
2026       RegInfo->setPhysRegUsed(PhysReg);
2027       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2028       ReusedOperands.markClobbered(RReg);
2029       MI.getOperand(i).setReg(RReg);
2030
2031       if (!MO.isDead()) {
2032         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2033         SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2034                           LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2035         NextMII = next(MII);
2036
2037         // Check to see if this is a noop copy.  If so, eliminate the
2038         // instruction before considering the dest reg to be changed.
2039         {
2040           unsigned Src, Dst, SrcSR, DstSR;
2041           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2042             ++NumDCE;
2043             DOUT << "Removing now-noop copy: " << MI;
2044             InvalidateKills(MI, RegKills, KillOps);
2045             VRM.RemoveMachineInstrFromMaps(&MI);
2046             MBB.erase(&MI);
2047             Erased = true;
2048             UpdateKills(*LastStore, RegKills, KillOps, TRI);
2049             goto ProcessNextInst;
2050           }
2051         }
2052       }    
2053     }
2054   ProcessNextInst:
2055     DistanceMap.insert(std::make_pair(&MI, Dist++));
2056     if (!Erased && !BackTracked) {
2057       for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2058         UpdateKills(*II, RegKills, KillOps, TRI);
2059     }
2060     MII = NextMII;
2061   }
2062
2063 }
2064
2065 llvm::Spiller* llvm::createSpiller() {
2066   switch (SpillerOpt) {
2067   default: assert(0 && "Unreachable!");
2068   case local:
2069     return new LocalSpiller();
2070   case simple:
2071     return new SimpleSpiller();
2072   }
2073 }