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);
496 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
497 assert(TID.getNumDefs() != 1 &&
498 "Don't know how to remat instructions that define > 1 values!");
501 TII->reMaterialize(MBB, MII, DestReg,
502 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
503 MachineInstr *NewMI = prior(MII);
504 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
505 MachineOperand &MO = NewMI->getOperand(i);
506 if (!MO.isReg() || MO.getReg() == 0)
508 unsigned VirtReg = MO.getReg();
509 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
512 unsigned SubIdx = MO.getSubReg();
513 unsigned Phys = VRM.getPhys(VirtReg);
515 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
522 /// findSuperReg - Find the SubReg's super-register of given register class
523 /// where its SubIdx sub-register is SubReg.
524 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
525 unsigned SubIdx, const TargetRegisterInfo *TRI) {
526 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
529 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
535 // ******************************** //
536 // Available Spills Implementation //
537 // ******************************** //
539 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
540 /// stackslot register. The register is still available but is no longer
541 /// allowed to be modifed.
542 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
543 std::multimap<unsigned, int>::iterator I =
544 PhysRegsAvailable.lower_bound(PhysReg);
545 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
546 int SlotOrReMat = I->second;
548 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
549 "Bidirectional map mismatch!");
550 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
551 DOUT << "PhysReg " << TRI->getName(PhysReg)
552 << " copied, it is available for use but can no longer be modified\n";
556 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
557 /// stackslot register and its aliases. The register and its aliases may
558 /// still available but is no longer allowed to be modifed.
559 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
560 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
561 disallowClobberPhysRegOnly(*AS);
562 disallowClobberPhysRegOnly(PhysReg);
565 /// ClobberPhysRegOnly - This is called when the specified physreg changes
566 /// value. We use this to invalidate any info about stuff we thing lives in it.
567 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
568 std::multimap<unsigned, int>::iterator I =
569 PhysRegsAvailable.lower_bound(PhysReg);
570 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
571 int SlotOrReMat = I->second;
572 PhysRegsAvailable.erase(I++);
573 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
574 "Bidirectional map mismatch!");
575 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
576 DOUT << "PhysReg " << TRI->getName(PhysReg)
577 << " clobbered, invalidating ";
578 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
579 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
581 DOUT << "SS#" << SlotOrReMat << "\n";
585 /// ClobberPhysReg - This is called when the specified physreg changes
586 /// value. We use this to invalidate any info about stuff we thing lives in
587 /// it and any of its aliases.
588 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
589 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
590 ClobberPhysRegOnly(*AS);
591 ClobberPhysRegOnly(PhysReg);
594 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
595 /// into the specified MBB. Add available physical registers as potential
596 /// live-in's. If they are reused in the MBB, they will be added to the
597 /// live-in set to make register scavenger and post-allocation scheduler.
598 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
600 std::vector<MachineOperand*> &KillOps) {
601 std::set<unsigned> NotAvailable;
602 for (std::multimap<unsigned, int>::iterator
603 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
605 unsigned Reg = I->first;
606 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
607 // FIXME: A temporary workaround. We can't reuse available value if it's
608 // not safe to move the def of the virtual register's class. e.g.
609 // X86::RFP* register classes. Do not add it as a live-in.
610 if (!TII->isSafeToMoveRegClassDefs(RC))
611 // This is no longer available.
612 NotAvailable.insert(Reg);
615 InvalidateKill(Reg, TRI, RegKills, KillOps);
618 // Skip over the same register.
619 std::multimap<unsigned, int>::iterator NI = next(I);
620 while (NI != E && NI->first == Reg) {
626 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
627 E = NotAvailable.end(); I != E; ++I) {
629 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
631 ClobberPhysReg(*SubRegs);
635 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
636 /// slot changes. This removes information about which register the previous
637 /// value for this slot lives in (as the previous value is dead now).
638 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
639 std::map<int, unsigned>::iterator It =
640 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
641 if (It == SpillSlotsOrReMatsAvailable.end()) return;
642 unsigned Reg = It->second >> 1;
643 SpillSlotsOrReMatsAvailable.erase(It);
645 // This register may hold the value of multiple stack slots, only remove this
646 // stack slot from the set of values the register contains.
647 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
649 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
650 "Map inverse broken!");
651 if (I->second == SlotOrReMat) break;
653 PhysRegsAvailable.erase(I);
656 // ************************** //
657 // Reuse Info Implementation //
658 // ************************** //
660 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
661 /// is some other operand that is using the specified register, either pick
662 /// a new register to use, or evict the previous reload and use this reg.
663 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
664 AvailableSpills &Spills,
665 std::vector<MachineInstr*> &MaybeDeadStores,
666 SmallSet<unsigned, 8> &Rejected,
668 std::vector<MachineOperand*> &KillOps,
670 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
673 if (Reuses.empty()) return PhysReg; // This is most often empty.
675 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
676 ReusedOp &Op = Reuses[ro];
677 // If we find some other reuse that was supposed to use this register
678 // exactly for its reload, we can change this reload to use ITS reload
679 // register. That is, unless its reload register has already been
680 // considered and subsequently rejected because it has also been reused
681 // by another operand.
682 if (Op.PhysRegReused == PhysReg &&
683 Rejected.count(Op.AssignedPhysReg) == 0) {
684 // Yup, use the reload register that we didn't use before.
685 unsigned NewReg = Op.AssignedPhysReg;
686 Rejected.insert(PhysReg);
687 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
688 RegKills, KillOps, VRM);
690 // Otherwise, we might also have a problem if a previously reused
691 // value aliases the new register. If so, codegen the previous reload
693 unsigned PRRU = Op.PhysRegReused;
694 const TargetRegisterInfo *TRI = Spills.getRegInfo();
695 if (TRI->areAliases(PRRU, PhysReg)) {
696 // Okay, we found out that an alias of a reused register
697 // was used. This isn't good because it means we have
698 // to undo a previous reuse.
699 MachineBasicBlock *MBB = MI->getParent();
700 const TargetRegisterClass *AliasRC =
701 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
703 // Copy Op out of the vector and remove it, we're going to insert an
704 // explicit load for it.
706 Reuses.erase(Reuses.begin()+ro);
708 // Ok, we're going to try to reload the assigned physreg into the
709 // slot that we were supposed to in the first place. However, that
710 // register could hold a reuse. Check to see if it conflicts or
711 // would prefer us to use a different register.
712 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
713 MI, Spills, MaybeDeadStores,
714 Rejected, RegKills, KillOps, VRM);
716 MachineBasicBlock::iterator MII = MI;
717 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
718 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
720 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
721 NewOp.StackSlotOrReMat, AliasRC);
722 MachineInstr *LoadMI = prior(MII);
723 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
724 // Any stores to this stack slot are not dead anymore.
725 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
728 Spills.ClobberPhysReg(NewPhysReg);
729 Spills.ClobberPhysReg(NewOp.PhysRegReused);
731 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
732 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
733 MI->getOperand(NewOp.Operand).setReg(RReg);
734 MI->getOperand(NewOp.Operand).setSubReg(0);
736 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
738 UpdateKills(*MII, TRI, RegKills, KillOps);
739 DOUT << '\t' << *MII;
741 DOUT << "Reuse undone!\n";
744 // Finally, PhysReg is now available, go ahead and use it.
752 // ************************************************************************ //
754 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
755 /// stack slot mod/ref. It also checks if it's possible to unfold the
756 /// instruction by having it define a specified physical register instead.
757 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
758 const TargetInstrInfo *TII,
759 const TargetRegisterInfo *TRI,
761 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
765 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
766 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
767 unsigned VirtReg = I->second.first;
768 VirtRegMap::ModRef MR = I->second.second;
769 if (MR & VirtRegMap::isModRef)
770 if (VRM.getStackSlot(VirtReg) == SS) {
771 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
778 // Does the instruction uses a register that overlaps the scratch register?
779 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
780 MachineOperand &MO = MI.getOperand(i);
781 if (!MO.isReg() || MO.getReg() == 0)
783 unsigned Reg = MO.getReg();
784 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
785 if (!VRM.hasPhys(Reg))
787 Reg = VRM.getPhys(Reg);
789 if (TRI->regsOverlap(PhysReg, Reg))
795 /// FindFreeRegister - Find a free register of a given register class by looking
796 /// at (at most) the last two machine instructions.
797 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
798 MachineBasicBlock &MBB,
799 const TargetRegisterClass *RC,
800 const TargetRegisterInfo *TRI,
801 BitVector &AllocatableRegs) {
802 BitVector Defs(TRI->getNumRegs());
803 BitVector Uses(TRI->getNumRegs());
804 SmallVector<unsigned, 4> LocalUses;
805 SmallVector<unsigned, 4> Kills;
807 // Take a look at 2 instructions at most.
808 for (unsigned Count = 0; Count < 2; ++Count) {
809 if (MII == MBB.begin())
811 MachineInstr *PrevMI = prior(MII);
812 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
813 MachineOperand &MO = PrevMI->getOperand(i);
814 if (!MO.isReg() || MO.getReg() == 0)
816 unsigned Reg = MO.getReg();
819 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
822 LocalUses.push_back(Reg);
823 if (MO.isKill() && AllocatableRegs[Reg])
824 Kills.push_back(Reg);
828 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
829 unsigned Kill = Kills[i];
830 if (!Defs[Kill] && !Uses[Kill] &&
831 TRI->getPhysicalRegisterRegClass(Kill) == RC)
834 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
835 unsigned Reg = LocalUses[i];
837 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
848 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
849 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
850 MachineOperand &MO = MI->getOperand(i);
851 if (MO.isReg() && MO.getReg() == VirtReg)
858 bool operator()(const std::pair<MachineInstr*, int> &A,
859 const std::pair<MachineInstr*, int> &B) {
860 return A.second < B.second;
865 // ***************************** //
866 // Local Spiller Implementation //
867 // ***************************** //
869 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
870 MachineRegisterInfo *RegInfo;
871 const TargetRegisterInfo *TRI;
872 const TargetInstrInfo *TII;
873 BitVector AllocatableRegs;
874 DenseMap<MachineInstr*, unsigned> DistanceMap;
877 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
878 LiveIntervals* LIs) {
879 RegInfo = &MF.getRegInfo();
880 TRI = MF.getTarget().getRegisterInfo();
881 TII = MF.getTarget().getInstrInfo();
882 AllocatableRegs = TRI->getAllocatableSet(MF);
883 DOUT << "\n**** Local spiller rewriting function '"
884 << MF.getFunction()->getName() << "':\n";
885 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
889 // Spills - Keep track of which spilled values are available in physregs
890 // so that we can choose to reuse the physregs instead of emitting
891 // reloads. This is usually refreshed per basic block.
892 AvailableSpills Spills(TRI, TII);
894 // Keep track of kill information.
895 BitVector RegKills(TRI->getNumRegs());
896 std::vector<MachineOperand*> KillOps;
897 KillOps.resize(TRI->getNumRegs(), NULL);
899 // SingleEntrySuccs - Successor blocks which have a single predecessor.
900 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
901 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
903 // Traverse the basic blocks depth first.
904 MachineBasicBlock *Entry = MF.begin();
905 SmallPtrSet<MachineBasicBlock*,16> Visited;
906 for (df_ext_iterator<MachineBasicBlock*,
907 SmallPtrSet<MachineBasicBlock*,16> >
908 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
910 MachineBasicBlock *MBB = *DFI;
911 if (!EarlyVisited.count(MBB))
912 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
914 // If this MBB is the only predecessor of a successor. Keep the
915 // availability information and visit it next.
917 // Keep visiting single predecessor successor as long as possible.
918 SinglePredSuccs.clear();
919 findSinglePredSuccessor(MBB, SinglePredSuccs);
920 if (SinglePredSuccs.empty())
923 // FIXME: More than one successors, each of which has MBB has
924 // the only predecessor.
925 MBB = SinglePredSuccs[0];
926 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
927 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
928 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
933 // Clear the availability info.
937 DOUT << "**** Post Machine Instrs ****\n";
940 // Mark unused spill slots.
941 MachineFrameInfo *MFI = MF.getFrameInfo();
942 int SS = VRM.getLowSpillSlot();
943 if (SS != VirtRegMap::NO_STACK_SLOT)
944 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
945 if (!VRM.isSpillSlotUsed(SS)) {
946 MFI->RemoveStackObject(SS);
955 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
956 /// a scratch register is available.
957 /// xorq %r12<kill>, %r13
958 /// addq %rax, -184(%rbp)
959 /// addq %r13, -184(%rbp)
961 /// xorq %r12<kill>, %r13
962 /// movq -184(%rbp), %r12
965 /// movq %r12, -184(%rbp)
966 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
967 MachineBasicBlock &MBB,
968 MachineBasicBlock::iterator &MII,
969 std::vector<MachineInstr*> &MaybeDeadStores,
970 AvailableSpills &Spills,
972 std::vector<MachineOperand*> &KillOps,
975 MachineBasicBlock::iterator NextMII = next(MII);
976 if (NextMII == MBB.end())
979 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
982 // Now let's see if the last couple of instructions happens to have freed up
984 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
985 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
989 MachineFunction &MF = *MBB.getParent();
990 TRI = MF.getTarget().getRegisterInfo();
991 MachineInstr &MI = *MII;
992 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
995 // If the next instruction also folds the same SS modref and can be unfoled,
996 // then it's worthwhile to issue a load from SS into the free register and
997 // then unfold these instructions.
998 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1001 // Load from SS to the spare physical register.
1002 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1003 // This invalidates Phys.
1004 Spills.ClobberPhysReg(PhysReg);
1005 // Remember it's available.
1006 Spills.addAvailable(SS, PhysReg);
1007 MaybeDeadStores[SS] = NULL;
1009 // Unfold current MI.
1010 SmallVector<MachineInstr*, 4> NewMIs;
1011 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1012 llvm_unreachable("Unable unfold the load / store folding instruction!");
1013 assert(NewMIs.size() == 1);
1014 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1015 VRM.transferRestorePts(&MI, NewMIs[0]);
1016 MII = MBB.insert(MII, NewMIs[0]);
1017 InvalidateKills(MI, TRI, RegKills, KillOps);
1018 VRM.RemoveMachineInstrFromMaps(&MI);
1022 // Unfold next instructions that fold the same SS.
1024 MachineInstr &NextMI = *NextMII;
1025 NextMII = next(NextMII);
1027 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1028 llvm_unreachable("Unable unfold the load / store folding instruction!");
1029 assert(NewMIs.size() == 1);
1030 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1031 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1032 MBB.insert(NextMII, NewMIs[0]);
1033 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1034 VRM.RemoveMachineInstrFromMaps(&NextMI);
1037 if (NextMII == MBB.end())
1039 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1041 // Store the value back into SS.
1042 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1043 MachineInstr *StoreMI = prior(NextMII);
1044 VRM.addSpillSlotUse(SS, StoreMI);
1045 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1050 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1051 /// instruction. e.g.
1053 /// movl %eax, -32(%ebp)
1054 /// movl -36(%ebp), %eax
1055 /// orl %eax, -32(%ebp)
1058 /// orl -36(%ebp), %eax
1059 /// mov %eax, -32(%ebp)
1060 /// This enables unfolding optimization for a subsequent instruction which will
1061 /// also eliminate the newly introduced store instruction.
1062 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1063 MachineBasicBlock::iterator &MII,
1064 std::vector<MachineInstr*> &MaybeDeadStores,
1065 AvailableSpills &Spills,
1066 BitVector &RegKills,
1067 std::vector<MachineOperand*> &KillOps,
1069 MachineFunction &MF = *MBB.getParent();
1070 MachineInstr &MI = *MII;
1071 unsigned UnfoldedOpc = 0;
1072 unsigned UnfoldPR = 0;
1073 unsigned UnfoldVR = 0;
1074 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1075 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1076 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1077 // Only transform a MI that folds a single register.
1080 UnfoldVR = I->second.first;
1081 VirtRegMap::ModRef MR = I->second.second;
1082 // MI2VirtMap be can updated which invalidate the iterator.
1083 // Increment the iterator first.
1085 if (VRM.isAssignedReg(UnfoldVR))
1087 // If this reference is not a use, any previous store is now dead.
1088 // Otherwise, the store to this stack slot is not dead anymore.
1089 FoldedSS = VRM.getStackSlot(UnfoldVR);
1090 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1091 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1092 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1093 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1096 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1105 // Look for other unfolding opportunities.
1106 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1107 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1110 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1111 MachineOperand &MO = MI.getOperand(i);
1112 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1114 unsigned VirtReg = MO.getReg();
1115 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1117 if (VRM.isAssignedReg(VirtReg)) {
1118 unsigned PhysReg = VRM.getPhys(VirtReg);
1119 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1121 } else if (VRM.isReMaterialized(VirtReg))
1123 int SS = VRM.getStackSlot(VirtReg);
1124 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1126 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1130 if (VRM.hasPhys(VirtReg)) {
1131 PhysReg = VRM.getPhys(VirtReg);
1132 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1136 // Ok, we'll need to reload the value into a register which makes
1137 // it impossible to perform the store unfolding optimization later.
1138 // Let's see if it is possible to fold the load if the store is
1139 // unfolded. This allows us to perform the store unfolding
1141 SmallVector<MachineInstr*, 4> NewMIs;
1142 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1143 assert(NewMIs.size() == 1);
1144 MachineInstr *NewMI = NewMIs.back();
1146 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1148 SmallVector<unsigned, 1> Ops;
1150 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1152 VRM.addSpillSlotUse(SS, FoldedMI);
1153 if (!VRM.hasPhys(UnfoldVR))
1154 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1155 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1156 MII = MBB.insert(MII, FoldedMI);
1157 InvalidateKills(MI, TRI, RegKills, KillOps);
1158 VRM.RemoveMachineInstrFromMaps(&MI);
1160 MF.DeleteMachineInstr(NewMI);
1163 MF.DeleteMachineInstr(NewMI);
1170 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1171 /// where SrcReg is r1 and it is tied to r0. Return true if after
1172 /// commuting this instruction it will be r0 = op r2, r1.
1173 static bool CommuteChangesDestination(MachineInstr *DefMI,
1174 const TargetInstrDesc &TID,
1176 const TargetInstrInfo *TII,
1178 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1180 if (!DefMI->getOperand(1).isReg() ||
1181 DefMI->getOperand(1).getReg() != SrcReg)
1184 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1186 unsigned SrcIdx1, SrcIdx2;
1187 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1189 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1196 /// CommuteToFoldReload -
1199 /// r1 = op r1, r2<kill>
1202 /// If op is commutable and r2 is killed, then we can xform these to
1203 /// r2 = op r2, fi#1
1205 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1206 MachineBasicBlock::iterator &MII,
1207 unsigned VirtReg, unsigned SrcReg, int SS,
1208 AvailableSpills &Spills,
1209 BitVector &RegKills,
1210 std::vector<MachineOperand*> &KillOps,
1211 const TargetRegisterInfo *TRI,
1213 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1216 MachineFunction &MF = *MBB.getParent();
1217 MachineInstr &MI = *MII;
1218 MachineBasicBlock::iterator DefMII = prior(MII);
1219 MachineInstr *DefMI = DefMII;
1220 const TargetInstrDesc &TID = DefMI->getDesc();
1222 if (DefMII != MBB.begin() &&
1223 TID.isCommutable() &&
1224 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1225 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1226 unsigned NewReg = NewDstMO.getReg();
1227 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1229 MachineInstr *ReloadMI = prior(DefMII);
1231 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1232 if (DestReg != SrcReg || FrameIdx != SS)
1234 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1238 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1240 assert(DefMI->getOperand(DefIdx).isReg() &&
1241 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1243 // Now commute def instruction.
1244 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1247 SmallVector<unsigned, 1> Ops;
1248 Ops.push_back(NewDstIdx);
1249 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1250 // Not needed since foldMemoryOperand returns new MI.
1251 MF.DeleteMachineInstr(CommutedMI);
1255 VRM.addSpillSlotUse(SS, FoldedMI);
1256 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1257 // Insert new def MI and spill MI.
1258 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1259 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1261 MachineInstr *StoreMI = MII;
1262 VRM.addSpillSlotUse(SS, StoreMI);
1263 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1264 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1266 // Delete all 3 old instructions.
1267 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1268 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1269 MBB.erase(ReloadMI);
1270 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1271 VRM.RemoveMachineInstrFromMaps(DefMI);
1273 InvalidateKills(MI, TRI, RegKills, KillOps);
1274 VRM.RemoveMachineInstrFromMaps(&MI);
1277 // If NewReg was previously holding value of some SS, it's now clobbered.
1278 // This has to be done now because it's a physical register. When this
1279 // instruction is re-visited, it's ignored.
1280 Spills.ClobberPhysReg(NewReg);
1289 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1290 /// the last store to the same slot is now dead. If so, remove the last store.
1291 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1292 MachineBasicBlock::iterator &MII,
1293 int Idx, unsigned PhysReg, int StackSlot,
1294 const TargetRegisterClass *RC,
1295 bool isAvailable, MachineInstr *&LastStore,
1296 AvailableSpills &Spills,
1297 SmallSet<MachineInstr*, 4> &ReMatDefs,
1298 BitVector &RegKills,
1299 std::vector<MachineOperand*> &KillOps,
1302 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1303 MachineInstr *StoreMI = next(MII);
1304 VRM.addSpillSlotUse(StackSlot, StoreMI);
1305 DOUT << "Store:\t" << *StoreMI;
1307 // If there is a dead store to this stack slot, nuke it now.
1309 DOUT << "Removed dead store:\t" << *LastStore;
1311 SmallVector<unsigned, 2> KillRegs;
1312 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1313 MachineBasicBlock::iterator PrevMII = LastStore;
1314 bool CheckDef = PrevMII != MBB.begin();
1317 VRM.RemoveMachineInstrFromMaps(LastStore);
1318 MBB.erase(LastStore);
1320 // Look at defs of killed registers on the store. Mark the defs
1321 // as dead since the store has been deleted and they aren't
1323 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1324 bool HasOtherDef = false;
1325 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1326 MachineInstr *DeadDef = PrevMII;
1327 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1328 // FIXME: This assumes a remat def does not have side effects.
1329 VRM.RemoveMachineInstrFromMaps(DeadDef);
1338 LastStore = next(MII);
1340 // If the stack slot value was previously available in some other
1341 // register, change it now. Otherwise, make the register available,
1343 Spills.ModifyStackSlotOrReMat(StackSlot);
1344 Spills.ClobberPhysReg(PhysReg);
1345 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1349 /// TransferDeadness - A identity copy definition is dead and it's being
1350 /// removed. Find the last def or use and mark it as dead / kill.
1351 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1352 unsigned Reg, BitVector &RegKills,
1353 std::vector<MachineOperand*> &KillOps,
1355 SmallPtrSet<MachineInstr*, 4> Seens;
1356 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1357 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1358 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1359 MachineInstr *UDMI = &*RI;
1360 if (UDMI->getParent() != MBB)
1362 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1363 if (DI == DistanceMap.end() || DI->second > CurDist)
1365 if (Seens.insert(UDMI))
1366 Refs.push_back(std::make_pair(UDMI, DI->second));
1371 std::sort(Refs.begin(), Refs.end(), RefSorter());
1373 while (!Refs.empty()) {
1374 MachineInstr *LastUDMI = Refs.back().first;
1377 MachineOperand *LastUD = NULL;
1378 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1379 MachineOperand &MO = LastUDMI->getOperand(i);
1380 if (!MO.isReg() || MO.getReg() != Reg)
1382 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1384 if (LastUDMI->isRegTiedToDefOperand(i))
1387 if (LastUD->isDef()) {
1388 // If the instruction has no side effect, delete it and propagate
1389 // backward further. Otherwise, mark is dead and we are done.
1390 const TargetInstrDesc &TID = LastUDMI->getDesc();
1391 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1392 TID.hasUnmodeledSideEffects()) {
1393 LastUD->setIsDead();
1396 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1397 MBB->erase(LastUDMI);
1399 LastUD->setIsKill();
1401 KillOps[Reg] = LastUD;
1407 /// rewriteMBB - Keep track of which spills are available even after the
1408 /// register allocator is done with them. If possible, avid reloading vregs.
1409 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1411 AvailableSpills &Spills, BitVector &RegKills,
1412 std::vector<MachineOperand*> &KillOps) {
1414 DOUT << "\n**** Local spiller rewriting MBB '"
1415 << MBB.getBasicBlock()->getName() << "':\n";
1417 MachineFunction &MF = *MBB.getParent();
1419 // MaybeDeadStores - When we need to write a value back into a stack slot,
1420 // keep track of the inserted store. If the stack slot value is never read
1421 // (because the value was used from some available register, for example), and
1422 // subsequently stored to, the original store is dead. This map keeps track
1423 // of inserted stores that are not used. If we see a subsequent store to the
1424 // same stack slot, the original store is deleted.
1425 std::vector<MachineInstr*> MaybeDeadStores;
1426 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1428 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1429 SmallSet<MachineInstr*, 4> ReMatDefs;
1432 SmallSet<unsigned, 2> KilledMIRegs;
1435 KillOps.resize(TRI->getNumRegs(), NULL);
1438 DistanceMap.clear();
1439 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1441 MachineBasicBlock::iterator NextMII = next(MII);
1443 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1444 bool Erased = false;
1445 bool BackTracked = false;
1446 if (OptimizeByUnfold(MBB, MII,
1447 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1448 NextMII = next(MII);
1450 MachineInstr &MI = *MII;
1452 if (VRM.hasEmergencySpills(&MI)) {
1453 // Spill physical register(s) in the rare case the allocator has run out
1454 // of registers to allocate.
1455 SmallSet<int, 4> UsedSS;
1456 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1457 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1458 unsigned PhysReg = EmSpills[i];
1459 const TargetRegisterClass *RC =
1460 TRI->getPhysicalRegisterRegClass(PhysReg);
1461 assert(RC && "Unable to determine register class!");
1462 int SS = VRM.getEmergencySpillSlot(RC);
1463 if (UsedSS.count(SS))
1464 llvm_unreachable("Need to spill more than one physical registers!");
1466 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1467 MachineInstr *StoreMI = prior(MII);
1468 VRM.addSpillSlotUse(SS, StoreMI);
1469 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1470 MachineInstr *LoadMI = next(MII);
1471 VRM.addSpillSlotUse(SS, LoadMI);
1474 NextMII = next(MII);
1477 // Insert restores here if asked to.
1478 if (VRM.isRestorePt(&MI)) {
1479 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1480 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1481 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1482 if (!VRM.getPreSplitReg(VirtReg))
1483 continue; // Split interval spilled again.
1484 unsigned Phys = VRM.getPhys(VirtReg);
1485 RegInfo->setPhysRegUsed(Phys);
1487 // Check if the value being restored if available. If so, it must be
1488 // from a predecessor BB that fallthrough into this BB. We do not
1494 // ... # r1 not clobbered
1497 bool DoReMat = VRM.isReMaterialized(VirtReg);
1498 int SSorRMId = DoReMat
1499 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1500 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1501 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1502 if (InReg == Phys) {
1503 // If the value is already available in the expected register, save
1504 // a reload / remat.
1506 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1508 DOUT << "Reusing SS#" << SSorRMId;
1509 DOUT << " from physreg "
1510 << TRI->getName(InReg) << " for vreg"
1511 << VirtReg <<" instead of reloading into physreg "
1512 << TRI->getName(Phys) << "\n";
1515 } else if (InReg && InReg != Phys) {
1517 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1519 DOUT << "Reusing SS#" << SSorRMId;
1520 DOUT << " from physreg "
1521 << TRI->getName(InReg) << " for vreg"
1522 << VirtReg <<" by copying it into physreg "
1523 << TRI->getName(Phys) << "\n";
1525 // If the reloaded / remat value is available in another register,
1526 // copy it to the desired register.
1527 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1529 // This invalidates Phys.
1530 Spills.ClobberPhysReg(Phys);
1531 // Remember it's available.
1532 Spills.addAvailable(SSorRMId, Phys);
1535 MachineInstr *CopyMI = prior(MII);
1536 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1537 KillOpnd->setIsKill();
1538 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1540 DOUT << '\t' << *CopyMI;
1545 if (VRM.isReMaterialized(VirtReg)) {
1546 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1548 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1549 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1550 MachineInstr *LoadMI = prior(MII);
1551 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1555 // This invalidates Phys.
1556 Spills.ClobberPhysReg(Phys);
1557 // Remember it's available.
1558 Spills.addAvailable(SSorRMId, Phys);
1560 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1561 DOUT << '\t' << *prior(MII);
1565 // Insert spills here if asked to.
1566 if (VRM.isSpillPt(&MI)) {
1567 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1568 VRM.getSpillPtSpills(&MI);
1569 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1570 unsigned VirtReg = SpillRegs[i].first;
1571 bool isKill = SpillRegs[i].second;
1572 if (!VRM.getPreSplitReg(VirtReg))
1573 continue; // Split interval spilled again.
1574 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1575 unsigned Phys = VRM.getPhys(VirtReg);
1576 int StackSlot = VRM.getStackSlot(VirtReg);
1577 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1578 MachineInstr *StoreMI = next(MII);
1579 VRM.addSpillSlotUse(StackSlot, StoreMI);
1580 DOUT << "Store:\t" << *StoreMI;
1581 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1583 NextMII = next(MII);
1586 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1588 ReuseInfo ReusedOperands(MI, TRI);
1589 SmallVector<unsigned, 4> VirtUseOps;
1590 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1591 MachineOperand &MO = MI.getOperand(i);
1592 if (!MO.isReg() || MO.getReg() == 0)
1593 continue; // Ignore non-register operands.
1595 unsigned VirtReg = MO.getReg();
1596 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1597 // Ignore physregs for spilling, but remember that it is used by this
1599 RegInfo->setPhysRegUsed(VirtReg);
1603 // We want to process implicit virtual register uses first.
1604 if (MO.isImplicit())
1605 // If the virtual register is implicitly defined, emit a implicit_def
1606 // before so scavenger knows it's "defined".
1607 // FIXME: This is a horrible hack done the by register allocator to
1608 // remat a definition with virtual register operand.
1609 VirtUseOps.insert(VirtUseOps.begin(), i);
1611 VirtUseOps.push_back(i);
1614 // Process all of the spilled uses and all non spilled reg references.
1615 SmallVector<int, 2> PotentialDeadStoreSlots;
1616 KilledMIRegs.clear();
1617 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1618 unsigned i = VirtUseOps[j];
1619 MachineOperand &MO = MI.getOperand(i);
1620 unsigned VirtReg = MO.getReg();
1621 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1622 "Not a virtual register?");
1624 unsigned SubIdx = MO.getSubReg();
1625 if (VRM.isAssignedReg(VirtReg)) {
1626 // This virtual register was assigned a physreg!
1627 unsigned Phys = VRM.getPhys(VirtReg);
1628 RegInfo->setPhysRegUsed(Phys);
1630 ReusedOperands.markClobbered(Phys);
1631 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1632 MI.getOperand(i).setReg(RReg);
1633 MI.getOperand(i).setSubReg(0);
1634 if (VRM.isImplicitlyDefined(VirtReg))
1635 // FIXME: Is this needed?
1636 BuildMI(MBB, &MI, MI.getDebugLoc(),
1637 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1641 // This virtual register is now known to be a spilled value.
1643 continue; // Handle defs in the loop below (handle use&def here though)
1645 bool AvoidReload = MO.isUndef();
1646 // Check if it is defined by an implicit def. It should not be spilled.
1647 // Note, this is for correctness reason. e.g.
1648 // 8 %reg1024<def> = IMPLICIT_DEF
1649 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1650 // The live range [12, 14) are not part of the r1024 live interval since
1651 // it's defined by an implicit def. It will not conflicts with live
1652 // interval of r1025. Now suppose both registers are spilled, you can
1653 // easily see a situation where both registers are reloaded before
1654 // the INSERT_SUBREG and both target registers that would overlap.
1655 bool DoReMat = VRM.isReMaterialized(VirtReg);
1656 int SSorRMId = DoReMat
1657 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1658 int ReuseSlot = SSorRMId;
1660 // Check to see if this stack slot is available.
1661 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1663 // If this is a sub-register use, make sure the reuse register is in the
1664 // right register class. For example, for x86 not all of the 32-bit
1665 // registers have accessible sub-registers.
1666 // Similarly so for EXTRACT_SUBREG. Consider this:
1668 // MOV32_mr fi#1, EDI
1670 // = EXTRACT_SUBREG fi#1
1671 // fi#1 is available in EDI, but it cannot be reused because it's not in
1672 // the right register file.
1673 if (PhysReg && !AvoidReload &&
1674 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1675 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1676 if (!RC->contains(PhysReg))
1680 if (PhysReg && !AvoidReload) {
1681 // This spilled operand might be part of a two-address operand. If this
1682 // is the case, then changing it will necessarily require changing the
1683 // def part of the instruction as well. However, in some cases, we
1684 // aren't allowed to modify the reused register. If none of these cases
1686 bool CanReuse = true;
1687 bool isTied = MI.isRegTiedToDefOperand(i);
1689 // Okay, we have a two address operand. We can reuse this physreg as
1690 // long as we are allowed to clobber the value and there isn't an
1691 // earlier def that has already clobbered the physreg.
1692 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1693 Spills.canClobberPhysReg(PhysReg);
1697 // If this stack slot value is already available, reuse it!
1698 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1699 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1701 DOUT << "Reusing SS#" << ReuseSlot;
1702 DOUT << " from physreg "
1703 << TRI->getName(PhysReg) << " for vreg"
1704 << VirtReg <<" instead of reloading into physreg "
1705 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1706 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1707 MI.getOperand(i).setReg(RReg);
1708 MI.getOperand(i).setSubReg(0);
1710 // The only technical detail we have is that we don't know that
1711 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1712 // later in the instruction. In particular, consider 'op V1, V2'.
1713 // If V1 is available in physreg R0, we would choose to reuse it
1714 // here, instead of reloading it into the register the allocator
1715 // indicated (say R1). However, V2 might have to be reloaded
1716 // later, and it might indicate that it needs to live in R0. When
1717 // this occurs, we need to have information available that
1718 // indicates it is safe to use R1 for the reload instead of R0.
1720 // To further complicate matters, we might conflict with an alias,
1721 // or R0 and R1 might not be compatible with each other. In this
1722 // case, we actually insert a reload for V1 in R1, ensuring that
1723 // we can get at R0 or its alias.
1724 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1725 VRM.getPhys(VirtReg), VirtReg);
1727 // Only mark it clobbered if this is a use&def operand.
1728 ReusedOperands.markClobbered(PhysReg);
1731 if (MI.getOperand(i).isKill() &&
1732 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1734 // The store of this spilled value is potentially dead, but we
1735 // won't know for certain until we've confirmed that the re-use
1736 // above is valid, which means waiting until the other operands
1737 // are processed. For now we just track the spill slot, we'll
1738 // remove it after the other operands are processed if valid.
1740 PotentialDeadStoreSlots.push_back(ReuseSlot);
1743 // Mark is isKill if it's there no other uses of the same virtual
1744 // register and it's not a two-address operand. IsKill will be
1745 // unset if reg is reused.
1746 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1747 MI.getOperand(i).setIsKill();
1748 KilledMIRegs.insert(VirtReg);
1754 // Otherwise we have a situation where we have a two-address instruction
1755 // whose mod/ref operand needs to be reloaded. This reload is already
1756 // available in some register "PhysReg", but if we used PhysReg as the
1757 // operand to our 2-addr instruction, the instruction would modify
1758 // PhysReg. This isn't cool if something later uses PhysReg and expects
1759 // to get its initial value.
1761 // To avoid this problem, and to avoid doing a load right after a store,
1762 // we emit a copy from PhysReg into the designated register for this
1764 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1765 assert(DesignatedReg && "Must map virtreg to physreg!");
1767 // Note that, if we reused a register for a previous operand, the
1768 // register we want to reload into might not actually be
1769 // available. If this occurs, use the register indicated by the
1771 if (ReusedOperands.hasReuses())
1772 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1773 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1775 // If the mapped designated register is actually the physreg we have
1776 // incoming, we don't need to inserted a dead copy.
1777 if (DesignatedReg == PhysReg) {
1778 // If this stack slot value is already available, reuse it!
1779 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1780 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1782 DOUT << "Reusing SS#" << ReuseSlot;
1783 DOUT << " from physreg " << TRI->getName(PhysReg)
1784 << " for vreg" << VirtReg
1785 << " instead of reloading into same physreg.\n";
1786 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1787 MI.getOperand(i).setReg(RReg);
1788 MI.getOperand(i).setSubReg(0);
1789 ReusedOperands.markClobbered(RReg);
1794 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1795 RegInfo->setPhysRegUsed(DesignatedReg);
1796 ReusedOperands.markClobbered(DesignatedReg);
1797 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1799 MachineInstr *CopyMI = prior(MII);
1800 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1802 // This invalidates DesignatedReg.
1803 Spills.ClobberPhysReg(DesignatedReg);
1805 Spills.addAvailable(ReuseSlot, DesignatedReg);
1807 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1808 MI.getOperand(i).setReg(RReg);
1809 MI.getOperand(i).setSubReg(0);
1810 DOUT << '\t' << *prior(MII);
1815 // Otherwise, reload it and remember that we have it.
1816 PhysReg = VRM.getPhys(VirtReg);
1817 assert(PhysReg && "Must map virtreg to physreg!");
1819 // Note that, if we reused a register for a previous operand, the
1820 // register we want to reload into might not actually be
1821 // available. If this occurs, use the register indicated by the
1823 if (ReusedOperands.hasReuses())
1824 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1825 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1827 RegInfo->setPhysRegUsed(PhysReg);
1828 ReusedOperands.markClobbered(PhysReg);
1833 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1835 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1836 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1837 MachineInstr *LoadMI = prior(MII);
1838 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1841 // This invalidates PhysReg.
1842 Spills.ClobberPhysReg(PhysReg);
1844 // Any stores to this stack slot are not dead anymore.
1846 MaybeDeadStores[SSorRMId] = NULL;
1847 Spills.addAvailable(SSorRMId, PhysReg);
1848 // Assumes this is the last use. IsKill will be unset if reg is reused
1849 // unless it's a two-address operand.
1850 if (!MI.isRegTiedToDefOperand(i) &&
1851 KilledMIRegs.count(VirtReg) == 0) {
1852 MI.getOperand(i).setIsKill();
1853 KilledMIRegs.insert(VirtReg);
1856 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1857 DOUT << '\t' << *prior(MII);
1859 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1860 MI.getOperand(i).setReg(RReg);
1861 MI.getOperand(i).setSubReg(0);
1864 // Ok - now we can remove stores that have been confirmed dead.
1865 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1866 // This was the last use and the spilled value is still available
1867 // for reuse. That means the spill was unnecessary!
1868 int PDSSlot = PotentialDeadStoreSlots[j];
1869 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1871 DOUT << "Removed dead store:\t" << *DeadStore;
1872 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1873 VRM.RemoveMachineInstrFromMaps(DeadStore);
1874 MBB.erase(DeadStore);
1875 MaybeDeadStores[PDSSlot] = NULL;
1884 // If we have folded references to memory operands, make sure we clear all
1885 // physical registers that may contain the value of the spilled virtual
1887 SmallSet<int, 2> FoldedSS;
1888 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1889 unsigned VirtReg = I->second.first;
1890 VirtRegMap::ModRef MR = I->second.second;
1891 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1893 // MI2VirtMap be can updated which invalidate the iterator.
1894 // Increment the iterator first.
1896 int SS = VRM.getStackSlot(VirtReg);
1897 if (SS == VirtRegMap::NO_STACK_SLOT)
1899 FoldedSS.insert(SS);
1900 DOUT << " - StackSlot: " << SS << "\n";
1902 // If this folded instruction is just a use, check to see if it's a
1903 // straight load from the virt reg slot.
1904 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1906 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1907 if (DestReg && FrameIdx == SS) {
1908 // If this spill slot is available, turn it into a copy (or nothing)
1909 // instead of leaving it as a load!
1910 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1911 DOUT << "Promoted Load To Copy: " << MI;
1912 if (DestReg != InReg) {
1913 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1914 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1915 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1916 unsigned SubIdx = DefMO->getSubReg();
1917 // Revisit the copy so we make sure to notice the effects of the
1918 // operation on the destreg (either needing to RA it if it's
1919 // virtual or needing to clobber any values if it's physical).
1921 --NextMII; // backtrack to the copy.
1922 // Propagate the sub-register index over.
1924 DefMO = NextMII->findRegisterDefOperand(DestReg);
1925 DefMO->setSubReg(SubIdx);
1929 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1930 KillOpnd->setIsKill();
1934 DOUT << "Removing now-noop copy: " << MI;
1935 // Unset last kill since it's being reused.
1936 InvalidateKill(InReg, TRI, RegKills, KillOps);
1937 Spills.disallowClobberPhysReg(InReg);
1940 InvalidateKills(MI, TRI, RegKills, KillOps);
1941 VRM.RemoveMachineInstrFromMaps(&MI);
1944 goto ProcessNextInst;
1947 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1948 SmallVector<MachineInstr*, 4> NewMIs;
1950 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1951 MBB.insert(MII, NewMIs[0]);
1952 InvalidateKills(MI, TRI, RegKills, KillOps);
1953 VRM.RemoveMachineInstrFromMaps(&MI);
1956 --NextMII; // backtrack to the unfolded instruction.
1958 goto ProcessNextInst;
1963 // If this reference is not a use, any previous store is now dead.
1964 // Otherwise, the store to this stack slot is not dead anymore.
1965 MachineInstr* DeadStore = MaybeDeadStores[SS];
1967 bool isDead = !(MR & VirtRegMap::isRef);
1968 MachineInstr *NewStore = NULL;
1969 if (MR & VirtRegMap::isModRef) {
1970 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1971 SmallVector<MachineInstr*, 4> NewMIs;
1972 // We can reuse this physreg as long as we are allowed to clobber
1973 // the value and there isn't an earlier def that has already clobbered
1976 !ReusedOperands.isClobbered(PhysReg) &&
1977 Spills.canClobberPhysReg(PhysReg) &&
1978 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1979 MachineOperand *KillOpnd =
1980 DeadStore->findRegisterUseOperand(PhysReg, true);
1981 // Note, if the store is storing a sub-register, it's possible the
1982 // super-register is needed below.
1983 if (KillOpnd && !KillOpnd->getSubReg() &&
1984 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1985 MBB.insert(MII, NewMIs[0]);
1986 NewStore = NewMIs[1];
1987 MBB.insert(MII, NewStore);
1988 VRM.addSpillSlotUse(SS, NewStore);
1989 InvalidateKills(MI, TRI, RegKills, KillOps);
1990 VRM.RemoveMachineInstrFromMaps(&MI);
1994 --NextMII; // backtrack to the unfolded instruction.
2002 if (isDead) { // Previous store is dead.
2003 // If we get here, the store is dead, nuke it now.
2004 DOUT << "Removed dead store:\t" << *DeadStore;
2005 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2006 VRM.RemoveMachineInstrFromMaps(DeadStore);
2007 MBB.erase(DeadStore);
2012 MaybeDeadStores[SS] = NULL;
2014 // Treat this store as a spill merged into a copy. That makes the
2015 // stack slot value available.
2016 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2017 goto ProcessNextInst;
2021 // If the spill slot value is available, and this is a new definition of
2022 // the value, the value is not available anymore.
2023 if (MR & VirtRegMap::isMod) {
2024 // Notice that the value in this stack slot has been modified.
2025 Spills.ModifyStackSlotOrReMat(SS);
2027 // If this is *just* a mod of the value, check to see if this is just a
2028 // store to the spill slot (i.e. the spill got merged into the copy). If
2029 // so, realize that the vreg is available now, and add the store to the
2030 // MaybeDeadStore info.
2032 if (!(MR & VirtRegMap::isRef)) {
2033 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2034 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2035 "Src hasn't been allocated yet?");
2037 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2038 Spills, RegKills, KillOps, TRI, VRM)) {
2039 NextMII = next(MII);
2041 goto ProcessNextInst;
2044 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2045 // this as a potentially dead store in case there is a subsequent
2046 // store into the stack slot without a read from it.
2047 MaybeDeadStores[StackSlot] = &MI;
2049 // If the stack slot value was previously available in some other
2050 // register, change it now. Otherwise, make the register
2051 // available in PhysReg.
2052 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2058 // Process all of the spilled defs.
2059 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2060 MachineOperand &MO = MI.getOperand(i);
2061 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2064 unsigned VirtReg = MO.getReg();
2065 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2066 // Check to see if this is a noop copy. If so, eliminate the
2067 // instruction before considering the dest reg to be changed.
2068 // Also check if it's copying from an "undef", if so, we can't
2069 // eliminate this or else the undef marker is lost and it will
2070 // confuses the scavenger. This is extremely rare.
2071 unsigned Src, Dst, SrcSR, DstSR;
2072 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2073 !MI.findRegisterUseOperand(Src)->isUndef()) {
2075 DOUT << "Removing now-noop copy: " << MI;
2076 SmallVector<unsigned, 2> KillRegs;
2077 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2078 if (MO.isDead() && !KillRegs.empty()) {
2079 // Source register or an implicit super/sub-register use is killed.
2080 assert(KillRegs[0] == Dst ||
2081 TRI->isSubRegister(KillRegs[0], Dst) ||
2082 TRI->isSuperRegister(KillRegs[0], Dst));
2083 // Last def is now dead.
2084 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2086 VRM.RemoveMachineInstrFromMaps(&MI);
2089 Spills.disallowClobberPhysReg(VirtReg);
2090 goto ProcessNextInst;
2093 // If it's not a no-op copy, it clobbers the value in the destreg.
2094 Spills.ClobberPhysReg(VirtReg);
2095 ReusedOperands.markClobbered(VirtReg);
2097 // Check to see if this instruction is a load from a stack slot into
2098 // a register. If so, this provides the stack slot value in the reg.
2100 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2101 assert(DestReg == VirtReg && "Unknown load situation!");
2103 // If it is a folded reference, then it's not safe to clobber.
2104 bool Folded = FoldedSS.count(FrameIdx);
2105 // Otherwise, if it wasn't available, remember that it is now!
2106 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2107 goto ProcessNextInst;
2113 unsigned SubIdx = MO.getSubReg();
2114 bool DoReMat = VRM.isReMaterialized(VirtReg);
2116 ReMatDefs.insert(&MI);
2118 // The only vregs left are stack slot definitions.
2119 int StackSlot = VRM.getStackSlot(VirtReg);
2120 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2122 // If this def is part of a two-address operand, make sure to execute
2123 // the store from the correct physical register.
2126 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2127 PhysReg = MI.getOperand(TiedOp).getReg();
2129 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2130 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2131 "Can't find corresponding super-register!");
2135 PhysReg = VRM.getPhys(VirtReg);
2136 if (ReusedOperands.isClobbered(PhysReg)) {
2137 // Another def has taken the assigned physreg. It must have been a
2138 // use&def which got it due to reuse. Undo the reuse!
2139 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2140 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2144 assert(PhysReg && "VR not assigned a physical register?");
2145 RegInfo->setPhysRegUsed(PhysReg);
2146 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2147 ReusedOperands.markClobbered(RReg);
2148 MI.getOperand(i).setReg(RReg);
2149 MI.getOperand(i).setSubReg(0);
2152 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2153 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2154 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2155 NextMII = next(MII);
2157 // Check to see if this is a noop copy. If so, eliminate the
2158 // instruction before considering the dest reg to be changed.
2160 unsigned Src, Dst, SrcSR, DstSR;
2161 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2163 DOUT << "Removing now-noop copy: " << MI;
2164 InvalidateKills(MI, TRI, RegKills, KillOps);
2165 VRM.RemoveMachineInstrFromMaps(&MI);
2168 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2169 goto ProcessNextInst;
2175 DistanceMap.insert(std::make_pair(&MI, Dist++));
2176 if (!Erased && !BackTracked) {
2177 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2178 UpdateKills(*II, TRI, RegKills, KillOps);
2187 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2188 switch (RewriterOpt) {
2189 default: llvm_unreachable("Unreachable!");
2191 return new LocalRewriter();
2193 return new TrivialRewriter();