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 "VirtRegMap.h"
13 #include "llvm/Function.h"
14 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
29 STATISTIC(NumDSE , "Number of dead stores elided");
30 STATISTIC(NumDSS , "Number of dead spill slots removed");
31 STATISTIC(NumCommutes, "Number of instructions commuted");
32 STATISTIC(NumDRM , "Number of re-materializable defs elided");
33 STATISTIC(NumStores , "Number of stores added");
34 STATISTIC(NumPSpills , "Number of physical register spills");
35 STATISTIC(NumOmitted , "Number of reloads omited");
36 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
37 STATISTIC(NumCopified, "Number of available reloads turned into copies");
38 STATISTIC(NumReMats , "Number of re-materialization");
39 STATISTIC(NumLoads , "Number of loads added");
40 STATISTIC(NumReused , "Number of values reused");
41 STATISTIC(NumDCE , "Number of copies elided");
42 STATISTIC(NumSUnfold , "Number of stores unfolded");
43 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
46 enum RewriterName { local, trivial };
49 static cl::opt<RewriterName>
50 RewriterOpt("rewriter",
51 cl::desc("Rewriter to use (default=local)"),
53 cl::values(clEnumVal(local, "local rewriter"),
54 clEnumVal(trivial, "trivial rewriter"),
59 ScheduleSpills("schedule-spills",
60 cl::desc("Schedule spill code"),
63 VirtRegRewriter::~VirtRegRewriter() {}
65 /// substitutePhysReg - Replace virtual register in MachineOperand with a
66 /// physical register. Do the right thing with the sub-register index.
67 /// Note that operands may be added, so the MO reference is no longer valid.
68 static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
69 const TargetRegisterInfo &TRI) {
70 if (unsigned SubIdx = MO.getSubReg()) {
71 // Insert the physical subreg and reset the subreg field.
72 MO.setReg(TRI.getSubReg(Reg, SubIdx));
75 // Any def, dead, and kill flags apply to the full virtual register, so they
76 // also apply to the full physical register. Add imp-def/dead and imp-kill
78 MachineInstr &MI = *MO.getParent();
81 MI.addRegisterDead(Reg, &TRI, /*AddIfNotFound=*/ true);
83 MI.addRegisterDefined(Reg, &TRI);
84 else if (!MO.isUndef() &&
86 MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
87 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
95 /// This class is intended for use with the new spilling framework only. It
96 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
98 struct TrivialRewriter : public VirtRegRewriter {
100 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
101 LiveIntervals* LIs) {
102 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
103 DEBUG(dbgs() << "********** Function: "
104 << MF.getFunction()->getName() << '\n');
105 DEBUG(dbgs() << "**** Machine Instrs"
106 << "(NOTE! Does not include spills and reloads!) ****\n");
109 MachineRegisterInfo *mri = &MF.getRegInfo();
110 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
112 bool changed = false;
114 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
115 liItr != liEnd; ++liItr) {
117 const LiveInterval *li = liItr->second;
118 unsigned reg = li->reg;
120 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
122 mri->setPhysRegUsed(reg);
125 if (!VRM.hasPhys(reg))
127 unsigned pReg = VRM.getPhys(reg);
128 mri->setPhysRegUsed(pReg);
129 // Copy the register use-list before traversing it.
130 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
131 for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
132 E = mri->reg_end(); I != E; ++I)
133 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
134 for (unsigned N=0; N != reglist.size(); ++N)
135 substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
137 changed |= !reglist.empty();
141 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
151 // ************************************************************************ //
155 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
156 /// from top down, keep track of which spill slots or remat are available in
159 /// Note that not all physregs are created equal here. In particular, some
160 /// physregs are reloads that we are allowed to clobber or ignore at any time.
161 /// Other physregs are values that the register allocated program is using
162 /// that we cannot CHANGE, but we can read if we like. We keep track of this
163 /// on a per-stack-slot / remat id basis as the low bit in the value of the
164 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
165 /// this bit and addAvailable sets it if.
166 class AvailableSpills {
167 const TargetRegisterInfo *TRI;
168 const TargetInstrInfo *TII;
170 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
171 // or remat'ed virtual register values that are still available, due to
172 // being loaded or stored to, but not invalidated yet.
173 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
175 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
176 // indicating which stack slot values are currently held by a physreg. This
177 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
178 // physreg is modified.
179 std::multimap<unsigned, int> PhysRegsAvailable;
181 void disallowClobberPhysRegOnly(unsigned PhysReg);
183 void ClobberPhysRegOnly(unsigned PhysReg);
185 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
186 : TRI(tri), TII(tii) {
189 /// clear - Reset the state.
191 SpillSlotsOrReMatsAvailable.clear();
192 PhysRegsAvailable.clear();
195 const TargetRegisterInfo *getRegInfo() const { return TRI; }
197 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
198 /// available in a physical register, return that PhysReg, otherwise
200 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
201 std::map<int, unsigned>::const_iterator I =
202 SpillSlotsOrReMatsAvailable.find(Slot);
203 if (I != SpillSlotsOrReMatsAvailable.end()) {
204 return I->second >> 1; // Remove the CanClobber bit.
209 /// addAvailable - Mark that the specified stack slot / remat is available
210 /// in the specified physreg. If CanClobber is true, the physreg can be
211 /// modified at any time without changing the semantics of the program.
212 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
213 // If this stack slot is thought to be available in some other physreg,
214 // remove its record.
215 ModifyStackSlotOrReMat(SlotOrReMat);
217 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
218 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
219 (unsigned)CanClobber;
221 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
222 DEBUG(dbgs() << "Remembering RM#"
223 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
225 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
226 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
229 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
230 /// the value of the specified stackslot register if it desires. The
231 /// specified stack slot must be available in a physreg for this query to
233 bool canClobberPhysRegForSS(int SlotOrReMat) const {
234 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
235 "Value not available!");
236 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
239 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
240 /// physical register where values for some stack slot(s) might be
242 bool canClobberPhysReg(unsigned PhysReg) const {
243 std::multimap<unsigned, int>::const_iterator I =
244 PhysRegsAvailable.lower_bound(PhysReg);
245 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
246 int SlotOrReMat = I->second;
248 if (!canClobberPhysRegForSS(SlotOrReMat))
254 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
255 /// stackslot register. The register is still available but is no longer
256 /// allowed to be modifed.
257 void disallowClobberPhysReg(unsigned PhysReg);
259 /// ClobberPhysReg - This is called when the specified physreg changes
260 /// value. We use this to invalidate any info about stuff that lives in
261 /// it and any of its aliases.
262 void ClobberPhysReg(unsigned PhysReg);
264 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
265 /// slot changes. This removes information about which register the
266 /// previous value for this slot lives in (as the previous value is dead
268 void ModifyStackSlotOrReMat(int SlotOrReMat);
270 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
271 /// into the specified MBB. Add available physical registers as potential
272 /// live-in's. If they are reused in the MBB, they will be added to the
273 /// live-in set to make register scavenger and post-allocation scheduler.
274 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
275 std::vector<MachineOperand*> &KillOps);
280 // ************************************************************************ //
282 // Given a location where a reload of a spilled register or a remat of
283 // a constant is to be inserted, attempt to find a safe location to
284 // insert the load at an earlier point in the basic-block, to hide
285 // latency of the load and to avoid address-generation interlock
287 static MachineBasicBlock::iterator
288 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
289 MachineBasicBlock::iterator const Begin,
291 const TargetRegisterInfo *TRI,
294 const TargetInstrInfo *TII,
295 const MachineFunction &MF)
300 // Spill backscheduling is of primary interest to addresses, so
301 // don't do anything if the register isn't in the register class
302 // used for pointers.
304 const TargetLowering *TL = MF.getTarget().getTargetLowering();
306 if (!TL->isTypeLegal(TL->getPointerTy()))
307 // Believe it or not, this is true on PIC16.
310 const TargetRegisterClass *ptrRegClass =
311 TL->getRegClassFor(TL->getPointerTy());
312 if (!ptrRegClass->contains(PhysReg))
315 // Scan upwards through the preceding instructions. If an instruction doesn't
316 // reference the stack slot or the register we're loading, we can
317 // backschedule the reload up past it.
318 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
319 while (NewInsertLoc != Begin) {
320 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
321 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
322 MachineOperand &Op = Prev->getOperand(i);
323 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
326 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
327 Prev->findRegisterDefOperand(PhysReg))
329 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
330 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
331 Prev->findRegisterDefOperand(*Alias))
337 // If we made it to the beginning of the block, turn around and move back
338 // down just past any existing reloads. They're likely to be reloads/remats
339 // for instructions earlier than what our current reload/remat is for, so
340 // they should be scheduled earlier.
341 if (NewInsertLoc == Begin) {
343 while (InsertLoc != NewInsertLoc &&
344 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
345 TII->isTriviallyReMaterializable(NewInsertLoc)))
354 // ReusedOp - For each reused operand, we keep track of a bit of information,
355 // in case we need to rollback upon processing a new operand. See comments
358 // The MachineInstr operand that reused an available value.
361 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
362 unsigned StackSlotOrReMat;
364 // PhysRegReused - The physical register the value was available in.
365 unsigned PhysRegReused;
367 // AssignedPhysReg - The physreg that was assigned for use by the reload.
368 unsigned AssignedPhysReg;
370 // VirtReg - The virtual register itself.
373 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
375 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
376 AssignedPhysReg(apr), VirtReg(vreg) {}
379 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
380 /// is reused instead of reloaded.
383 std::vector<ReusedOp> Reuses;
384 BitVector PhysRegsClobbered;
386 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
387 PhysRegsClobbered.resize(tri->getNumRegs());
390 bool hasReuses() const {
391 return !Reuses.empty();
394 /// addReuse - If we choose to reuse a virtual register that is already
395 /// available instead of reloading it, remember that we did so.
396 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
397 unsigned PhysRegReused, unsigned AssignedPhysReg,
399 // If the reload is to the assigned register anyway, no undo will be
401 if (PhysRegReused == AssignedPhysReg) return;
403 // Otherwise, remember this.
404 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
405 AssignedPhysReg, VirtReg));
408 void markClobbered(unsigned PhysReg) {
409 PhysRegsClobbered.set(PhysReg);
412 bool isClobbered(unsigned PhysReg) const {
413 return PhysRegsClobbered.test(PhysReg);
416 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
417 /// is some other operand that is using the specified register, either pick
418 /// a new register to use, or evict the previous reload and use this reg.
419 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
420 MachineFunction &MF, MachineInstr *MI,
421 AvailableSpills &Spills,
422 std::vector<MachineInstr*> &MaybeDeadStores,
423 SmallSet<unsigned, 8> &Rejected,
425 std::vector<MachineOperand*> &KillOps,
428 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
429 /// 'Rejected' set to remember which registers have been considered and
430 /// rejected for the reload. This avoids infinite looping in case like
433 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
434 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
436 /// sees r1 is taken by t2, tries t2's reload register r0
437 /// sees r0 is taken by t3, tries t3's reload register r1
438 /// sees r1 is taken by t2, tries t2's reload register r0 ...
439 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
440 AvailableSpills &Spills,
441 std::vector<MachineInstr*> &MaybeDeadStores,
443 std::vector<MachineOperand*> &KillOps,
445 SmallSet<unsigned, 8> Rejected;
446 MachineFunction &MF = *MI->getParent()->getParent();
447 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
448 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
449 Rejected, RegKills, KillOps, VRM);
455 // ****************** //
456 // Utility Functions //
457 // ****************** //
459 /// findSinglePredSuccessor - Return via reference a vector of machine basic
460 /// blocks each of which is a successor of the specified BB and has no other
462 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
463 SmallVectorImpl<MachineBasicBlock *> &Succs) {
464 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
465 SE = MBB->succ_end(); SI != SE; ++SI) {
466 MachineBasicBlock *SuccMBB = *SI;
467 if (SuccMBB->pred_size() == 1)
468 Succs.push_back(SuccMBB);
472 /// InvalidateKill - Invalidate register kill information for a specific
473 /// register. This also unsets the kills marker on the last kill operand.
474 static void InvalidateKill(unsigned Reg,
475 const TargetRegisterInfo* TRI,
477 std::vector<MachineOperand*> &KillOps) {
479 KillOps[Reg]->setIsKill(false);
480 // KillOps[Reg] might be a def of a super-register.
481 unsigned KReg = KillOps[Reg]->getReg();
482 KillOps[KReg] = NULL;
483 RegKills.reset(KReg);
484 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
486 KillOps[*SR]->setIsKill(false);
494 /// InvalidateKills - MI is going to be deleted. If any of its operands are
495 /// marked kill, then invalidate the information.
496 static void InvalidateKills(MachineInstr &MI,
497 const TargetRegisterInfo* TRI,
499 std::vector<MachineOperand*> &KillOps,
500 SmallVector<unsigned, 2> *KillRegs = NULL) {
501 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
502 MachineOperand &MO = MI.getOperand(i);
503 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
505 unsigned Reg = MO.getReg();
506 if (TargetRegisterInfo::isVirtualRegister(Reg))
509 KillRegs->push_back(Reg);
510 assert(Reg < KillOps.size());
511 if (KillOps[Reg] == &MO) {
514 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
524 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
525 /// (since its spill instruction is removed), mark it isDead. Also checks if
526 /// the def MI has other definition operands that are not dead. Returns it by
528 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
529 MachineInstr &NewDef, unsigned Reg,
531 const TargetRegisterInfo *TRI) {
532 // Due to remat, it's possible this reg isn't being reused. That is,
533 // the def of this reg (by prev MI) is now dead.
534 MachineInstr *DefMI = I;
535 MachineOperand *DefOp = NULL;
536 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
537 MachineOperand &MO = DefMI->getOperand(i);
538 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
540 if (MO.getReg() == Reg)
542 else if (!MO.isDead())
548 bool FoundUse = false, Done = false;
549 MachineBasicBlock::iterator E = &NewDef;
551 for (; !Done && I != E; ++I) {
552 MachineInstr *NMI = I;
553 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
554 MachineOperand &MO = NMI->getOperand(j);
555 if (!MO.isReg() || MO.getReg() == 0 ||
556 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
560 Done = true; // Stop after scanning all the operands of this MI.
571 /// UpdateKills - Track and update kill info. If a MI reads a register that is
572 /// marked kill, then it must be due to register reuse. Transfer the kill info
574 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
576 std::vector<MachineOperand*> &KillOps) {
577 // These do not affect kill info at all.
578 if (MI.isDebugValue())
580 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
581 MachineOperand &MO = MI.getOperand(i);
582 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
584 unsigned Reg = MO.getReg();
588 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
589 // That can't be right. Register is killed but not re-defined and it's
590 // being reused. Let's fix that.
591 KillOps[Reg]->setIsKill(false);
592 // KillOps[Reg] might be a def of a super-register.
593 unsigned KReg = KillOps[Reg]->getReg();
594 KillOps[KReg] = NULL;
595 RegKills.reset(KReg);
597 // Must be a def of a super-register. Its other sub-regsters are no
598 // longer killed as well.
599 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
604 // Check for subreg kills as well.
610 // = d4 <avoiding reload>
611 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
613 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
614 KillOps[SReg]->setIsKill(false);
615 unsigned KReg = KillOps[SReg]->getReg();
616 KillOps[KReg] = NULL;
617 RegKills.reset(KReg);
619 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
620 KillOps[*SSR] = NULL;
621 RegKills.reset(*SSR);
630 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
637 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI.getOperand(i);
639 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
641 unsigned Reg = MO.getReg();
644 // It also defines (or partially define) aliases.
645 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
649 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
656 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
658 static void ReMaterialize(MachineBasicBlock &MBB,
659 MachineBasicBlock::iterator &MII,
660 unsigned DestReg, unsigned Reg,
661 const TargetInstrInfo *TII,
662 const TargetRegisterInfo *TRI,
664 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
666 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
667 assert(TID.getNumDefs() == 1 &&
668 "Don't know how to remat instructions that define > 1 values!");
670 TII->reMaterialize(MBB, MII, DestReg,
671 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
672 MachineInstr *NewMI = prior(MII);
673 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
674 MachineOperand &MO = NewMI->getOperand(i);
675 if (!MO.isReg() || MO.getReg() == 0)
677 unsigned VirtReg = MO.getReg();
678 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
681 unsigned Phys = VRM.getPhys(VirtReg);
682 assert(Phys && "Virtual register is not assigned a register?");
683 substitutePhysReg(MO, Phys, *TRI);
688 /// findSuperReg - Find the SubReg's super-register of given register class
689 /// where its SubIdx sub-register is SubReg.
690 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
691 unsigned SubIdx, const TargetRegisterInfo *TRI) {
692 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
695 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
701 // ******************************** //
702 // Available Spills Implementation //
703 // ******************************** //
705 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
706 /// stackslot register. The register is still available but is no longer
707 /// allowed to be modifed.
708 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
709 std::multimap<unsigned, int>::iterator I =
710 PhysRegsAvailable.lower_bound(PhysReg);
711 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
712 int SlotOrReMat = I->second;
714 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
715 "Bidirectional map mismatch!");
716 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
717 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
718 << " copied, it is available for use but can no longer be modified\n");
722 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
723 /// stackslot register and its aliases. The register and its aliases may
724 /// still available but is no longer allowed to be modifed.
725 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
726 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
727 disallowClobberPhysRegOnly(*AS);
728 disallowClobberPhysRegOnly(PhysReg);
731 /// ClobberPhysRegOnly - This is called when the specified physreg changes
732 /// value. We use this to invalidate any info about stuff we thing lives in it.
733 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
734 std::multimap<unsigned, int>::iterator I =
735 PhysRegsAvailable.lower_bound(PhysReg);
736 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
737 int SlotOrReMat = I->second;
738 PhysRegsAvailable.erase(I++);
739 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
740 "Bidirectional map mismatch!");
741 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
742 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
743 << " clobbered, invalidating ");
744 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
745 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
747 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
751 /// ClobberPhysReg - This is called when the specified physreg changes
752 /// value. We use this to invalidate any info about stuff we thing lives in
753 /// it and any of its aliases.
754 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
755 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
756 ClobberPhysRegOnly(*AS);
757 ClobberPhysRegOnly(PhysReg);
760 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
761 /// into the specified MBB. Add available physical registers as potential
762 /// live-in's. If they are reused in the MBB, they will be added to the
763 /// live-in set to make register scavenger and post-allocation scheduler.
764 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
766 std::vector<MachineOperand*> &KillOps) {
767 std::set<unsigned> NotAvailable;
768 for (std::multimap<unsigned, int>::iterator
769 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
771 unsigned Reg = I->first;
772 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
773 // FIXME: A temporary workaround. We can't reuse available value if it's
774 // not safe to move the def of the virtual register's class. e.g.
775 // X86::RFP* register classes. Do not add it as a live-in.
776 if (!TII->isSafeToMoveRegClassDefs(RC))
777 // This is no longer available.
778 NotAvailable.insert(Reg);
781 InvalidateKill(Reg, TRI, RegKills, KillOps);
784 // Skip over the same register.
785 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
786 while (NI != E && NI->first == Reg) {
792 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
793 E = NotAvailable.end(); I != E; ++I) {
795 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
797 ClobberPhysReg(*SubRegs);
801 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
802 /// slot changes. This removes information about which register the previous
803 /// value for this slot lives in (as the previous value is dead now).
804 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
805 std::map<int, unsigned>::iterator It =
806 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
807 if (It == SpillSlotsOrReMatsAvailable.end()) return;
808 unsigned Reg = It->second >> 1;
809 SpillSlotsOrReMatsAvailable.erase(It);
811 // This register may hold the value of multiple stack slots, only remove this
812 // stack slot from the set of values the register contains.
813 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
815 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
816 "Map inverse broken!");
817 if (I->second == SlotOrReMat) break;
819 PhysRegsAvailable.erase(I);
822 // ************************** //
823 // Reuse Info Implementation //
824 // ************************** //
826 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
827 /// is some other operand that is using the specified register, either pick
828 /// a new register to use, or evict the previous reload and use this reg.
829 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
832 MachineInstr *MI, AvailableSpills &Spills,
833 std::vector<MachineInstr*> &MaybeDeadStores,
834 SmallSet<unsigned, 8> &Rejected,
836 std::vector<MachineOperand*> &KillOps,
838 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
839 const TargetRegisterInfo *TRI = Spills.getRegInfo();
841 if (Reuses.empty()) return PhysReg; // This is most often empty.
843 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
844 ReusedOp &Op = Reuses[ro];
845 // If we find some other reuse that was supposed to use this register
846 // exactly for its reload, we can change this reload to use ITS reload
847 // register. That is, unless its reload register has already been
848 // considered and subsequently rejected because it has also been reused
849 // by another operand.
850 if (Op.PhysRegReused == PhysReg &&
851 Rejected.count(Op.AssignedPhysReg) == 0 &&
852 RC->contains(Op.AssignedPhysReg)) {
853 // Yup, use the reload register that we didn't use before.
854 unsigned NewReg = Op.AssignedPhysReg;
855 Rejected.insert(PhysReg);
856 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
857 RegKills, KillOps, VRM);
859 // Otherwise, we might also have a problem if a previously reused
860 // value aliases the new register. If so, codegen the previous reload
862 unsigned PRRU = Op.PhysRegReused;
863 if (TRI->regsOverlap(PRRU, PhysReg)) {
864 // Okay, we found out that an alias of a reused register
865 // was used. This isn't good because it means we have
866 // to undo a previous reuse.
867 MachineBasicBlock *MBB = MI->getParent();
868 const TargetRegisterClass *AliasRC =
869 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
871 // Copy Op out of the vector and remove it, we're going to insert an
872 // explicit load for it.
874 Reuses.erase(Reuses.begin()+ro);
876 // MI may be using only a sub-register of PhysRegUsed.
877 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
879 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
880 "A reuse cannot be a virtual register");
881 if (PRRU != RealPhysRegUsed) {
882 // What was the sub-register index?
883 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
885 "Operand physreg is not a sub-register of PhysRegUsed");
888 // Ok, we're going to try to reload the assigned physreg into the
889 // slot that we were supposed to in the first place. However, that
890 // register could hold a reuse. Check to see if it conflicts or
891 // would prefer us to use a different register.
892 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
893 MF, MI, Spills, MaybeDeadStores,
894 Rejected, RegKills, KillOps, VRM);
896 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
897 int SSorRMId = DoReMat
898 ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
900 // Back-schedule reloads and remats.
901 MachineBasicBlock::iterator InsertLoc =
902 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
903 DoReMat, SSorRMId, TII, MF);
906 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
909 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
910 NewOp.StackSlotOrReMat, AliasRC, TRI);
911 MachineInstr *LoadMI = prior(InsertLoc);
912 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
913 // Any stores to this stack slot are not dead anymore.
914 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
917 Spills.ClobberPhysReg(NewPhysReg);
918 Spills.ClobberPhysReg(NewOp.PhysRegReused);
920 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
921 MI->getOperand(NewOp.Operand).setReg(RReg);
922 MI->getOperand(NewOp.Operand).setSubReg(0);
924 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
925 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
926 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
928 DEBUG(dbgs() << "Reuse undone!\n");
931 // Finally, PhysReg is now available, go ahead and use it.
939 // ************************************************************************ //
941 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
942 /// stack slot mod/ref. It also checks if it's possible to unfold the
943 /// instruction by having it define a specified physical register instead.
944 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
945 const TargetInstrInfo *TII,
946 const TargetRegisterInfo *TRI,
948 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
952 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
953 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
954 unsigned VirtReg = I->second.first;
955 VirtRegMap::ModRef MR = I->second.second;
956 if (MR & VirtRegMap::isModRef)
957 if (VRM.getStackSlot(VirtReg) == SS) {
958 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
965 // Does the instruction uses a register that overlaps the scratch register?
966 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
967 MachineOperand &MO = MI.getOperand(i);
968 if (!MO.isReg() || MO.getReg() == 0)
970 unsigned Reg = MO.getReg();
971 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
972 if (!VRM.hasPhys(Reg))
974 Reg = VRM.getPhys(Reg);
976 if (TRI->regsOverlap(PhysReg, Reg))
982 /// FindFreeRegister - Find a free register of a given register class by looking
983 /// at (at most) the last two machine instructions.
984 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
985 MachineBasicBlock &MBB,
986 const TargetRegisterClass *RC,
987 const TargetRegisterInfo *TRI,
988 BitVector &AllocatableRegs) {
989 BitVector Defs(TRI->getNumRegs());
990 BitVector Uses(TRI->getNumRegs());
991 SmallVector<unsigned, 4> LocalUses;
992 SmallVector<unsigned, 4> Kills;
994 // Take a look at 2 instructions at most.
997 if (MII == MBB.begin())
999 MachineInstr *PrevMI = prior(MII);
1002 if (PrevMI->isDebugValue())
1003 continue; // Skip over dbg_value instructions.
1006 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
1007 MachineOperand &MO = PrevMI->getOperand(i);
1008 if (!MO.isReg() || MO.getReg() == 0)
1010 unsigned Reg = MO.getReg();
1013 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1016 LocalUses.push_back(Reg);
1017 if (MO.isKill() && AllocatableRegs[Reg])
1018 Kills.push_back(Reg);
1022 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1023 unsigned Kill = Kills[i];
1024 if (!Defs[Kill] && !Uses[Kill] &&
1025 TRI->getPhysicalRegisterRegClass(Kill) == RC)
1028 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1029 unsigned Reg = LocalUses[i];
1031 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1040 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1041 const TargetRegisterInfo &TRI) {
1042 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1043 MachineOperand &MO = MI->getOperand(i);
1044 if (MO.isReg() && MO.getReg() == VirtReg)
1045 substitutePhysReg(MO, PhysReg, TRI);
1052 bool operator()(const std::pair<MachineInstr*, int> &A,
1053 const std::pair<MachineInstr*, int> &B) {
1054 return A.second < B.second;
1058 // ***************************** //
1059 // Local Spiller Implementation //
1060 // ***************************** //
1062 class LocalRewriter : public VirtRegRewriter {
1063 MachineRegisterInfo *MRI;
1064 const TargetRegisterInfo *TRI;
1065 const TargetInstrInfo *TII;
1067 BitVector AllocatableRegs;
1068 DenseMap<MachineInstr*, unsigned> DistanceMap;
1069 DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
1071 MachineBasicBlock *MBB; // Basic block currently being processed.
1075 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1076 LiveIntervals* LIs);
1080 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1081 MachineBasicBlock::iterator &MII,
1082 std::vector<MachineInstr*> &MaybeDeadStores,
1083 AvailableSpills &Spills,
1084 BitVector &RegKills,
1085 std::vector<MachineOperand*> &KillOps);
1087 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1088 std::vector<MachineInstr*> &MaybeDeadStores,
1089 AvailableSpills &Spills,
1090 BitVector &RegKills,
1091 std::vector<MachineOperand*> &KillOps);
1093 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1094 unsigned VirtReg, unsigned SrcReg, int SS,
1095 AvailableSpills &Spills,
1096 BitVector &RegKills,
1097 std::vector<MachineOperand*> &KillOps,
1098 const TargetRegisterInfo *TRI);
1100 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1101 int Idx, unsigned PhysReg, int StackSlot,
1102 const TargetRegisterClass *RC,
1103 bool isAvailable, MachineInstr *&LastStore,
1104 AvailableSpills &Spills,
1105 SmallSet<MachineInstr*, 4> &ReMatDefs,
1106 BitVector &RegKills,
1107 std::vector<MachineOperand*> &KillOps);
1109 void TransferDeadness(unsigned Reg, BitVector &RegKills,
1110 std::vector<MachineOperand*> &KillOps);
1112 bool InsertEmergencySpills(MachineInstr *MI);
1114 bool InsertRestores(MachineInstr *MI,
1115 AvailableSpills &Spills,
1116 BitVector &RegKills,
1117 std::vector<MachineOperand*> &KillOps);
1119 bool InsertSpills(MachineInstr *MI);
1121 void RewriteMBB(LiveIntervals *LIs,
1122 AvailableSpills &Spills, BitVector &RegKills,
1123 std::vector<MachineOperand*> &KillOps);
1127 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1128 LiveIntervals* LIs) {
1129 MRI = &MF.getRegInfo();
1130 TRI = MF.getTarget().getRegisterInfo();
1131 TII = MF.getTarget().getInstrInfo();
1133 AllocatableRegs = TRI->getAllocatableSet(MF);
1134 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1135 << MF.getFunction()->getName() << "':\n");
1136 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1137 " reloads!) ****\n");
1140 // Spills - Keep track of which spilled values are available in physregs
1141 // so that we can choose to reuse the physregs instead of emitting
1142 // reloads. This is usually refreshed per basic block.
1143 AvailableSpills Spills(TRI, TII);
1145 // Keep track of kill information.
1146 BitVector RegKills(TRI->getNumRegs());
1147 std::vector<MachineOperand*> KillOps;
1148 KillOps.resize(TRI->getNumRegs(), NULL);
1150 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1151 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1152 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1154 // Traverse the basic blocks depth first.
1155 MachineBasicBlock *Entry = MF.begin();
1156 SmallPtrSet<MachineBasicBlock*,16> Visited;
1157 for (df_ext_iterator<MachineBasicBlock*,
1158 SmallPtrSet<MachineBasicBlock*,16> >
1159 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1162 if (!EarlyVisited.count(MBB))
1163 RewriteMBB(LIs, Spills, RegKills, KillOps);
1165 // If this MBB is the only predecessor of a successor. Keep the
1166 // availability information and visit it next.
1168 // Keep visiting single predecessor successor as long as possible.
1169 SinglePredSuccs.clear();
1170 findSinglePredSuccessor(MBB, SinglePredSuccs);
1171 if (SinglePredSuccs.empty())
1174 // FIXME: More than one successors, each of which has MBB has
1175 // the only predecessor.
1176 MBB = SinglePredSuccs[0];
1177 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1178 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1179 RewriteMBB(LIs, Spills, RegKills, KillOps);
1184 // Clear the availability info.
1188 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1191 // Mark unused spill slots.
1192 MachineFrameInfo *MFI = MF.getFrameInfo();
1193 int SS = VRM->getLowSpillSlot();
1194 if (SS != VirtRegMap::NO_STACK_SLOT) {
1195 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1196 SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
1197 if (!VRM->isSpillSlotUsed(SS)) {
1198 MFI->RemoveStackObject(SS);
1199 for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1200 MachineInstr *DVMI = DbgValues[j];
1201 MachineBasicBlock *DVMBB = DVMI->getParent();
1202 DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1203 VRM->RemoveMachineInstrFromMaps(DVMI);
1211 Slot2DbgValues.clear();
1216 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1217 /// a scratch register is available.
1218 /// xorq %r12<kill>, %r13
1219 /// addq %rax, -184(%rbp)
1220 /// addq %r13, -184(%rbp)
1222 /// xorq %r12<kill>, %r13
1223 /// movq -184(%rbp), %r12
1226 /// movq %r12, -184(%rbp)
1227 bool LocalRewriter::
1228 OptimizeByUnfold2(unsigned VirtReg, int SS,
1229 MachineBasicBlock::iterator &MII,
1230 std::vector<MachineInstr*> &MaybeDeadStores,
1231 AvailableSpills &Spills,
1232 BitVector &RegKills,
1233 std::vector<MachineOperand*> &KillOps) {
1235 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1236 // Skip over dbg_value instructions.
1237 while (NextMII != MBB->end() && NextMII->isDebugValue())
1238 NextMII = llvm::next(NextMII);
1239 if (NextMII == MBB->end())
1242 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1245 // Now let's see if the last couple of instructions happens to have freed up
1247 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1248 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1252 MachineFunction &MF = *MBB->getParent();
1253 TRI = MF.getTarget().getRegisterInfo();
1254 MachineInstr &MI = *MII;
1255 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1258 // If the next instruction also folds the same SS modref and can be unfoled,
1259 // then it's worthwhile to issue a load from SS into the free register and
1260 // then unfold these instructions.
1261 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1264 // Back-schedule reloads and remats.
1265 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1267 // Load from SS to the spare physical register.
1268 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
1269 // This invalidates Phys.
1270 Spills.ClobberPhysReg(PhysReg);
1271 // Remember it's available.
1272 Spills.addAvailable(SS, PhysReg);
1273 MaybeDeadStores[SS] = NULL;
1275 // Unfold current MI.
1276 SmallVector<MachineInstr*, 4> NewMIs;
1277 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1278 llvm_unreachable("Unable unfold the load / store folding instruction!");
1279 assert(NewMIs.size() == 1);
1280 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1281 VRM->transferRestorePts(&MI, NewMIs[0]);
1282 MII = MBB->insert(MII, NewMIs[0]);
1283 InvalidateKills(MI, TRI, RegKills, KillOps);
1284 VRM->RemoveMachineInstrFromMaps(&MI);
1288 // Unfold next instructions that fold the same SS.
1290 MachineInstr &NextMI = *NextMII;
1291 NextMII = llvm::next(NextMII);
1293 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1294 llvm_unreachable("Unable unfold the load / store folding instruction!");
1295 assert(NewMIs.size() == 1);
1296 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1297 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1298 MBB->insert(NextMII, NewMIs[0]);
1299 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1300 VRM->RemoveMachineInstrFromMaps(&NextMI);
1301 MBB->erase(&NextMI);
1303 // Skip over dbg_value instructions.
1304 while (NextMII != MBB->end() && NextMII->isDebugValue())
1305 NextMII = llvm::next(NextMII);
1306 if (NextMII == MBB->end())
1308 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1310 // Store the value back into SS.
1311 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
1312 MachineInstr *StoreMI = prior(NextMII);
1313 VRM->addSpillSlotUse(SS, StoreMI);
1314 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1319 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1320 /// instruction. e.g.
1322 /// movl %eax, -32(%ebp)
1323 /// movl -36(%ebp), %eax
1324 /// orl %eax, -32(%ebp)
1327 /// orl -36(%ebp), %eax
1328 /// mov %eax, -32(%ebp)
1329 /// This enables unfolding optimization for a subsequent instruction which will
1330 /// also eliminate the newly introduced store instruction.
1331 bool LocalRewriter::
1332 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1333 std::vector<MachineInstr*> &MaybeDeadStores,
1334 AvailableSpills &Spills,
1335 BitVector &RegKills,
1336 std::vector<MachineOperand*> &KillOps) {
1337 MachineFunction &MF = *MBB->getParent();
1338 MachineInstr &MI = *MII;
1339 unsigned UnfoldedOpc = 0;
1340 unsigned UnfoldPR = 0;
1341 unsigned UnfoldVR = 0;
1342 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1343 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1344 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1345 // Only transform a MI that folds a single register.
1348 UnfoldVR = I->second.first;
1349 VirtRegMap::ModRef MR = I->second.second;
1350 // MI2VirtMap be can updated which invalidate the iterator.
1351 // Increment the iterator first.
1353 if (VRM->isAssignedReg(UnfoldVR))
1355 // If this reference is not a use, any previous store is now dead.
1356 // Otherwise, the store to this stack slot is not dead anymore.
1357 FoldedSS = VRM->getStackSlot(UnfoldVR);
1358 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1359 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1360 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1361 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1364 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1373 // Look for other unfolding opportunities.
1374 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1378 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1379 MachineOperand &MO = MI.getOperand(i);
1380 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1382 unsigned VirtReg = MO.getReg();
1383 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1385 if (VRM->isAssignedReg(VirtReg)) {
1386 unsigned PhysReg = VRM->getPhys(VirtReg);
1387 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1389 } else if (VRM->isReMaterialized(VirtReg))
1391 int SS = VRM->getStackSlot(VirtReg);
1392 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1394 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1398 if (VRM->hasPhys(VirtReg)) {
1399 PhysReg = VRM->getPhys(VirtReg);
1400 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1404 // Ok, we'll need to reload the value into a register which makes
1405 // it impossible to perform the store unfolding optimization later.
1406 // Let's see if it is possible to fold the load if the store is
1407 // unfolded. This allows us to perform the store unfolding
1409 SmallVector<MachineInstr*, 4> NewMIs;
1410 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1411 assert(NewMIs.size() == 1);
1412 MachineInstr *NewMI = NewMIs.back();
1414 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1416 SmallVector<unsigned, 1> Ops;
1418 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1420 VRM->addSpillSlotUse(SS, FoldedMI);
1421 if (!VRM->hasPhys(UnfoldVR))
1422 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1423 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1424 MII = MBB->insert(MII, FoldedMI);
1425 InvalidateKills(MI, TRI, RegKills, KillOps);
1426 VRM->RemoveMachineInstrFromMaps(&MI);
1428 MF.DeleteMachineInstr(NewMI);
1431 MF.DeleteMachineInstr(NewMI);
1438 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1439 /// where SrcReg is r1 and it is tied to r0. Return true if after
1440 /// commuting this instruction it will be r0 = op r2, r1.
1441 static bool CommuteChangesDestination(MachineInstr *DefMI,
1442 const TargetInstrDesc &TID,
1444 const TargetInstrInfo *TII,
1446 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1448 if (!DefMI->getOperand(1).isReg() ||
1449 DefMI->getOperand(1).getReg() != SrcReg)
1452 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1454 unsigned SrcIdx1, SrcIdx2;
1455 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1457 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1464 /// CommuteToFoldReload -
1467 /// r1 = op r1, r2<kill>
1470 /// If op is commutable and r2 is killed, then we can xform these to
1471 /// r2 = op r2, fi#1
1473 bool LocalRewriter::
1474 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1475 unsigned VirtReg, unsigned SrcReg, int SS,
1476 AvailableSpills &Spills,
1477 BitVector &RegKills,
1478 std::vector<MachineOperand*> &KillOps,
1479 const TargetRegisterInfo *TRI) {
1480 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1483 MachineFunction &MF = *MBB->getParent();
1484 MachineInstr &MI = *MII;
1485 MachineBasicBlock::iterator DefMII = prior(MII);
1486 MachineInstr *DefMI = DefMII;
1487 const TargetInstrDesc &TID = DefMI->getDesc();
1489 if (DefMII != MBB->begin() &&
1490 TID.isCommutable() &&
1491 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1492 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1493 unsigned NewReg = NewDstMO.getReg();
1494 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1496 MachineInstr *ReloadMI = prior(DefMII);
1498 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1499 if (DestReg != SrcReg || FrameIdx != SS)
1501 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1505 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1507 assert(DefMI->getOperand(DefIdx).isReg() &&
1508 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1510 // Now commute def instruction.
1511 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1514 SmallVector<unsigned, 1> Ops;
1515 Ops.push_back(NewDstIdx);
1516 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1517 // Not needed since foldMemoryOperand returns new MI.
1518 MF.DeleteMachineInstr(CommutedMI);
1522 VRM->addSpillSlotUse(SS, FoldedMI);
1523 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1524 // Insert new def MI and spill MI.
1525 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1526 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
1528 MachineInstr *StoreMI = MII;
1529 VRM->addSpillSlotUse(SS, StoreMI);
1530 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1531 MII = MBB->insert(MII, FoldedMI); // Update MII to backtrack.
1533 // Delete all 3 old instructions.
1534 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1535 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1536 MBB->erase(ReloadMI);
1537 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1538 VRM->RemoveMachineInstrFromMaps(DefMI);
1540 InvalidateKills(MI, TRI, RegKills, KillOps);
1541 VRM->RemoveMachineInstrFromMaps(&MI);
1544 // If NewReg was previously holding value of some SS, it's now clobbered.
1545 // This has to be done now because it's a physical register. When this
1546 // instruction is re-visited, it's ignored.
1547 Spills.ClobberPhysReg(NewReg);
1556 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1557 /// the last store to the same slot is now dead. If so, remove the last store.
1558 void LocalRewriter::
1559 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1560 int Idx, unsigned PhysReg, int StackSlot,
1561 const TargetRegisterClass *RC,
1562 bool isAvailable, MachineInstr *&LastStore,
1563 AvailableSpills &Spills,
1564 SmallSet<MachineInstr*, 4> &ReMatDefs,
1565 BitVector &RegKills,
1566 std::vector<MachineOperand*> &KillOps) {
1568 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1569 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1571 MachineInstr *StoreMI = prior(oldNextMII);
1572 VRM->addSpillSlotUse(StackSlot, StoreMI);
1573 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1575 // If there is a dead store to this stack slot, nuke it now.
1577 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1579 SmallVector<unsigned, 2> KillRegs;
1580 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1581 MachineBasicBlock::iterator PrevMII = LastStore;
1582 bool CheckDef = PrevMII != MBB->begin();
1585 VRM->RemoveMachineInstrFromMaps(LastStore);
1586 MBB->erase(LastStore);
1588 // Look at defs of killed registers on the store. Mark the defs
1589 // as dead since the store has been deleted and they aren't
1591 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1592 bool HasOtherDef = false;
1593 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1594 MachineInstr *DeadDef = PrevMII;
1595 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1596 // FIXME: This assumes a remat def does not have side effects.
1597 VRM->RemoveMachineInstrFromMaps(DeadDef);
1598 MBB->erase(DeadDef);
1606 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1607 // the last of multiple instructions is the actual store.
1608 LastStore = prior(oldNextMII);
1610 // If the stack slot value was previously available in some other
1611 // register, change it now. Otherwise, make the register available,
1613 Spills.ModifyStackSlotOrReMat(StackSlot);
1614 Spills.ClobberPhysReg(PhysReg);
1615 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1619 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1620 /// effect and all of its defs are dead.
1621 static bool isSafeToDelete(MachineInstr &MI) {
1622 const TargetInstrDesc &TID = MI.getDesc();
1623 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1624 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1625 TID.hasUnmodeledSideEffects())
1627 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1628 MachineOperand &MO = MI.getOperand(i);
1629 if (!MO.isReg() || !MO.getReg())
1631 if (MO.isDef() && !MO.isDead())
1633 if (MO.isUse() && MO.isKill())
1634 // FIXME: We can't remove kill markers or else the scavenger will assert.
1635 // An alternative is to add a ADD pseudo instruction to replace kill
1642 /// TransferDeadness - A identity copy definition is dead and it's being
1643 /// removed. Find the last def or use and mark it as dead / kill.
1644 void LocalRewriter::
1645 TransferDeadness(unsigned Reg, BitVector &RegKills,
1646 std::vector<MachineOperand*> &KillOps) {
1647 SmallPtrSet<MachineInstr*, 4> Seens;
1648 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1649 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1650 RE = MRI->reg_end(); RI != RE; ++RI) {
1651 MachineInstr *UDMI = &*RI;
1652 if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
1654 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1655 if (DI == DistanceMap.end())
1657 if (Seens.insert(UDMI))
1658 Refs.push_back(std::make_pair(UDMI, DI->second));
1663 std::sort(Refs.begin(), Refs.end(), RefSorter());
1665 while (!Refs.empty()) {
1666 MachineInstr *LastUDMI = Refs.back().first;
1669 MachineOperand *LastUD = NULL;
1670 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1671 MachineOperand &MO = LastUDMI->getOperand(i);
1672 if (!MO.isReg() || MO.getReg() != Reg)
1674 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1676 if (LastUDMI->isRegTiedToDefOperand(i))
1679 if (LastUD->isDef()) {
1680 // If the instruction has no side effect, delete it and propagate
1681 // backward further. Otherwise, mark is dead and we are done.
1682 if (!isSafeToDelete(*LastUDMI)) {
1683 LastUD->setIsDead();
1686 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1687 MBB->erase(LastUDMI);
1689 LastUD->setIsKill();
1691 KillOps[Reg] = LastUD;
1697 /// InsertEmergencySpills - Insert emergency spills before MI if requested by
1698 /// VRM. Return true if spills were inserted.
1699 bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1700 if (!VRM->hasEmergencySpills(MI))
1702 MachineBasicBlock::iterator MII = MI;
1703 SmallSet<int, 4> UsedSS;
1704 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1705 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1706 unsigned PhysReg = EmSpills[i];
1707 const TargetRegisterClass *RC = TRI->getPhysicalRegisterRegClass(PhysReg);
1708 assert(RC && "Unable to determine register class!");
1709 int SS = VRM->getEmergencySpillSlot(RC);
1710 if (UsedSS.count(SS))
1711 llvm_unreachable("Need to spill more than one physical registers!");
1713 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
1714 MachineInstr *StoreMI = prior(MII);
1715 VRM->addSpillSlotUse(SS, StoreMI);
1717 // Back-schedule reloads and remats.
1718 MachineBasicBlock::iterator InsertLoc =
1719 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1720 TII, *MBB->getParent());
1722 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
1724 MachineInstr *LoadMI = prior(InsertLoc);
1725 VRM->addSpillSlotUse(SS, LoadMI);
1727 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1732 /// InsertRestores - Restore registers before MI is requested by VRM. Return
1733 /// true is any instructions were inserted.
1734 bool LocalRewriter::InsertRestores(MachineInstr *MI,
1735 AvailableSpills &Spills,
1736 BitVector &RegKills,
1737 std::vector<MachineOperand*> &KillOps) {
1738 if (!VRM->isRestorePt(MI))
1740 MachineBasicBlock::iterator MII = MI;
1741 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1742 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1743 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1744 if (!VRM->getPreSplitReg(VirtReg))
1745 continue; // Split interval spilled again.
1746 unsigned Phys = VRM->getPhys(VirtReg);
1747 MRI->setPhysRegUsed(Phys);
1749 // Check if the value being restored if available. If so, it must be
1750 // from a predecessor BB that fallthrough into this BB. We do not
1756 // ... # r1 not clobbered
1759 bool DoReMat = VRM->isReMaterialized(VirtReg);
1760 int SSorRMId = DoReMat
1761 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1762 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1763 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1764 if (InReg == Phys) {
1765 // If the value is already available in the expected register, save
1766 // a reload / remat.
1768 DEBUG(dbgs() << "Reusing RM#"
1769 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1771 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1772 DEBUG(dbgs() << " from physreg "
1773 << TRI->getName(InReg) << " for vreg"
1774 << VirtReg <<" instead of reloading into physreg "
1775 << TRI->getName(Phys) << '\n');
1778 } else if (InReg && InReg != Phys) {
1780 DEBUG(dbgs() << "Reusing RM#"
1781 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1783 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1784 DEBUG(dbgs() << " from physreg "
1785 << TRI->getName(InReg) << " for vreg"
1786 << VirtReg <<" by copying it into physreg "
1787 << TRI->getName(Phys) << '\n');
1789 // If the reloaded / remat value is available in another register,
1790 // copy it to the desired register.
1792 // Back-schedule reloads and remats.
1793 MachineBasicBlock::iterator InsertLoc =
1794 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1797 TII->copyRegToReg(*MBB, InsertLoc, Phys, InReg, RC, RC,
1800 // This invalidates Phys.
1801 Spills.ClobberPhysReg(Phys);
1802 // Remember it's available.
1803 Spills.addAvailable(SSorRMId, Phys);
1806 MachineInstr *CopyMI = prior(InsertLoc);
1807 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1808 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1809 KillOpnd->setIsKill();
1810 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1812 DEBUG(dbgs() << '\t' << *CopyMI);
1817 // Back-schedule reloads and remats.
1818 MachineBasicBlock::iterator InsertLoc =
1819 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1822 if (VRM->isReMaterialized(VirtReg)) {
1823 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1825 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1826 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
1827 MachineInstr *LoadMI = prior(InsertLoc);
1828 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1830 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1833 // This invalidates Phys.
1834 Spills.ClobberPhysReg(Phys);
1835 // Remember it's available.
1836 Spills.addAvailable(SSorRMId, Phys);
1838 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1839 DEBUG(dbgs() << '\t' << *prior(MII));
1844 /// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1845 /// true if spills were inserted.
1846 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1847 if (!VRM->isSpillPt(MI))
1849 MachineBasicBlock::iterator MII = MI;
1850 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1851 VRM->getSpillPtSpills(MI);
1852 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1853 unsigned VirtReg = SpillRegs[i].first;
1854 bool isKill = SpillRegs[i].second;
1855 if (!VRM->getPreSplitReg(VirtReg))
1856 continue; // Split interval spilled again.
1857 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1858 unsigned Phys = VRM->getPhys(VirtReg);
1859 int StackSlot = VRM->getStackSlot(VirtReg);
1860 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1861 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1863 MachineInstr *StoreMI = prior(oldNextMII);
1864 VRM->addSpillSlotUse(StackSlot, StoreMI);
1865 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1866 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1872 /// rewriteMBB - Keep track of which spills are available even after the
1873 /// register allocator is done with them. If possible, avid reloading vregs.
1875 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1876 AvailableSpills &Spills, BitVector &RegKills,
1877 std::vector<MachineOperand*> &KillOps) {
1879 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1880 << MBB->getName() << "':\n");
1882 MachineFunction &MF = *MBB->getParent();
1884 // MaybeDeadStores - When we need to write a value back into a stack slot,
1885 // keep track of the inserted store. If the stack slot value is never read
1886 // (because the value was used from some available register, for example), and
1887 // subsequently stored to, the original store is dead. This map keeps track
1888 // of inserted stores that are not used. If we see a subsequent store to the
1889 // same stack slot, the original store is deleted.
1890 std::vector<MachineInstr*> MaybeDeadStores;
1891 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1893 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1894 SmallSet<MachineInstr*, 4> ReMatDefs;
1897 SmallSet<unsigned, 2> KilledMIRegs;
1900 KillOps.resize(TRI->getNumRegs(), NULL);
1902 DistanceMap.clear();
1903 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1905 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1907 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1908 NextMII = llvm::next(MII);
1910 if (InsertEmergencySpills(MII))
1911 NextMII = llvm::next(MII);
1913 InsertRestores(MII, Spills, RegKills, KillOps);
1915 if (InsertSpills(MII))
1916 NextMII = llvm::next(MII);
1918 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1919 bool Erased = false;
1920 bool BackTracked = false;
1921 MachineInstr &MI = *MII;
1923 // Remember DbgValue's which reference stack slots.
1924 if (MI.isDebugValue() && MI.getOperand(0).isFI())
1925 Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
1927 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1929 ReuseInfo ReusedOperands(MI, TRI);
1930 SmallVector<unsigned, 4> VirtUseOps;
1931 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1932 MachineOperand &MO = MI.getOperand(i);
1933 if (!MO.isReg() || MO.getReg() == 0)
1934 continue; // Ignore non-register operands.
1936 unsigned VirtReg = MO.getReg();
1937 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1938 // Ignore physregs for spilling, but remember that it is used by this
1940 MRI->setPhysRegUsed(VirtReg);
1944 // We want to process implicit virtual register uses first.
1945 if (MO.isImplicit())
1946 // If the virtual register is implicitly defined, emit a implicit_def
1947 // before so scavenger knows it's "defined".
1948 // FIXME: This is a horrible hack done the by register allocator to
1949 // remat a definition with virtual register operand.
1950 VirtUseOps.insert(VirtUseOps.begin(), i);
1952 VirtUseOps.push_back(i);
1955 // Process all of the spilled uses and all non spilled reg references.
1956 SmallVector<int, 2> PotentialDeadStoreSlots;
1957 KilledMIRegs.clear();
1958 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1959 unsigned i = VirtUseOps[j];
1960 unsigned VirtReg = MI.getOperand(i).getReg();
1961 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1962 "Not a virtual register?");
1964 unsigned SubIdx = MI.getOperand(i).getSubReg();
1965 if (VRM->isAssignedReg(VirtReg)) {
1966 // This virtual register was assigned a physreg!
1967 unsigned Phys = VRM->getPhys(VirtReg);
1968 MRI->setPhysRegUsed(Phys);
1969 if (MI.getOperand(i).isDef())
1970 ReusedOperands.markClobbered(Phys);
1971 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1972 if (VRM->isImplicitlyDefined(VirtReg))
1973 // FIXME: Is this needed?
1974 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1975 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1979 // This virtual register is now known to be a spilled value.
1980 if (!MI.getOperand(i).isUse())
1981 continue; // Handle defs in the loop below (handle use&def here though)
1983 bool AvoidReload = MI.getOperand(i).isUndef();
1984 // Check if it is defined by an implicit def. It should not be spilled.
1985 // Note, this is for correctness reason. e.g.
1986 // 8 %reg1024<def> = IMPLICIT_DEF
1987 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1988 // The live range [12, 14) are not part of the r1024 live interval since
1989 // it's defined by an implicit def. It will not conflicts with live
1990 // interval of r1025. Now suppose both registers are spilled, you can
1991 // easily see a situation where both registers are reloaded before
1992 // the INSERT_SUBREG and both target registers that would overlap.
1993 bool DoReMat = VRM->isReMaterialized(VirtReg);
1994 int SSorRMId = DoReMat
1995 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1996 int ReuseSlot = SSorRMId;
1998 // Check to see if this stack slot is available.
1999 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
2001 // If this is a sub-register use, make sure the reuse register is in the
2002 // right register class. For example, for x86 not all of the 32-bit
2003 // registers have accessible sub-registers.
2004 // Similarly so for EXTRACT_SUBREG. Consider this:
2006 // MOV32_mr fi#1, EDI
2008 // = EXTRACT_SUBREG fi#1
2009 // fi#1 is available in EDI, but it cannot be reused because it's not in
2010 // the right register file.
2011 if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
2012 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2013 if (!RC->contains(PhysReg))
2017 if (PhysReg && !AvoidReload) {
2018 // This spilled operand might be part of a two-address operand. If this
2019 // is the case, then changing it will necessarily require changing the
2020 // def part of the instruction as well. However, in some cases, we
2021 // aren't allowed to modify the reused register. If none of these cases
2023 bool CanReuse = true;
2024 bool isTied = MI.isRegTiedToDefOperand(i);
2026 // Okay, we have a two address operand. We can reuse this physreg as
2027 // long as we are allowed to clobber the value and there isn't an
2028 // earlier def that has already clobbered the physreg.
2029 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
2030 Spills.canClobberPhysReg(PhysReg);
2034 // If this stack slot value is already available, reuse it!
2035 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2036 DEBUG(dbgs() << "Reusing RM#"
2037 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2039 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2040 DEBUG(dbgs() << " from physreg "
2041 << TRI->getName(PhysReg) << " for vreg"
2042 << VirtReg <<" instead of reloading into physreg "
2043 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2044 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2045 MI.getOperand(i).setReg(RReg);
2046 MI.getOperand(i).setSubReg(0);
2048 // The only technical detail we have is that we don't know that
2049 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2050 // later in the instruction. In particular, consider 'op V1, V2'.
2051 // If V1 is available in physreg R0, we would choose to reuse it
2052 // here, instead of reloading it into the register the allocator
2053 // indicated (say R1). However, V2 might have to be reloaded
2054 // later, and it might indicate that it needs to live in R0. When
2055 // this occurs, we need to have information available that
2056 // indicates it is safe to use R1 for the reload instead of R0.
2058 // To further complicate matters, we might conflict with an alias,
2059 // or R0 and R1 might not be compatible with each other. In this
2060 // case, we actually insert a reload for V1 in R1, ensuring that
2061 // we can get at R0 or its alias.
2062 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2063 VRM->getPhys(VirtReg), VirtReg);
2065 // Only mark it clobbered if this is a use&def operand.
2066 ReusedOperands.markClobbered(PhysReg);
2069 if (MI.getOperand(i).isKill() &&
2070 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2072 // The store of this spilled value is potentially dead, but we
2073 // won't know for certain until we've confirmed that the re-use
2074 // above is valid, which means waiting until the other operands
2075 // are processed. For now we just track the spill slot, we'll
2076 // remove it after the other operands are processed if valid.
2078 PotentialDeadStoreSlots.push_back(ReuseSlot);
2081 // Mark is isKill if it's there no other uses of the same virtual
2082 // register and it's not a two-address operand. IsKill will be
2083 // unset if reg is reused.
2084 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2085 MI.getOperand(i).setIsKill();
2086 KilledMIRegs.insert(VirtReg);
2092 // Otherwise we have a situation where we have a two-address instruction
2093 // whose mod/ref operand needs to be reloaded. This reload is already
2094 // available in some register "PhysReg", but if we used PhysReg as the
2095 // operand to our 2-addr instruction, the instruction would modify
2096 // PhysReg. This isn't cool if something later uses PhysReg and expects
2097 // to get its initial value.
2099 // To avoid this problem, and to avoid doing a load right after a store,
2100 // we emit a copy from PhysReg into the designated register for this
2102 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2103 assert(DesignatedReg && "Must map virtreg to physreg!");
2105 // Note that, if we reused a register for a previous operand, the
2106 // register we want to reload into might not actually be
2107 // available. If this occurs, use the register indicated by the
2109 if (ReusedOperands.hasReuses())
2110 DesignatedReg = ReusedOperands.
2111 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2112 MaybeDeadStores, RegKills, KillOps, *VRM);
2114 // If the mapped designated register is actually the physreg we have
2115 // incoming, we don't need to inserted a dead copy.
2116 if (DesignatedReg == PhysReg) {
2117 // If this stack slot value is already available, reuse it!
2118 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2119 DEBUG(dbgs() << "Reusing RM#"
2120 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2122 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2123 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2124 << " for vreg" << VirtReg
2125 << " instead of reloading into same physreg.\n");
2126 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2127 MI.getOperand(i).setReg(RReg);
2128 MI.getOperand(i).setSubReg(0);
2129 ReusedOperands.markClobbered(RReg);
2134 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2135 MRI->setPhysRegUsed(DesignatedReg);
2136 ReusedOperands.markClobbered(DesignatedReg);
2138 // Back-schedule reloads and remats.
2139 MachineBasicBlock::iterator InsertLoc =
2140 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2143 TII->copyRegToReg(*MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC,
2146 MachineInstr *CopyMI = prior(InsertLoc);
2147 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2148 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2150 // This invalidates DesignatedReg.
2151 Spills.ClobberPhysReg(DesignatedReg);
2153 Spills.addAvailable(ReuseSlot, DesignatedReg);
2155 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2156 MI.getOperand(i).setReg(RReg);
2157 MI.getOperand(i).setSubReg(0);
2158 DEBUG(dbgs() << '\t' << *prior(MII));
2163 // Otherwise, reload it and remember that we have it.
2164 PhysReg = VRM->getPhys(VirtReg);
2165 assert(PhysReg && "Must map virtreg to physreg!");
2167 // Note that, if we reused a register for a previous operand, the
2168 // register we want to reload into might not actually be
2169 // available. If this occurs, use the register indicated by the
2171 if (ReusedOperands.hasReuses())
2172 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2173 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2175 MRI->setPhysRegUsed(PhysReg);
2176 ReusedOperands.markClobbered(PhysReg);
2180 // Back-schedule reloads and remats.
2181 MachineBasicBlock::iterator InsertLoc =
2182 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2186 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2188 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2189 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2190 MachineInstr *LoadMI = prior(InsertLoc);
2191 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2193 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2195 // This invalidates PhysReg.
2196 Spills.ClobberPhysReg(PhysReg);
2198 // Any stores to this stack slot are not dead anymore.
2200 MaybeDeadStores[SSorRMId] = NULL;
2201 Spills.addAvailable(SSorRMId, PhysReg);
2202 // Assumes this is the last use. IsKill will be unset if reg is reused
2203 // unless it's a two-address operand.
2204 if (!MI.isRegTiedToDefOperand(i) &&
2205 KilledMIRegs.count(VirtReg) == 0) {
2206 MI.getOperand(i).setIsKill();
2207 KilledMIRegs.insert(VirtReg);
2210 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2211 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2213 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2214 MI.getOperand(i).setReg(RReg);
2215 MI.getOperand(i).setSubReg(0);
2218 // Ok - now we can remove stores that have been confirmed dead.
2219 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2220 // This was the last use and the spilled value is still available
2221 // for reuse. That means the spill was unnecessary!
2222 int PDSSlot = PotentialDeadStoreSlots[j];
2223 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2225 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2226 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2227 VRM->RemoveMachineInstrFromMaps(DeadStore);
2228 MBB->erase(DeadStore);
2229 MaybeDeadStores[PDSSlot] = NULL;
2235 DEBUG(dbgs() << '\t' << MI);
2238 // If we have folded references to memory operands, make sure we clear all
2239 // physical registers that may contain the value of the spilled virtual
2241 SmallSet<int, 2> FoldedSS;
2242 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
2243 unsigned VirtReg = I->second.first;
2244 VirtRegMap::ModRef MR = I->second.second;
2245 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2247 // MI2VirtMap be can updated which invalidate the iterator.
2248 // Increment the iterator first.
2250 int SS = VRM->getStackSlot(VirtReg);
2251 if (SS == VirtRegMap::NO_STACK_SLOT)
2253 FoldedSS.insert(SS);
2254 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2256 // If this folded instruction is just a use, check to see if it's a
2257 // straight load from the virt reg slot.
2258 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2260 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2261 if (DestReg && FrameIdx == SS) {
2262 // If this spill slot is available, turn it into a copy (or nothing)
2263 // instead of leaving it as a load!
2264 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2265 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2266 if (DestReg != InReg) {
2267 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2268 TII->copyRegToReg(*MBB, &MI, DestReg, InReg, RC, RC,
2270 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2271 unsigned SubIdx = DefMO->getSubReg();
2272 // Revisit the copy so we make sure to notice the effects of the
2273 // operation on the destreg (either needing to RA it if it's
2274 // virtual or needing to clobber any values if it's physical).
2276 --NextMII; // backtrack to the copy.
2277 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2278 // Propagate the sub-register index over.
2280 DefMO = NextMII->findRegisterDefOperand(DestReg);
2281 DefMO->setSubReg(SubIdx);
2285 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2286 KillOpnd->setIsKill();
2290 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2291 // Unset last kill since it's being reused.
2292 InvalidateKill(InReg, TRI, RegKills, KillOps);
2293 Spills.disallowClobberPhysReg(InReg);
2296 InvalidateKills(MI, TRI, RegKills, KillOps);
2297 VRM->RemoveMachineInstrFromMaps(&MI);
2300 goto ProcessNextInst;
2303 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2304 SmallVector<MachineInstr*, 4> NewMIs;
2306 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2307 MBB->insert(MII, NewMIs[0]);
2308 InvalidateKills(MI, TRI, RegKills, KillOps);
2309 VRM->RemoveMachineInstrFromMaps(&MI);
2312 --NextMII; // backtrack to the unfolded instruction.
2314 goto ProcessNextInst;
2319 // If this reference is not a use, any previous store is now dead.
2320 // Otherwise, the store to this stack slot is not dead anymore.
2321 MachineInstr* DeadStore = MaybeDeadStores[SS];
2323 bool isDead = !(MR & VirtRegMap::isRef);
2324 MachineInstr *NewStore = NULL;
2325 if (MR & VirtRegMap::isModRef) {
2326 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2327 SmallVector<MachineInstr*, 4> NewMIs;
2328 // We can reuse this physreg as long as we are allowed to clobber
2329 // the value and there isn't an earlier def that has already clobbered
2332 !ReusedOperands.isClobbered(PhysReg) &&
2333 Spills.canClobberPhysReg(PhysReg) &&
2334 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2335 MachineOperand *KillOpnd =
2336 DeadStore->findRegisterUseOperand(PhysReg, true);
2337 // Note, if the store is storing a sub-register, it's possible the
2338 // super-register is needed below.
2339 if (KillOpnd && !KillOpnd->getSubReg() &&
2340 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2341 MBB->insert(MII, NewMIs[0]);
2342 NewStore = NewMIs[1];
2343 MBB->insert(MII, NewStore);
2344 VRM->addSpillSlotUse(SS, NewStore);
2345 InvalidateKills(MI, TRI, RegKills, KillOps);
2346 VRM->RemoveMachineInstrFromMaps(&MI);
2350 --NextMII; // backtrack to the unfolded instruction.
2358 if (isDead) { // Previous store is dead.
2359 // If we get here, the store is dead, nuke it now.
2360 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2361 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2362 VRM->RemoveMachineInstrFromMaps(DeadStore);
2363 MBB->erase(DeadStore);
2368 MaybeDeadStores[SS] = NULL;
2370 // Treat this store as a spill merged into a copy. That makes the
2371 // stack slot value available.
2372 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2373 goto ProcessNextInst;
2377 // If the spill slot value is available, and this is a new definition of
2378 // the value, the value is not available anymore.
2379 if (MR & VirtRegMap::isMod) {
2380 // Notice that the value in this stack slot has been modified.
2381 Spills.ModifyStackSlotOrReMat(SS);
2383 // If this is *just* a mod of the value, check to see if this is just a
2384 // store to the spill slot (i.e. the spill got merged into the copy). If
2385 // so, realize that the vreg is available now, and add the store to the
2386 // MaybeDeadStore info.
2388 if (!(MR & VirtRegMap::isRef)) {
2389 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2390 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2391 "Src hasn't been allocated yet?");
2393 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2394 Spills, RegKills, KillOps, TRI)) {
2395 NextMII = llvm::next(MII);
2397 goto ProcessNextInst;
2400 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2401 // this as a potentially dead store in case there is a subsequent
2402 // store into the stack slot without a read from it.
2403 MaybeDeadStores[StackSlot] = &MI;
2405 // If the stack slot value was previously available in some other
2406 // register, change it now. Otherwise, make the register
2407 // available in PhysReg.
2408 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2414 // Process all of the spilled defs.
2415 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2416 MachineOperand &MO = MI.getOperand(i);
2417 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2420 unsigned VirtReg = MO.getReg();
2421 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2422 // Check to see if this is a noop copy. If so, eliminate the
2423 // instruction before considering the dest reg to be changed.
2424 // Also check if it's copying from an "undef", if so, we can't
2425 // eliminate this or else the undef marker is lost and it will
2426 // confuses the scavenger. This is extremely rare.
2427 unsigned Src, Dst, SrcSR, DstSR;
2428 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) &&
2429 Src == Dst && SrcSR == DstSR &&
2430 !MI.findRegisterUseOperand(Src)->isUndef()) {
2432 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2433 SmallVector<unsigned, 2> KillRegs;
2434 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2435 if (MO.isDead() && !KillRegs.empty()) {
2436 // Source register or an implicit super/sub-register use is killed.
2437 assert(KillRegs[0] == Dst ||
2438 TRI->isSubRegister(KillRegs[0], Dst) ||
2439 TRI->isSuperRegister(KillRegs[0], Dst));
2440 // Last def is now dead.
2441 TransferDeadness(Src, RegKills, KillOps);
2443 VRM->RemoveMachineInstrFromMaps(&MI);
2446 Spills.disallowClobberPhysReg(VirtReg);
2447 goto ProcessNextInst;
2450 // If it's not a no-op copy, it clobbers the value in the destreg.
2451 Spills.ClobberPhysReg(VirtReg);
2452 ReusedOperands.markClobbered(VirtReg);
2454 // Check to see if this instruction is a load from a stack slot into
2455 // a register. If so, this provides the stack slot value in the reg.
2457 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2458 assert(DestReg == VirtReg && "Unknown load situation!");
2460 // If it is a folded reference, then it's not safe to clobber.
2461 bool Folded = FoldedSS.count(FrameIdx);
2462 // Otherwise, if it wasn't available, remember that it is now!
2463 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2464 goto ProcessNextInst;
2470 unsigned SubIdx = MO.getSubReg();
2471 bool DoReMat = VRM->isReMaterialized(VirtReg);
2473 ReMatDefs.insert(&MI);
2475 // The only vregs left are stack slot definitions.
2476 int StackSlot = VRM->getStackSlot(VirtReg);
2477 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2479 // If this def is part of a two-address operand, make sure to execute
2480 // the store from the correct physical register.
2483 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2484 PhysReg = MI.getOperand(TiedOp).getReg();
2486 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2487 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2488 "Can't find corresponding super-register!");
2492 PhysReg = VRM->getPhys(VirtReg);
2493 if (ReusedOperands.isClobbered(PhysReg)) {
2494 // Another def has taken the assigned physreg. It must have been a
2495 // use&def which got it due to reuse. Undo the reuse!
2496 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2497 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2501 assert(PhysReg && "VR not assigned a physical register?");
2502 MRI->setPhysRegUsed(PhysReg);
2503 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2504 ReusedOperands.markClobbered(RReg);
2505 MI.getOperand(i).setReg(RReg);
2506 MI.getOperand(i).setSubReg(0);
2509 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2510 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2511 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2512 NextMII = llvm::next(MII);
2514 // Check to see if this is a noop copy. If so, eliminate the
2515 // instruction before considering the dest reg to be changed.
2517 unsigned Src, Dst, SrcSR, DstSR;
2518 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) &&
2519 Src == Dst && SrcSR == DstSR) {
2521 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2522 InvalidateKills(MI, TRI, RegKills, KillOps);
2523 VRM->RemoveMachineInstrFromMaps(&MI);
2526 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2527 goto ProcessNextInst;
2533 // Delete dead instructions without side effects.
2534 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2535 InvalidateKills(MI, TRI, RegKills, KillOps);
2536 VRM->RemoveMachineInstrFromMaps(&MI);
2541 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2542 if (!Erased && !BackTracked) {
2543 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2544 UpdateKills(*II, TRI, RegKills, KillOps);
2551 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2552 switch (RewriterOpt) {
2553 default: llvm_unreachable("Unreachable!");
2555 return new LocalRewriter();
2557 return new TrivialRewriter();