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(const TargetRegisterClass *RC, unsigned PhysReg,
281 MachineFunction &MF, MachineInstr *MI,
282 AvailableSpills &Spills,
283 std::vector<MachineInstr*> &MaybeDeadStores,
284 SmallSet<unsigned, 8> &Rejected,
286 std::vector<MachineOperand*> &KillOps,
289 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
290 /// 'Rejected' set to remember which registers have been considered and
291 /// rejected for the reload. This avoids infinite looping in case like
294 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
295 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
297 /// sees r1 is taken by t2, tries t2's reload register r0
298 /// sees r0 is taken by t3, tries t3's reload register r1
299 /// sees r1 is taken by t2, tries t2's reload register r0 ...
300 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
301 AvailableSpills &Spills,
302 std::vector<MachineInstr*> &MaybeDeadStores,
304 std::vector<MachineOperand*> &KillOps,
306 SmallSet<unsigned, 8> Rejected;
307 MachineFunction &MF = *MI->getParent()->getParent();
308 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
309 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
310 Rejected, RegKills, KillOps, VRM);
315 // ****************** //
316 // Utility Functions //
317 // ****************** //
319 /// findSinglePredSuccessor - Return via reference a vector of machine basic
320 /// blocks each of which is a successor of the specified BB and has no other
322 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
323 SmallVectorImpl<MachineBasicBlock *> &Succs) {
324 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
325 SE = MBB->succ_end(); SI != SE; ++SI) {
326 MachineBasicBlock *SuccMBB = *SI;
327 if (SuccMBB->pred_size() == 1)
328 Succs.push_back(SuccMBB);
332 /// InvalidateKill - Invalidate register kill information for a specific
333 /// register. This also unsets the kills marker on the last kill operand.
334 static void InvalidateKill(unsigned Reg,
335 const TargetRegisterInfo* TRI,
337 std::vector<MachineOperand*> &KillOps) {
339 KillOps[Reg]->setIsKill(false);
340 // KillOps[Reg] might be a def of a super-register.
341 unsigned KReg = KillOps[Reg]->getReg();
342 KillOps[KReg] = NULL;
343 RegKills.reset(KReg);
344 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
346 KillOps[*SR]->setIsKill(false);
354 /// InvalidateKills - MI is going to be deleted. If any of its operands are
355 /// marked kill, then invalidate the information.
356 static void InvalidateKills(MachineInstr &MI,
357 const TargetRegisterInfo* TRI,
359 std::vector<MachineOperand*> &KillOps,
360 SmallVector<unsigned, 2> *KillRegs = NULL) {
361 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
362 MachineOperand &MO = MI.getOperand(i);
363 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
365 unsigned Reg = MO.getReg();
366 if (TargetRegisterInfo::isVirtualRegister(Reg))
369 KillRegs->push_back(Reg);
370 assert(Reg < KillOps.size());
371 if (KillOps[Reg] == &MO) {
374 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
384 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
385 /// (since it's spill instruction is removed), mark it isDead. Also checks if
386 /// the def MI has other definition operands that are not dead. Returns it by
388 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
389 MachineInstr &NewDef, unsigned Reg,
391 // Due to remat, it's possible this reg isn't being reused. That is,
392 // the def of this reg (by prev MI) is now dead.
393 MachineInstr *DefMI = I;
394 MachineOperand *DefOp = NULL;
395 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
396 MachineOperand &MO = DefMI->getOperand(i);
397 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
399 if (MO.getReg() == Reg)
401 else if (!MO.isDead())
407 bool FoundUse = false, Done = false;
408 MachineBasicBlock::iterator E = &NewDef;
410 for (; !Done && I != E; ++I) {
411 MachineInstr *NMI = I;
412 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
413 MachineOperand &MO = NMI->getOperand(j);
414 if (!MO.isReg() || MO.getReg() != Reg)
418 Done = true; // Stop after scanning all the operands of this MI.
429 /// UpdateKills - Track and update kill info. If a MI reads a register that is
430 /// marked kill, then it must be due to register reuse. Transfer the kill info
432 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
434 std::vector<MachineOperand*> &KillOps) {
435 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
436 MachineOperand &MO = MI.getOperand(i);
437 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
439 unsigned Reg = MO.getReg();
443 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
444 // That can't be right. Register is killed but not re-defined and it's
445 // being reused. Let's fix that.
446 KillOps[Reg]->setIsKill(false);
447 // KillOps[Reg] might be a def of a super-register.
448 unsigned KReg = KillOps[Reg]->getReg();
449 KillOps[KReg] = NULL;
450 RegKills.reset(KReg);
452 // Must be a def of a super-register. Its other sub-regsters are no
453 // longer killed as well.
454 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
459 if (!MI.isRegTiedToDefOperand(i))
460 // Unless it's a two-address operand, this is the new kill.
466 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
473 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
474 const MachineOperand &MO = MI.getOperand(i);
475 if (!MO.isReg() || !MO.isDef())
477 unsigned Reg = MO.getReg();
480 // It also defines (or partially define) aliases.
481 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
488 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
490 static void ReMaterialize(MachineBasicBlock &MBB,
491 MachineBasicBlock::iterator &MII,
492 unsigned DestReg, unsigned Reg,
493 const TargetInstrInfo *TII,
494 const TargetRegisterInfo *TRI,
496 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
498 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
499 assert(TID.getNumDefs() == 1 &&
500 "Don't know how to remat instructions that define > 1 values!");
502 TII->reMaterialize(MBB, MII, DestReg,
503 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
504 MachineInstr *NewMI = prior(MII);
505 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
506 MachineOperand &MO = NewMI->getOperand(i);
507 if (!MO.isReg() || MO.getReg() == 0)
509 unsigned VirtReg = MO.getReg();
510 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
513 unsigned SubIdx = MO.getSubReg();
514 unsigned Phys = VRM.getPhys(VirtReg);
516 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
523 /// findSuperReg - Find the SubReg's super-register of given register class
524 /// where its SubIdx sub-register is SubReg.
525 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
526 unsigned SubIdx, const TargetRegisterInfo *TRI) {
527 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
530 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
536 // ******************************** //
537 // Available Spills Implementation //
538 // ******************************** //
540 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
541 /// stackslot register. The register is still available but is no longer
542 /// allowed to be modifed.
543 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
544 std::multimap<unsigned, int>::iterator I =
545 PhysRegsAvailable.lower_bound(PhysReg);
546 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
547 int SlotOrReMat = I->second;
549 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
550 "Bidirectional map mismatch!");
551 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
552 DOUT << "PhysReg " << TRI->getName(PhysReg)
553 << " copied, it is available for use but can no longer be modified\n";
557 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
558 /// stackslot register and its aliases. The register and its aliases may
559 /// still available but is no longer allowed to be modifed.
560 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
561 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
562 disallowClobberPhysRegOnly(*AS);
563 disallowClobberPhysRegOnly(PhysReg);
566 /// ClobberPhysRegOnly - This is called when the specified physreg changes
567 /// value. We use this to invalidate any info about stuff we thing lives in it.
568 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
569 std::multimap<unsigned, int>::iterator I =
570 PhysRegsAvailable.lower_bound(PhysReg);
571 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
572 int SlotOrReMat = I->second;
573 PhysRegsAvailable.erase(I++);
574 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
575 "Bidirectional map mismatch!");
576 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
577 DOUT << "PhysReg " << TRI->getName(PhysReg)
578 << " clobbered, invalidating ";
579 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
580 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
582 DOUT << "SS#" << SlotOrReMat << "\n";
586 /// ClobberPhysReg - This is called when the specified physreg changes
587 /// value. We use this to invalidate any info about stuff we thing lives in
588 /// it and any of its aliases.
589 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
590 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
591 ClobberPhysRegOnly(*AS);
592 ClobberPhysRegOnly(PhysReg);
595 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
596 /// into the specified MBB. Add available physical registers as potential
597 /// live-in's. If they are reused in the MBB, they will be added to the
598 /// live-in set to make register scavenger and post-allocation scheduler.
599 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
601 std::vector<MachineOperand*> &KillOps) {
602 std::set<unsigned> NotAvailable;
603 for (std::multimap<unsigned, int>::iterator
604 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
606 unsigned Reg = I->first;
607 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
608 // FIXME: A temporary workaround. We can't reuse available value if it's
609 // not safe to move the def of the virtual register's class. e.g.
610 // X86::RFP* register classes. Do not add it as a live-in.
611 if (!TII->isSafeToMoveRegClassDefs(RC))
612 // This is no longer available.
613 NotAvailable.insert(Reg);
616 InvalidateKill(Reg, TRI, RegKills, KillOps);
619 // Skip over the same register.
620 std::multimap<unsigned, int>::iterator NI = next(I);
621 while (NI != E && NI->first == Reg) {
627 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
628 E = NotAvailable.end(); I != E; ++I) {
630 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
632 ClobberPhysReg(*SubRegs);
636 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
637 /// slot changes. This removes information about which register the previous
638 /// value for this slot lives in (as the previous value is dead now).
639 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
640 std::map<int, unsigned>::iterator It =
641 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
642 if (It == SpillSlotsOrReMatsAvailable.end()) return;
643 unsigned Reg = It->second >> 1;
644 SpillSlotsOrReMatsAvailable.erase(It);
646 // This register may hold the value of multiple stack slots, only remove this
647 // stack slot from the set of values the register contains.
648 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
650 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
651 "Map inverse broken!");
652 if (I->second == SlotOrReMat) break;
654 PhysRegsAvailable.erase(I);
657 // ************************** //
658 // Reuse Info Implementation //
659 // ************************** //
661 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
662 /// is some other operand that is using the specified register, either pick
663 /// a new register to use, or evict the previous reload and use this reg.
664 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
667 MachineInstr *MI, AvailableSpills &Spills,
668 std::vector<MachineInstr*> &MaybeDeadStores,
669 SmallSet<unsigned, 8> &Rejected,
671 std::vector<MachineOperand*> &KillOps,
673 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
674 const TargetRegisterInfo *TRI = Spills.getRegInfo();
676 if (Reuses.empty()) return PhysReg; // This is most often empty.
678 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
679 ReusedOp &Op = Reuses[ro];
680 // If we find some other reuse that was supposed to use this register
681 // exactly for its reload, we can change this reload to use ITS reload
682 // register. That is, unless its reload register has already been
683 // considered and subsequently rejected because it has also been reused
684 // by another operand.
685 if (Op.PhysRegReused == PhysReg &&
686 Rejected.count(Op.AssignedPhysReg) == 0 &&
687 RC->contains(Op.AssignedPhysReg)) {
688 // Yup, use the reload register that we didn't use before.
689 unsigned NewReg = Op.AssignedPhysReg;
690 Rejected.insert(PhysReg);
691 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
692 RegKills, KillOps, VRM);
694 // Otherwise, we might also have a problem if a previously reused
695 // value aliases the new register. If so, codegen the previous reload
697 unsigned PRRU = Op.PhysRegReused;
698 if (TRI->areAliases(PRRU, PhysReg)) {
699 // Okay, we found out that an alias of a reused register
700 // was used. This isn't good because it means we have
701 // to undo a previous reuse.
702 MachineBasicBlock *MBB = MI->getParent();
703 const TargetRegisterClass *AliasRC =
704 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
706 // Copy Op out of the vector and remove it, we're going to insert an
707 // explicit load for it.
709 Reuses.erase(Reuses.begin()+ro);
711 // Ok, we're going to try to reload the assigned physreg into the
712 // slot that we were supposed to in the first place. However, that
713 // register could hold a reuse. Check to see if it conflicts or
714 // would prefer us to use a different register.
715 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
716 MF, MI, Spills, MaybeDeadStores,
717 Rejected, RegKills, KillOps, VRM);
719 MachineBasicBlock::iterator MII = MI;
720 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
721 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
723 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
724 NewOp.StackSlotOrReMat, AliasRC);
725 MachineInstr *LoadMI = prior(MII);
726 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
727 // Any stores to this stack slot are not dead anymore.
728 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
731 Spills.ClobberPhysReg(NewPhysReg);
732 Spills.ClobberPhysReg(NewOp.PhysRegReused);
734 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
735 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
736 MI->getOperand(NewOp.Operand).setReg(RReg);
737 MI->getOperand(NewOp.Operand).setSubReg(0);
739 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
741 UpdateKills(*MII, TRI, RegKills, KillOps);
742 DOUT << '\t' << *MII;
744 DOUT << "Reuse undone!\n";
747 // Finally, PhysReg is now available, go ahead and use it.
755 // ************************************************************************ //
757 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
758 /// stack slot mod/ref. It also checks if it's possible to unfold the
759 /// instruction by having it define a specified physical register instead.
760 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
761 const TargetInstrInfo *TII,
762 const TargetRegisterInfo *TRI,
764 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
768 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
769 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
770 unsigned VirtReg = I->second.first;
771 VirtRegMap::ModRef MR = I->second.second;
772 if (MR & VirtRegMap::isModRef)
773 if (VRM.getStackSlot(VirtReg) == SS) {
774 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
781 // Does the instruction uses a register that overlaps the scratch register?
782 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
783 MachineOperand &MO = MI.getOperand(i);
784 if (!MO.isReg() || MO.getReg() == 0)
786 unsigned Reg = MO.getReg();
787 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
788 if (!VRM.hasPhys(Reg))
790 Reg = VRM.getPhys(Reg);
792 if (TRI->regsOverlap(PhysReg, Reg))
798 /// FindFreeRegister - Find a free register of a given register class by looking
799 /// at (at most) the last two machine instructions.
800 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
801 MachineBasicBlock &MBB,
802 const TargetRegisterClass *RC,
803 const TargetRegisterInfo *TRI,
804 BitVector &AllocatableRegs) {
805 BitVector Defs(TRI->getNumRegs());
806 BitVector Uses(TRI->getNumRegs());
807 SmallVector<unsigned, 4> LocalUses;
808 SmallVector<unsigned, 4> Kills;
810 // Take a look at 2 instructions at most.
811 for (unsigned Count = 0; Count < 2; ++Count) {
812 if (MII == MBB.begin())
814 MachineInstr *PrevMI = prior(MII);
815 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
816 MachineOperand &MO = PrevMI->getOperand(i);
817 if (!MO.isReg() || MO.getReg() == 0)
819 unsigned Reg = MO.getReg();
822 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
825 LocalUses.push_back(Reg);
826 if (MO.isKill() && AllocatableRegs[Reg])
827 Kills.push_back(Reg);
831 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
832 unsigned Kill = Kills[i];
833 if (!Defs[Kill] && !Uses[Kill] &&
834 TRI->getPhysicalRegisterRegClass(Kill) == RC)
837 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
838 unsigned Reg = LocalUses[i];
840 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
851 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
852 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
853 MachineOperand &MO = MI->getOperand(i);
854 if (MO.isReg() && MO.getReg() == VirtReg)
861 bool operator()(const std::pair<MachineInstr*, int> &A,
862 const std::pair<MachineInstr*, int> &B) {
863 return A.second < B.second;
868 // ***************************** //
869 // Local Spiller Implementation //
870 // ***************************** //
872 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
873 MachineRegisterInfo *RegInfo;
874 const TargetRegisterInfo *TRI;
875 const TargetInstrInfo *TII;
876 BitVector AllocatableRegs;
877 DenseMap<MachineInstr*, unsigned> DistanceMap;
880 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
881 LiveIntervals* LIs) {
882 RegInfo = &MF.getRegInfo();
883 TRI = MF.getTarget().getRegisterInfo();
884 TII = MF.getTarget().getInstrInfo();
885 AllocatableRegs = TRI->getAllocatableSet(MF);
886 DOUT << "\n**** Local spiller rewriting function '"
887 << MF.getFunction()->getName() << "':\n";
888 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
892 // Spills - Keep track of which spilled values are available in physregs
893 // so that we can choose to reuse the physregs instead of emitting
894 // reloads. This is usually refreshed per basic block.
895 AvailableSpills Spills(TRI, TII);
897 // Keep track of kill information.
898 BitVector RegKills(TRI->getNumRegs());
899 std::vector<MachineOperand*> KillOps;
900 KillOps.resize(TRI->getNumRegs(), NULL);
902 // SingleEntrySuccs - Successor blocks which have a single predecessor.
903 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
904 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
906 // Traverse the basic blocks depth first.
907 MachineBasicBlock *Entry = MF.begin();
908 SmallPtrSet<MachineBasicBlock*,16> Visited;
909 for (df_ext_iterator<MachineBasicBlock*,
910 SmallPtrSet<MachineBasicBlock*,16> >
911 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
913 MachineBasicBlock *MBB = *DFI;
914 if (!EarlyVisited.count(MBB))
915 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
917 // If this MBB is the only predecessor of a successor. Keep the
918 // availability information and visit it next.
920 // Keep visiting single predecessor successor as long as possible.
921 SinglePredSuccs.clear();
922 findSinglePredSuccessor(MBB, SinglePredSuccs);
923 if (SinglePredSuccs.empty())
926 // FIXME: More than one successors, each of which has MBB has
927 // the only predecessor.
928 MBB = SinglePredSuccs[0];
929 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
930 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
931 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
936 // Clear the availability info.
940 DOUT << "**** Post Machine Instrs ****\n";
943 // Mark unused spill slots.
944 MachineFrameInfo *MFI = MF.getFrameInfo();
945 int SS = VRM.getLowSpillSlot();
946 if (SS != VirtRegMap::NO_STACK_SLOT)
947 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
948 if (!VRM.isSpillSlotUsed(SS)) {
949 MFI->RemoveStackObject(SS);
958 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
959 /// a scratch register is available.
960 /// xorq %r12<kill>, %r13
961 /// addq %rax, -184(%rbp)
962 /// addq %r13, -184(%rbp)
964 /// xorq %r12<kill>, %r13
965 /// movq -184(%rbp), %r12
968 /// movq %r12, -184(%rbp)
969 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
970 MachineBasicBlock &MBB,
971 MachineBasicBlock::iterator &MII,
972 std::vector<MachineInstr*> &MaybeDeadStores,
973 AvailableSpills &Spills,
975 std::vector<MachineOperand*> &KillOps,
978 MachineBasicBlock::iterator NextMII = next(MII);
979 if (NextMII == MBB.end())
982 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
985 // Now let's see if the last couple of instructions happens to have freed up
987 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
988 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
992 MachineFunction &MF = *MBB.getParent();
993 TRI = MF.getTarget().getRegisterInfo();
994 MachineInstr &MI = *MII;
995 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
998 // If the next instruction also folds the same SS modref and can be unfoled,
999 // then it's worthwhile to issue a load from SS into the free register and
1000 // then unfold these instructions.
1001 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1004 // Load from SS to the spare physical register.
1005 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1006 // This invalidates Phys.
1007 Spills.ClobberPhysReg(PhysReg);
1008 // Remember it's available.
1009 Spills.addAvailable(SS, PhysReg);
1010 MaybeDeadStores[SS] = NULL;
1012 // Unfold current MI.
1013 SmallVector<MachineInstr*, 4> NewMIs;
1014 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1015 llvm_unreachable("Unable unfold the load / store folding instruction!");
1016 assert(NewMIs.size() == 1);
1017 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1018 VRM.transferRestorePts(&MI, NewMIs[0]);
1019 MII = MBB.insert(MII, NewMIs[0]);
1020 InvalidateKills(MI, TRI, RegKills, KillOps);
1021 VRM.RemoveMachineInstrFromMaps(&MI);
1025 // Unfold next instructions that fold the same SS.
1027 MachineInstr &NextMI = *NextMII;
1028 NextMII = next(NextMII);
1030 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1031 llvm_unreachable("Unable unfold the load / store folding instruction!");
1032 assert(NewMIs.size() == 1);
1033 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1034 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1035 MBB.insert(NextMII, NewMIs[0]);
1036 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1037 VRM.RemoveMachineInstrFromMaps(&NextMI);
1040 if (NextMII == MBB.end())
1042 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1044 // Store the value back into SS.
1045 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1046 MachineInstr *StoreMI = prior(NextMII);
1047 VRM.addSpillSlotUse(SS, StoreMI);
1048 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1053 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1054 /// instruction. e.g.
1056 /// movl %eax, -32(%ebp)
1057 /// movl -36(%ebp), %eax
1058 /// orl %eax, -32(%ebp)
1061 /// orl -36(%ebp), %eax
1062 /// mov %eax, -32(%ebp)
1063 /// This enables unfolding optimization for a subsequent instruction which will
1064 /// also eliminate the newly introduced store instruction.
1065 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1066 MachineBasicBlock::iterator &MII,
1067 std::vector<MachineInstr*> &MaybeDeadStores,
1068 AvailableSpills &Spills,
1069 BitVector &RegKills,
1070 std::vector<MachineOperand*> &KillOps,
1072 MachineFunction &MF = *MBB.getParent();
1073 MachineInstr &MI = *MII;
1074 unsigned UnfoldedOpc = 0;
1075 unsigned UnfoldPR = 0;
1076 unsigned UnfoldVR = 0;
1077 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1078 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1079 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1080 // Only transform a MI that folds a single register.
1083 UnfoldVR = I->second.first;
1084 VirtRegMap::ModRef MR = I->second.second;
1085 // MI2VirtMap be can updated which invalidate the iterator.
1086 // Increment the iterator first.
1088 if (VRM.isAssignedReg(UnfoldVR))
1090 // If this reference is not a use, any previous store is now dead.
1091 // Otherwise, the store to this stack slot is not dead anymore.
1092 FoldedSS = VRM.getStackSlot(UnfoldVR);
1093 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1094 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1095 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1096 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1099 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1108 // Look for other unfolding opportunities.
1109 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1110 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1113 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1114 MachineOperand &MO = MI.getOperand(i);
1115 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1117 unsigned VirtReg = MO.getReg();
1118 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1120 if (VRM.isAssignedReg(VirtReg)) {
1121 unsigned PhysReg = VRM.getPhys(VirtReg);
1122 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1124 } else if (VRM.isReMaterialized(VirtReg))
1126 int SS = VRM.getStackSlot(VirtReg);
1127 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1129 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1133 if (VRM.hasPhys(VirtReg)) {
1134 PhysReg = VRM.getPhys(VirtReg);
1135 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1139 // Ok, we'll need to reload the value into a register which makes
1140 // it impossible to perform the store unfolding optimization later.
1141 // Let's see if it is possible to fold the load if the store is
1142 // unfolded. This allows us to perform the store unfolding
1144 SmallVector<MachineInstr*, 4> NewMIs;
1145 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1146 assert(NewMIs.size() == 1);
1147 MachineInstr *NewMI = NewMIs.back();
1149 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1151 SmallVector<unsigned, 1> Ops;
1153 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1155 VRM.addSpillSlotUse(SS, FoldedMI);
1156 if (!VRM.hasPhys(UnfoldVR))
1157 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1158 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1159 MII = MBB.insert(MII, FoldedMI);
1160 InvalidateKills(MI, TRI, RegKills, KillOps);
1161 VRM.RemoveMachineInstrFromMaps(&MI);
1163 MF.DeleteMachineInstr(NewMI);
1166 MF.DeleteMachineInstr(NewMI);
1173 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1174 /// where SrcReg is r1 and it is tied to r0. Return true if after
1175 /// commuting this instruction it will be r0 = op r2, r1.
1176 static bool CommuteChangesDestination(MachineInstr *DefMI,
1177 const TargetInstrDesc &TID,
1179 const TargetInstrInfo *TII,
1181 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1183 if (!DefMI->getOperand(1).isReg() ||
1184 DefMI->getOperand(1).getReg() != SrcReg)
1187 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1189 unsigned SrcIdx1, SrcIdx2;
1190 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1192 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1199 /// CommuteToFoldReload -
1202 /// r1 = op r1, r2<kill>
1205 /// If op is commutable and r2 is killed, then we can xform these to
1206 /// r2 = op r2, fi#1
1208 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1209 MachineBasicBlock::iterator &MII,
1210 unsigned VirtReg, unsigned SrcReg, int SS,
1211 AvailableSpills &Spills,
1212 BitVector &RegKills,
1213 std::vector<MachineOperand*> &KillOps,
1214 const TargetRegisterInfo *TRI,
1216 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1219 MachineFunction &MF = *MBB.getParent();
1220 MachineInstr &MI = *MII;
1221 MachineBasicBlock::iterator DefMII = prior(MII);
1222 MachineInstr *DefMI = DefMII;
1223 const TargetInstrDesc &TID = DefMI->getDesc();
1225 if (DefMII != MBB.begin() &&
1226 TID.isCommutable() &&
1227 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1228 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1229 unsigned NewReg = NewDstMO.getReg();
1230 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1232 MachineInstr *ReloadMI = prior(DefMII);
1234 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1235 if (DestReg != SrcReg || FrameIdx != SS)
1237 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1241 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1243 assert(DefMI->getOperand(DefIdx).isReg() &&
1244 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1246 // Now commute def instruction.
1247 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1250 SmallVector<unsigned, 1> Ops;
1251 Ops.push_back(NewDstIdx);
1252 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1253 // Not needed since foldMemoryOperand returns new MI.
1254 MF.DeleteMachineInstr(CommutedMI);
1258 VRM.addSpillSlotUse(SS, FoldedMI);
1259 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1260 // Insert new def MI and spill MI.
1261 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1262 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1264 MachineInstr *StoreMI = MII;
1265 VRM.addSpillSlotUse(SS, StoreMI);
1266 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1267 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1269 // Delete all 3 old instructions.
1270 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1271 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1272 MBB.erase(ReloadMI);
1273 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1274 VRM.RemoveMachineInstrFromMaps(DefMI);
1276 InvalidateKills(MI, TRI, RegKills, KillOps);
1277 VRM.RemoveMachineInstrFromMaps(&MI);
1280 // If NewReg was previously holding value of some SS, it's now clobbered.
1281 // This has to be done now because it's a physical register. When this
1282 // instruction is re-visited, it's ignored.
1283 Spills.ClobberPhysReg(NewReg);
1292 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1293 /// the last store to the same slot is now dead. If so, remove the last store.
1294 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1295 MachineBasicBlock::iterator &MII,
1296 int Idx, unsigned PhysReg, int StackSlot,
1297 const TargetRegisterClass *RC,
1298 bool isAvailable, MachineInstr *&LastStore,
1299 AvailableSpills &Spills,
1300 SmallSet<MachineInstr*, 4> &ReMatDefs,
1301 BitVector &RegKills,
1302 std::vector<MachineOperand*> &KillOps,
1305 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1306 MachineInstr *StoreMI = next(MII);
1307 VRM.addSpillSlotUse(StackSlot, StoreMI);
1308 DOUT << "Store:\t" << *StoreMI;
1310 // If there is a dead store to this stack slot, nuke it now.
1312 DOUT << "Removed dead store:\t" << *LastStore;
1314 SmallVector<unsigned, 2> KillRegs;
1315 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1316 MachineBasicBlock::iterator PrevMII = LastStore;
1317 bool CheckDef = PrevMII != MBB.begin();
1320 VRM.RemoveMachineInstrFromMaps(LastStore);
1321 MBB.erase(LastStore);
1323 // Look at defs of killed registers on the store. Mark the defs
1324 // as dead since the store has been deleted and they aren't
1326 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1327 bool HasOtherDef = false;
1328 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1329 MachineInstr *DeadDef = PrevMII;
1330 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1331 // FIXME: This assumes a remat def does not have side effects.
1332 VRM.RemoveMachineInstrFromMaps(DeadDef);
1341 LastStore = next(MII);
1343 // If the stack slot value was previously available in some other
1344 // register, change it now. Otherwise, make the register available,
1346 Spills.ModifyStackSlotOrReMat(StackSlot);
1347 Spills.ClobberPhysReg(PhysReg);
1348 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1352 /// TransferDeadness - A identity copy definition is dead and it's being
1353 /// removed. Find the last def or use and mark it as dead / kill.
1354 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1355 unsigned Reg, BitVector &RegKills,
1356 std::vector<MachineOperand*> &KillOps,
1358 SmallPtrSet<MachineInstr*, 4> Seens;
1359 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1360 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1361 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1362 MachineInstr *UDMI = &*RI;
1363 if (UDMI->getParent() != MBB)
1365 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1366 if (DI == DistanceMap.end() || DI->second > CurDist)
1368 if (Seens.insert(UDMI))
1369 Refs.push_back(std::make_pair(UDMI, DI->second));
1374 std::sort(Refs.begin(), Refs.end(), RefSorter());
1376 while (!Refs.empty()) {
1377 MachineInstr *LastUDMI = Refs.back().first;
1380 MachineOperand *LastUD = NULL;
1381 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1382 MachineOperand &MO = LastUDMI->getOperand(i);
1383 if (!MO.isReg() || MO.getReg() != Reg)
1385 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1387 if (LastUDMI->isRegTiedToDefOperand(i))
1390 if (LastUD->isDef()) {
1391 // If the instruction has no side effect, delete it and propagate
1392 // backward further. Otherwise, mark is dead and we are done.
1393 if (!TII->isDeadInstruction(LastUDMI)) {
1394 LastUD->setIsDead();
1397 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1398 MBB->erase(LastUDMI);
1400 LastUD->setIsKill();
1402 KillOps[Reg] = LastUD;
1408 /// rewriteMBB - Keep track of which spills are available even after the
1409 /// register allocator is done with them. If possible, avid reloading vregs.
1410 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1412 AvailableSpills &Spills, BitVector &RegKills,
1413 std::vector<MachineOperand*> &KillOps) {
1415 DOUT << "\n**** Local spiller rewriting MBB '"
1416 << MBB.getBasicBlock()->getName() << "':\n";
1418 MachineFunction &MF = *MBB.getParent();
1420 // MaybeDeadStores - When we need to write a value back into a stack slot,
1421 // keep track of the inserted store. If the stack slot value is never read
1422 // (because the value was used from some available register, for example), and
1423 // subsequently stored to, the original store is dead. This map keeps track
1424 // of inserted stores that are not used. If we see a subsequent store to the
1425 // same stack slot, the original store is deleted.
1426 std::vector<MachineInstr*> MaybeDeadStores;
1427 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1429 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1430 SmallSet<MachineInstr*, 4> ReMatDefs;
1433 SmallSet<unsigned, 2> KilledMIRegs;
1436 KillOps.resize(TRI->getNumRegs(), NULL);
1439 DistanceMap.clear();
1440 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1442 MachineBasicBlock::iterator NextMII = next(MII);
1444 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1445 bool Erased = false;
1446 bool BackTracked = false;
1447 if (OptimizeByUnfold(MBB, MII,
1448 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1449 NextMII = next(MII);
1451 MachineInstr &MI = *MII;
1453 if (VRM.hasEmergencySpills(&MI)) {
1454 // Spill physical register(s) in the rare case the allocator has run out
1455 // of registers to allocate.
1456 SmallSet<int, 4> UsedSS;
1457 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1458 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1459 unsigned PhysReg = EmSpills[i];
1460 const TargetRegisterClass *RC =
1461 TRI->getPhysicalRegisterRegClass(PhysReg);
1462 assert(RC && "Unable to determine register class!");
1463 int SS = VRM.getEmergencySpillSlot(RC);
1464 if (UsedSS.count(SS))
1465 llvm_unreachable("Need to spill more than one physical registers!");
1467 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1468 MachineInstr *StoreMI = prior(MII);
1469 VRM.addSpillSlotUse(SS, StoreMI);
1470 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1471 MachineInstr *LoadMI = next(MII);
1472 VRM.addSpillSlotUse(SS, LoadMI);
1475 NextMII = next(MII);
1478 // Insert restores here if asked to.
1479 if (VRM.isRestorePt(&MI)) {
1480 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1481 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1482 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1483 if (!VRM.getPreSplitReg(VirtReg))
1484 continue; // Split interval spilled again.
1485 unsigned Phys = VRM.getPhys(VirtReg);
1486 RegInfo->setPhysRegUsed(Phys);
1488 // Check if the value being restored if available. If so, it must be
1489 // from a predecessor BB that fallthrough into this BB. We do not
1495 // ... # r1 not clobbered
1498 bool DoReMat = VRM.isReMaterialized(VirtReg);
1499 int SSorRMId = DoReMat
1500 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1501 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1502 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1503 if (InReg == Phys) {
1504 // If the value is already available in the expected register, save
1505 // a reload / remat.
1507 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1509 DOUT << "Reusing SS#" << SSorRMId;
1510 DOUT << " from physreg "
1511 << TRI->getName(InReg) << " for vreg"
1512 << VirtReg <<" instead of reloading into physreg "
1513 << TRI->getName(Phys) << "\n";
1516 } else if (InReg && InReg != Phys) {
1518 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1520 DOUT << "Reusing SS#" << SSorRMId;
1521 DOUT << " from physreg "
1522 << TRI->getName(InReg) << " for vreg"
1523 << VirtReg <<" by copying it into physreg "
1524 << TRI->getName(Phys) << "\n";
1526 // If the reloaded / remat value is available in another register,
1527 // copy it to the desired register.
1528 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1530 // This invalidates Phys.
1531 Spills.ClobberPhysReg(Phys);
1532 // Remember it's available.
1533 Spills.addAvailable(SSorRMId, Phys);
1536 MachineInstr *CopyMI = prior(MII);
1537 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1538 KillOpnd->setIsKill();
1539 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1541 DOUT << '\t' << *CopyMI;
1546 if (VRM.isReMaterialized(VirtReg)) {
1547 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1549 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1550 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1551 MachineInstr *LoadMI = prior(MII);
1552 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1556 // This invalidates Phys.
1557 Spills.ClobberPhysReg(Phys);
1558 // Remember it's available.
1559 Spills.addAvailable(SSorRMId, Phys);
1561 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1562 DOUT << '\t' << *prior(MII);
1566 // Insert spills here if asked to.
1567 if (VRM.isSpillPt(&MI)) {
1568 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1569 VRM.getSpillPtSpills(&MI);
1570 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1571 unsigned VirtReg = SpillRegs[i].first;
1572 bool isKill = SpillRegs[i].second;
1573 if (!VRM.getPreSplitReg(VirtReg))
1574 continue; // Split interval spilled again.
1575 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1576 unsigned Phys = VRM.getPhys(VirtReg);
1577 int StackSlot = VRM.getStackSlot(VirtReg);
1578 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1579 MachineInstr *StoreMI = next(MII);
1580 VRM.addSpillSlotUse(StackSlot, StoreMI);
1581 DOUT << "Store:\t" << *StoreMI;
1582 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1584 NextMII = next(MII);
1587 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1589 ReuseInfo ReusedOperands(MI, TRI);
1590 SmallVector<unsigned, 4> VirtUseOps;
1591 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1592 MachineOperand &MO = MI.getOperand(i);
1593 if (!MO.isReg() || MO.getReg() == 0)
1594 continue; // Ignore non-register operands.
1596 unsigned VirtReg = MO.getReg();
1597 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1598 // Ignore physregs for spilling, but remember that it is used by this
1600 RegInfo->setPhysRegUsed(VirtReg);
1604 // We want to process implicit virtual register uses first.
1605 if (MO.isImplicit())
1606 // If the virtual register is implicitly defined, emit a implicit_def
1607 // before so scavenger knows it's "defined".
1608 // FIXME: This is a horrible hack done the by register allocator to
1609 // remat a definition with virtual register operand.
1610 VirtUseOps.insert(VirtUseOps.begin(), i);
1612 VirtUseOps.push_back(i);
1615 // Process all of the spilled uses and all non spilled reg references.
1616 SmallVector<int, 2> PotentialDeadStoreSlots;
1617 KilledMIRegs.clear();
1618 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1619 unsigned i = VirtUseOps[j];
1620 MachineOperand &MO = MI.getOperand(i);
1621 unsigned VirtReg = MO.getReg();
1622 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1623 "Not a virtual register?");
1625 unsigned SubIdx = MO.getSubReg();
1626 if (VRM.isAssignedReg(VirtReg)) {
1627 // This virtual register was assigned a physreg!
1628 unsigned Phys = VRM.getPhys(VirtReg);
1629 RegInfo->setPhysRegUsed(Phys);
1631 ReusedOperands.markClobbered(Phys);
1632 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1633 MI.getOperand(i).setReg(RReg);
1634 MI.getOperand(i).setSubReg(0);
1635 if (VRM.isImplicitlyDefined(VirtReg))
1636 // FIXME: Is this needed?
1637 BuildMI(MBB, &MI, MI.getDebugLoc(),
1638 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1642 // This virtual register is now known to be a spilled value.
1644 continue; // Handle defs in the loop below (handle use&def here though)
1646 bool AvoidReload = MO.isUndef();
1647 // Check if it is defined by an implicit def. It should not be spilled.
1648 // Note, this is for correctness reason. e.g.
1649 // 8 %reg1024<def> = IMPLICIT_DEF
1650 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1651 // The live range [12, 14) are not part of the r1024 live interval since
1652 // it's defined by an implicit def. It will not conflicts with live
1653 // interval of r1025. Now suppose both registers are spilled, you can
1654 // easily see a situation where both registers are reloaded before
1655 // the INSERT_SUBREG and both target registers that would overlap.
1656 bool DoReMat = VRM.isReMaterialized(VirtReg);
1657 int SSorRMId = DoReMat
1658 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1659 int ReuseSlot = SSorRMId;
1661 // Check to see if this stack slot is available.
1662 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1664 // If this is a sub-register use, make sure the reuse register is in the
1665 // right register class. For example, for x86 not all of the 32-bit
1666 // registers have accessible sub-registers.
1667 // Similarly so for EXTRACT_SUBREG. Consider this:
1669 // MOV32_mr fi#1, EDI
1671 // = EXTRACT_SUBREG fi#1
1672 // fi#1 is available in EDI, but it cannot be reused because it's not in
1673 // the right register file.
1674 if (PhysReg && !AvoidReload &&
1675 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1676 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1677 if (!RC->contains(PhysReg))
1681 if (PhysReg && !AvoidReload) {
1682 // This spilled operand might be part of a two-address operand. If this
1683 // is the case, then changing it will necessarily require changing the
1684 // def part of the instruction as well. However, in some cases, we
1685 // aren't allowed to modify the reused register. If none of these cases
1687 bool CanReuse = true;
1688 bool isTied = MI.isRegTiedToDefOperand(i);
1690 // Okay, we have a two address operand. We can reuse this physreg as
1691 // long as we are allowed to clobber the value and there isn't an
1692 // earlier def that has already clobbered the physreg.
1693 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1694 Spills.canClobberPhysReg(PhysReg);
1698 // If this stack slot value is already available, reuse it!
1699 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1700 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1702 DOUT << "Reusing SS#" << ReuseSlot;
1703 DOUT << " from physreg "
1704 << TRI->getName(PhysReg) << " for vreg"
1705 << VirtReg <<" instead of reloading into physreg "
1706 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1707 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1708 MI.getOperand(i).setReg(RReg);
1709 MI.getOperand(i).setSubReg(0);
1711 // The only technical detail we have is that we don't know that
1712 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1713 // later in the instruction. In particular, consider 'op V1, V2'.
1714 // If V1 is available in physreg R0, we would choose to reuse it
1715 // here, instead of reloading it into the register the allocator
1716 // indicated (say R1). However, V2 might have to be reloaded
1717 // later, and it might indicate that it needs to live in R0. When
1718 // this occurs, we need to have information available that
1719 // indicates it is safe to use R1 for the reload instead of R0.
1721 // To further complicate matters, we might conflict with an alias,
1722 // or R0 and R1 might not be compatible with each other. In this
1723 // case, we actually insert a reload for V1 in R1, ensuring that
1724 // we can get at R0 or its alias.
1725 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1726 VRM.getPhys(VirtReg), VirtReg);
1728 // Only mark it clobbered if this is a use&def operand.
1729 ReusedOperands.markClobbered(PhysReg);
1732 if (MI.getOperand(i).isKill() &&
1733 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1735 // The store of this spilled value is potentially dead, but we
1736 // won't know for certain until we've confirmed that the re-use
1737 // above is valid, which means waiting until the other operands
1738 // are processed. For now we just track the spill slot, we'll
1739 // remove it after the other operands are processed if valid.
1741 PotentialDeadStoreSlots.push_back(ReuseSlot);
1744 // Mark is isKill if it's there no other uses of the same virtual
1745 // register and it's not a two-address operand. IsKill will be
1746 // unset if reg is reused.
1747 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1748 MI.getOperand(i).setIsKill();
1749 KilledMIRegs.insert(VirtReg);
1755 // Otherwise we have a situation where we have a two-address instruction
1756 // whose mod/ref operand needs to be reloaded. This reload is already
1757 // available in some register "PhysReg", but if we used PhysReg as the
1758 // operand to our 2-addr instruction, the instruction would modify
1759 // PhysReg. This isn't cool if something later uses PhysReg and expects
1760 // to get its initial value.
1762 // To avoid this problem, and to avoid doing a load right after a store,
1763 // we emit a copy from PhysReg into the designated register for this
1765 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1766 assert(DesignatedReg && "Must map virtreg to physreg!");
1768 // Note that, if we reused a register for a previous operand, the
1769 // register we want to reload into might not actually be
1770 // available. If this occurs, use the register indicated by the
1772 if (ReusedOperands.hasReuses())
1773 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
1775 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1777 // If the mapped designated register is actually the physreg we have
1778 // incoming, we don't need to inserted a dead copy.
1779 if (DesignatedReg == PhysReg) {
1780 // If this stack slot value is already available, reuse it!
1781 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1782 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1784 DOUT << "Reusing SS#" << ReuseSlot;
1785 DOUT << " from physreg " << TRI->getName(PhysReg)
1786 << " for vreg" << VirtReg
1787 << " instead of reloading into same physreg.\n";
1788 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1789 MI.getOperand(i).setReg(RReg);
1790 MI.getOperand(i).setSubReg(0);
1791 ReusedOperands.markClobbered(RReg);
1796 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1797 RegInfo->setPhysRegUsed(DesignatedReg);
1798 ReusedOperands.markClobbered(DesignatedReg);
1799 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1801 MachineInstr *CopyMI = prior(MII);
1802 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1804 // This invalidates DesignatedReg.
1805 Spills.ClobberPhysReg(DesignatedReg);
1807 Spills.addAvailable(ReuseSlot, DesignatedReg);
1809 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1810 MI.getOperand(i).setReg(RReg);
1811 MI.getOperand(i).setSubReg(0);
1812 DOUT << '\t' << *prior(MII);
1817 // Otherwise, reload it and remember that we have it.
1818 PhysReg = VRM.getPhys(VirtReg);
1819 assert(PhysReg && "Must map virtreg to physreg!");
1821 // Note that, if we reused a register for a previous operand, the
1822 // register we want to reload into might not actually be
1823 // available. If this occurs, use the register indicated by the
1825 if (ReusedOperands.hasReuses())
1826 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
1827 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1829 RegInfo->setPhysRegUsed(PhysReg);
1830 ReusedOperands.markClobbered(PhysReg);
1835 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1837 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1838 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1839 MachineInstr *LoadMI = prior(MII);
1840 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1843 // This invalidates PhysReg.
1844 Spills.ClobberPhysReg(PhysReg);
1846 // Any stores to this stack slot are not dead anymore.
1848 MaybeDeadStores[SSorRMId] = NULL;
1849 Spills.addAvailable(SSorRMId, PhysReg);
1850 // Assumes this is the last use. IsKill will be unset if reg is reused
1851 // unless it's a two-address operand.
1852 if (!MI.isRegTiedToDefOperand(i) &&
1853 KilledMIRegs.count(VirtReg) == 0) {
1854 MI.getOperand(i).setIsKill();
1855 KilledMIRegs.insert(VirtReg);
1858 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1859 DOUT << '\t' << *prior(MII);
1861 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1862 MI.getOperand(i).setReg(RReg);
1863 MI.getOperand(i).setSubReg(0);
1866 // Ok - now we can remove stores that have been confirmed dead.
1867 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1868 // This was the last use and the spilled value is still available
1869 // for reuse. That means the spill was unnecessary!
1870 int PDSSlot = PotentialDeadStoreSlots[j];
1871 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1873 DOUT << "Removed dead store:\t" << *DeadStore;
1874 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1875 VRM.RemoveMachineInstrFromMaps(DeadStore);
1876 MBB.erase(DeadStore);
1877 MaybeDeadStores[PDSSlot] = NULL;
1886 // If we have folded references to memory operands, make sure we clear all
1887 // physical registers that may contain the value of the spilled virtual
1889 SmallSet<int, 2> FoldedSS;
1890 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1891 unsigned VirtReg = I->second.first;
1892 VirtRegMap::ModRef MR = I->second.second;
1893 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1895 // MI2VirtMap be can updated which invalidate the iterator.
1896 // Increment the iterator first.
1898 int SS = VRM.getStackSlot(VirtReg);
1899 if (SS == VirtRegMap::NO_STACK_SLOT)
1901 FoldedSS.insert(SS);
1902 DOUT << " - StackSlot: " << SS << "\n";
1904 // If this folded instruction is just a use, check to see if it's a
1905 // straight load from the virt reg slot.
1906 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1908 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1909 if (DestReg && FrameIdx == SS) {
1910 // If this spill slot is available, turn it into a copy (or nothing)
1911 // instead of leaving it as a load!
1912 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1913 DOUT << "Promoted Load To Copy: " << MI;
1914 if (DestReg != InReg) {
1915 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1916 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1917 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1918 unsigned SubIdx = DefMO->getSubReg();
1919 // Revisit the copy so we make sure to notice the effects of the
1920 // operation on the destreg (either needing to RA it if it's
1921 // virtual or needing to clobber any values if it's physical).
1923 --NextMII; // backtrack to the copy.
1924 // Propagate the sub-register index over.
1926 DefMO = NextMII->findRegisterDefOperand(DestReg);
1927 DefMO->setSubReg(SubIdx);
1931 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1932 KillOpnd->setIsKill();
1936 DOUT << "Removing now-noop copy: " << MI;
1937 // Unset last kill since it's being reused.
1938 InvalidateKill(InReg, TRI, RegKills, KillOps);
1939 Spills.disallowClobberPhysReg(InReg);
1942 InvalidateKills(MI, TRI, RegKills, KillOps);
1943 VRM.RemoveMachineInstrFromMaps(&MI);
1946 goto ProcessNextInst;
1949 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1950 SmallVector<MachineInstr*, 4> NewMIs;
1952 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1953 MBB.insert(MII, NewMIs[0]);
1954 InvalidateKills(MI, TRI, RegKills, KillOps);
1955 VRM.RemoveMachineInstrFromMaps(&MI);
1958 --NextMII; // backtrack to the unfolded instruction.
1960 goto ProcessNextInst;
1965 // If this reference is not a use, any previous store is now dead.
1966 // Otherwise, the store to this stack slot is not dead anymore.
1967 MachineInstr* DeadStore = MaybeDeadStores[SS];
1969 bool isDead = !(MR & VirtRegMap::isRef);
1970 MachineInstr *NewStore = NULL;
1971 if (MR & VirtRegMap::isModRef) {
1972 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1973 SmallVector<MachineInstr*, 4> NewMIs;
1974 // We can reuse this physreg as long as we are allowed to clobber
1975 // the value and there isn't an earlier def that has already clobbered
1978 !ReusedOperands.isClobbered(PhysReg) &&
1979 Spills.canClobberPhysReg(PhysReg) &&
1980 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1981 MachineOperand *KillOpnd =
1982 DeadStore->findRegisterUseOperand(PhysReg, true);
1983 // Note, if the store is storing a sub-register, it's possible the
1984 // super-register is needed below.
1985 if (KillOpnd && !KillOpnd->getSubReg() &&
1986 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1987 MBB.insert(MII, NewMIs[0]);
1988 NewStore = NewMIs[1];
1989 MBB.insert(MII, NewStore);
1990 VRM.addSpillSlotUse(SS, NewStore);
1991 InvalidateKills(MI, TRI, RegKills, KillOps);
1992 VRM.RemoveMachineInstrFromMaps(&MI);
1996 --NextMII; // backtrack to the unfolded instruction.
2004 if (isDead) { // Previous store is dead.
2005 // If we get here, the store is dead, nuke it now.
2006 DOUT << "Removed dead store:\t" << *DeadStore;
2007 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2008 VRM.RemoveMachineInstrFromMaps(DeadStore);
2009 MBB.erase(DeadStore);
2014 MaybeDeadStores[SS] = NULL;
2016 // Treat this store as a spill merged into a copy. That makes the
2017 // stack slot value available.
2018 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2019 goto ProcessNextInst;
2023 // If the spill slot value is available, and this is a new definition of
2024 // the value, the value is not available anymore.
2025 if (MR & VirtRegMap::isMod) {
2026 // Notice that the value in this stack slot has been modified.
2027 Spills.ModifyStackSlotOrReMat(SS);
2029 // If this is *just* a mod of the value, check to see if this is just a
2030 // store to the spill slot (i.e. the spill got merged into the copy). If
2031 // so, realize that the vreg is available now, and add the store to the
2032 // MaybeDeadStore info.
2034 if (!(MR & VirtRegMap::isRef)) {
2035 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2036 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2037 "Src hasn't been allocated yet?");
2039 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2040 Spills, RegKills, KillOps, TRI, VRM)) {
2041 NextMII = next(MII);
2043 goto ProcessNextInst;
2046 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2047 // this as a potentially dead store in case there is a subsequent
2048 // store into the stack slot without a read from it.
2049 MaybeDeadStores[StackSlot] = &MI;
2051 // If the stack slot value was previously available in some other
2052 // register, change it now. Otherwise, make the register
2053 // available in PhysReg.
2054 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2060 // Process all of the spilled defs.
2061 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2062 MachineOperand &MO = MI.getOperand(i);
2063 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2066 unsigned VirtReg = MO.getReg();
2067 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2068 // Check to see if this is a noop copy. If so, eliminate the
2069 // instruction before considering the dest reg to be changed.
2070 // Also check if it's copying from an "undef", if so, we can't
2071 // eliminate this or else the undef marker is lost and it will
2072 // confuses the scavenger. This is extremely rare.
2073 unsigned Src, Dst, SrcSR, DstSR;
2074 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2075 !MI.findRegisterUseOperand(Src)->isUndef()) {
2077 DOUT << "Removing now-noop copy: " << MI;
2078 SmallVector<unsigned, 2> KillRegs;
2079 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2080 if (MO.isDead() && !KillRegs.empty()) {
2081 // Source register or an implicit super/sub-register use is killed.
2082 assert(KillRegs[0] == Dst ||
2083 TRI->isSubRegister(KillRegs[0], Dst) ||
2084 TRI->isSuperRegister(KillRegs[0], Dst));
2085 // Last def is now dead.
2086 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2088 VRM.RemoveMachineInstrFromMaps(&MI);
2091 Spills.disallowClobberPhysReg(VirtReg);
2092 goto ProcessNextInst;
2095 // If it's not a no-op copy, it clobbers the value in the destreg.
2096 Spills.ClobberPhysReg(VirtReg);
2097 ReusedOperands.markClobbered(VirtReg);
2099 // Check to see if this instruction is a load from a stack slot into
2100 // a register. If so, this provides the stack slot value in the reg.
2102 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2103 assert(DestReg == VirtReg && "Unknown load situation!");
2105 // If it is a folded reference, then it's not safe to clobber.
2106 bool Folded = FoldedSS.count(FrameIdx);
2107 // Otherwise, if it wasn't available, remember that it is now!
2108 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2109 goto ProcessNextInst;
2115 unsigned SubIdx = MO.getSubReg();
2116 bool DoReMat = VRM.isReMaterialized(VirtReg);
2118 ReMatDefs.insert(&MI);
2120 // The only vregs left are stack slot definitions.
2121 int StackSlot = VRM.getStackSlot(VirtReg);
2122 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2124 // If this def is part of a two-address operand, make sure to execute
2125 // the store from the correct physical register.
2128 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2129 PhysReg = MI.getOperand(TiedOp).getReg();
2131 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2132 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2133 "Can't find corresponding super-register!");
2137 PhysReg = VRM.getPhys(VirtReg);
2138 if (ReusedOperands.isClobbered(PhysReg)) {
2139 // Another def has taken the assigned physreg. It must have been a
2140 // use&def which got it due to reuse. Undo the reuse!
2141 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2142 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2146 assert(PhysReg && "VR not assigned a physical register?");
2147 RegInfo->setPhysRegUsed(PhysReg);
2148 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2149 ReusedOperands.markClobbered(RReg);
2150 MI.getOperand(i).setReg(RReg);
2151 MI.getOperand(i).setSubReg(0);
2154 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2155 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2156 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2157 NextMII = next(MII);
2159 // Check to see if this is a noop copy. If so, eliminate the
2160 // instruction before considering the dest reg to be changed.
2162 unsigned Src, Dst, SrcSR, DstSR;
2163 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2165 DOUT << "Removing now-noop copy: " << MI;
2166 InvalidateKills(MI, TRI, RegKills, KillOps);
2167 VRM.RemoveMachineInstrFromMaps(&MI);
2170 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2171 goto ProcessNextInst;
2177 // Delete dead instructions without side effects.
2178 if (!Erased && !BackTracked && TII->isDeadInstruction(&MI)) {
2179 InvalidateKills(MI, TRI, RegKills, KillOps);
2180 VRM.RemoveMachineInstrFromMaps(&MI);
2185 DistanceMap.insert(std::make_pair(&MI, Dist++));
2186 if (!Erased && !BackTracked) {
2187 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2188 UpdateKills(*II, TRI, RegKills, KillOps);
2197 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2198 switch (RewriterOpt) {
2199 default: llvm_unreachable("Unreachable!");
2201 return new LocalRewriter();
2203 return new TrivialRewriter();