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 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
495 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
496 assert(TID.getNumDefs() == 1 &&
497 "Don't know how to remat instructions that define > 1 values!");
499 TII->reMaterialize(MBB, MII, DestReg,
500 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
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, TRI, 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, TRI, RegKills, KillOps);
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)
856 bool operator()(const std::pair<MachineInstr*, int> &A,
857 const std::pair<MachineInstr*, int> &B) {
858 return A.second < B.second;
863 // ***************************** //
864 // Local Spiller Implementation //
865 // ***************************** //
867 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
868 MachineRegisterInfo *RegInfo;
869 const TargetRegisterInfo *TRI;
870 const TargetInstrInfo *TII;
871 BitVector AllocatableRegs;
872 DenseMap<MachineInstr*, unsigned> DistanceMap;
875 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
876 LiveIntervals* LIs) {
877 RegInfo = &MF.getRegInfo();
878 TRI = MF.getTarget().getRegisterInfo();
879 TII = MF.getTarget().getInstrInfo();
880 AllocatableRegs = TRI->getAllocatableSet(MF);
881 DOUT << "\n**** Local spiller rewriting function '"
882 << MF.getFunction()->getName() << "':\n";
883 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
887 // Spills - Keep track of which spilled values are available in physregs
888 // so that we can choose to reuse the physregs instead of emitting
889 // reloads. This is usually refreshed per basic block.
890 AvailableSpills Spills(TRI, TII);
892 // Keep track of kill information.
893 BitVector RegKills(TRI->getNumRegs());
894 std::vector<MachineOperand*> KillOps;
895 KillOps.resize(TRI->getNumRegs(), NULL);
897 // SingleEntrySuccs - Successor blocks which have a single predecessor.
898 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
899 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
901 // Traverse the basic blocks depth first.
902 MachineBasicBlock *Entry = MF.begin();
903 SmallPtrSet<MachineBasicBlock*,16> Visited;
904 for (df_ext_iterator<MachineBasicBlock*,
905 SmallPtrSet<MachineBasicBlock*,16> >
906 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
908 MachineBasicBlock *MBB = *DFI;
909 if (!EarlyVisited.count(MBB))
910 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
912 // If this MBB is the only predecessor of a successor. Keep the
913 // availability information and visit it next.
915 // Keep visiting single predecessor successor as long as possible.
916 SinglePredSuccs.clear();
917 findSinglePredSuccessor(MBB, SinglePredSuccs);
918 if (SinglePredSuccs.empty())
921 // FIXME: More than one successors, each of which has MBB has
922 // the only predecessor.
923 MBB = SinglePredSuccs[0];
924 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
925 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
926 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
931 // Clear the availability info.
935 DOUT << "**** Post Machine Instrs ****\n";
938 // Mark unused spill slots.
939 MachineFrameInfo *MFI = MF.getFrameInfo();
940 int SS = VRM.getLowSpillSlot();
941 if (SS != VirtRegMap::NO_STACK_SLOT)
942 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
943 if (!VRM.isSpillSlotUsed(SS)) {
944 MFI->RemoveStackObject(SS);
953 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
954 /// a scratch register is available.
955 /// xorq %r12<kill>, %r13
956 /// addq %rax, -184(%rbp)
957 /// addq %r13, -184(%rbp)
959 /// xorq %r12<kill>, %r13
960 /// movq -184(%rbp), %r12
963 /// movq %r12, -184(%rbp)
964 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
965 MachineBasicBlock &MBB,
966 MachineBasicBlock::iterator &MII,
967 std::vector<MachineInstr*> &MaybeDeadStores,
968 AvailableSpills &Spills,
970 std::vector<MachineOperand*> &KillOps,
973 MachineBasicBlock::iterator NextMII = next(MII);
974 if (NextMII == MBB.end())
977 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
980 // Now let's see if the last couple of instructions happens to have freed up
982 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
983 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
987 MachineFunction &MF = *MBB.getParent();
988 TRI = MF.getTarget().getRegisterInfo();
989 MachineInstr &MI = *MII;
990 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
993 // If the next instruction also folds the same SS modref and can be unfoled,
994 // then it's worthwhile to issue a load from SS into the free register and
995 // then unfold these instructions.
996 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
999 // Load from SS to the spare physical register.
1000 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1001 // This invalidates Phys.
1002 Spills.ClobberPhysReg(PhysReg);
1003 // Remember it's available.
1004 Spills.addAvailable(SS, PhysReg);
1005 MaybeDeadStores[SS] = NULL;
1007 // Unfold current MI.
1008 SmallVector<MachineInstr*, 4> NewMIs;
1009 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1010 llvm_unreachable("Unable unfold the load / store folding instruction!");
1011 assert(NewMIs.size() == 1);
1012 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1013 VRM.transferRestorePts(&MI, NewMIs[0]);
1014 MII = MBB.insert(MII, NewMIs[0]);
1015 InvalidateKills(MI, TRI, RegKills, KillOps);
1016 VRM.RemoveMachineInstrFromMaps(&MI);
1020 // Unfold next instructions that fold the same SS.
1022 MachineInstr &NextMI = *NextMII;
1023 NextMII = next(NextMII);
1025 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1026 llvm_unreachable("Unable unfold the load / store folding instruction!");
1027 assert(NewMIs.size() == 1);
1028 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1029 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1030 MBB.insert(NextMII, NewMIs[0]);
1031 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1032 VRM.RemoveMachineInstrFromMaps(&NextMI);
1035 if (NextMII == MBB.end())
1037 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1039 // Store the value back into SS.
1040 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1041 MachineInstr *StoreMI = prior(NextMII);
1042 VRM.addSpillSlotUse(SS, StoreMI);
1043 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1048 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1049 /// instruction. e.g.
1051 /// movl %eax, -32(%ebp)
1052 /// movl -36(%ebp), %eax
1053 /// orl %eax, -32(%ebp)
1056 /// orl -36(%ebp), %eax
1057 /// mov %eax, -32(%ebp)
1058 /// This enables unfolding optimization for a subsequent instruction which will
1059 /// also eliminate the newly introduced store instruction.
1060 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1061 MachineBasicBlock::iterator &MII,
1062 std::vector<MachineInstr*> &MaybeDeadStores,
1063 AvailableSpills &Spills,
1064 BitVector &RegKills,
1065 std::vector<MachineOperand*> &KillOps,
1067 MachineFunction &MF = *MBB.getParent();
1068 MachineInstr &MI = *MII;
1069 unsigned UnfoldedOpc = 0;
1070 unsigned UnfoldPR = 0;
1071 unsigned UnfoldVR = 0;
1072 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1073 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1074 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1075 // Only transform a MI that folds a single register.
1078 UnfoldVR = I->second.first;
1079 VirtRegMap::ModRef MR = I->second.second;
1080 // MI2VirtMap be can updated which invalidate the iterator.
1081 // Increment the iterator first.
1083 if (VRM.isAssignedReg(UnfoldVR))
1085 // If this reference is not a use, any previous store is now dead.
1086 // Otherwise, the store to this stack slot is not dead anymore.
1087 FoldedSS = VRM.getStackSlot(UnfoldVR);
1088 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1089 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1090 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1091 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1094 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1103 // Look for other unfolding opportunities.
1104 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1105 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1108 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1109 MachineOperand &MO = MI.getOperand(i);
1110 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1112 unsigned VirtReg = MO.getReg();
1113 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1115 if (VRM.isAssignedReg(VirtReg)) {
1116 unsigned PhysReg = VRM.getPhys(VirtReg);
1117 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1119 } else if (VRM.isReMaterialized(VirtReg))
1121 int SS = VRM.getStackSlot(VirtReg);
1122 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1124 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1128 if (VRM.hasPhys(VirtReg)) {
1129 PhysReg = VRM.getPhys(VirtReg);
1130 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1134 // Ok, we'll need to reload the value into a register which makes
1135 // it impossible to perform the store unfolding optimization later.
1136 // Let's see if it is possible to fold the load if the store is
1137 // unfolded. This allows us to perform the store unfolding
1139 SmallVector<MachineInstr*, 4> NewMIs;
1140 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1141 assert(NewMIs.size() == 1);
1142 MachineInstr *NewMI = NewMIs.back();
1144 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1146 SmallVector<unsigned, 1> Ops;
1148 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1150 VRM.addSpillSlotUse(SS, FoldedMI);
1151 if (!VRM.hasPhys(UnfoldVR))
1152 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1153 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1154 MII = MBB.insert(MII, FoldedMI);
1155 InvalidateKills(MI, TRI, RegKills, KillOps);
1156 VRM.RemoveMachineInstrFromMaps(&MI);
1158 MF.DeleteMachineInstr(NewMI);
1161 MF.DeleteMachineInstr(NewMI);
1168 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1169 /// where SrcReg is r1 and it is tied to r0. Return true if after
1170 /// commuting this instruction it will be r0 = op r2, r1.
1171 static bool CommuteChangesDestination(MachineInstr *DefMI,
1172 const TargetInstrDesc &TID,
1174 const TargetInstrInfo *TII,
1176 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1178 if (!DefMI->getOperand(1).isReg() ||
1179 DefMI->getOperand(1).getReg() != SrcReg)
1182 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1184 unsigned SrcIdx1, SrcIdx2;
1185 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1187 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1194 /// CommuteToFoldReload -
1197 /// r1 = op r1, r2<kill>
1200 /// If op is commutable and r2 is killed, then we can xform these to
1201 /// r2 = op r2, fi#1
1203 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1204 MachineBasicBlock::iterator &MII,
1205 unsigned VirtReg, unsigned SrcReg, int SS,
1206 AvailableSpills &Spills,
1207 BitVector &RegKills,
1208 std::vector<MachineOperand*> &KillOps,
1209 const TargetRegisterInfo *TRI,
1211 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1214 MachineFunction &MF = *MBB.getParent();
1215 MachineInstr &MI = *MII;
1216 MachineBasicBlock::iterator DefMII = prior(MII);
1217 MachineInstr *DefMI = DefMII;
1218 const TargetInstrDesc &TID = DefMI->getDesc();
1220 if (DefMII != MBB.begin() &&
1221 TID.isCommutable() &&
1222 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1223 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1224 unsigned NewReg = NewDstMO.getReg();
1225 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1227 MachineInstr *ReloadMI = prior(DefMII);
1229 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1230 if (DestReg != SrcReg || FrameIdx != SS)
1232 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1236 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1238 assert(DefMI->getOperand(DefIdx).isReg() &&
1239 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1241 // Now commute def instruction.
1242 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1245 SmallVector<unsigned, 1> Ops;
1246 Ops.push_back(NewDstIdx);
1247 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1248 // Not needed since foldMemoryOperand returns new MI.
1249 MF.DeleteMachineInstr(CommutedMI);
1253 VRM.addSpillSlotUse(SS, FoldedMI);
1254 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1255 // Insert new def MI and spill MI.
1256 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1257 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1259 MachineInstr *StoreMI = MII;
1260 VRM.addSpillSlotUse(SS, StoreMI);
1261 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1262 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1264 // Delete all 3 old instructions.
1265 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1266 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1267 MBB.erase(ReloadMI);
1268 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1269 VRM.RemoveMachineInstrFromMaps(DefMI);
1271 InvalidateKills(MI, TRI, RegKills, KillOps);
1272 VRM.RemoveMachineInstrFromMaps(&MI);
1275 // If NewReg was previously holding value of some SS, it's now clobbered.
1276 // This has to be done now because it's a physical register. When this
1277 // instruction is re-visited, it's ignored.
1278 Spills.ClobberPhysReg(NewReg);
1287 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1288 /// the last store to the same slot is now dead. If so, remove the last store.
1289 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1290 MachineBasicBlock::iterator &MII,
1291 int Idx, unsigned PhysReg, int StackSlot,
1292 const TargetRegisterClass *RC,
1293 bool isAvailable, MachineInstr *&LastStore,
1294 AvailableSpills &Spills,
1295 SmallSet<MachineInstr*, 4> &ReMatDefs,
1296 BitVector &RegKills,
1297 std::vector<MachineOperand*> &KillOps,
1300 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1301 MachineInstr *StoreMI = next(MII);
1302 VRM.addSpillSlotUse(StackSlot, StoreMI);
1303 DOUT << "Store:\t" << *StoreMI;
1305 // If there is a dead store to this stack slot, nuke it now.
1307 DOUT << "Removed dead store:\t" << *LastStore;
1309 SmallVector<unsigned, 2> KillRegs;
1310 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1311 MachineBasicBlock::iterator PrevMII = LastStore;
1312 bool CheckDef = PrevMII != MBB.begin();
1315 VRM.RemoveMachineInstrFromMaps(LastStore);
1316 MBB.erase(LastStore);
1318 // Look at defs of killed registers on the store. Mark the defs
1319 // as dead since the store has been deleted and they aren't
1321 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1322 bool HasOtherDef = false;
1323 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1324 MachineInstr *DeadDef = PrevMII;
1325 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1326 // FIXME: This assumes a remat def does not have side effects.
1327 VRM.RemoveMachineInstrFromMaps(DeadDef);
1336 LastStore = next(MII);
1338 // If the stack slot value was previously available in some other
1339 // register, change it now. Otherwise, make the register available,
1341 Spills.ModifyStackSlotOrReMat(StackSlot);
1342 Spills.ClobberPhysReg(PhysReg);
1343 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1347 /// TransferDeadness - A identity copy definition is dead and it's being
1348 /// removed. Find the last def or use and mark it as dead / kill.
1349 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1350 unsigned Reg, BitVector &RegKills,
1351 std::vector<MachineOperand*> &KillOps,
1353 SmallPtrSet<MachineInstr*, 4> Seens;
1354 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1355 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1356 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1357 MachineInstr *UDMI = &*RI;
1358 if (UDMI->getParent() != MBB)
1360 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1361 if (DI == DistanceMap.end() || DI->second > CurDist)
1363 if (Seens.insert(UDMI))
1364 Refs.push_back(std::make_pair(UDMI, DI->second));
1369 std::sort(Refs.begin(), Refs.end(), RefSorter());
1371 while (!Refs.empty()) {
1372 MachineInstr *LastUDMI = Refs.back().first;
1375 MachineOperand *LastUD = NULL;
1376 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1377 MachineOperand &MO = LastUDMI->getOperand(i);
1378 if (!MO.isReg() || MO.getReg() != Reg)
1380 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1382 if (LastUDMI->isRegTiedToDefOperand(i))
1385 if (LastUD->isDef()) {
1386 // If the instruction has no side effect, delete it and propagate
1387 // backward further. Otherwise, mark is dead and we are done.
1388 const TargetInstrDesc &TID = LastUDMI->getDesc();
1389 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1390 TID.hasUnmodeledSideEffects()) {
1391 LastUD->setIsDead();
1394 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1395 MBB->erase(LastUDMI);
1397 LastUD->setIsKill();
1399 KillOps[Reg] = LastUD;
1405 /// rewriteMBB - Keep track of which spills are available even after the
1406 /// register allocator is done with them. If possible, avid reloading vregs.
1407 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1409 AvailableSpills &Spills, BitVector &RegKills,
1410 std::vector<MachineOperand*> &KillOps) {
1412 DOUT << "\n**** Local spiller rewriting MBB '"
1413 << MBB.getBasicBlock()->getName() << "':\n";
1415 MachineFunction &MF = *MBB.getParent();
1417 // MaybeDeadStores - When we need to write a value back into a stack slot,
1418 // keep track of the inserted store. If the stack slot value is never read
1419 // (because the value was used from some available register, for example), and
1420 // subsequently stored to, the original store is dead. This map keeps track
1421 // of inserted stores that are not used. If we see a subsequent store to the
1422 // same stack slot, the original store is deleted.
1423 std::vector<MachineInstr*> MaybeDeadStores;
1424 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1426 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1427 SmallSet<MachineInstr*, 4> ReMatDefs;
1430 SmallSet<unsigned, 2> KilledMIRegs;
1433 KillOps.resize(TRI->getNumRegs(), NULL);
1436 DistanceMap.clear();
1437 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1439 MachineBasicBlock::iterator NextMII = next(MII);
1441 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1442 bool Erased = false;
1443 bool BackTracked = false;
1444 if (OptimizeByUnfold(MBB, MII,
1445 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1446 NextMII = next(MII);
1448 MachineInstr &MI = *MII;
1450 if (VRM.hasEmergencySpills(&MI)) {
1451 // Spill physical register(s) in the rare case the allocator has run out
1452 // of registers to allocate.
1453 SmallSet<int, 4> UsedSS;
1454 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1455 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1456 unsigned PhysReg = EmSpills[i];
1457 const TargetRegisterClass *RC =
1458 TRI->getPhysicalRegisterRegClass(PhysReg);
1459 assert(RC && "Unable to determine register class!");
1460 int SS = VRM.getEmergencySpillSlot(RC);
1461 if (UsedSS.count(SS))
1462 llvm_unreachable("Need to spill more than one physical registers!");
1464 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1465 MachineInstr *StoreMI = prior(MII);
1466 VRM.addSpillSlotUse(SS, StoreMI);
1467 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1468 MachineInstr *LoadMI = next(MII);
1469 VRM.addSpillSlotUse(SS, LoadMI);
1472 NextMII = next(MII);
1475 // Insert restores here if asked to.
1476 if (VRM.isRestorePt(&MI)) {
1477 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1478 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1479 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1480 if (!VRM.getPreSplitReg(VirtReg))
1481 continue; // Split interval spilled again.
1482 unsigned Phys = VRM.getPhys(VirtReg);
1483 RegInfo->setPhysRegUsed(Phys);
1485 // Check if the value being restored if available. If so, it must be
1486 // from a predecessor BB that fallthrough into this BB. We do not
1492 // ... # r1 not clobbered
1495 bool DoReMat = VRM.isReMaterialized(VirtReg);
1496 int SSorRMId = DoReMat
1497 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1498 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1499 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1500 if (InReg == Phys) {
1501 // If the value is already available in the expected register, save
1502 // a reload / remat.
1504 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1506 DOUT << "Reusing SS#" << SSorRMId;
1507 DOUT << " from physreg "
1508 << TRI->getName(InReg) << " for vreg"
1509 << VirtReg <<" instead of reloading into physreg "
1510 << TRI->getName(Phys) << "\n";
1513 } else if (InReg && InReg != Phys) {
1515 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1517 DOUT << "Reusing SS#" << SSorRMId;
1518 DOUT << " from physreg "
1519 << TRI->getName(InReg) << " for vreg"
1520 << VirtReg <<" by copying it into physreg "
1521 << TRI->getName(Phys) << "\n";
1523 // If the reloaded / remat value is available in another register,
1524 // copy it to the desired register.
1525 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1527 // This invalidates Phys.
1528 Spills.ClobberPhysReg(Phys);
1529 // Remember it's available.
1530 Spills.addAvailable(SSorRMId, Phys);
1533 MachineInstr *CopyMI = prior(MII);
1534 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1535 KillOpnd->setIsKill();
1536 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1538 DOUT << '\t' << *CopyMI;
1543 if (VRM.isReMaterialized(VirtReg)) {
1544 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1546 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1547 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1548 MachineInstr *LoadMI = prior(MII);
1549 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1553 // This invalidates Phys.
1554 Spills.ClobberPhysReg(Phys);
1555 // Remember it's available.
1556 Spills.addAvailable(SSorRMId, Phys);
1558 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1559 DOUT << '\t' << *prior(MII);
1563 // Insert spills here if asked to.
1564 if (VRM.isSpillPt(&MI)) {
1565 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1566 VRM.getSpillPtSpills(&MI);
1567 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1568 unsigned VirtReg = SpillRegs[i].first;
1569 bool isKill = SpillRegs[i].second;
1570 if (!VRM.getPreSplitReg(VirtReg))
1571 continue; // Split interval spilled again.
1572 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1573 unsigned Phys = VRM.getPhys(VirtReg);
1574 int StackSlot = VRM.getStackSlot(VirtReg);
1575 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1576 MachineInstr *StoreMI = next(MII);
1577 VRM.addSpillSlotUse(StackSlot, StoreMI);
1578 DOUT << "Store:\t" << *StoreMI;
1579 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1581 NextMII = next(MII);
1584 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1586 ReuseInfo ReusedOperands(MI, TRI);
1587 SmallVector<unsigned, 4> VirtUseOps;
1588 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1589 MachineOperand &MO = MI.getOperand(i);
1590 if (!MO.isReg() || MO.getReg() == 0)
1591 continue; // Ignore non-register operands.
1593 unsigned VirtReg = MO.getReg();
1594 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1595 // Ignore physregs for spilling, but remember that it is used by this
1597 RegInfo->setPhysRegUsed(VirtReg);
1601 // We want to process implicit virtual register uses first.
1602 if (MO.isImplicit())
1603 // If the virtual register is implicitly defined, emit a implicit_def
1604 // before so scavenger knows it's "defined".
1605 // FIXME: This is a horrible hack done the by register allocator to
1606 // remat a definition with virtual register operand.
1607 VirtUseOps.insert(VirtUseOps.begin(), i);
1609 VirtUseOps.push_back(i);
1612 // Process all of the spilled uses and all non spilled reg references.
1613 SmallVector<int, 2> PotentialDeadStoreSlots;
1614 KilledMIRegs.clear();
1615 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1616 unsigned i = VirtUseOps[j];
1617 MachineOperand &MO = MI.getOperand(i);
1618 unsigned VirtReg = MO.getReg();
1619 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1620 "Not a virtual register?");
1622 unsigned SubIdx = MO.getSubReg();
1623 if (VRM.isAssignedReg(VirtReg)) {
1624 // This virtual register was assigned a physreg!
1625 unsigned Phys = VRM.getPhys(VirtReg);
1626 RegInfo->setPhysRegUsed(Phys);
1628 ReusedOperands.markClobbered(Phys);
1629 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1630 MI.getOperand(i).setReg(RReg);
1631 MI.getOperand(i).setSubReg(0);
1632 if (VRM.isImplicitlyDefined(VirtReg))
1633 // FIXME: Is this needed?
1634 BuildMI(MBB, &MI, MI.getDebugLoc(),
1635 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1639 // This virtual register is now known to be a spilled value.
1641 continue; // Handle defs in the loop below (handle use&def here though)
1643 bool AvoidReload = MO.isUndef();
1644 // Check if it is defined by an implicit def. It should not be spilled.
1645 // Note, this is for correctness reason. e.g.
1646 // 8 %reg1024<def> = IMPLICIT_DEF
1647 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1648 // The live range [12, 14) are not part of the r1024 live interval since
1649 // it's defined by an implicit def. It will not conflicts with live
1650 // interval of r1025. Now suppose both registers are spilled, you can
1651 // easily see a situation where both registers are reloaded before
1652 // the INSERT_SUBREG and both target registers that would overlap.
1653 bool DoReMat = VRM.isReMaterialized(VirtReg);
1654 int SSorRMId = DoReMat
1655 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1656 int ReuseSlot = SSorRMId;
1658 // Check to see if this stack slot is available.
1659 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1661 // If this is a sub-register use, make sure the reuse register is in the
1662 // right register class. For example, for x86 not all of the 32-bit
1663 // registers have accessible sub-registers.
1664 // Similarly so for EXTRACT_SUBREG. Consider this:
1666 // MOV32_mr fi#1, EDI
1668 // = EXTRACT_SUBREG fi#1
1669 // fi#1 is available in EDI, but it cannot be reused because it's not in
1670 // the right register file.
1671 if (PhysReg && !AvoidReload &&
1672 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1673 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1674 if (!RC->contains(PhysReg))
1678 if (PhysReg && !AvoidReload) {
1679 // This spilled operand might be part of a two-address operand. If this
1680 // is the case, then changing it will necessarily require changing the
1681 // def part of the instruction as well. However, in some cases, we
1682 // aren't allowed to modify the reused register. If none of these cases
1684 bool CanReuse = true;
1685 bool isTied = MI.isRegTiedToDefOperand(i);
1687 // Okay, we have a two address operand. We can reuse this physreg as
1688 // long as we are allowed to clobber the value and there isn't an
1689 // earlier def that has already clobbered the physreg.
1690 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1691 Spills.canClobberPhysReg(PhysReg);
1695 // If this stack slot value is already available, reuse it!
1696 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1697 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1699 DOUT << "Reusing SS#" << ReuseSlot;
1700 DOUT << " from physreg "
1701 << TRI->getName(PhysReg) << " for vreg"
1702 << VirtReg <<" instead of reloading into physreg "
1703 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1704 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1705 MI.getOperand(i).setReg(RReg);
1706 MI.getOperand(i).setSubReg(0);
1708 // The only technical detail we have is that we don't know that
1709 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1710 // later in the instruction. In particular, consider 'op V1, V2'.
1711 // If V1 is available in physreg R0, we would choose to reuse it
1712 // here, instead of reloading it into the register the allocator
1713 // indicated (say R1). However, V2 might have to be reloaded
1714 // later, and it might indicate that it needs to live in R0. When
1715 // this occurs, we need to have information available that
1716 // indicates it is safe to use R1 for the reload instead of R0.
1718 // To further complicate matters, we might conflict with an alias,
1719 // or R0 and R1 might not be compatible with each other. In this
1720 // case, we actually insert a reload for V1 in R1, ensuring that
1721 // we can get at R0 or its alias.
1722 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1723 VRM.getPhys(VirtReg), VirtReg);
1725 // Only mark it clobbered if this is a use&def operand.
1726 ReusedOperands.markClobbered(PhysReg);
1729 if (MI.getOperand(i).isKill() &&
1730 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1732 // The store of this spilled value is potentially dead, but we
1733 // won't know for certain until we've confirmed that the re-use
1734 // above is valid, which means waiting until the other operands
1735 // are processed. For now we just track the spill slot, we'll
1736 // remove it after the other operands are processed if valid.
1738 PotentialDeadStoreSlots.push_back(ReuseSlot);
1741 // Mark is isKill if it's there no other uses of the same virtual
1742 // register and it's not a two-address operand. IsKill will be
1743 // unset if reg is reused.
1744 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1745 MI.getOperand(i).setIsKill();
1746 KilledMIRegs.insert(VirtReg);
1752 // Otherwise we have a situation where we have a two-address instruction
1753 // whose mod/ref operand needs to be reloaded. This reload is already
1754 // available in some register "PhysReg", but if we used PhysReg as the
1755 // operand to our 2-addr instruction, the instruction would modify
1756 // PhysReg. This isn't cool if something later uses PhysReg and expects
1757 // to get its initial value.
1759 // To avoid this problem, and to avoid doing a load right after a store,
1760 // we emit a copy from PhysReg into the designated register for this
1762 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1763 assert(DesignatedReg && "Must map virtreg to physreg!");
1765 // Note that, if we reused a register for a previous operand, the
1766 // register we want to reload into might not actually be
1767 // available. If this occurs, use the register indicated by the
1769 if (ReusedOperands.hasReuses())
1770 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1771 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1773 // If the mapped designated register is actually the physreg we have
1774 // incoming, we don't need to inserted a dead copy.
1775 if (DesignatedReg == PhysReg) {
1776 // If this stack slot value is already available, reuse it!
1777 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1778 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1780 DOUT << "Reusing SS#" << ReuseSlot;
1781 DOUT << " from physreg " << TRI->getName(PhysReg)
1782 << " for vreg" << VirtReg
1783 << " instead of reloading into same physreg.\n";
1784 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1785 MI.getOperand(i).setReg(RReg);
1786 MI.getOperand(i).setSubReg(0);
1787 ReusedOperands.markClobbered(RReg);
1792 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1793 RegInfo->setPhysRegUsed(DesignatedReg);
1794 ReusedOperands.markClobbered(DesignatedReg);
1795 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1797 MachineInstr *CopyMI = prior(MII);
1798 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1800 // This invalidates DesignatedReg.
1801 Spills.ClobberPhysReg(DesignatedReg);
1803 Spills.addAvailable(ReuseSlot, DesignatedReg);
1805 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1806 MI.getOperand(i).setReg(RReg);
1807 MI.getOperand(i).setSubReg(0);
1808 DOUT << '\t' << *prior(MII);
1813 // Otherwise, reload it and remember that we have it.
1814 PhysReg = VRM.getPhys(VirtReg);
1815 assert(PhysReg && "Must map virtreg to physreg!");
1817 // Note that, if we reused a register for a previous operand, the
1818 // register we want to reload into might not actually be
1819 // available. If this occurs, use the register indicated by the
1821 if (ReusedOperands.hasReuses())
1822 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1823 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1825 RegInfo->setPhysRegUsed(PhysReg);
1826 ReusedOperands.markClobbered(PhysReg);
1831 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1833 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1834 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1835 MachineInstr *LoadMI = prior(MII);
1836 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1839 // This invalidates PhysReg.
1840 Spills.ClobberPhysReg(PhysReg);
1842 // Any stores to this stack slot are not dead anymore.
1844 MaybeDeadStores[SSorRMId] = NULL;
1845 Spills.addAvailable(SSorRMId, PhysReg);
1846 // Assumes this is the last use. IsKill will be unset if reg is reused
1847 // unless it's a two-address operand.
1848 if (!MI.isRegTiedToDefOperand(i) &&
1849 KilledMIRegs.count(VirtReg) == 0) {
1850 MI.getOperand(i).setIsKill();
1851 KilledMIRegs.insert(VirtReg);
1854 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1855 DOUT << '\t' << *prior(MII);
1857 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1858 MI.getOperand(i).setReg(RReg);
1859 MI.getOperand(i).setSubReg(0);
1862 // Ok - now we can remove stores that have been confirmed dead.
1863 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1864 // This was the last use and the spilled value is still available
1865 // for reuse. That means the spill was unnecessary!
1866 int PDSSlot = PotentialDeadStoreSlots[j];
1867 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1869 DOUT << "Removed dead store:\t" << *DeadStore;
1870 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1871 VRM.RemoveMachineInstrFromMaps(DeadStore);
1872 MBB.erase(DeadStore);
1873 MaybeDeadStores[PDSSlot] = NULL;
1882 // If we have folded references to memory operands, make sure we clear all
1883 // physical registers that may contain the value of the spilled virtual
1885 SmallSet<int, 2> FoldedSS;
1886 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1887 unsigned VirtReg = I->second.first;
1888 VirtRegMap::ModRef MR = I->second.second;
1889 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1891 // MI2VirtMap be can updated which invalidate the iterator.
1892 // Increment the iterator first.
1894 int SS = VRM.getStackSlot(VirtReg);
1895 if (SS == VirtRegMap::NO_STACK_SLOT)
1897 FoldedSS.insert(SS);
1898 DOUT << " - StackSlot: " << SS << "\n";
1900 // If this folded instruction is just a use, check to see if it's a
1901 // straight load from the virt reg slot.
1902 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1904 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1905 if (DestReg && FrameIdx == SS) {
1906 // If this spill slot is available, turn it into a copy (or nothing)
1907 // instead of leaving it as a load!
1908 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1909 DOUT << "Promoted Load To Copy: " << MI;
1910 if (DestReg != InReg) {
1911 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1912 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1913 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1914 unsigned SubIdx = DefMO->getSubReg();
1915 // Revisit the copy so we make sure to notice the effects of the
1916 // operation on the destreg (either needing to RA it if it's
1917 // virtual or needing to clobber any values if it's physical).
1919 --NextMII; // backtrack to the copy.
1920 // Propagate the sub-register index over.
1922 DefMO = NextMII->findRegisterDefOperand(DestReg);
1923 DefMO->setSubReg(SubIdx);
1927 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1928 KillOpnd->setIsKill();
1932 DOUT << "Removing now-noop copy: " << MI;
1933 // Unset last kill since it's being reused.
1934 InvalidateKill(InReg, TRI, RegKills, KillOps);
1935 Spills.disallowClobberPhysReg(InReg);
1938 InvalidateKills(MI, TRI, RegKills, KillOps);
1939 VRM.RemoveMachineInstrFromMaps(&MI);
1942 goto ProcessNextInst;
1945 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1946 SmallVector<MachineInstr*, 4> NewMIs;
1948 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1949 MBB.insert(MII, NewMIs[0]);
1950 InvalidateKills(MI, TRI, RegKills, KillOps);
1951 VRM.RemoveMachineInstrFromMaps(&MI);
1954 --NextMII; // backtrack to the unfolded instruction.
1956 goto ProcessNextInst;
1961 // If this reference is not a use, any previous store is now dead.
1962 // Otherwise, the store to this stack slot is not dead anymore.
1963 MachineInstr* DeadStore = MaybeDeadStores[SS];
1965 bool isDead = !(MR & VirtRegMap::isRef);
1966 MachineInstr *NewStore = NULL;
1967 if (MR & VirtRegMap::isModRef) {
1968 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1969 SmallVector<MachineInstr*, 4> NewMIs;
1970 // We can reuse this physreg as long as we are allowed to clobber
1971 // the value and there isn't an earlier def that has already clobbered
1974 !ReusedOperands.isClobbered(PhysReg) &&
1975 Spills.canClobberPhysReg(PhysReg) &&
1976 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1977 MachineOperand *KillOpnd =
1978 DeadStore->findRegisterUseOperand(PhysReg, true);
1979 // Note, if the store is storing a sub-register, it's possible the
1980 // super-register is needed below.
1981 if (KillOpnd && !KillOpnd->getSubReg() &&
1982 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1983 MBB.insert(MII, NewMIs[0]);
1984 NewStore = NewMIs[1];
1985 MBB.insert(MII, NewStore);
1986 VRM.addSpillSlotUse(SS, NewStore);
1987 InvalidateKills(MI, TRI, RegKills, KillOps);
1988 VRM.RemoveMachineInstrFromMaps(&MI);
1992 --NextMII; // backtrack to the unfolded instruction.
2000 if (isDead) { // Previous store is dead.
2001 // If we get here, the store is dead, nuke it now.
2002 DOUT << "Removed dead store:\t" << *DeadStore;
2003 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2004 VRM.RemoveMachineInstrFromMaps(DeadStore);
2005 MBB.erase(DeadStore);
2010 MaybeDeadStores[SS] = NULL;
2012 // Treat this store as a spill merged into a copy. That makes the
2013 // stack slot value available.
2014 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2015 goto ProcessNextInst;
2019 // If the spill slot value is available, and this is a new definition of
2020 // the value, the value is not available anymore.
2021 if (MR & VirtRegMap::isMod) {
2022 // Notice that the value in this stack slot has been modified.
2023 Spills.ModifyStackSlotOrReMat(SS);
2025 // If this is *just* a mod of the value, check to see if this is just a
2026 // store to the spill slot (i.e. the spill got merged into the copy). If
2027 // so, realize that the vreg is available now, and add the store to the
2028 // MaybeDeadStore info.
2030 if (!(MR & VirtRegMap::isRef)) {
2031 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2032 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2033 "Src hasn't been allocated yet?");
2035 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2036 Spills, RegKills, KillOps, TRI, VRM)) {
2037 NextMII = next(MII);
2039 goto ProcessNextInst;
2042 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2043 // this as a potentially dead store in case there is a subsequent
2044 // store into the stack slot without a read from it.
2045 MaybeDeadStores[StackSlot] = &MI;
2047 // If the stack slot value was previously available in some other
2048 // register, change it now. Otherwise, make the register
2049 // available in PhysReg.
2050 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2056 // Process all of the spilled defs.
2057 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2058 MachineOperand &MO = MI.getOperand(i);
2059 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2062 unsigned VirtReg = MO.getReg();
2063 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2064 // Check to see if this is a noop copy. If so, eliminate the
2065 // instruction before considering the dest reg to be changed.
2066 // Also check if it's copying from an "undef", if so, we can't
2067 // eliminate this or else the undef marker is lost and it will
2068 // confuses the scavenger. This is extremely rare.
2069 unsigned Src, Dst, SrcSR, DstSR;
2070 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2071 !MI.findRegisterUseOperand(Src)->isUndef()) {
2073 DOUT << "Removing now-noop copy: " << MI;
2074 SmallVector<unsigned, 2> KillRegs;
2075 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2076 if (MO.isDead() && !KillRegs.empty()) {
2077 // Source register or an implicit super/sub-register use is killed.
2078 assert(KillRegs[0] == Dst ||
2079 TRI->isSubRegister(KillRegs[0], Dst) ||
2080 TRI->isSuperRegister(KillRegs[0], Dst));
2081 // Last def is now dead.
2082 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2084 VRM.RemoveMachineInstrFromMaps(&MI);
2087 Spills.disallowClobberPhysReg(VirtReg);
2088 goto ProcessNextInst;
2091 // If it's not a no-op copy, it clobbers the value in the destreg.
2092 Spills.ClobberPhysReg(VirtReg);
2093 ReusedOperands.markClobbered(VirtReg);
2095 // Check to see if this instruction is a load from a stack slot into
2096 // a register. If so, this provides the stack slot value in the reg.
2098 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2099 assert(DestReg == VirtReg && "Unknown load situation!");
2101 // If it is a folded reference, then it's not safe to clobber.
2102 bool Folded = FoldedSS.count(FrameIdx);
2103 // Otherwise, if it wasn't available, remember that it is now!
2104 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2105 goto ProcessNextInst;
2111 unsigned SubIdx = MO.getSubReg();
2112 bool DoReMat = VRM.isReMaterialized(VirtReg);
2114 ReMatDefs.insert(&MI);
2116 // The only vregs left are stack slot definitions.
2117 int StackSlot = VRM.getStackSlot(VirtReg);
2118 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2120 // If this def is part of a two-address operand, make sure to execute
2121 // the store from the correct physical register.
2124 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2125 PhysReg = MI.getOperand(TiedOp).getReg();
2127 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2128 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2129 "Can't find corresponding super-register!");
2133 PhysReg = VRM.getPhys(VirtReg);
2134 if (ReusedOperands.isClobbered(PhysReg)) {
2135 // Another def has taken the assigned physreg. It must have been a
2136 // use&def which got it due to reuse. Undo the reuse!
2137 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2138 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2142 assert(PhysReg && "VR not assigned a physical register?");
2143 RegInfo->setPhysRegUsed(PhysReg);
2144 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2145 ReusedOperands.markClobbered(RReg);
2146 MI.getOperand(i).setReg(RReg);
2147 MI.getOperand(i).setSubReg(0);
2150 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2151 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2152 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2153 NextMII = next(MII);
2155 // Check to see if this is a noop copy. If so, eliminate the
2156 // instruction before considering the dest reg to be changed.
2158 unsigned Src, Dst, SrcSR, DstSR;
2159 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2161 DOUT << "Removing now-noop copy: " << MI;
2162 InvalidateKills(MI, TRI, RegKills, KillOps);
2163 VRM.RemoveMachineInstrFromMaps(&MI);
2166 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2167 goto ProcessNextInst;
2173 DistanceMap.insert(std::make_pair(&MI, Dist++));
2174 if (!Erased && !BackTracked) {
2175 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2176 UpdateKills(*II, TRI, RegKills, KillOps);
2185 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2186 switch (RewriterOpt) {
2187 default: llvm_unreachable("Unreachable!");
2189 return new LocalRewriter();
2191 return new TrivialRewriter();