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/Support/ErrorHandling.h"
14 #include "llvm/ADT/DepthFirstIterator.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/STLExtras.h"
20 STATISTIC(NumDSE , "Number of dead stores elided");
21 STATISTIC(NumDSS , "Number of dead spill slots removed");
22 STATISTIC(NumCommutes, "Number of instructions commuted");
23 STATISTIC(NumDRM , "Number of re-materializable defs elided");
24 STATISTIC(NumStores , "Number of stores added");
25 STATISTIC(NumPSpills , "Number of physical register spills");
26 STATISTIC(NumOmitted , "Number of reloads omited");
27 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
28 STATISTIC(NumCopified, "Number of available reloads turned into copies");
29 STATISTIC(NumReMats , "Number of re-materialization");
30 STATISTIC(NumLoads , "Number of loads added");
31 STATISTIC(NumReused , "Number of values reused");
32 STATISTIC(NumDCE , "Number of copies elided");
33 STATISTIC(NumSUnfold , "Number of stores unfolded");
34 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
37 enum RewriterName { local, trivial };
40 static cl::opt<RewriterName>
41 RewriterOpt("rewriter",
42 cl::desc("Rewriter to use: (default: local)"),
44 cl::values(clEnumVal(local, "local rewriter"),
45 clEnumVal(trivial, "trivial rewriter"),
49 VirtRegRewriter::~VirtRegRewriter() {}
53 /// This class is intended for use with the new spilling framework only. It
54 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
56 struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
58 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
60 DOUT << "********** REWRITE MACHINE CODE **********\n";
61 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
62 MachineRegisterInfo *mri = &MF.getRegInfo();
66 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
67 liItr != liEnd; ++liItr) {
69 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
70 if (VRM.hasPhys(liItr->first)) {
71 unsigned preg = VRM.getPhys(liItr->first);
72 mri->replaceRegWith(liItr->first, preg);
73 mri->setPhysRegUsed(preg);
78 if (!liItr->second->empty()) {
79 mri->setPhysRegUsed(liItr->first);
89 // ************************************************************************ //
91 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
92 /// from top down, keep track of which spill slots or remat are available in
95 /// Note that not all physregs are created equal here. In particular, some
96 /// physregs are reloads that we are allowed to clobber or ignore at any time.
97 /// Other physregs are values that the register allocated program is using
98 /// that we cannot CHANGE, but we can read if we like. We keep track of this
99 /// on a per-stack-slot / remat id basis as the low bit in the value of the
100 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
101 /// this bit and addAvailable sets it if.
102 class VISIBILITY_HIDDEN AvailableSpills {
103 const TargetRegisterInfo *TRI;
104 const TargetInstrInfo *TII;
106 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
107 // or remat'ed virtual register values that are still available, due to
108 // being loaded or stored to, but not invalidated yet.
109 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
111 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
112 // indicating which stack slot values are currently held by a physreg. This
113 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
114 // physreg is modified.
115 std::multimap<unsigned, int> PhysRegsAvailable;
117 void disallowClobberPhysRegOnly(unsigned PhysReg);
119 void ClobberPhysRegOnly(unsigned PhysReg);
121 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
122 : TRI(tri), TII(tii) {
125 /// clear - Reset the state.
127 SpillSlotsOrReMatsAvailable.clear();
128 PhysRegsAvailable.clear();
131 const TargetRegisterInfo *getRegInfo() const { return TRI; }
133 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
134 /// available in a physical register, return that PhysReg, otherwise
136 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
137 std::map<int, unsigned>::const_iterator I =
138 SpillSlotsOrReMatsAvailable.find(Slot);
139 if (I != SpillSlotsOrReMatsAvailable.end()) {
140 return I->second >> 1; // Remove the CanClobber bit.
145 /// addAvailable - Mark that the specified stack slot / remat is available
146 /// in the specified physreg. If CanClobber is true, the physreg can be
147 /// modified at any time without changing the semantics of the program.
148 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
149 // If this stack slot is thought to be available in some other physreg,
150 // remove its record.
151 ModifyStackSlotOrReMat(SlotOrReMat);
153 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
154 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
155 (unsigned)CanClobber;
157 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
158 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
160 DOUT << "Remembering SS#" << SlotOrReMat;
161 DOUT << " in physreg " << TRI->getName(Reg) << "\n";
164 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
165 /// the value of the specified stackslot register if it desires. The
166 /// specified stack slot must be available in a physreg for this query to
168 bool canClobberPhysRegForSS(int SlotOrReMat) const {
169 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
170 "Value not available!");
171 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
174 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
175 /// physical register where values for some stack slot(s) might be
177 bool canClobberPhysReg(unsigned PhysReg) const {
178 std::multimap<unsigned, int>::const_iterator I =
179 PhysRegsAvailable.lower_bound(PhysReg);
180 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
181 int SlotOrReMat = I->second;
183 if (!canClobberPhysRegForSS(SlotOrReMat))
189 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
190 /// stackslot register. The register is still available but is no longer
191 /// allowed to be modifed.
192 void disallowClobberPhysReg(unsigned PhysReg);
194 /// ClobberPhysReg - This is called when the specified physreg changes
195 /// value. We use this to invalidate any info about stuff that lives in
196 /// it and any of its aliases.
197 void ClobberPhysReg(unsigned PhysReg);
199 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
200 /// slot changes. This removes information about which register the
201 /// previous value for this slot lives in (as the previous value is dead
203 void ModifyStackSlotOrReMat(int SlotOrReMat);
205 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
206 /// into the specified MBB. Add available physical registers as potential
207 /// live-in's. If they are reused in the MBB, they will be added to the
208 /// live-in set to make register scavenger and post-allocation scheduler.
209 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
210 std::vector<MachineOperand*> &KillOps);
213 // ************************************************************************ //
215 // ReusedOp - For each reused operand, we keep track of a bit of information,
216 // in case we need to rollback upon processing a new operand. See comments
219 // The MachineInstr operand that reused an available value.
222 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
223 unsigned StackSlotOrReMat;
225 // PhysRegReused - The physical register the value was available in.
226 unsigned PhysRegReused;
228 // AssignedPhysReg - The physreg that was assigned for use by the reload.
229 unsigned AssignedPhysReg;
231 // VirtReg - The virtual register itself.
234 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
236 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
237 AssignedPhysReg(apr), VirtReg(vreg) {}
240 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
241 /// is reused instead of reloaded.
242 class VISIBILITY_HIDDEN ReuseInfo {
244 std::vector<ReusedOp> Reuses;
245 BitVector PhysRegsClobbered;
247 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
248 PhysRegsClobbered.resize(tri->getNumRegs());
251 bool hasReuses() const {
252 return !Reuses.empty();
255 /// addReuse - If we choose to reuse a virtual register that is already
256 /// available instead of reloading it, remember that we did so.
257 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
258 unsigned PhysRegReused, unsigned AssignedPhysReg,
260 // If the reload is to the assigned register anyway, no undo will be
262 if (PhysRegReused == AssignedPhysReg) return;
264 // Otherwise, remember this.
265 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
266 AssignedPhysReg, VirtReg));
269 void markClobbered(unsigned PhysReg) {
270 PhysRegsClobbered.set(PhysReg);
273 bool isClobbered(unsigned PhysReg) const {
274 return PhysRegsClobbered.test(PhysReg);
277 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
278 /// is some other operand that is using the specified register, either pick
279 /// a new register to use, or evict the previous reload and use this reg.
280 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
281 AvailableSpills &Spills,
282 std::vector<MachineInstr*> &MaybeDeadStores,
283 SmallSet<unsigned, 8> &Rejected,
285 std::vector<MachineOperand*> &KillOps,
288 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
289 /// 'Rejected' set to remember which registers have been considered and
290 /// rejected for the reload. This avoids infinite looping in case like
293 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
294 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
296 /// sees r1 is taken by t2, tries t2's reload register r0
297 /// sees r0 is taken by t3, tries t3's reload register r1
298 /// sees r1 is taken by t2, tries t2's reload register r0 ...
299 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
300 AvailableSpills &Spills,
301 std::vector<MachineInstr*> &MaybeDeadStores,
303 std::vector<MachineOperand*> &KillOps,
305 SmallSet<unsigned, 8> Rejected;
306 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
307 RegKills, KillOps, VRM);
312 // ****************** //
313 // Utility Functions //
314 // ****************** //
316 /// findSinglePredSuccessor - Return via reference a vector of machine basic
317 /// blocks each of which is a successor of the specified BB and has no other
319 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
320 SmallVectorImpl<MachineBasicBlock *> &Succs) {
321 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
322 SE = MBB->succ_end(); SI != SE; ++SI) {
323 MachineBasicBlock *SuccMBB = *SI;
324 if (SuccMBB->pred_size() == 1)
325 Succs.push_back(SuccMBB);
329 /// InvalidateKill - Invalidate register kill information for a specific
330 /// register. This also unsets the kills marker on the last kill operand.
331 static void InvalidateKill(unsigned Reg,
332 const TargetRegisterInfo* TRI,
334 std::vector<MachineOperand*> &KillOps) {
336 KillOps[Reg]->setIsKill(false);
337 // KillOps[Reg] might be a def of a super-register.
338 unsigned KReg = KillOps[Reg]->getReg();
339 KillOps[KReg] = NULL;
340 RegKills.reset(KReg);
341 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
343 KillOps[*SR]->setIsKill(false);
351 /// InvalidateKills - MI is going to be deleted. If any of its operands are
352 /// marked kill, then invalidate the information.
353 static void InvalidateKills(MachineInstr &MI,
354 const TargetRegisterInfo* TRI,
356 std::vector<MachineOperand*> &KillOps,
357 SmallVector<unsigned, 2> *KillRegs = NULL) {
358 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
359 MachineOperand &MO = MI.getOperand(i);
360 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
362 unsigned Reg = MO.getReg();
363 if (TargetRegisterInfo::isVirtualRegister(Reg))
366 KillRegs->push_back(Reg);
367 assert(Reg < KillOps.size());
368 if (KillOps[Reg] == &MO) {
371 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
381 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
382 /// (since it's spill instruction is removed), mark it isDead. Also checks if
383 /// the def MI has other definition operands that are not dead. Returns it by
385 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
386 MachineInstr &NewDef, unsigned Reg,
388 // Due to remat, it's possible this reg isn't being reused. That is,
389 // the def of this reg (by prev MI) is now dead.
390 MachineInstr *DefMI = I;
391 MachineOperand *DefOp = NULL;
392 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
393 MachineOperand &MO = DefMI->getOperand(i);
394 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
396 if (MO.getReg() == Reg)
398 else if (!MO.isDead())
404 bool FoundUse = false, Done = false;
405 MachineBasicBlock::iterator E = &NewDef;
407 for (; !Done && I != E; ++I) {
408 MachineInstr *NMI = I;
409 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
410 MachineOperand &MO = NMI->getOperand(j);
411 if (!MO.isReg() || MO.getReg() != Reg)
415 Done = true; // Stop after scanning all the operands of this MI.
426 /// UpdateKills - Track and update kill info. If a MI reads a register that is
427 /// marked kill, then it must be due to register reuse. Transfer the kill info
429 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
431 std::vector<MachineOperand*> &KillOps) {
432 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
433 MachineOperand &MO = MI.getOperand(i);
434 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
436 unsigned Reg = MO.getReg();
440 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
441 // That can't be right. Register is killed but not re-defined and it's
442 // being reused. Let's fix that.
443 KillOps[Reg]->setIsKill(false);
444 // KillOps[Reg] might be a def of a super-register.
445 unsigned KReg = KillOps[Reg]->getReg();
446 KillOps[KReg] = NULL;
447 RegKills.reset(KReg);
449 // Must be a def of a super-register. Its other sub-regsters are no
450 // longer killed as well.
451 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
456 if (!MI.isRegTiedToDefOperand(i))
457 // Unless it's a two-address operand, this is the new kill.
463 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
470 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
471 const MachineOperand &MO = MI.getOperand(i);
472 if (!MO.isReg() || !MO.isDef())
474 unsigned Reg = MO.getReg();
477 // It also defines (or partially define) aliases.
478 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
485 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
487 static void ReMaterialize(MachineBasicBlock &MBB,
488 MachineBasicBlock::iterator &MII,
489 unsigned DestReg, unsigned Reg,
490 const TargetInstrInfo *TII,
491 const TargetRegisterInfo *TRI,
493 TII->reMaterialize(MBB, MII, DestReg, 0, VRM.getReMaterializedMI(Reg));
494 MachineInstr *NewMI = prior(MII);
495 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
496 MachineOperand &MO = NewMI->getOperand(i);
497 if (!MO.isReg() || MO.getReg() == 0)
499 unsigned VirtReg = MO.getReg();
500 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
503 unsigned SubIdx = MO.getSubReg();
504 unsigned Phys = VRM.getPhys(VirtReg);
506 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
513 /// findSuperReg - Find the SubReg's super-register of given register class
514 /// where its SubIdx sub-register is SubReg.
515 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
516 unsigned SubIdx, const TargetRegisterInfo *TRI) {
517 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
520 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
526 // ******************************** //
527 // Available Spills Implementation //
528 // ******************************** //
530 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
531 /// stackslot register. The register is still available but is no longer
532 /// allowed to be modifed.
533 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
534 std::multimap<unsigned, int>::iterator I =
535 PhysRegsAvailable.lower_bound(PhysReg);
536 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
537 int SlotOrReMat = I->second;
539 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
540 "Bidirectional map mismatch!");
541 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
542 DOUT << "PhysReg " << TRI->getName(PhysReg)
543 << " copied, it is available for use but can no longer be modified\n";
547 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
548 /// stackslot register and its aliases. The register and its aliases may
549 /// still available but is no longer allowed to be modifed.
550 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
551 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
552 disallowClobberPhysRegOnly(*AS);
553 disallowClobberPhysRegOnly(PhysReg);
556 /// ClobberPhysRegOnly - This is called when the specified physreg changes
557 /// value. We use this to invalidate any info about stuff we thing lives in it.
558 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
559 std::multimap<unsigned, int>::iterator I =
560 PhysRegsAvailable.lower_bound(PhysReg);
561 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
562 int SlotOrReMat = I->second;
563 PhysRegsAvailable.erase(I++);
564 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
565 "Bidirectional map mismatch!");
566 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
567 DOUT << "PhysReg " << TRI->getName(PhysReg)
568 << " clobbered, invalidating ";
569 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
570 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
572 DOUT << "SS#" << SlotOrReMat << "\n";
576 /// ClobberPhysReg - This is called when the specified physreg changes
577 /// value. We use this to invalidate any info about stuff we thing lives in
578 /// it and any of its aliases.
579 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
580 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
581 ClobberPhysRegOnly(*AS);
582 ClobberPhysRegOnly(PhysReg);
585 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
586 /// into the specified MBB. Add available physical registers as potential
587 /// live-in's. If they are reused in the MBB, they will be added to the
588 /// live-in set to make register scavenger and post-allocation scheduler.
589 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
591 std::vector<MachineOperand*> &KillOps) {
592 std::set<unsigned> NotAvailable;
593 for (std::multimap<unsigned, int>::iterator
594 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
596 unsigned Reg = I->first;
597 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
598 // FIXME: A temporary workaround. We can't reuse available value if it's
599 // not safe to move the def of the virtual register's class. e.g.
600 // X86::RFP* register classes. Do not add it as a live-in.
601 if (!TII->isSafeToMoveRegClassDefs(RC))
602 // This is no longer available.
603 NotAvailable.insert(Reg);
606 InvalidateKill(Reg, TRI, RegKills, KillOps);
609 // Skip over the same register.
610 std::multimap<unsigned, int>::iterator NI = next(I);
611 while (NI != E && NI->first == Reg) {
617 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
618 E = NotAvailable.end(); I != E; ++I) {
620 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
622 ClobberPhysReg(*SubRegs);
626 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
627 /// slot changes. This removes information about which register the previous
628 /// value for this slot lives in (as the previous value is dead now).
629 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
630 std::map<int, unsigned>::iterator It =
631 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
632 if (It == SpillSlotsOrReMatsAvailable.end()) return;
633 unsigned Reg = It->second >> 1;
634 SpillSlotsOrReMatsAvailable.erase(It);
636 // This register may hold the value of multiple stack slots, only remove this
637 // stack slot from the set of values the register contains.
638 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
640 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
641 "Map inverse broken!");
642 if (I->second == SlotOrReMat) break;
644 PhysRegsAvailable.erase(I);
647 // ************************** //
648 // Reuse Info Implementation //
649 // ************************** //
651 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
652 /// is some other operand that is using the specified register, either pick
653 /// a new register to use, or evict the previous reload and use this reg.
654 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
655 AvailableSpills &Spills,
656 std::vector<MachineInstr*> &MaybeDeadStores,
657 SmallSet<unsigned, 8> &Rejected,
659 std::vector<MachineOperand*> &KillOps,
661 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
664 if (Reuses.empty()) return PhysReg; // This is most often empty.
666 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
667 ReusedOp &Op = Reuses[ro];
668 // If we find some other reuse that was supposed to use this register
669 // exactly for its reload, we can change this reload to use ITS reload
670 // register. That is, unless its reload register has already been
671 // considered and subsequently rejected because it has also been reused
672 // by another operand.
673 if (Op.PhysRegReused == PhysReg &&
674 Rejected.count(Op.AssignedPhysReg) == 0) {
675 // Yup, use the reload register that we didn't use before.
676 unsigned NewReg = Op.AssignedPhysReg;
677 Rejected.insert(PhysReg);
678 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
679 RegKills, KillOps, VRM);
681 // Otherwise, we might also have a problem if a previously reused
682 // value aliases the new register. If so, codegen the previous reload
684 unsigned PRRU = Op.PhysRegReused;
685 const TargetRegisterInfo *TRI = Spills.getRegInfo();
686 if (TRI->areAliases(PRRU, PhysReg)) {
687 // Okay, we found out that an alias of a reused register
688 // was used. This isn't good because it means we have
689 // to undo a previous reuse.
690 MachineBasicBlock *MBB = MI->getParent();
691 const TargetRegisterClass *AliasRC =
692 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
694 // Copy Op out of the vector and remove it, we're going to insert an
695 // explicit load for it.
697 Reuses.erase(Reuses.begin()+ro);
699 // Ok, we're going to try to reload the assigned physreg into the
700 // slot that we were supposed to in the first place. However, that
701 // register could hold a reuse. Check to see if it conflicts or
702 // would prefer us to use a different register.
703 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
704 MI, Spills, MaybeDeadStores,
705 Rejected, RegKills, KillOps, VRM);
707 MachineBasicBlock::iterator MII = MI;
708 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
709 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
711 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
712 NewOp.StackSlotOrReMat, AliasRC);
713 MachineInstr *LoadMI = prior(MII);
714 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
715 // Any stores to this stack slot are not dead anymore.
716 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
719 Spills.ClobberPhysReg(NewPhysReg);
720 Spills.ClobberPhysReg(NewOp.PhysRegReused);
722 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
723 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
724 MI->getOperand(NewOp.Operand).setReg(RReg);
725 MI->getOperand(NewOp.Operand).setSubReg(0);
727 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
729 UpdateKills(*MII, TRI, RegKills, KillOps);
730 DOUT << '\t' << *MII;
732 DOUT << "Reuse undone!\n";
735 // Finally, PhysReg is now available, go ahead and use it.
743 // ************************************************************************ //
745 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
746 /// stack slot mod/ref. It also checks if it's possible to unfold the
747 /// instruction by having it define a specified physical register instead.
748 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
749 const TargetInstrInfo *TII,
750 const TargetRegisterInfo *TRI,
752 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
756 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
757 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
758 unsigned VirtReg = I->second.first;
759 VirtRegMap::ModRef MR = I->second.second;
760 if (MR & VirtRegMap::isModRef)
761 if (VRM.getStackSlot(VirtReg) == SS) {
762 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
769 // Does the instruction uses a register that overlaps the scratch register?
770 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
771 MachineOperand &MO = MI.getOperand(i);
772 if (!MO.isReg() || MO.getReg() == 0)
774 unsigned Reg = MO.getReg();
775 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
776 if (!VRM.hasPhys(Reg))
778 Reg = VRM.getPhys(Reg);
780 if (TRI->regsOverlap(PhysReg, Reg))
786 /// FindFreeRegister - Find a free register of a given register class by looking
787 /// at (at most) the last two machine instructions.
788 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
789 MachineBasicBlock &MBB,
790 const TargetRegisterClass *RC,
791 const TargetRegisterInfo *TRI,
792 BitVector &AllocatableRegs) {
793 BitVector Defs(TRI->getNumRegs());
794 BitVector Uses(TRI->getNumRegs());
795 SmallVector<unsigned, 4> LocalUses;
796 SmallVector<unsigned, 4> Kills;
798 // Take a look at 2 instructions at most.
799 for (unsigned Count = 0; Count < 2; ++Count) {
800 if (MII == MBB.begin())
802 MachineInstr *PrevMI = prior(MII);
803 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
804 MachineOperand &MO = PrevMI->getOperand(i);
805 if (!MO.isReg() || MO.getReg() == 0)
807 unsigned Reg = MO.getReg();
810 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
813 LocalUses.push_back(Reg);
814 if (MO.isKill() && AllocatableRegs[Reg])
815 Kills.push_back(Reg);
819 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
820 unsigned Kill = Kills[i];
821 if (!Defs[Kill] && !Uses[Kill] &&
822 TRI->getPhysicalRegisterRegClass(Kill) == RC)
825 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
826 unsigned Reg = LocalUses[i];
828 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
839 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
840 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
841 MachineOperand &MO = MI->getOperand(i);
842 if (MO.isReg() && MO.getReg() == VirtReg)
849 bool operator()(const std::pair<MachineInstr*, int> &A,
850 const std::pair<MachineInstr*, int> &B) {
851 return A.second < B.second;
856 // ***************************** //
857 // Local Spiller Implementation //
858 // ***************************** //
860 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
861 MachineRegisterInfo *RegInfo;
862 const TargetRegisterInfo *TRI;
863 const TargetInstrInfo *TII;
864 BitVector AllocatableRegs;
865 DenseMap<MachineInstr*, unsigned> DistanceMap;
868 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
869 LiveIntervals* LIs) {
870 RegInfo = &MF.getRegInfo();
871 TRI = MF.getTarget().getRegisterInfo();
872 TII = MF.getTarget().getInstrInfo();
873 AllocatableRegs = TRI->getAllocatableSet(MF);
874 DOUT << "\n**** Local spiller rewriting function '"
875 << MF.getFunction()->getName() << "':\n";
876 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
880 // Spills - Keep track of which spilled values are available in physregs
881 // so that we can choose to reuse the physregs instead of emitting
882 // reloads. This is usually refreshed per basic block.
883 AvailableSpills Spills(TRI, TII);
885 // Keep track of kill information.
886 BitVector RegKills(TRI->getNumRegs());
887 std::vector<MachineOperand*> KillOps;
888 KillOps.resize(TRI->getNumRegs(), NULL);
890 // SingleEntrySuccs - Successor blocks which have a single predecessor.
891 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
892 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
894 // Traverse the basic blocks depth first.
895 MachineBasicBlock *Entry = MF.begin();
896 SmallPtrSet<MachineBasicBlock*,16> Visited;
897 for (df_ext_iterator<MachineBasicBlock*,
898 SmallPtrSet<MachineBasicBlock*,16> >
899 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
901 MachineBasicBlock *MBB = *DFI;
902 if (!EarlyVisited.count(MBB))
903 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
905 // If this MBB is the only predecessor of a successor. Keep the
906 // availability information and visit it next.
908 // Keep visiting single predecessor successor as long as possible.
909 SinglePredSuccs.clear();
910 findSinglePredSuccessor(MBB, SinglePredSuccs);
911 if (SinglePredSuccs.empty())
914 // FIXME: More than one successors, each of which has MBB has
915 // the only predecessor.
916 MBB = SinglePredSuccs[0];
917 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
918 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
919 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
924 // Clear the availability info.
928 DOUT << "**** Post Machine Instrs ****\n";
931 // Mark unused spill slots.
932 MachineFrameInfo *MFI = MF.getFrameInfo();
933 int SS = VRM.getLowSpillSlot();
934 if (SS != VirtRegMap::NO_STACK_SLOT)
935 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
936 if (!VRM.isSpillSlotUsed(SS)) {
937 MFI->RemoveStackObject(SS);
946 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
947 /// a scratch register is available.
948 /// xorq %r12<kill>, %r13
949 /// addq %rax, -184(%rbp)
950 /// addq %r13, -184(%rbp)
952 /// xorq %r12<kill>, %r13
953 /// movq -184(%rbp), %r12
956 /// movq %r12, -184(%rbp)
957 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
958 MachineBasicBlock &MBB,
959 MachineBasicBlock::iterator &MII,
960 std::vector<MachineInstr*> &MaybeDeadStores,
961 AvailableSpills &Spills,
963 std::vector<MachineOperand*> &KillOps,
966 MachineBasicBlock::iterator NextMII = next(MII);
967 if (NextMII == MBB.end())
970 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
973 // Now let's see if the last couple of instructions happens to have freed up
975 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
976 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
980 MachineFunction &MF = *MBB.getParent();
981 TRI = MF.getTarget().getRegisterInfo();
982 MachineInstr &MI = *MII;
983 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
986 // If the next instruction also folds the same SS modref and can be unfoled,
987 // then it's worthwhile to issue a load from SS into the free register and
988 // then unfold these instructions.
989 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
992 // Load from SS to the spare physical register.
993 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
994 // This invalidates Phys.
995 Spills.ClobberPhysReg(PhysReg);
996 // Remember it's available.
997 Spills.addAvailable(SS, PhysReg);
998 MaybeDeadStores[SS] = NULL;
1000 // Unfold current MI.
1001 SmallVector<MachineInstr*, 4> NewMIs;
1002 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1003 llvm_unreachable("Unable unfold the load / store folding instruction!");
1004 assert(NewMIs.size() == 1);
1005 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1006 VRM.transferRestorePts(&MI, NewMIs[0]);
1007 MII = MBB.insert(MII, NewMIs[0]);
1008 InvalidateKills(MI, TRI, RegKills, KillOps);
1009 VRM.RemoveMachineInstrFromMaps(&MI);
1013 // Unfold next instructions that fold the same SS.
1015 MachineInstr &NextMI = *NextMII;
1016 NextMII = next(NextMII);
1018 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1019 llvm_unreachable("Unable unfold the load / store folding instruction!");
1020 assert(NewMIs.size() == 1);
1021 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1022 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1023 MBB.insert(NextMII, NewMIs[0]);
1024 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1025 VRM.RemoveMachineInstrFromMaps(&NextMI);
1028 if (NextMII == MBB.end())
1030 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1032 // Store the value back into SS.
1033 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1034 MachineInstr *StoreMI = prior(NextMII);
1035 VRM.addSpillSlotUse(SS, StoreMI);
1036 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1041 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1042 /// instruction. e.g.
1044 /// movl %eax, -32(%ebp)
1045 /// movl -36(%ebp), %eax
1046 /// orl %eax, -32(%ebp)
1049 /// orl -36(%ebp), %eax
1050 /// mov %eax, -32(%ebp)
1051 /// This enables unfolding optimization for a subsequent instruction which will
1052 /// also eliminate the newly introduced store instruction.
1053 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1054 MachineBasicBlock::iterator &MII,
1055 std::vector<MachineInstr*> &MaybeDeadStores,
1056 AvailableSpills &Spills,
1057 BitVector &RegKills,
1058 std::vector<MachineOperand*> &KillOps,
1060 MachineFunction &MF = *MBB.getParent();
1061 MachineInstr &MI = *MII;
1062 unsigned UnfoldedOpc = 0;
1063 unsigned UnfoldPR = 0;
1064 unsigned UnfoldVR = 0;
1065 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1066 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1067 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1068 // Only transform a MI that folds a single register.
1071 UnfoldVR = I->second.first;
1072 VirtRegMap::ModRef MR = I->second.second;
1073 // MI2VirtMap be can updated which invalidate the iterator.
1074 // Increment the iterator first.
1076 if (VRM.isAssignedReg(UnfoldVR))
1078 // If this reference is not a use, any previous store is now dead.
1079 // Otherwise, the store to this stack slot is not dead anymore.
1080 FoldedSS = VRM.getStackSlot(UnfoldVR);
1081 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1082 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1083 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1084 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1087 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1096 // Look for other unfolding opportunities.
1097 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1098 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1101 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1102 MachineOperand &MO = MI.getOperand(i);
1103 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1105 unsigned VirtReg = MO.getReg();
1106 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1108 if (VRM.isAssignedReg(VirtReg)) {
1109 unsigned PhysReg = VRM.getPhys(VirtReg);
1110 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1112 } else if (VRM.isReMaterialized(VirtReg))
1114 int SS = VRM.getStackSlot(VirtReg);
1115 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1117 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1121 if (VRM.hasPhys(VirtReg)) {
1122 PhysReg = VRM.getPhys(VirtReg);
1123 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1127 // Ok, we'll need to reload the value into a register which makes
1128 // it impossible to perform the store unfolding optimization later.
1129 // Let's see if it is possible to fold the load if the store is
1130 // unfolded. This allows us to perform the store unfolding
1132 SmallVector<MachineInstr*, 4> NewMIs;
1133 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1134 assert(NewMIs.size() == 1);
1135 MachineInstr *NewMI = NewMIs.back();
1137 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1139 SmallVector<unsigned, 1> Ops;
1141 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1143 VRM.addSpillSlotUse(SS, FoldedMI);
1144 if (!VRM.hasPhys(UnfoldVR))
1145 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1146 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1147 MII = MBB.insert(MII, FoldedMI);
1148 InvalidateKills(MI, TRI, RegKills, KillOps);
1149 VRM.RemoveMachineInstrFromMaps(&MI);
1151 MF.DeleteMachineInstr(NewMI);
1154 MF.DeleteMachineInstr(NewMI);
1161 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1162 /// where SrcReg is r1 and it is tied to r0. Return true if after
1163 /// commuting this instruction it will be r0 = op r2, r1.
1164 static bool CommuteChangesDestination(MachineInstr *DefMI,
1165 const TargetInstrDesc &TID,
1167 const TargetInstrInfo *TII,
1169 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1171 if (!DefMI->getOperand(1).isReg() ||
1172 DefMI->getOperand(1).getReg() != SrcReg)
1175 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1177 unsigned SrcIdx1, SrcIdx2;
1178 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1180 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1187 /// CommuteToFoldReload -
1190 /// r1 = op r1, r2<kill>
1193 /// If op is commutable and r2 is killed, then we can xform these to
1194 /// r2 = op r2, fi#1
1196 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1197 MachineBasicBlock::iterator &MII,
1198 unsigned VirtReg, unsigned SrcReg, int SS,
1199 AvailableSpills &Spills,
1200 BitVector &RegKills,
1201 std::vector<MachineOperand*> &KillOps,
1202 const TargetRegisterInfo *TRI,
1204 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1207 MachineFunction &MF = *MBB.getParent();
1208 MachineInstr &MI = *MII;
1209 MachineBasicBlock::iterator DefMII = prior(MII);
1210 MachineInstr *DefMI = DefMII;
1211 const TargetInstrDesc &TID = DefMI->getDesc();
1213 if (DefMII != MBB.begin() &&
1214 TID.isCommutable() &&
1215 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1216 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1217 unsigned NewReg = NewDstMO.getReg();
1218 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1220 MachineInstr *ReloadMI = prior(DefMII);
1222 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1223 if (DestReg != SrcReg || FrameIdx != SS)
1225 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1229 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1231 assert(DefMI->getOperand(DefIdx).isReg() &&
1232 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1234 // Now commute def instruction.
1235 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1238 SmallVector<unsigned, 1> Ops;
1239 Ops.push_back(NewDstIdx);
1240 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1241 // Not needed since foldMemoryOperand returns new MI.
1242 MF.DeleteMachineInstr(CommutedMI);
1246 VRM.addSpillSlotUse(SS, FoldedMI);
1247 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1248 // Insert new def MI and spill MI.
1249 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1250 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1252 MachineInstr *StoreMI = MII;
1253 VRM.addSpillSlotUse(SS, StoreMI);
1254 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1255 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1257 // Delete all 3 old instructions.
1258 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1259 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1260 MBB.erase(ReloadMI);
1261 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1262 VRM.RemoveMachineInstrFromMaps(DefMI);
1264 InvalidateKills(MI, TRI, RegKills, KillOps);
1265 VRM.RemoveMachineInstrFromMaps(&MI);
1268 // If NewReg was previously holding value of some SS, it's now clobbered.
1269 // This has to be done now because it's a physical register. When this
1270 // instruction is re-visited, it's ignored.
1271 Spills.ClobberPhysReg(NewReg);
1280 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1281 /// the last store to the same slot is now dead. If so, remove the last store.
1282 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1283 MachineBasicBlock::iterator &MII,
1284 int Idx, unsigned PhysReg, int StackSlot,
1285 const TargetRegisterClass *RC,
1286 bool isAvailable, MachineInstr *&LastStore,
1287 AvailableSpills &Spills,
1288 SmallSet<MachineInstr*, 4> &ReMatDefs,
1289 BitVector &RegKills,
1290 std::vector<MachineOperand*> &KillOps,
1293 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1294 MachineInstr *StoreMI = next(MII);
1295 VRM.addSpillSlotUse(StackSlot, StoreMI);
1296 DOUT << "Store:\t" << *StoreMI;
1298 // If there is a dead store to this stack slot, nuke it now.
1300 DOUT << "Removed dead store:\t" << *LastStore;
1302 SmallVector<unsigned, 2> KillRegs;
1303 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1304 MachineBasicBlock::iterator PrevMII = LastStore;
1305 bool CheckDef = PrevMII != MBB.begin();
1308 VRM.RemoveMachineInstrFromMaps(LastStore);
1309 MBB.erase(LastStore);
1311 // Look at defs of killed registers on the store. Mark the defs
1312 // as dead since the store has been deleted and they aren't
1314 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1315 bool HasOtherDef = false;
1316 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1317 MachineInstr *DeadDef = PrevMII;
1318 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1319 // FIXME: This assumes a remat def does not have side effects.
1320 VRM.RemoveMachineInstrFromMaps(DeadDef);
1329 LastStore = next(MII);
1331 // If the stack slot value was previously available in some other
1332 // register, change it now. Otherwise, make the register available,
1334 Spills.ModifyStackSlotOrReMat(StackSlot);
1335 Spills.ClobberPhysReg(PhysReg);
1336 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1340 /// TransferDeadness - A identity copy definition is dead and it's being
1341 /// removed. Find the last def or use and mark it as dead / kill.
1342 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1343 unsigned Reg, BitVector &RegKills,
1344 std::vector<MachineOperand*> &KillOps,
1346 SmallPtrSet<MachineInstr*, 4> Seens;
1347 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1348 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1349 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1350 MachineInstr *UDMI = &*RI;
1351 if (UDMI->getParent() != MBB)
1353 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1354 if (DI == DistanceMap.end() || DI->second > CurDist)
1356 if (Seens.insert(UDMI))
1357 Refs.push_back(std::make_pair(UDMI, DI->second));
1362 std::sort(Refs.begin(), Refs.end(), RefSorter());
1364 while (!Refs.empty()) {
1365 MachineInstr *LastUDMI = Refs.back().first;
1368 MachineOperand *LastUD = NULL;
1369 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1370 MachineOperand &MO = LastUDMI->getOperand(i);
1371 if (!MO.isReg() || MO.getReg() != Reg)
1373 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1375 if (LastUDMI->isRegTiedToDefOperand(i))
1378 if (LastUD->isDef()) {
1379 // If the instruction has no side effect, delete it and propagate
1380 // backward further. Otherwise, mark is dead and we are done.
1381 const TargetInstrDesc &TID = LastUDMI->getDesc();
1382 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1383 TID.hasUnmodeledSideEffects()) {
1384 LastUD->setIsDead();
1387 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1388 MBB->erase(LastUDMI);
1390 LastUD->setIsKill();
1392 KillOps[Reg] = LastUD;
1398 /// rewriteMBB - Keep track of which spills are available even after the
1399 /// register allocator is done with them. If possible, avid reloading vregs.
1400 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1402 AvailableSpills &Spills, BitVector &RegKills,
1403 std::vector<MachineOperand*> &KillOps) {
1405 DOUT << "\n**** Local spiller rewriting MBB '"
1406 << MBB.getBasicBlock()->getName() << "':\n";
1408 MachineFunction &MF = *MBB.getParent();
1410 // MaybeDeadStores - When we need to write a value back into a stack slot,
1411 // keep track of the inserted store. If the stack slot value is never read
1412 // (because the value was used from some available register, for example), and
1413 // subsequently stored to, the original store is dead. This map keeps track
1414 // of inserted stores that are not used. If we see a subsequent store to the
1415 // same stack slot, the original store is deleted.
1416 std::vector<MachineInstr*> MaybeDeadStores;
1417 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1419 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1420 SmallSet<MachineInstr*, 4> ReMatDefs;
1423 SmallSet<unsigned, 2> KilledMIRegs;
1426 KillOps.resize(TRI->getNumRegs(), NULL);
1429 DistanceMap.clear();
1430 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1432 MachineBasicBlock::iterator NextMII = next(MII);
1434 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1435 bool Erased = false;
1436 bool BackTracked = false;
1437 if (OptimizeByUnfold(MBB, MII,
1438 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1439 NextMII = next(MII);
1441 MachineInstr &MI = *MII;
1443 if (VRM.hasEmergencySpills(&MI)) {
1444 // Spill physical register(s) in the rare case the allocator has run out
1445 // of registers to allocate.
1446 SmallSet<int, 4> UsedSS;
1447 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1448 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1449 unsigned PhysReg = EmSpills[i];
1450 const TargetRegisterClass *RC =
1451 TRI->getPhysicalRegisterRegClass(PhysReg);
1452 assert(RC && "Unable to determine register class!");
1453 int SS = VRM.getEmergencySpillSlot(RC);
1454 if (UsedSS.count(SS))
1455 llvm_unreachable("Need to spill more than one physical registers!");
1457 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1458 MachineInstr *StoreMI = prior(MII);
1459 VRM.addSpillSlotUse(SS, StoreMI);
1460 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1461 MachineInstr *LoadMI = next(MII);
1462 VRM.addSpillSlotUse(SS, LoadMI);
1465 NextMII = next(MII);
1468 // Insert restores here if asked to.
1469 if (VRM.isRestorePt(&MI)) {
1470 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1471 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1472 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1473 if (!VRM.getPreSplitReg(VirtReg))
1474 continue; // Split interval spilled again.
1475 unsigned Phys = VRM.getPhys(VirtReg);
1476 RegInfo->setPhysRegUsed(Phys);
1478 // Check if the value being restored if available. If so, it must be
1479 // from a predecessor BB that fallthrough into this BB. We do not
1485 // ... # r1 not clobbered
1488 bool DoReMat = VRM.isReMaterialized(VirtReg);
1489 int SSorRMId = DoReMat
1490 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1491 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1492 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1493 if (InReg == Phys) {
1494 // If the value is already available in the expected register, save
1495 // a reload / remat.
1497 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1499 DOUT << "Reusing SS#" << SSorRMId;
1500 DOUT << " from physreg "
1501 << TRI->getName(InReg) << " for vreg"
1502 << VirtReg <<" instead of reloading into physreg "
1503 << TRI->getName(Phys) << "\n";
1506 } else if (InReg && InReg != Phys) {
1508 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1510 DOUT << "Reusing SS#" << SSorRMId;
1511 DOUT << " from physreg "
1512 << TRI->getName(InReg) << " for vreg"
1513 << VirtReg <<" by copying it into physreg "
1514 << TRI->getName(Phys) << "\n";
1516 // If the reloaded / remat value is available in another register,
1517 // copy it to the desired register.
1518 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1520 // This invalidates Phys.
1521 Spills.ClobberPhysReg(Phys);
1522 // Remember it's available.
1523 Spills.addAvailable(SSorRMId, Phys);
1526 MachineInstr *CopyMI = prior(MII);
1527 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1528 KillOpnd->setIsKill();
1529 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1531 DOUT << '\t' << *CopyMI;
1536 if (VRM.isReMaterialized(VirtReg)) {
1537 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1539 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1540 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1541 MachineInstr *LoadMI = prior(MII);
1542 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1546 // This invalidates Phys.
1547 Spills.ClobberPhysReg(Phys);
1548 // Remember it's available.
1549 Spills.addAvailable(SSorRMId, Phys);
1551 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1552 DOUT << '\t' << *prior(MII);
1556 // Insert spills here if asked to.
1557 if (VRM.isSpillPt(&MI)) {
1558 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1559 VRM.getSpillPtSpills(&MI);
1560 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1561 unsigned VirtReg = SpillRegs[i].first;
1562 bool isKill = SpillRegs[i].second;
1563 if (!VRM.getPreSplitReg(VirtReg))
1564 continue; // Split interval spilled again.
1565 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1566 unsigned Phys = VRM.getPhys(VirtReg);
1567 int StackSlot = VRM.getStackSlot(VirtReg);
1568 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1569 MachineInstr *StoreMI = next(MII);
1570 VRM.addSpillSlotUse(StackSlot, StoreMI);
1571 DOUT << "Store:\t" << *StoreMI;
1572 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1574 NextMII = next(MII);
1577 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1579 ReuseInfo ReusedOperands(MI, TRI);
1580 SmallVector<unsigned, 4> VirtUseOps;
1581 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1582 MachineOperand &MO = MI.getOperand(i);
1583 if (!MO.isReg() || MO.getReg() == 0)
1584 continue; // Ignore non-register operands.
1586 unsigned VirtReg = MO.getReg();
1587 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1588 // Ignore physregs for spilling, but remember that it is used by this
1590 RegInfo->setPhysRegUsed(VirtReg);
1594 // We want to process implicit virtual register uses first.
1595 if (MO.isImplicit())
1596 // If the virtual register is implicitly defined, emit a implicit_def
1597 // before so scavenger knows it's "defined".
1598 // FIXME: This is a horrible hack done the by register allocator to
1599 // remat a definition with virtual register operand.
1600 VirtUseOps.insert(VirtUseOps.begin(), i);
1602 VirtUseOps.push_back(i);
1605 // Process all of the spilled uses and all non spilled reg references.
1606 SmallVector<int, 2> PotentialDeadStoreSlots;
1607 KilledMIRegs.clear();
1608 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1609 unsigned i = VirtUseOps[j];
1610 MachineOperand &MO = MI.getOperand(i);
1611 unsigned VirtReg = MO.getReg();
1612 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1613 "Not a virtual register?");
1615 unsigned SubIdx = MO.getSubReg();
1616 if (VRM.isAssignedReg(VirtReg)) {
1617 // This virtual register was assigned a physreg!
1618 unsigned Phys = VRM.getPhys(VirtReg);
1619 RegInfo->setPhysRegUsed(Phys);
1621 ReusedOperands.markClobbered(Phys);
1622 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1623 MI.getOperand(i).setReg(RReg);
1624 MI.getOperand(i).setSubReg(0);
1625 if (VRM.isImplicitlyDefined(VirtReg))
1626 // FIXME: Is this needed?
1627 BuildMI(MBB, &MI, MI.getDebugLoc(),
1628 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1632 // This virtual register is now known to be a spilled value.
1634 continue; // Handle defs in the loop below (handle use&def here though)
1636 bool AvoidReload = MO.isUndef();
1637 // Check if it is defined by an implicit def. It should not be spilled.
1638 // Note, this is for correctness reason. e.g.
1639 // 8 %reg1024<def> = IMPLICIT_DEF
1640 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1641 // The live range [12, 14) are not part of the r1024 live interval since
1642 // it's defined by an implicit def. It will not conflicts with live
1643 // interval of r1025. Now suppose both registers are spilled, you can
1644 // easily see a situation where both registers are reloaded before
1645 // the INSERT_SUBREG and both target registers that would overlap.
1646 bool DoReMat = VRM.isReMaterialized(VirtReg);
1647 int SSorRMId = DoReMat
1648 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1649 int ReuseSlot = SSorRMId;
1651 // Check to see if this stack slot is available.
1652 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1654 // If this is a sub-register use, make sure the reuse register is in the
1655 // right register class. For example, for x86 not all of the 32-bit
1656 // registers have accessible sub-registers.
1657 // Similarly so for EXTRACT_SUBREG. Consider this:
1659 // MOV32_mr fi#1, EDI
1661 // = EXTRACT_SUBREG fi#1
1662 // fi#1 is available in EDI, but it cannot be reused because it's not in
1663 // the right register file.
1664 if (PhysReg && !AvoidReload &&
1665 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1666 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1667 if (!RC->contains(PhysReg))
1671 if (PhysReg && !AvoidReload) {
1672 // This spilled operand might be part of a two-address operand. If this
1673 // is the case, then changing it will necessarily require changing the
1674 // def part of the instruction as well. However, in some cases, we
1675 // aren't allowed to modify the reused register. If none of these cases
1677 bool CanReuse = true;
1678 bool isTied = MI.isRegTiedToDefOperand(i);
1680 // Okay, we have a two address operand. We can reuse this physreg as
1681 // long as we are allowed to clobber the value and there isn't an
1682 // earlier def that has already clobbered the physreg.
1683 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1684 Spills.canClobberPhysReg(PhysReg);
1688 // If this stack slot value is already available, reuse it!
1689 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1690 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1692 DOUT << "Reusing SS#" << ReuseSlot;
1693 DOUT << " from physreg "
1694 << TRI->getName(PhysReg) << " for vreg"
1695 << VirtReg <<" instead of reloading into physreg "
1696 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1697 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1698 MI.getOperand(i).setReg(RReg);
1699 MI.getOperand(i).setSubReg(0);
1701 // The only technical detail we have is that we don't know that
1702 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1703 // later in the instruction. In particular, consider 'op V1, V2'.
1704 // If V1 is available in physreg R0, we would choose to reuse it
1705 // here, instead of reloading it into the register the allocator
1706 // indicated (say R1). However, V2 might have to be reloaded
1707 // later, and it might indicate that it needs to live in R0. When
1708 // this occurs, we need to have information available that
1709 // indicates it is safe to use R1 for the reload instead of R0.
1711 // To further complicate matters, we might conflict with an alias,
1712 // or R0 and R1 might not be compatible with each other. In this
1713 // case, we actually insert a reload for V1 in R1, ensuring that
1714 // we can get at R0 or its alias.
1715 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1716 VRM.getPhys(VirtReg), VirtReg);
1718 // Only mark it clobbered if this is a use&def operand.
1719 ReusedOperands.markClobbered(PhysReg);
1722 if (MI.getOperand(i).isKill() &&
1723 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1725 // The store of this spilled value is potentially dead, but we
1726 // won't know for certain until we've confirmed that the re-use
1727 // above is valid, which means waiting until the other operands
1728 // are processed. For now we just track the spill slot, we'll
1729 // remove it after the other operands are processed if valid.
1731 PotentialDeadStoreSlots.push_back(ReuseSlot);
1734 // Mark is isKill if it's there no other uses of the same virtual
1735 // register and it's not a two-address operand. IsKill will be
1736 // unset if reg is reused.
1737 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1738 MI.getOperand(i).setIsKill();
1739 KilledMIRegs.insert(VirtReg);
1745 // Otherwise we have a situation where we have a two-address instruction
1746 // whose mod/ref operand needs to be reloaded. This reload is already
1747 // available in some register "PhysReg", but if we used PhysReg as the
1748 // operand to our 2-addr instruction, the instruction would modify
1749 // PhysReg. This isn't cool if something later uses PhysReg and expects
1750 // to get its initial value.
1752 // To avoid this problem, and to avoid doing a load right after a store,
1753 // we emit a copy from PhysReg into the designated register for this
1755 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1756 assert(DesignatedReg && "Must map virtreg to physreg!");
1758 // Note that, if we reused a register for a previous operand, the
1759 // register we want to reload into might not actually be
1760 // available. If this occurs, use the register indicated by the
1762 if (ReusedOperands.hasReuses())
1763 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1764 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1766 // If the mapped designated register is actually the physreg we have
1767 // incoming, we don't need to inserted a dead copy.
1768 if (DesignatedReg == PhysReg) {
1769 // If this stack slot value is already available, reuse it!
1770 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1771 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1773 DOUT << "Reusing SS#" << ReuseSlot;
1774 DOUT << " from physreg " << TRI->getName(PhysReg)
1775 << " for vreg" << VirtReg
1776 << " instead of reloading into same physreg.\n";
1777 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1778 MI.getOperand(i).setReg(RReg);
1779 MI.getOperand(i).setSubReg(0);
1780 ReusedOperands.markClobbered(RReg);
1785 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1786 RegInfo->setPhysRegUsed(DesignatedReg);
1787 ReusedOperands.markClobbered(DesignatedReg);
1788 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1790 MachineInstr *CopyMI = prior(MII);
1791 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1793 // This invalidates DesignatedReg.
1794 Spills.ClobberPhysReg(DesignatedReg);
1796 Spills.addAvailable(ReuseSlot, DesignatedReg);
1798 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1799 MI.getOperand(i).setReg(RReg);
1800 MI.getOperand(i).setSubReg(0);
1801 DOUT << '\t' << *prior(MII);
1806 // Otherwise, reload it and remember that we have it.
1807 PhysReg = VRM.getPhys(VirtReg);
1808 assert(PhysReg && "Must map virtreg to physreg!");
1810 // Note that, if we reused a register for a previous operand, the
1811 // register we want to reload into might not actually be
1812 // available. If this occurs, use the register indicated by the
1814 if (ReusedOperands.hasReuses())
1815 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1816 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1818 RegInfo->setPhysRegUsed(PhysReg);
1819 ReusedOperands.markClobbered(PhysReg);
1824 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1826 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1827 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1828 MachineInstr *LoadMI = prior(MII);
1829 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1832 // This invalidates PhysReg.
1833 Spills.ClobberPhysReg(PhysReg);
1835 // Any stores to this stack slot are not dead anymore.
1837 MaybeDeadStores[SSorRMId] = NULL;
1838 Spills.addAvailable(SSorRMId, PhysReg);
1839 // Assumes this is the last use. IsKill will be unset if reg is reused
1840 // unless it's a two-address operand.
1841 if (!MI.isRegTiedToDefOperand(i) &&
1842 KilledMIRegs.count(VirtReg) == 0) {
1843 MI.getOperand(i).setIsKill();
1844 KilledMIRegs.insert(VirtReg);
1847 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1848 DOUT << '\t' << *prior(MII);
1850 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1851 MI.getOperand(i).setReg(RReg);
1852 MI.getOperand(i).setSubReg(0);
1855 // Ok - now we can remove stores that have been confirmed dead.
1856 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1857 // This was the last use and the spilled value is still available
1858 // for reuse. That means the spill was unnecessary!
1859 int PDSSlot = PotentialDeadStoreSlots[j];
1860 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1862 DOUT << "Removed dead store:\t" << *DeadStore;
1863 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1864 VRM.RemoveMachineInstrFromMaps(DeadStore);
1865 MBB.erase(DeadStore);
1866 MaybeDeadStores[PDSSlot] = NULL;
1875 // If we have folded references to memory operands, make sure we clear all
1876 // physical registers that may contain the value of the spilled virtual
1878 SmallSet<int, 2> FoldedSS;
1879 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1880 unsigned VirtReg = I->second.first;
1881 VirtRegMap::ModRef MR = I->second.second;
1882 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1884 // MI2VirtMap be can updated which invalidate the iterator.
1885 // Increment the iterator first.
1887 int SS = VRM.getStackSlot(VirtReg);
1888 if (SS == VirtRegMap::NO_STACK_SLOT)
1890 FoldedSS.insert(SS);
1891 DOUT << " - StackSlot: " << SS << "\n";
1893 // If this folded instruction is just a use, check to see if it's a
1894 // straight load from the virt reg slot.
1895 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1897 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1898 if (DestReg && FrameIdx == SS) {
1899 // If this spill slot is available, turn it into a copy (or nothing)
1900 // instead of leaving it as a load!
1901 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1902 DOUT << "Promoted Load To Copy: " << MI;
1903 if (DestReg != InReg) {
1904 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1905 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1906 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1907 unsigned SubIdx = DefMO->getSubReg();
1908 // Revisit the copy so we make sure to notice the effects of the
1909 // operation on the destreg (either needing to RA it if it's
1910 // virtual or needing to clobber any values if it's physical).
1912 --NextMII; // backtrack to the copy.
1913 // Propagate the sub-register index over.
1915 DefMO = NextMII->findRegisterDefOperand(DestReg);
1916 DefMO->setSubReg(SubIdx);
1920 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1921 KillOpnd->setIsKill();
1925 DOUT << "Removing now-noop copy: " << MI;
1926 // Unset last kill since it's being reused.
1927 InvalidateKill(InReg, TRI, RegKills, KillOps);
1928 Spills.disallowClobberPhysReg(InReg);
1931 InvalidateKills(MI, TRI, RegKills, KillOps);
1932 VRM.RemoveMachineInstrFromMaps(&MI);
1935 goto ProcessNextInst;
1938 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1939 SmallVector<MachineInstr*, 4> NewMIs;
1941 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1942 MBB.insert(MII, NewMIs[0]);
1943 InvalidateKills(MI, TRI, RegKills, KillOps);
1944 VRM.RemoveMachineInstrFromMaps(&MI);
1947 --NextMII; // backtrack to the unfolded instruction.
1949 goto ProcessNextInst;
1954 // If this reference is not a use, any previous store is now dead.
1955 // Otherwise, the store to this stack slot is not dead anymore.
1956 MachineInstr* DeadStore = MaybeDeadStores[SS];
1958 bool isDead = !(MR & VirtRegMap::isRef);
1959 MachineInstr *NewStore = NULL;
1960 if (MR & VirtRegMap::isModRef) {
1961 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1962 SmallVector<MachineInstr*, 4> NewMIs;
1963 // We can reuse this physreg as long as we are allowed to clobber
1964 // the value and there isn't an earlier def that has already clobbered
1967 !ReusedOperands.isClobbered(PhysReg) &&
1968 Spills.canClobberPhysReg(PhysReg) &&
1969 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1970 MachineOperand *KillOpnd =
1971 DeadStore->findRegisterUseOperand(PhysReg, true);
1972 // Note, if the store is storing a sub-register, it's possible the
1973 // super-register is needed below.
1974 if (KillOpnd && !KillOpnd->getSubReg() &&
1975 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1976 MBB.insert(MII, NewMIs[0]);
1977 NewStore = NewMIs[1];
1978 MBB.insert(MII, NewStore);
1979 VRM.addSpillSlotUse(SS, NewStore);
1980 InvalidateKills(MI, TRI, RegKills, KillOps);
1981 VRM.RemoveMachineInstrFromMaps(&MI);
1985 --NextMII; // backtrack to the unfolded instruction.
1993 if (isDead) { // Previous store is dead.
1994 // If we get here, the store is dead, nuke it now.
1995 DOUT << "Removed dead store:\t" << *DeadStore;
1996 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1997 VRM.RemoveMachineInstrFromMaps(DeadStore);
1998 MBB.erase(DeadStore);
2003 MaybeDeadStores[SS] = NULL;
2005 // Treat this store as a spill merged into a copy. That makes the
2006 // stack slot value available.
2007 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2008 goto ProcessNextInst;
2012 // If the spill slot value is available, and this is a new definition of
2013 // the value, the value is not available anymore.
2014 if (MR & VirtRegMap::isMod) {
2015 // Notice that the value in this stack slot has been modified.
2016 Spills.ModifyStackSlotOrReMat(SS);
2018 // If this is *just* a mod of the value, check to see if this is just a
2019 // store to the spill slot (i.e. the spill got merged into the copy). If
2020 // so, realize that the vreg is available now, and add the store to the
2021 // MaybeDeadStore info.
2023 if (!(MR & VirtRegMap::isRef)) {
2024 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2025 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2026 "Src hasn't been allocated yet?");
2028 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2029 Spills, RegKills, KillOps, TRI, VRM)) {
2030 NextMII = next(MII);
2032 goto ProcessNextInst;
2035 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2036 // this as a potentially dead store in case there is a subsequent
2037 // store into the stack slot without a read from it.
2038 MaybeDeadStores[StackSlot] = &MI;
2040 // If the stack slot value was previously available in some other
2041 // register, change it now. Otherwise, make the register
2042 // available in PhysReg.
2043 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2049 // Process all of the spilled defs.
2050 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2051 MachineOperand &MO = MI.getOperand(i);
2052 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2055 unsigned VirtReg = MO.getReg();
2056 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2057 // Check to see if this is a noop copy. If so, eliminate the
2058 // instruction before considering the dest reg to be changed.
2059 // Also check if it's copying from an "undef", if so, we can't
2060 // eliminate this or else the undef marker is lost and it will
2061 // confuses the scavenger. This is extremely rare.
2062 unsigned Src, Dst, SrcSR, DstSR;
2063 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2064 !MI.findRegisterUseOperand(Src)->isUndef()) {
2066 DOUT << "Removing now-noop copy: " << MI;
2067 SmallVector<unsigned, 2> KillRegs;
2068 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2069 if (MO.isDead() && !KillRegs.empty()) {
2070 // Source register or an implicit super/sub-register use is killed.
2071 assert(KillRegs[0] == Dst ||
2072 TRI->isSubRegister(KillRegs[0], Dst) ||
2073 TRI->isSuperRegister(KillRegs[0], Dst));
2074 // Last def is now dead.
2075 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2077 VRM.RemoveMachineInstrFromMaps(&MI);
2080 Spills.disallowClobberPhysReg(VirtReg);
2081 goto ProcessNextInst;
2084 // If it's not a no-op copy, it clobbers the value in the destreg.
2085 Spills.ClobberPhysReg(VirtReg);
2086 ReusedOperands.markClobbered(VirtReg);
2088 // Check to see if this instruction is a load from a stack slot into
2089 // a register. If so, this provides the stack slot value in the reg.
2091 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2092 assert(DestReg == VirtReg && "Unknown load situation!");
2094 // If it is a folded reference, then it's not safe to clobber.
2095 bool Folded = FoldedSS.count(FrameIdx);
2096 // Otherwise, if it wasn't available, remember that it is now!
2097 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2098 goto ProcessNextInst;
2104 unsigned SubIdx = MO.getSubReg();
2105 bool DoReMat = VRM.isReMaterialized(VirtReg);
2107 ReMatDefs.insert(&MI);
2109 // The only vregs left are stack slot definitions.
2110 int StackSlot = VRM.getStackSlot(VirtReg);
2111 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2113 // If this def is part of a two-address operand, make sure to execute
2114 // the store from the correct physical register.
2117 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2118 PhysReg = MI.getOperand(TiedOp).getReg();
2120 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2121 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2122 "Can't find corresponding super-register!");
2126 PhysReg = VRM.getPhys(VirtReg);
2127 if (ReusedOperands.isClobbered(PhysReg)) {
2128 // Another def has taken the assigned physreg. It must have been a
2129 // use&def which got it due to reuse. Undo the reuse!
2130 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2131 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2135 assert(PhysReg && "VR not assigned a physical register?");
2136 RegInfo->setPhysRegUsed(PhysReg);
2137 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2138 ReusedOperands.markClobbered(RReg);
2139 MI.getOperand(i).setReg(RReg);
2140 MI.getOperand(i).setSubReg(0);
2143 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2144 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2145 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2146 NextMII = next(MII);
2148 // Check to see if this is a noop copy. If so, eliminate the
2149 // instruction before considering the dest reg to be changed.
2151 unsigned Src, Dst, SrcSR, DstSR;
2152 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2154 DOUT << "Removing now-noop copy: " << MI;
2155 InvalidateKills(MI, TRI, RegKills, KillOps);
2156 VRM.RemoveMachineInstrFromMaps(&MI);
2159 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2160 goto ProcessNextInst;
2166 DistanceMap.insert(std::make_pair(&MI, Dist++));
2167 if (!Erased && !BackTracked) {
2168 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2169 UpdateKills(*II, TRI, RegKills, KillOps);
2178 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2179 switch (RewriterOpt) {
2180 default: llvm_unreachable("Unreachable!");
2182 return new LocalRewriter();
2184 return new TrivialRewriter();