1 //===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "virtregrewriter"
11 #include "VirtRegRewriter.h"
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/ADT/DepthFirstIterator.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/ADT/STLExtras.h"
19 STATISTIC(NumDSE , "Number of dead stores elided");
20 STATISTIC(NumDSS , "Number of dead spill slots removed");
21 STATISTIC(NumCommutes, "Number of instructions commuted");
22 STATISTIC(NumDRM , "Number of re-materializable defs elided");
23 STATISTIC(NumStores , "Number of stores added");
24 STATISTIC(NumPSpills , "Number of physical register spills");
25 STATISTIC(NumOmitted , "Number of reloads omited");
26 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
27 STATISTIC(NumCopified, "Number of available reloads turned into copies");
28 STATISTIC(NumReMats , "Number of re-materialization");
29 STATISTIC(NumLoads , "Number of loads added");
30 STATISTIC(NumReused , "Number of values reused");
31 STATISTIC(NumDCE , "Number of copies elided");
32 STATISTIC(NumSUnfold , "Number of stores unfolded");
33 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
36 enum RewriterName { simple, local };
39 static cl::opt<RewriterName>
40 RewriterOpt("rewriter",
41 cl::desc("Rewriter to use: (default: local)"),
43 cl::values(clEnumVal(simple, "simple rewriter"),
44 clEnumVal(local, "local rewriter"),
48 VirtRegRewriter::~VirtRegRewriter() {}
51 // ****************************** //
52 // Simple Spiller Implementation //
53 // ****************************** //
55 struct VISIBILITY_HIDDEN SimpleRewriter : public VirtRegRewriter {
57 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
59 DOUT << "********** REWRITE MACHINE CODE **********\n";
60 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
61 const TargetMachine &TM = MF.getTarget();
62 const TargetInstrInfo &TII = *TM.getInstrInfo();
63 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
66 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
67 // each vreg once (in the case where a spilled vreg is used by multiple
68 // operands). This is always smaller than the number of operands to the
69 // current machine instr, so it should be small.
70 std::vector<unsigned> LoadedRegs;
72 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
74 DOUT << MBBI->getBasicBlock()->getName() << ":\n";
75 MachineBasicBlock &MBB = *MBBI;
76 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
78 MachineInstr &MI = *MII;
79 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
80 MachineOperand &MO = MI.getOperand(i);
81 if (MO.isReg() && MO.getReg()) {
82 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
83 unsigned VirtReg = MO.getReg();
84 unsigned SubIdx = MO.getSubReg();
85 unsigned PhysReg = VRM.getPhys(VirtReg);
86 unsigned RReg = SubIdx ? TRI.getSubReg(PhysReg, SubIdx) : PhysReg;
87 if (!VRM.isAssignedReg(VirtReg)) {
88 int StackSlot = VRM.getStackSlot(VirtReg);
89 const TargetRegisterClass* RC =
90 MF.getRegInfo().getRegClass(VirtReg);
93 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
94 == LoadedRegs.end()) {
95 TII.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
96 MachineInstr *LoadMI = prior(MII);
97 VRM.addSpillSlotUse(StackSlot, LoadMI);
98 LoadedRegs.push_back(VirtReg);
100 DOUT << '\t' << *LoadMI;
104 TII.storeRegToStackSlot(MBB, next(MII), PhysReg, true,
106 MachineInstr *StoreMI = next(MII);
107 VRM.addSpillSlotUse(StackSlot, StoreMI);
111 MF.getRegInfo().setPhysRegUsed(RReg);
112 MI.getOperand(i).setReg(RReg);
113 MI.getOperand(i).setSubReg(0);
115 MF.getRegInfo().setPhysRegUsed(MO.getReg());
129 // ************************************************************************ //
131 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
132 /// from top down, keep track of which spill slots or remat are available in
135 /// Note that not all physregs are created equal here. In particular, some
136 /// physregs are reloads that we are allowed to clobber or ignore at any time.
137 /// Other physregs are values that the register allocated program is using
138 /// that we cannot CHANGE, but we can read if we like. We keep track of this
139 /// on a per-stack-slot / remat id basis as the low bit in the value of the
140 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
141 /// this bit and addAvailable sets it if.
142 class VISIBILITY_HIDDEN AvailableSpills {
143 const TargetRegisterInfo *TRI;
144 const TargetInstrInfo *TII;
146 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
147 // or remat'ed virtual register values that are still available, due to
148 // being loaded or stored to, but not invalidated yet.
149 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
151 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
152 // indicating which stack slot values are currently held by a physreg. This
153 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
154 // physreg is modified.
155 std::multimap<unsigned, int> PhysRegsAvailable;
157 void disallowClobberPhysRegOnly(unsigned PhysReg);
159 void ClobberPhysRegOnly(unsigned PhysReg);
161 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
162 : TRI(tri), TII(tii) {
165 /// clear - Reset the state.
167 SpillSlotsOrReMatsAvailable.clear();
168 PhysRegsAvailable.clear();
171 const TargetRegisterInfo *getRegInfo() const { return TRI; }
173 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
174 /// available in a physical register, return that PhysReg, otherwise
176 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
177 std::map<int, unsigned>::const_iterator I =
178 SpillSlotsOrReMatsAvailable.find(Slot);
179 if (I != SpillSlotsOrReMatsAvailable.end()) {
180 return I->second >> 1; // Remove the CanClobber bit.
185 /// addAvailable - Mark that the specified stack slot / remat is available
186 /// in the specified physreg. If CanClobber is true, the physreg can be
187 /// modified at any time without changing the semantics of the program.
188 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
189 // If this stack slot is thought to be available in some other physreg,
190 // remove its record.
191 ModifyStackSlotOrReMat(SlotOrReMat);
193 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
194 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
195 (unsigned)CanClobber;
197 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
198 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
200 DOUT << "Remembering SS#" << SlotOrReMat;
201 DOUT << " in physreg " << TRI->getName(Reg) << "\n";
204 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
205 /// the value of the specified stackslot register if it desires. The
206 /// specified stack slot must be available in a physreg for this query to
208 bool canClobberPhysRegForSS(int SlotOrReMat) const {
209 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
210 "Value not available!");
211 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
214 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
215 /// physical register where values for some stack slot(s) might be
217 bool canClobberPhysReg(unsigned PhysReg) const {
218 std::multimap<unsigned, int>::const_iterator I =
219 PhysRegsAvailable.lower_bound(PhysReg);
220 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
221 int SlotOrReMat = I->second;
223 if (!canClobberPhysRegForSS(SlotOrReMat))
229 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
230 /// stackslot register. The register is still available but is no longer
231 /// allowed to be modifed.
232 void disallowClobberPhysReg(unsigned PhysReg);
234 /// ClobberPhysReg - This is called when the specified physreg changes
235 /// value. We use this to invalidate any info about stuff that lives in
236 /// it and any of its aliases.
237 void ClobberPhysReg(unsigned PhysReg);
239 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
240 /// slot changes. This removes information about which register the
241 /// previous value for this slot lives in (as the previous value is dead
243 void ModifyStackSlotOrReMat(int SlotOrReMat);
245 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
246 /// into the specified MBB. Add available physical registers as potential
247 /// live-in's. If they are reused in the MBB, they will be added to the
248 /// live-in set to make register scavenger and post-allocation scheduler.
249 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
250 std::vector<MachineOperand*> &KillOps);
253 // ************************************************************************ //
255 // ReusedOp - For each reused operand, we keep track of a bit of information,
256 // in case we need to rollback upon processing a new operand. See comments
259 // The MachineInstr operand that reused an available value.
262 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
263 unsigned StackSlotOrReMat;
265 // PhysRegReused - The physical register the value was available in.
266 unsigned PhysRegReused;
268 // AssignedPhysReg - The physreg that was assigned for use by the reload.
269 unsigned AssignedPhysReg;
271 // VirtReg - The virtual register itself.
274 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
276 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
277 AssignedPhysReg(apr), VirtReg(vreg) {}
280 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
281 /// is reused instead of reloaded.
282 class VISIBILITY_HIDDEN ReuseInfo {
284 std::vector<ReusedOp> Reuses;
285 BitVector PhysRegsClobbered;
287 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
288 PhysRegsClobbered.resize(tri->getNumRegs());
291 bool hasReuses() const {
292 return !Reuses.empty();
295 /// addReuse - If we choose to reuse a virtual register that is already
296 /// available instead of reloading it, remember that we did so.
297 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
298 unsigned PhysRegReused, unsigned AssignedPhysReg,
300 // If the reload is to the assigned register anyway, no undo will be
302 if (PhysRegReused == AssignedPhysReg) return;
304 // Otherwise, remember this.
305 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
306 AssignedPhysReg, VirtReg));
309 void markClobbered(unsigned PhysReg) {
310 PhysRegsClobbered.set(PhysReg);
313 bool isClobbered(unsigned PhysReg) const {
314 return PhysRegsClobbered.test(PhysReg);
317 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
318 /// is some other operand that is using the specified register, either pick
319 /// a new register to use, or evict the previous reload and use this reg.
320 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
321 AvailableSpills &Spills,
322 std::vector<MachineInstr*> &MaybeDeadStores,
323 SmallSet<unsigned, 8> &Rejected,
325 std::vector<MachineOperand*> &KillOps,
328 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
329 /// 'Rejected' set to remember which registers have been considered and
330 /// rejected for the reload. This avoids infinite looping in case like
333 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
334 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
336 /// sees r1 is taken by t2, tries t2's reload register r0
337 /// sees r0 is taken by t3, tries t3's reload register r1
338 /// sees r1 is taken by t2, tries t2's reload register r0 ...
339 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
340 AvailableSpills &Spills,
341 std::vector<MachineInstr*> &MaybeDeadStores,
343 std::vector<MachineOperand*> &KillOps,
345 SmallSet<unsigned, 8> Rejected;
346 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
347 RegKills, KillOps, VRM);
352 // ****************** //
353 // Utility Functions //
354 // ****************** //
356 /// InvalidateKill - A MI that defines the specified register is being deleted,
357 /// invalidate the register kill information.
358 static void InvalidateKill(unsigned Reg, BitVector &RegKills,
359 std::vector<MachineOperand*> &KillOps) {
361 KillOps[Reg]->setIsKill(false);
367 /// findSinglePredSuccessor - Return via reference a vector of machine basic
368 /// blocks each of which is a successor of the specified BB and has no other
370 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
371 SmallVectorImpl<MachineBasicBlock *> &Succs) {
372 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
373 SE = MBB->succ_end(); SI != SE; ++SI) {
374 MachineBasicBlock *SuccMBB = *SI;
375 if (SuccMBB->pred_size() == 1)
376 Succs.push_back(SuccMBB);
380 /// InvalidateKills - MI is going to be deleted. If any of its operands are
381 /// marked kill, then invalidate the information.
382 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
383 std::vector<MachineOperand*> &KillOps,
384 SmallVector<unsigned, 2> *KillRegs = NULL) {
385 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
386 MachineOperand &MO = MI.getOperand(i);
387 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
389 unsigned Reg = MO.getReg();
390 if (TargetRegisterInfo::isVirtualRegister(Reg))
393 KillRegs->push_back(Reg);
394 assert(Reg < KillOps.size());
395 if (KillOps[Reg] == &MO) {
402 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
403 /// (since it's spill instruction is removed), mark it isDead. Also checks if
404 /// the def MI has other definition operands that are not dead. Returns it by
406 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
407 MachineInstr &NewDef, unsigned Reg,
409 // Due to remat, it's possible this reg isn't being reused. That is,
410 // the def of this reg (by prev MI) is now dead.
411 MachineInstr *DefMI = I;
412 MachineOperand *DefOp = NULL;
413 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
414 MachineOperand &MO = DefMI->getOperand(i);
415 if (MO.isReg() && MO.isDef()) {
416 if (MO.getReg() == Reg)
418 else if (!MO.isDead())
425 bool FoundUse = false, Done = false;
426 MachineBasicBlock::iterator E = &NewDef;
428 for (; !Done && I != E; ++I) {
429 MachineInstr *NMI = I;
430 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
431 MachineOperand &MO = NMI->getOperand(j);
432 if (!MO.isReg() || MO.getReg() != Reg)
436 Done = true; // Stop after scanning all the operands of this MI.
447 /// UpdateKills - Track and update kill info. If a MI reads a register that is
448 /// marked kill, then it must be due to register reuse. Transfer the kill info
450 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
451 std::vector<MachineOperand*> &KillOps,
452 const TargetRegisterInfo* TRI) {
453 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
454 MachineOperand &MO = MI.getOperand(i);
455 if (!MO.isReg() || !MO.isUse())
457 unsigned Reg = MO.getReg();
461 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
462 // That can't be right. Register is killed but not re-defined and it's
463 // being reused. Let's fix that.
464 KillOps[Reg]->setIsKill(false);
467 if (!MI.isRegTiedToDefOperand(i))
468 // Unless it's a two-address operand, this is the new kill.
477 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
478 const MachineOperand &MO = MI.getOperand(i);
479 if (!MO.isReg() || !MO.isDef())
481 unsigned Reg = MO.getReg();
484 // It also defines (or partially define) aliases.
485 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
492 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
494 static void ReMaterialize(MachineBasicBlock &MBB,
495 MachineBasicBlock::iterator &MII,
496 unsigned DestReg, unsigned Reg,
497 const TargetInstrInfo *TII,
498 const TargetRegisterInfo *TRI,
500 TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
501 MachineInstr *NewMI = prior(MII);
502 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = NewMI->getOperand(i);
504 if (!MO.isReg() || MO.getReg() == 0)
506 unsigned VirtReg = MO.getReg();
507 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
510 unsigned SubIdx = MO.getSubReg();
511 unsigned Phys = VRM.getPhys(VirtReg);
513 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
520 /// findSuperReg - Find the SubReg's super-register of given register class
521 /// where its SubIdx sub-register is SubReg.
522 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
523 unsigned SubIdx, const TargetRegisterInfo *TRI) {
524 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
527 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
533 // ******************************** //
534 // Available Spills Implementation //
535 // ******************************** //
537 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
538 /// stackslot register. The register is still available but is no longer
539 /// allowed to be modifed.
540 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
541 std::multimap<unsigned, int>::iterator I =
542 PhysRegsAvailable.lower_bound(PhysReg);
543 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
544 int SlotOrReMat = I->second;
546 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
547 "Bidirectional map mismatch!");
548 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
549 DOUT << "PhysReg " << TRI->getName(PhysReg)
550 << " copied, it is available for use but can no longer be modified\n";
554 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
555 /// stackslot register and its aliases. The register and its aliases may
556 /// still available but is no longer allowed to be modifed.
557 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
558 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
559 disallowClobberPhysRegOnly(*AS);
560 disallowClobberPhysRegOnly(PhysReg);
563 /// ClobberPhysRegOnly - This is called when the specified physreg changes
564 /// value. We use this to invalidate any info about stuff we thing lives in it.
565 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
566 std::multimap<unsigned, int>::iterator I =
567 PhysRegsAvailable.lower_bound(PhysReg);
568 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
569 int SlotOrReMat = I->second;
570 PhysRegsAvailable.erase(I++);
571 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
572 "Bidirectional map mismatch!");
573 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
574 DOUT << "PhysReg " << TRI->getName(PhysReg)
575 << " clobbered, invalidating ";
576 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
577 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
579 DOUT << "SS#" << SlotOrReMat << "\n";
583 /// ClobberPhysReg - This is called when the specified physreg changes
584 /// value. We use this to invalidate any info about stuff we thing lives in
585 /// it and any of its aliases.
586 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
587 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
588 ClobberPhysRegOnly(*AS);
589 ClobberPhysRegOnly(PhysReg);
592 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
593 /// into the specified MBB. Add available physical registers as potential
594 /// live-in's. If they are reused in the MBB, they will be added to the
595 /// live-in set to make register scavenger and post-allocation scheduler.
596 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
598 std::vector<MachineOperand*> &KillOps) {
599 std::set<unsigned> NotAvailable;
600 for (std::multimap<unsigned, int>::iterator
601 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
603 unsigned Reg = I->first;
604 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
605 // FIXME: A temporary workaround. We can't reuse available value if it's
606 // not safe to move the def of the virtual register's class. e.g.
607 // X86::RFP* register classes. Do not add it as a live-in.
608 if (!TII->isSafeToMoveRegClassDefs(RC))
609 // This is no longer available.
610 NotAvailable.insert(Reg);
613 InvalidateKill(Reg, RegKills, KillOps);
616 // Skip over the same register.
617 std::multimap<unsigned, int>::iterator NI = next(I);
618 while (NI != E && NI->first == Reg) {
624 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
625 E = NotAvailable.end(); I != E; ++I) {
627 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
629 ClobberPhysReg(*SubRegs);
633 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
634 /// slot changes. This removes information about which register the previous
635 /// value for this slot lives in (as the previous value is dead now).
636 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
637 std::map<int, unsigned>::iterator It =
638 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
639 if (It == SpillSlotsOrReMatsAvailable.end()) return;
640 unsigned Reg = It->second >> 1;
641 SpillSlotsOrReMatsAvailable.erase(It);
643 // This register may hold the value of multiple stack slots, only remove this
644 // stack slot from the set of values the register contains.
645 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
647 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
648 "Map inverse broken!");
649 if (I->second == SlotOrReMat) break;
651 PhysRegsAvailable.erase(I);
654 // ************************** //
655 // Reuse Info Implementation //
656 // ************************** //
658 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
659 /// is some other operand that is using the specified register, either pick
660 /// a new register to use, or evict the previous reload and use this reg.
661 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
662 AvailableSpills &Spills,
663 std::vector<MachineInstr*> &MaybeDeadStores,
664 SmallSet<unsigned, 8> &Rejected,
666 std::vector<MachineOperand*> &KillOps,
668 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
671 if (Reuses.empty()) return PhysReg; // This is most often empty.
673 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
674 ReusedOp &Op = Reuses[ro];
675 // If we find some other reuse that was supposed to use this register
676 // exactly for its reload, we can change this reload to use ITS reload
677 // register. That is, unless its reload register has already been
678 // considered and subsequently rejected because it has also been reused
679 // by another operand.
680 if (Op.PhysRegReused == PhysReg &&
681 Rejected.count(Op.AssignedPhysReg) == 0) {
682 // Yup, use the reload register that we didn't use before.
683 unsigned NewReg = Op.AssignedPhysReg;
684 Rejected.insert(PhysReg);
685 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
686 RegKills, KillOps, VRM);
688 // Otherwise, we might also have a problem if a previously reused
689 // value aliases the new register. If so, codegen the previous reload
691 unsigned PRRU = Op.PhysRegReused;
692 const TargetRegisterInfo *TRI = Spills.getRegInfo();
693 if (TRI->areAliases(PRRU, PhysReg)) {
694 // Okay, we found out that an alias of a reused register
695 // was used. This isn't good because it means we have
696 // to undo a previous reuse.
697 MachineBasicBlock *MBB = MI->getParent();
698 const TargetRegisterClass *AliasRC =
699 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
701 // Copy Op out of the vector and remove it, we're going to insert an
702 // explicit load for it.
704 Reuses.erase(Reuses.begin()+ro);
706 // Ok, we're going to try to reload the assigned physreg into the
707 // slot that we were supposed to in the first place. However, that
708 // register could hold a reuse. Check to see if it conflicts or
709 // would prefer us to use a different register.
710 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
711 MI, Spills, MaybeDeadStores,
712 Rejected, RegKills, KillOps, VRM);
714 MachineBasicBlock::iterator MII = MI;
715 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
716 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
718 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
719 NewOp.StackSlotOrReMat, AliasRC);
720 MachineInstr *LoadMI = prior(MII);
721 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
722 // Any stores to this stack slot are not dead anymore.
723 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
726 Spills.ClobberPhysReg(NewPhysReg);
727 Spills.ClobberPhysReg(NewOp.PhysRegReused);
729 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
730 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
731 MI->getOperand(NewOp.Operand).setReg(RReg);
732 MI->getOperand(NewOp.Operand).setSubReg(0);
734 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
736 UpdateKills(*MII, RegKills, KillOps, TRI);
737 DOUT << '\t' << *MII;
739 DOUT << "Reuse undone!\n";
742 // Finally, PhysReg is now available, go ahead and use it.
750 // ************************************************************************ //
752 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
753 /// stack slot mod/ref. It also checks if it's possible to unfold the
754 /// instruction by having it define a specified physical register instead.
755 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
756 const TargetInstrInfo *TII,
757 const TargetRegisterInfo *TRI,
759 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
763 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
764 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
765 unsigned VirtReg = I->second.first;
766 VirtRegMap::ModRef MR = I->second.second;
767 if (MR & VirtRegMap::isModRef)
768 if (VRM.getStackSlot(VirtReg) == SS) {
769 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
776 // Does the instruction uses a register that overlaps the scratch register?
777 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
778 MachineOperand &MO = MI.getOperand(i);
779 if (!MO.isReg() || MO.getReg() == 0)
781 unsigned Reg = MO.getReg();
782 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
783 if (!VRM.hasPhys(Reg))
785 Reg = VRM.getPhys(Reg);
787 if (TRI->regsOverlap(PhysReg, Reg))
793 /// FindFreeRegister - Find a free register of a given register class by looking
794 /// at (at most) the last two machine instructions.
795 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
796 MachineBasicBlock &MBB,
797 const TargetRegisterClass *RC,
798 const TargetRegisterInfo *TRI,
799 BitVector &AllocatableRegs) {
800 BitVector Defs(TRI->getNumRegs());
801 BitVector Uses(TRI->getNumRegs());
802 SmallVector<unsigned, 4> LocalUses;
803 SmallVector<unsigned, 4> Kills;
805 // Take a look at 2 instructions at most.
806 for (unsigned Count = 0; Count < 2; ++Count) {
807 if (MII == MBB.begin())
809 MachineInstr *PrevMI = prior(MII);
810 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
811 MachineOperand &MO = PrevMI->getOperand(i);
812 if (!MO.isReg() || MO.getReg() == 0)
814 unsigned Reg = MO.getReg();
817 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
820 LocalUses.push_back(Reg);
821 if (MO.isKill() && AllocatableRegs[Reg])
822 Kills.push_back(Reg);
826 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
827 unsigned Kill = Kills[i];
828 if (!Defs[Kill] && !Uses[Kill] &&
829 TRI->getPhysicalRegisterRegClass(Kill) == RC)
832 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
833 unsigned Reg = LocalUses[i];
835 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
846 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
847 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
848 MachineOperand &MO = MI->getOperand(i);
849 if (MO.isReg() && MO.getReg() == VirtReg)
855 // ***************************** //
856 // Local Spiller Implementation //
857 // ***************************** //
859 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
860 MachineRegisterInfo *RegInfo;
861 const TargetRegisterInfo *TRI;
862 const TargetInstrInfo *TII;
863 BitVector AllocatableRegs;
864 DenseMap<MachineInstr*, unsigned> DistanceMap;
867 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
868 LiveIntervals* LIs) {
869 RegInfo = &MF.getRegInfo();
870 TRI = MF.getTarget().getRegisterInfo();
871 TII = MF.getTarget().getInstrInfo();
872 AllocatableRegs = TRI->getAllocatableSet(MF);
873 DOUT << "\n**** Local spiller rewriting function '"
874 << MF.getFunction()->getName() << "':\n";
875 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
879 // Spills - Keep track of which spilled values are available in physregs
880 // so that we can choose to reuse the physregs instead of emitting
881 // reloads. This is usually refreshed per basic block.
882 AvailableSpills Spills(TRI, TII);
884 // Keep track of kill information.
885 BitVector RegKills(TRI->getNumRegs());
886 std::vector<MachineOperand*> KillOps;
887 KillOps.resize(TRI->getNumRegs(), NULL);
889 // SingleEntrySuccs - Successor blocks which have a single predecessor.
890 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
891 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
893 // Traverse the basic blocks depth first.
894 MachineBasicBlock *Entry = MF.begin();
895 SmallPtrSet<MachineBasicBlock*,16> Visited;
896 for (df_ext_iterator<MachineBasicBlock*,
897 SmallPtrSet<MachineBasicBlock*,16> >
898 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
900 MachineBasicBlock *MBB = *DFI;
901 if (!EarlyVisited.count(MBB))
902 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
904 // If this MBB is the only predecessor of a successor. Keep the
905 // availability information and visit it next.
907 // Keep visiting single predecessor successor as long as possible.
908 SinglePredSuccs.clear();
909 findSinglePredSuccessor(MBB, SinglePredSuccs);
910 if (SinglePredSuccs.empty())
913 // FIXME: More than one successors, each of which has MBB has
914 // the only predecessor.
915 MBB = SinglePredSuccs[0];
916 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
917 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
918 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
923 // Clear the availability info.
927 DOUT << "**** Post Machine Instrs ****\n";
930 // Mark unused spill slots.
931 MachineFrameInfo *MFI = MF.getFrameInfo();
932 int SS = VRM.getLowSpillSlot();
933 if (SS != VirtRegMap::NO_STACK_SLOT)
934 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
935 if (!VRM.isSpillSlotUsed(SS)) {
936 MFI->RemoveStackObject(SS);
945 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
946 /// a scratch register is available.
947 /// xorq %r12<kill>, %r13
948 /// addq %rax, -184(%rbp)
949 /// addq %r13, -184(%rbp)
951 /// xorq %r12<kill>, %r13
952 /// movq -184(%rbp), %r12
955 /// movq %r12, -184(%rbp)
956 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
957 MachineBasicBlock &MBB,
958 MachineBasicBlock::iterator &MII,
959 std::vector<MachineInstr*> &MaybeDeadStores,
960 AvailableSpills &Spills,
962 std::vector<MachineOperand*> &KillOps,
965 MachineBasicBlock::iterator NextMII = next(MII);
966 if (NextMII == MBB.end())
969 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
972 // Now let's see if the last couple of instructions happens to have freed up
974 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
975 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
979 MachineFunction &MF = *MBB.getParent();
980 TRI = MF.getTarget().getRegisterInfo();
981 MachineInstr &MI = *MII;
982 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
985 // If the next instruction also folds the same SS modref and can be unfoled,
986 // then it's worthwhile to issue a load from SS into the free register and
987 // then unfold these instructions.
988 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
991 // Load from SS to the spare physical register.
992 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
993 // This invalidates Phys.
994 Spills.ClobberPhysReg(PhysReg);
995 // Remember it's available.
996 Spills.addAvailable(SS, PhysReg);
997 MaybeDeadStores[SS] = NULL;
999 // Unfold current MI.
1000 SmallVector<MachineInstr*, 4> NewMIs;
1001 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1002 assert(0 && "Unable unfold the load / store folding instruction!");
1003 assert(NewMIs.size() == 1);
1004 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1005 VRM.transferRestorePts(&MI, NewMIs[0]);
1006 MII = MBB.insert(MII, NewMIs[0]);
1007 InvalidateKills(MI, RegKills, KillOps);
1008 VRM.RemoveMachineInstrFromMaps(&MI);
1012 // Unfold next instructions that fold the same SS.
1014 MachineInstr &NextMI = *NextMII;
1015 NextMII = next(NextMII);
1017 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1018 assert(0 && "Unable unfold the load / store folding instruction!");
1019 assert(NewMIs.size() == 1);
1020 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1021 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1022 MBB.insert(NextMII, NewMIs[0]);
1023 InvalidateKills(NextMI, RegKills, KillOps);
1024 VRM.RemoveMachineInstrFromMaps(&NextMI);
1027 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1029 // Store the value back into SS.
1030 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1031 MachineInstr *StoreMI = prior(NextMII);
1032 VRM.addSpillSlotUse(SS, StoreMI);
1033 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1038 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1039 /// instruction. e.g.
1041 /// movl %eax, -32(%ebp)
1042 /// movl -36(%ebp), %eax
1043 /// orl %eax, -32(%ebp)
1046 /// orl -36(%ebp), %eax
1047 /// mov %eax, -32(%ebp)
1048 /// This enables unfolding optimization for a subsequent instruction which will
1049 /// also eliminate the newly introduced store instruction.
1050 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1051 MachineBasicBlock::iterator &MII,
1052 std::vector<MachineInstr*> &MaybeDeadStores,
1053 AvailableSpills &Spills,
1054 BitVector &RegKills,
1055 std::vector<MachineOperand*> &KillOps,
1057 MachineFunction &MF = *MBB.getParent();
1058 MachineInstr &MI = *MII;
1059 unsigned UnfoldedOpc = 0;
1060 unsigned UnfoldPR = 0;
1061 unsigned UnfoldVR = 0;
1062 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1063 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1064 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1065 // Only transform a MI that folds a single register.
1068 UnfoldVR = I->second.first;
1069 VirtRegMap::ModRef MR = I->second.second;
1070 // MI2VirtMap be can updated which invalidate the iterator.
1071 // Increment the iterator first.
1073 if (VRM.isAssignedReg(UnfoldVR))
1075 // If this reference is not a use, any previous store is now dead.
1076 // Otherwise, the store to this stack slot is not dead anymore.
1077 FoldedSS = VRM.getStackSlot(UnfoldVR);
1078 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1079 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1080 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1081 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1084 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1093 // Look for other unfolding opportunities.
1094 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1095 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1098 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1099 MachineOperand &MO = MI.getOperand(i);
1100 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1102 unsigned VirtReg = MO.getReg();
1103 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1105 if (VRM.isAssignedReg(VirtReg)) {
1106 unsigned PhysReg = VRM.getPhys(VirtReg);
1107 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1109 } else if (VRM.isReMaterialized(VirtReg))
1111 int SS = VRM.getStackSlot(VirtReg);
1112 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1114 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1118 if (VRM.hasPhys(VirtReg)) {
1119 PhysReg = VRM.getPhys(VirtReg);
1120 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1124 // Ok, we'll need to reload the value into a register which makes
1125 // it impossible to perform the store unfolding optimization later.
1126 // Let's see if it is possible to fold the load if the store is
1127 // unfolded. This allows us to perform the store unfolding
1129 SmallVector<MachineInstr*, 4> NewMIs;
1130 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1131 assert(NewMIs.size() == 1);
1132 MachineInstr *NewMI = NewMIs.back();
1134 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1136 SmallVector<unsigned, 1> Ops;
1138 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1140 VRM.addSpillSlotUse(SS, FoldedMI);
1141 if (!VRM.hasPhys(UnfoldVR))
1142 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1143 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1144 MII = MBB.insert(MII, FoldedMI);
1145 InvalidateKills(MI, RegKills, KillOps);
1146 VRM.RemoveMachineInstrFromMaps(&MI);
1148 MF.DeleteMachineInstr(NewMI);
1151 MF.DeleteMachineInstr(NewMI);
1158 /// CommuteToFoldReload -
1161 /// r1 = op r1, r2<kill>
1164 /// If op is commutable and r2 is killed, then we can xform these to
1165 /// r2 = op r2, fi#1
1167 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1168 MachineBasicBlock::iterator &MII,
1169 unsigned VirtReg, unsigned SrcReg, int SS,
1170 AvailableSpills &Spills,
1171 BitVector &RegKills,
1172 std::vector<MachineOperand*> &KillOps,
1173 const TargetRegisterInfo *TRI,
1175 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1178 MachineFunction &MF = *MBB.getParent();
1179 MachineInstr &MI = *MII;
1180 MachineBasicBlock::iterator DefMII = prior(MII);
1181 MachineInstr *DefMI = DefMII;
1182 const TargetInstrDesc &TID = DefMI->getDesc();
1184 if (DefMII != MBB.begin() &&
1185 TID.isCommutable() &&
1186 TII->CommuteChangesDestination(DefMI, NewDstIdx)) {
1187 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1188 unsigned NewReg = NewDstMO.getReg();
1189 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1191 MachineInstr *ReloadMI = prior(DefMII);
1193 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1194 if (DestReg != SrcReg || FrameIdx != SS)
1196 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1200 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1202 assert(DefMI->getOperand(DefIdx).isReg() &&
1203 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1205 // Now commute def instruction.
1206 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1209 SmallVector<unsigned, 1> Ops;
1210 Ops.push_back(NewDstIdx);
1211 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1212 // Not needed since foldMemoryOperand returns new MI.
1213 MF.DeleteMachineInstr(CommutedMI);
1217 VRM.addSpillSlotUse(SS, FoldedMI);
1218 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1219 // Insert new def MI and spill MI.
1220 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1221 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1223 MachineInstr *StoreMI = MII;
1224 VRM.addSpillSlotUse(SS, StoreMI);
1225 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1226 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1228 // Delete all 3 old instructions.
1229 InvalidateKills(*ReloadMI, RegKills, KillOps);
1230 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1231 MBB.erase(ReloadMI);
1232 InvalidateKills(*DefMI, RegKills, KillOps);
1233 VRM.RemoveMachineInstrFromMaps(DefMI);
1235 InvalidateKills(MI, RegKills, KillOps);
1236 VRM.RemoveMachineInstrFromMaps(&MI);
1239 // If NewReg was previously holding value of some SS, it's now clobbered.
1240 // This has to be done now because it's a physical register. When this
1241 // instruction is re-visited, it's ignored.
1242 Spills.ClobberPhysReg(NewReg);
1251 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1252 /// the last store to the same slot is now dead. If so, remove the last store.
1253 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1254 MachineBasicBlock::iterator &MII,
1255 int Idx, unsigned PhysReg, int StackSlot,
1256 const TargetRegisterClass *RC,
1257 bool isAvailable, MachineInstr *&LastStore,
1258 AvailableSpills &Spills,
1259 SmallSet<MachineInstr*, 4> &ReMatDefs,
1260 BitVector &RegKills,
1261 std::vector<MachineOperand*> &KillOps,
1264 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1265 MachineInstr *StoreMI = next(MII);
1266 VRM.addSpillSlotUse(StackSlot, StoreMI);
1267 DOUT << "Store:\t" << *StoreMI;
1269 // If there is a dead store to this stack slot, nuke it now.
1271 DOUT << "Removed dead store:\t" << *LastStore;
1273 SmallVector<unsigned, 2> KillRegs;
1274 InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
1275 MachineBasicBlock::iterator PrevMII = LastStore;
1276 bool CheckDef = PrevMII != MBB.begin();
1279 VRM.RemoveMachineInstrFromMaps(LastStore);
1280 MBB.erase(LastStore);
1282 // Look at defs of killed registers on the store. Mark the defs
1283 // as dead since the store has been deleted and they aren't
1285 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1286 bool HasOtherDef = false;
1287 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1288 MachineInstr *DeadDef = PrevMII;
1289 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1290 // FIXME: This assumes a remat def does not have side
1292 VRM.RemoveMachineInstrFromMaps(DeadDef);
1301 LastStore = next(MII);
1303 // If the stack slot value was previously available in some other
1304 // register, change it now. Otherwise, make the register available,
1306 Spills.ModifyStackSlotOrReMat(StackSlot);
1307 Spills.ClobberPhysReg(PhysReg);
1308 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1312 /// TransferDeadness - A identity copy definition is dead and it's being
1313 /// removed. Find the last def or use and mark it as dead / kill.
1314 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1315 unsigned Reg, BitVector &RegKills,
1316 std::vector<MachineOperand*> &KillOps) {
1317 int LastUDDist = -1;
1318 MachineInstr *LastUDMI = NULL;
1319 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1320 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1321 MachineInstr *UDMI = &*RI;
1322 if (UDMI->getParent() != MBB)
1324 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1325 if (DI == DistanceMap.end() || DI->second > CurDist)
1327 if ((int)DI->second < LastUDDist)
1329 LastUDDist = DI->second;
1334 MachineOperand *LastUD = NULL;
1335 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1336 MachineOperand &MO = LastUDMI->getOperand(i);
1337 if (!MO.isReg() || MO.getReg() != Reg)
1339 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1341 if (LastUDMI->isRegTiedToDefOperand(i))
1344 if (LastUD->isDef())
1345 LastUD->setIsDead();
1347 LastUD->setIsKill();
1349 KillOps[Reg] = LastUD;
1354 /// rewriteMBB - Keep track of which spills are available even after the
1355 /// register allocator is done with them. If possible, avid reloading vregs.
1356 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1358 AvailableSpills &Spills, BitVector &RegKills,
1359 std::vector<MachineOperand*> &KillOps) {
1361 DOUT << "\n**** Local spiller rewriting MBB '"
1362 << MBB.getBasicBlock()->getName() << "':\n";
1364 MachineFunction &MF = *MBB.getParent();
1366 // MaybeDeadStores - When we need to write a value back into a stack slot,
1367 // keep track of the inserted store. If the stack slot value is never read
1368 // (because the value was used from some available register, for example), and
1369 // subsequently stored to, the original store is dead. This map keeps track
1370 // of inserted stores that are not used. If we see a subsequent store to the
1371 // same stack slot, the original store is deleted.
1372 std::vector<MachineInstr*> MaybeDeadStores;
1373 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1375 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1376 SmallSet<MachineInstr*, 4> ReMatDefs;
1379 SmallSet<unsigned, 2> KilledMIRegs;
1382 KillOps.resize(TRI->getNumRegs(), NULL);
1385 DistanceMap.clear();
1386 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1388 MachineBasicBlock::iterator NextMII = next(MII);
1390 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1391 bool Erased = false;
1392 bool BackTracked = false;
1393 if (OptimizeByUnfold(MBB, MII,
1394 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1395 NextMII = next(MII);
1397 MachineInstr &MI = *MII;
1399 if (VRM.hasEmergencySpills(&MI)) {
1400 // Spill physical register(s) in the rare case the allocator has run out
1401 // of registers to allocate.
1402 SmallSet<int, 4> UsedSS;
1403 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1404 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1405 unsigned PhysReg = EmSpills[i];
1406 const TargetRegisterClass *RC =
1407 TRI->getPhysicalRegisterRegClass(PhysReg);
1408 assert(RC && "Unable to determine register class!");
1409 int SS = VRM.getEmergencySpillSlot(RC);
1410 if (UsedSS.count(SS))
1411 assert(0 && "Need to spill more than one physical registers!");
1413 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1414 MachineInstr *StoreMI = prior(MII);
1415 VRM.addSpillSlotUse(SS, StoreMI);
1416 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1417 MachineInstr *LoadMI = next(MII);
1418 VRM.addSpillSlotUse(SS, LoadMI);
1421 NextMII = next(MII);
1424 // Insert restores here if asked to.
1425 if (VRM.isRestorePt(&MI)) {
1426 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1427 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1428 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1429 if (!VRM.getPreSplitReg(VirtReg))
1430 continue; // Split interval spilled again.
1431 unsigned Phys = VRM.getPhys(VirtReg);
1432 RegInfo->setPhysRegUsed(Phys);
1434 // Check if the value being restored if available. If so, it must be
1435 // from a predecessor BB that fallthrough into this BB. We do not
1441 // ... # r1 not clobbered
1444 bool DoReMat = VRM.isReMaterialized(VirtReg);
1445 int SSorRMId = DoReMat
1446 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1447 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1448 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1449 if (InReg == Phys) {
1450 // If the value is already available in the expected register, save
1451 // a reload / remat.
1453 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1455 DOUT << "Reusing SS#" << SSorRMId;
1456 DOUT << " from physreg "
1457 << TRI->getName(InReg) << " for vreg"
1458 << VirtReg <<" instead of reloading into physreg "
1459 << TRI->getName(Phys) << "\n";
1462 } else if (InReg && InReg != Phys) {
1464 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1466 DOUT << "Reusing SS#" << SSorRMId;
1467 DOUT << " from physreg "
1468 << TRI->getName(InReg) << " for vreg"
1469 << VirtReg <<" by copying it into physreg "
1470 << TRI->getName(Phys) << "\n";
1472 // If the reloaded / remat value is available in another register,
1473 // copy it to the desired register.
1474 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1476 // This invalidates Phys.
1477 Spills.ClobberPhysReg(Phys);
1478 // Remember it's available.
1479 Spills.addAvailable(SSorRMId, Phys);
1482 MachineInstr *CopyMI = prior(MII);
1483 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1484 KillOpnd->setIsKill();
1485 UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1487 DOUT << '\t' << *CopyMI;
1492 if (VRM.isReMaterialized(VirtReg)) {
1493 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1495 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1496 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1497 MachineInstr *LoadMI = prior(MII);
1498 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1502 // This invalidates Phys.
1503 Spills.ClobberPhysReg(Phys);
1504 // Remember it's available.
1505 Spills.addAvailable(SSorRMId, Phys);
1507 UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1508 DOUT << '\t' << *prior(MII);
1512 // Insert spills here if asked to.
1513 if (VRM.isSpillPt(&MI)) {
1514 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1515 VRM.getSpillPtSpills(&MI);
1516 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1517 unsigned VirtReg = SpillRegs[i].first;
1518 bool isKill = SpillRegs[i].second;
1519 if (!VRM.getPreSplitReg(VirtReg))
1520 continue; // Split interval spilled again.
1521 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1522 unsigned Phys = VRM.getPhys(VirtReg);
1523 int StackSlot = VRM.getStackSlot(VirtReg);
1524 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1525 MachineInstr *StoreMI = next(MII);
1526 VRM.addSpillSlotUse(StackSlot, StoreMI);
1527 DOUT << "Store:\t" << *StoreMI;
1528 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1530 NextMII = next(MII);
1533 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1535 ReuseInfo ReusedOperands(MI, TRI);
1536 SmallVector<unsigned, 4> VirtUseOps;
1537 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1538 MachineOperand &MO = MI.getOperand(i);
1539 if (!MO.isReg() || MO.getReg() == 0)
1540 continue; // Ignore non-register operands.
1542 unsigned VirtReg = MO.getReg();
1543 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1544 // Ignore physregs for spilling, but remember that it is used by this
1546 RegInfo->setPhysRegUsed(VirtReg);
1550 // We want to process implicit virtual register uses first.
1551 if (MO.isImplicit())
1552 // If the virtual register is implicitly defined, emit a implicit_def
1553 // before so scavenger knows it's "defined".
1554 VirtUseOps.insert(VirtUseOps.begin(), i);
1556 VirtUseOps.push_back(i);
1559 // Process all of the spilled uses and all non spilled reg references.
1560 SmallVector<int, 2> PotentialDeadStoreSlots;
1561 KilledMIRegs.clear();
1562 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1563 unsigned i = VirtUseOps[j];
1564 MachineOperand &MO = MI.getOperand(i);
1565 unsigned VirtReg = MO.getReg();
1566 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1567 "Not a virtual register?");
1569 unsigned SubIdx = MO.getSubReg();
1570 if (VRM.isAssignedReg(VirtReg)) {
1571 // This virtual register was assigned a physreg!
1572 unsigned Phys = VRM.getPhys(VirtReg);
1573 RegInfo->setPhysRegUsed(Phys);
1575 ReusedOperands.markClobbered(Phys);
1576 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1577 MI.getOperand(i).setReg(RReg);
1578 MI.getOperand(i).setSubReg(0);
1579 if (VRM.isImplicitlyDefined(VirtReg))
1580 BuildMI(MBB, &MI, MI.getDebugLoc(),
1581 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1585 // This virtual register is now known to be a spilled value.
1587 continue; // Handle defs in the loop below (handle use&def here though)
1589 bool AvoidReload = false;
1590 if (LIs->hasInterval(VirtReg)) {
1591 LiveInterval &LI = LIs->getInterval(VirtReg);
1592 if (!LI.liveAt(LIs->getUseIndex(LI.beginNumber())))
1593 // Must be defined by an implicit def. It should not be spilled. Note,
1594 // this is for correctness reason. e.g.
1595 // 8 %reg1024<def> = IMPLICIT_DEF
1596 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1597 // The live range [12, 14) are not part of the r1024 live interval since
1598 // it's defined by an implicit def. It will not conflicts with live
1599 // interval of r1025. Now suppose both registers are spilled, you can
1600 // easily see a situation where both registers are reloaded before
1601 // the INSERT_SUBREG and both target registers that would overlap.
1605 bool DoReMat = VRM.isReMaterialized(VirtReg);
1606 int SSorRMId = DoReMat
1607 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1608 int ReuseSlot = SSorRMId;
1610 // Check to see if this stack slot is available.
1611 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1613 // If this is a sub-register use, make sure the reuse register is in the
1614 // right register class. For example, for x86 not all of the 32-bit
1615 // registers have accessible sub-registers.
1616 // Similarly so for EXTRACT_SUBREG. Consider this:
1618 // MOV32_mr fi#1, EDI
1620 // = EXTRACT_SUBREG fi#1
1621 // fi#1 is available in EDI, but it cannot be reused because it's not in
1622 // the right register file.
1623 if (PhysReg && !AvoidReload &&
1624 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1625 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1626 if (!RC->contains(PhysReg))
1630 if (PhysReg && !AvoidReload) {
1631 // This spilled operand might be part of a two-address operand. If this
1632 // is the case, then changing it will necessarily require changing the
1633 // def part of the instruction as well. However, in some cases, we
1634 // aren't allowed to modify the reused register. If none of these cases
1636 bool CanReuse = true;
1637 bool isTied = MI.isRegTiedToDefOperand(i);
1639 // Okay, we have a two address operand. We can reuse this physreg as
1640 // long as we are allowed to clobber the value and there isn't an
1641 // earlier def that has already clobbered the physreg.
1642 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1643 Spills.canClobberPhysReg(PhysReg);
1647 // If this stack slot value is already available, reuse it!
1648 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1649 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1651 DOUT << "Reusing SS#" << ReuseSlot;
1652 DOUT << " from physreg "
1653 << TRI->getName(PhysReg) << " for vreg"
1654 << VirtReg <<" instead of reloading into physreg "
1655 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1656 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1657 MI.getOperand(i).setReg(RReg);
1658 MI.getOperand(i).setSubReg(0);
1660 // The only technical detail we have is that we don't know that
1661 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1662 // later in the instruction. In particular, consider 'op V1, V2'.
1663 // If V1 is available in physreg R0, we would choose to reuse it
1664 // here, instead of reloading it into the register the allocator
1665 // indicated (say R1). However, V2 might have to be reloaded
1666 // later, and it might indicate that it needs to live in R0. When
1667 // this occurs, we need to have information available that
1668 // indicates it is safe to use R1 for the reload instead of R0.
1670 // To further complicate matters, we might conflict with an alias,
1671 // or R0 and R1 might not be compatible with each other. In this
1672 // case, we actually insert a reload for V1 in R1, ensuring that
1673 // we can get at R0 or its alias.
1674 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1675 VRM.getPhys(VirtReg), VirtReg);
1677 // Only mark it clobbered if this is a use&def operand.
1678 ReusedOperands.markClobbered(PhysReg);
1681 if (MI.getOperand(i).isKill() &&
1682 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1684 // The store of this spilled value is potentially dead, but we
1685 // won't know for certain until we've confirmed that the re-use
1686 // above is valid, which means waiting until the other operands
1687 // are processed. For now we just track the spill slot, we'll
1688 // remove it after the other operands are processed if valid.
1690 PotentialDeadStoreSlots.push_back(ReuseSlot);
1693 // Mark is isKill if it's there no other uses of the same virtual
1694 // register and it's not a two-address operand. IsKill will be
1695 // unset if reg is reused.
1696 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1697 MI.getOperand(i).setIsKill();
1698 KilledMIRegs.insert(VirtReg);
1704 // Otherwise we have a situation where we have a two-address instruction
1705 // whose mod/ref operand needs to be reloaded. This reload is already
1706 // available in some register "PhysReg", but if we used PhysReg as the
1707 // operand to our 2-addr instruction, the instruction would modify
1708 // PhysReg. This isn't cool if something later uses PhysReg and expects
1709 // to get its initial value.
1711 // To avoid this problem, and to avoid doing a load right after a store,
1712 // we emit a copy from PhysReg into the designated register for this
1714 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1715 assert(DesignatedReg && "Must map virtreg to physreg!");
1717 // Note that, if we reused a register for a previous operand, the
1718 // register we want to reload into might not actually be
1719 // available. If this occurs, use the register indicated by the
1721 if (ReusedOperands.hasReuses())
1722 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1723 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1725 // If the mapped designated register is actually the physreg we have
1726 // incoming, we don't need to inserted a dead copy.
1727 if (DesignatedReg == PhysReg) {
1728 // If this stack slot value is already available, reuse it!
1729 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1730 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1732 DOUT << "Reusing SS#" << ReuseSlot;
1733 DOUT << " from physreg " << TRI->getName(PhysReg)
1734 << " for vreg" << VirtReg
1735 << " instead of reloading into same physreg.\n";
1736 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1737 MI.getOperand(i).setReg(RReg);
1738 MI.getOperand(i).setSubReg(0);
1739 ReusedOperands.markClobbered(RReg);
1744 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1745 RegInfo->setPhysRegUsed(DesignatedReg);
1746 ReusedOperands.markClobbered(DesignatedReg);
1747 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1749 MachineInstr *CopyMI = prior(MII);
1750 UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1752 // This invalidates DesignatedReg.
1753 Spills.ClobberPhysReg(DesignatedReg);
1755 Spills.addAvailable(ReuseSlot, DesignatedReg);
1757 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1758 MI.getOperand(i).setReg(RReg);
1759 MI.getOperand(i).setSubReg(0);
1760 DOUT << '\t' << *prior(MII);
1765 // Otherwise, reload it and remember that we have it.
1766 PhysReg = VRM.getPhys(VirtReg);
1767 assert(PhysReg && "Must map virtreg to physreg!");
1769 // Note that, if we reused a register for a previous operand, the
1770 // register we want to reload into might not actually be
1771 // available. If this occurs, use the register indicated by the
1773 if (ReusedOperands.hasReuses())
1774 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1775 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1777 RegInfo->setPhysRegUsed(PhysReg);
1778 ReusedOperands.markClobbered(PhysReg);
1783 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1785 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1786 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1787 MachineInstr *LoadMI = prior(MII);
1788 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1791 // This invalidates PhysReg.
1792 Spills.ClobberPhysReg(PhysReg);
1794 // Any stores to this stack slot are not dead anymore.
1796 MaybeDeadStores[SSorRMId] = NULL;
1797 Spills.addAvailable(SSorRMId, PhysReg);
1798 // Assumes this is the last use. IsKill will be unset if reg is reused
1799 // unless it's a two-address operand.
1800 if (!MI.isRegTiedToDefOperand(i) &&
1801 KilledMIRegs.count(VirtReg) == 0) {
1802 MI.getOperand(i).setIsKill();
1803 KilledMIRegs.insert(VirtReg);
1806 UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1807 DOUT << '\t' << *prior(MII);
1809 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1810 MI.getOperand(i).setReg(RReg);
1811 MI.getOperand(i).setSubReg(0);
1814 // Ok - now we can remove stores that have been confirmed dead.
1815 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1816 // This was the last use and the spilled value is still available
1817 // for reuse. That means the spill was unnecessary!
1818 int PDSSlot = PotentialDeadStoreSlots[j];
1819 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1821 DOUT << "Removed dead store:\t" << *DeadStore;
1822 InvalidateKills(*DeadStore, RegKills, KillOps);
1823 VRM.RemoveMachineInstrFromMaps(DeadStore);
1824 MBB.erase(DeadStore);
1825 MaybeDeadStores[PDSSlot] = NULL;
1834 // If we have folded references to memory operands, make sure we clear all
1835 // physical registers that may contain the value of the spilled virtual
1837 SmallSet<int, 2> FoldedSS;
1838 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1839 unsigned VirtReg = I->second.first;
1840 VirtRegMap::ModRef MR = I->second.second;
1841 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1843 // MI2VirtMap be can updated which invalidate the iterator.
1844 // Increment the iterator first.
1846 int SS = VRM.getStackSlot(VirtReg);
1847 if (SS == VirtRegMap::NO_STACK_SLOT)
1849 FoldedSS.insert(SS);
1850 DOUT << " - StackSlot: " << SS << "\n";
1852 // If this folded instruction is just a use, check to see if it's a
1853 // straight load from the virt reg slot.
1854 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1856 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1857 if (DestReg && FrameIdx == SS) {
1858 // If this spill slot is available, turn it into a copy (or nothing)
1859 // instead of leaving it as a load!
1860 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1861 DOUT << "Promoted Load To Copy: " << MI;
1862 if (DestReg != InReg) {
1863 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1864 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1865 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1866 unsigned SubIdx = DefMO->getSubReg();
1867 // Revisit the copy so we make sure to notice the effects of the
1868 // operation on the destreg (either needing to RA it if it's
1869 // virtual or needing to clobber any values if it's physical).
1871 --NextMII; // backtrack to the copy.
1872 // Propagate the sub-register index over.
1874 DefMO = NextMII->findRegisterDefOperand(DestReg);
1875 DefMO->setSubReg(SubIdx);
1879 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1880 KillOpnd->setIsKill();
1884 DOUT << "Removing now-noop copy: " << MI;
1885 // Unset last kill since it's being reused.
1886 InvalidateKill(InReg, RegKills, KillOps);
1887 Spills.disallowClobberPhysReg(InReg);
1890 InvalidateKills(MI, RegKills, KillOps);
1891 VRM.RemoveMachineInstrFromMaps(&MI);
1894 goto ProcessNextInst;
1897 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1898 SmallVector<MachineInstr*, 4> NewMIs;
1900 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1901 MBB.insert(MII, NewMIs[0]);
1902 InvalidateKills(MI, RegKills, KillOps);
1903 VRM.RemoveMachineInstrFromMaps(&MI);
1906 --NextMII; // backtrack to the unfolded instruction.
1908 goto ProcessNextInst;
1913 // If this reference is not a use, any previous store is now dead.
1914 // Otherwise, the store to this stack slot is not dead anymore.
1915 MachineInstr* DeadStore = MaybeDeadStores[SS];
1917 bool isDead = !(MR & VirtRegMap::isRef);
1918 MachineInstr *NewStore = NULL;
1919 if (MR & VirtRegMap::isModRef) {
1920 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1921 SmallVector<MachineInstr*, 4> NewMIs;
1922 // We can reuse this physreg as long as we are allowed to clobber
1923 // the value and there isn't an earlier def that has already clobbered
1926 !ReusedOperands.isClobbered(PhysReg) &&
1927 Spills.canClobberPhysReg(PhysReg) &&
1928 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1929 MachineOperand *KillOpnd =
1930 DeadStore->findRegisterUseOperand(PhysReg, true);
1931 // Note, if the store is storing a sub-register, it's possible the
1932 // super-register is needed below.
1933 if (KillOpnd && !KillOpnd->getSubReg() &&
1934 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1935 MBB.insert(MII, NewMIs[0]);
1936 NewStore = NewMIs[1];
1937 MBB.insert(MII, NewStore);
1938 VRM.addSpillSlotUse(SS, NewStore);
1939 InvalidateKills(MI, RegKills, KillOps);
1940 VRM.RemoveMachineInstrFromMaps(&MI);
1944 --NextMII; // backtrack to the unfolded instruction.
1952 if (isDead) { // Previous store is dead.
1953 // If we get here, the store is dead, nuke it now.
1954 DOUT << "Removed dead store:\t" << *DeadStore;
1955 InvalidateKills(*DeadStore, RegKills, KillOps);
1956 VRM.RemoveMachineInstrFromMaps(DeadStore);
1957 MBB.erase(DeadStore);
1962 MaybeDeadStores[SS] = NULL;
1964 // Treat this store as a spill merged into a copy. That makes the
1965 // stack slot value available.
1966 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1967 goto ProcessNextInst;
1971 // If the spill slot value is available, and this is a new definition of
1972 // the value, the value is not available anymore.
1973 if (MR & VirtRegMap::isMod) {
1974 // Notice that the value in this stack slot has been modified.
1975 Spills.ModifyStackSlotOrReMat(SS);
1977 // If this is *just* a mod of the value, check to see if this is just a
1978 // store to the spill slot (i.e. the spill got merged into the copy). If
1979 // so, realize that the vreg is available now, and add the store to the
1980 // MaybeDeadStore info.
1982 if (!(MR & VirtRegMap::isRef)) {
1983 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1984 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1985 "Src hasn't been allocated yet?");
1987 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
1988 Spills, RegKills, KillOps, TRI, VRM)) {
1989 NextMII = next(MII);
1991 goto ProcessNextInst;
1994 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
1995 // this as a potentially dead store in case there is a subsequent
1996 // store into the stack slot without a read from it.
1997 MaybeDeadStores[StackSlot] = &MI;
1999 // If the stack slot value was previously available in some other
2000 // register, change it now. Otherwise, make the register
2001 // available in PhysReg.
2002 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2008 // Process all of the spilled defs.
2009 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2010 MachineOperand &MO = MI.getOperand(i);
2011 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2014 unsigned VirtReg = MO.getReg();
2015 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2016 // Check to see if this is a noop copy. If so, eliminate the
2017 // instruction before considering the dest reg to be changed.
2018 unsigned Src, Dst, SrcSR, DstSR;
2019 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2021 DOUT << "Removing now-noop copy: " << MI;
2022 SmallVector<unsigned, 2> KillRegs;
2023 InvalidateKills(MI, RegKills, KillOps, &KillRegs);
2024 if (MO.isDead() && !KillRegs.empty()) {
2025 // Source register or an implicit super/sub-register use is killed.
2026 assert(KillRegs[0] == Dst ||
2027 TRI->isSubRegister(KillRegs[0], Dst) ||
2028 TRI->isSuperRegister(KillRegs[0], Dst));
2029 // Last def is now dead.
2030 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps);
2032 VRM.RemoveMachineInstrFromMaps(&MI);
2035 Spills.disallowClobberPhysReg(VirtReg);
2036 goto ProcessNextInst;
2039 // If it's not a no-op copy, it clobbers the value in the destreg.
2040 Spills.ClobberPhysReg(VirtReg);
2041 ReusedOperands.markClobbered(VirtReg);
2043 // Check to see if this instruction is a load from a stack slot into
2044 // a register. If so, this provides the stack slot value in the reg.
2046 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2047 assert(DestReg == VirtReg && "Unknown load situation!");
2049 // If it is a folded reference, then it's not safe to clobber.
2050 bool Folded = FoldedSS.count(FrameIdx);
2051 // Otherwise, if it wasn't available, remember that it is now!
2052 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2053 goto ProcessNextInst;
2059 unsigned SubIdx = MO.getSubReg();
2060 bool DoReMat = VRM.isReMaterialized(VirtReg);
2062 ReMatDefs.insert(&MI);
2064 // The only vregs left are stack slot definitions.
2065 int StackSlot = VRM.getStackSlot(VirtReg);
2066 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2068 // If this def is part of a two-address operand, make sure to execute
2069 // the store from the correct physical register.
2072 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2073 PhysReg = MI.getOperand(TiedOp).getReg();
2075 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2076 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2077 "Can't find corresponding super-register!");
2081 PhysReg = VRM.getPhys(VirtReg);
2082 if (ReusedOperands.isClobbered(PhysReg)) {
2083 // Another def has taken the assigned physreg. It must have been a
2084 // use&def which got it due to reuse. Undo the reuse!
2085 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2086 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2090 assert(PhysReg && "VR not assigned a physical register?");
2091 RegInfo->setPhysRegUsed(PhysReg);
2092 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2093 ReusedOperands.markClobbered(RReg);
2094 MI.getOperand(i).setReg(RReg);
2095 MI.getOperand(i).setSubReg(0);
2098 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2099 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2100 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2101 NextMII = next(MII);
2103 // Check to see if this is a noop copy. If so, eliminate the
2104 // instruction before considering the dest reg to be changed.
2106 unsigned Src, Dst, SrcSR, DstSR;
2107 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2109 DOUT << "Removing now-noop copy: " << MI;
2110 InvalidateKills(MI, RegKills, KillOps);
2111 VRM.RemoveMachineInstrFromMaps(&MI);
2114 UpdateKills(*LastStore, RegKills, KillOps, TRI);
2115 goto ProcessNextInst;
2121 DistanceMap.insert(std::make_pair(&MI, Dist++));
2122 if (!Erased && !BackTracked) {
2123 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2124 UpdateKills(*II, RegKills, KillOps, TRI);
2133 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2134 switch (RewriterOpt) {
2135 default: assert(0 && "Unreachable!");
2137 return new LocalRewriter();
2139 return new SimpleRewriter();