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/Function.h"
13 #include "llvm/CodeGen/MachineFrameInfo.h"
14 #include "llvm/CodeGen/MachineInstrBuilder.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/Statistic.h"
27 STATISTIC(NumDSE , "Number of dead stores elided");
28 STATISTIC(NumDSS , "Number of dead spill slots removed");
29 STATISTIC(NumCommutes, "Number of instructions commuted");
30 STATISTIC(NumDRM , "Number of re-materializable defs elided");
31 STATISTIC(NumStores , "Number of stores added");
32 STATISTIC(NumPSpills , "Number of physical register spills");
33 STATISTIC(NumOmitted , "Number of reloads omited");
34 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
35 STATISTIC(NumCopified, "Number of available reloads turned into copies");
36 STATISTIC(NumReMats , "Number of re-materialization");
37 STATISTIC(NumLoads , "Number of loads added");
38 STATISTIC(NumReused , "Number of values reused");
39 STATISTIC(NumDCE , "Number of copies elided");
40 STATISTIC(NumSUnfold , "Number of stores unfolded");
41 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
44 enum RewriterName { local, trivial };
47 static cl::opt<RewriterName>
48 RewriterOpt("rewriter",
49 cl::desc("Rewriter to use (default=local)"),
51 cl::values(clEnumVal(local, "local rewriter"),
52 clEnumVal(trivial, "trivial rewriter"),
57 ScheduleSpills("schedule-spills",
58 cl::desc("Schedule spill code"),
61 VirtRegRewriter::~VirtRegRewriter() {}
63 /// substitutePhysReg - Replace virtual register in MachineOperand with a
64 /// physical register. Do the right thing with the sub-register index.
65 /// Note that operands may be added, so the MO reference is no longer valid.
66 static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
67 const TargetRegisterInfo &TRI) {
68 if (unsigned SubIdx = MO.getSubReg()) {
69 // Insert the physical subreg and reset the subreg field.
70 MO.setReg(TRI.getSubReg(Reg, SubIdx));
73 // Any def, dead, and kill flags apply to the full virtual register, so they
74 // also apply to the full physical register. Add imp-def/dead and imp-kill
76 MachineInstr &MI = *MO.getParent();
79 MI.addRegisterDead(Reg, &TRI, /*AddIfNotFound=*/ true);
81 MI.addRegisterDefined(Reg, &TRI);
82 else if (!MO.isUndef() &&
84 MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
85 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
93 /// This class is intended for use with the new spilling framework only. It
94 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
96 struct TrivialRewriter : public VirtRegRewriter {
98 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
100 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
101 DEBUG(dbgs() << "********** Function: "
102 << MF.getFunction()->getName() << '\n');
103 DEBUG(dbgs() << "**** Machine Instrs"
104 << "(NOTE! Does not include spills and reloads!) ****\n");
107 MachineRegisterInfo *mri = &MF.getRegInfo();
108 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
110 bool changed = false;
112 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
113 liItr != liEnd; ++liItr) {
115 const LiveInterval *li = liItr->second;
116 unsigned reg = li->reg;
118 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
120 mri->setPhysRegUsed(reg);
123 if (!VRM.hasPhys(reg))
125 unsigned pReg = VRM.getPhys(reg);
126 mri->setPhysRegUsed(pReg);
127 // Copy the register use-list before traversing it.
128 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
129 for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
130 E = mri->reg_end(); I != E; ++I)
131 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
132 for (unsigned N=0; N != reglist.size(); ++N)
133 substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
135 changed |= !reglist.empty();
139 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
149 // ************************************************************************ //
153 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
154 /// from top down, keep track of which spill slots or remat are available in
157 /// Note that not all physregs are created equal here. In particular, some
158 /// physregs are reloads that we are allowed to clobber or ignore at any time.
159 /// Other physregs are values that the register allocated program is using
160 /// that we cannot CHANGE, but we can read if we like. We keep track of this
161 /// on a per-stack-slot / remat id basis as the low bit in the value of the
162 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
163 /// this bit and addAvailable sets it if.
164 class AvailableSpills {
165 const TargetRegisterInfo *TRI;
166 const TargetInstrInfo *TII;
168 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
169 // or remat'ed virtual register values that are still available, due to
170 // being loaded or stored to, but not invalidated yet.
171 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
173 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
174 // indicating which stack slot values are currently held by a physreg. This
175 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
176 // physreg is modified.
177 std::multimap<unsigned, int> PhysRegsAvailable;
179 void disallowClobberPhysRegOnly(unsigned PhysReg);
181 void ClobberPhysRegOnly(unsigned PhysReg);
183 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
184 : TRI(tri), TII(tii) {
187 /// clear - Reset the state.
189 SpillSlotsOrReMatsAvailable.clear();
190 PhysRegsAvailable.clear();
193 const TargetRegisterInfo *getRegInfo() const { return TRI; }
195 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
196 /// available in a physical register, return that PhysReg, otherwise
198 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
199 std::map<int, unsigned>::const_iterator I =
200 SpillSlotsOrReMatsAvailable.find(Slot);
201 if (I != SpillSlotsOrReMatsAvailable.end()) {
202 return I->second >> 1; // Remove the CanClobber bit.
207 /// addAvailable - Mark that the specified stack slot / remat is available
208 /// in the specified physreg. If CanClobber is true, the physreg can be
209 /// modified at any time without changing the semantics of the program.
210 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
211 // If this stack slot is thought to be available in some other physreg,
212 // remove its record.
213 ModifyStackSlotOrReMat(SlotOrReMat);
215 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
216 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
217 (unsigned)CanClobber;
219 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
220 DEBUG(dbgs() << "Remembering RM#"
221 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
223 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
224 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
227 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
228 /// the value of the specified stackslot register if it desires. The
229 /// specified stack slot must be available in a physreg for this query to
231 bool canClobberPhysRegForSS(int SlotOrReMat) const {
232 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
233 "Value not available!");
234 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
237 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
238 /// physical register where values for some stack slot(s) might be
240 bool canClobberPhysReg(unsigned PhysReg) const {
241 std::multimap<unsigned, int>::const_iterator I =
242 PhysRegsAvailable.lower_bound(PhysReg);
243 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
244 int SlotOrReMat = I->second;
246 if (!canClobberPhysRegForSS(SlotOrReMat))
252 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
253 /// stackslot register. The register is still available but is no longer
254 /// allowed to be modifed.
255 void disallowClobberPhysReg(unsigned PhysReg);
257 /// ClobberPhysReg - This is called when the specified physreg changes
258 /// value. We use this to invalidate any info about stuff that lives in
259 /// it and any of its aliases.
260 void ClobberPhysReg(unsigned PhysReg);
262 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
263 /// slot changes. This removes information about which register the
264 /// previous value for this slot lives in (as the previous value is dead
266 void ModifyStackSlotOrReMat(int SlotOrReMat);
268 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
269 /// into the specified MBB. Add available physical registers as potential
270 /// live-in's. If they are reused in the MBB, they will be added to the
271 /// live-in set to make register scavenger and post-allocation scheduler.
272 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
273 std::vector<MachineOperand*> &KillOps);
278 // ************************************************************************ //
280 // Given a location where a reload of a spilled register or a remat of
281 // a constant is to be inserted, attempt to find a safe location to
282 // insert the load at an earlier point in the basic-block, to hide
283 // latency of the load and to avoid address-generation interlock
285 static MachineBasicBlock::iterator
286 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
287 MachineBasicBlock::iterator const Begin,
289 const TargetRegisterInfo *TRI,
292 const TargetInstrInfo *TII,
293 const MachineFunction &MF)
298 // Spill backscheduling is of primary interest to addresses, so
299 // don't do anything if the register isn't in the register class
300 // used for pointers.
302 const TargetLowering *TL = MF.getTarget().getTargetLowering();
304 if (!TL->isTypeLegal(TL->getPointerTy()))
305 // Believe it or not, this is true on PIC16.
308 const TargetRegisterClass *ptrRegClass =
309 TL->getRegClassFor(TL->getPointerTy());
310 if (!ptrRegClass->contains(PhysReg))
313 // Scan upwards through the preceding instructions. If an instruction doesn't
314 // reference the stack slot or the register we're loading, we can
315 // backschedule the reload up past it.
316 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
317 while (NewInsertLoc != Begin) {
318 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
319 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
320 MachineOperand &Op = Prev->getOperand(i);
321 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
324 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
325 Prev->findRegisterDefOperand(PhysReg))
327 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
328 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
329 Prev->findRegisterDefOperand(*Alias))
335 // If we made it to the beginning of the block, turn around and move back
336 // down just past any existing reloads. They're likely to be reloads/remats
337 // for instructions earlier than what our current reload/remat is for, so
338 // they should be scheduled earlier.
339 if (NewInsertLoc == Begin) {
341 while (InsertLoc != NewInsertLoc &&
342 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
343 TII->isTriviallyReMaterializable(NewInsertLoc)))
352 // ReusedOp - For each reused operand, we keep track of a bit of information,
353 // in case we need to rollback upon processing a new operand. See comments
356 // The MachineInstr operand that reused an available value.
359 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
360 unsigned StackSlotOrReMat;
362 // PhysRegReused - The physical register the value was available in.
363 unsigned PhysRegReused;
365 // AssignedPhysReg - The physreg that was assigned for use by the reload.
366 unsigned AssignedPhysReg;
368 // VirtReg - The virtual register itself.
371 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
373 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
374 AssignedPhysReg(apr), VirtReg(vreg) {}
377 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
378 /// is reused instead of reloaded.
381 std::vector<ReusedOp> Reuses;
382 BitVector PhysRegsClobbered;
384 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
385 PhysRegsClobbered.resize(tri->getNumRegs());
388 bool hasReuses() const {
389 return !Reuses.empty();
392 /// addReuse - If we choose to reuse a virtual register that is already
393 /// available instead of reloading it, remember that we did so.
394 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
395 unsigned PhysRegReused, unsigned AssignedPhysReg,
397 // If the reload is to the assigned register anyway, no undo will be
399 if (PhysRegReused == AssignedPhysReg) return;
401 // Otherwise, remember this.
402 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
403 AssignedPhysReg, VirtReg));
406 void markClobbered(unsigned PhysReg) {
407 PhysRegsClobbered.set(PhysReg);
410 bool isClobbered(unsigned PhysReg) const {
411 return PhysRegsClobbered.test(PhysReg);
414 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
415 /// is some other operand that is using the specified register, either pick
416 /// a new register to use, or evict the previous reload and use this reg.
417 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
418 MachineFunction &MF, MachineInstr *MI,
419 AvailableSpills &Spills,
420 std::vector<MachineInstr*> &MaybeDeadStores,
421 SmallSet<unsigned, 8> &Rejected,
423 std::vector<MachineOperand*> &KillOps,
426 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
427 /// 'Rejected' set to remember which registers have been considered and
428 /// rejected for the reload. This avoids infinite looping in case like
431 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
432 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
434 /// sees r1 is taken by t2, tries t2's reload register r0
435 /// sees r0 is taken by t3, tries t3's reload register r1
436 /// sees r1 is taken by t2, tries t2's reload register r0 ...
437 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
438 AvailableSpills &Spills,
439 std::vector<MachineInstr*> &MaybeDeadStores,
441 std::vector<MachineOperand*> &KillOps,
443 SmallSet<unsigned, 8> Rejected;
444 MachineFunction &MF = *MI->getParent()->getParent();
445 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
446 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
447 Rejected, RegKills, KillOps, VRM);
453 // ****************** //
454 // Utility Functions //
455 // ****************** //
457 /// findSinglePredSuccessor - Return via reference a vector of machine basic
458 /// blocks each of which is a successor of the specified BB and has no other
460 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
461 SmallVectorImpl<MachineBasicBlock *> &Succs) {
462 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
463 SE = MBB->succ_end(); SI != SE; ++SI) {
464 MachineBasicBlock *SuccMBB = *SI;
465 if (SuccMBB->pred_size() == 1)
466 Succs.push_back(SuccMBB);
470 /// InvalidateKill - Invalidate register kill information for a specific
471 /// register. This also unsets the kills marker on the last kill operand.
472 static void InvalidateKill(unsigned Reg,
473 const TargetRegisterInfo* TRI,
475 std::vector<MachineOperand*> &KillOps) {
477 KillOps[Reg]->setIsKill(false);
478 // KillOps[Reg] might be a def of a super-register.
479 unsigned KReg = KillOps[Reg]->getReg();
480 KillOps[KReg] = NULL;
481 RegKills.reset(KReg);
482 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
484 KillOps[*SR]->setIsKill(false);
492 /// InvalidateKills - MI is going to be deleted. If any of its operands are
493 /// marked kill, then invalidate the information.
494 static void InvalidateKills(MachineInstr &MI,
495 const TargetRegisterInfo* TRI,
497 std::vector<MachineOperand*> &KillOps,
498 SmallVector<unsigned, 2> *KillRegs = NULL) {
499 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
500 MachineOperand &MO = MI.getOperand(i);
501 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
503 unsigned Reg = MO.getReg();
504 if (TargetRegisterInfo::isVirtualRegister(Reg))
507 KillRegs->push_back(Reg);
508 assert(Reg < KillOps.size());
509 if (KillOps[Reg] == &MO) {
512 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
522 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
523 /// (since its spill instruction is removed), mark it isDead. Also checks if
524 /// the def MI has other definition operands that are not dead. Returns it by
526 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
527 MachineInstr &NewDef, unsigned Reg,
529 const TargetRegisterInfo *TRI) {
530 // Due to remat, it's possible this reg isn't being reused. That is,
531 // the def of this reg (by prev MI) is now dead.
532 MachineInstr *DefMI = I;
533 MachineOperand *DefOp = NULL;
534 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
535 MachineOperand &MO = DefMI->getOperand(i);
536 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
538 if (MO.getReg() == Reg)
540 else if (!MO.isDead())
546 bool FoundUse = false, Done = false;
547 MachineBasicBlock::iterator E = &NewDef;
549 for (; !Done && I != E; ++I) {
550 MachineInstr *NMI = I;
551 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
552 MachineOperand &MO = NMI->getOperand(j);
553 if (!MO.isReg() || MO.getReg() == 0 ||
554 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
558 Done = true; // Stop after scanning all the operands of this MI.
569 /// UpdateKills - Track and update kill info. If a MI reads a register that is
570 /// marked kill, then it must be due to register reuse. Transfer the kill info
572 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
574 std::vector<MachineOperand*> &KillOps) {
575 // These do not affect kill info at all.
576 if (MI.isDebugValue())
578 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
579 MachineOperand &MO = MI.getOperand(i);
580 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
582 unsigned Reg = MO.getReg();
586 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
587 // That can't be right. Register is killed but not re-defined and it's
588 // being reused. Let's fix that.
589 KillOps[Reg]->setIsKill(false);
590 // KillOps[Reg] might be a def of a super-register.
591 unsigned KReg = KillOps[Reg]->getReg();
592 KillOps[KReg] = NULL;
593 RegKills.reset(KReg);
595 // Must be a def of a super-register. Its other sub-regsters are no
596 // longer killed as well.
597 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
602 // Check for subreg kills as well.
608 // = d4 <avoiding reload>
609 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
611 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
612 KillOps[SReg]->setIsKill(false);
613 unsigned KReg = KillOps[SReg]->getReg();
614 KillOps[KReg] = NULL;
615 RegKills.reset(KReg);
617 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
618 KillOps[*SSR] = NULL;
619 RegKills.reset(*SSR);
628 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
635 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
636 const MachineOperand &MO = MI.getOperand(i);
637 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
639 unsigned Reg = MO.getReg();
642 // It also defines (or partially define) aliases.
643 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
647 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
654 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
656 static void ReMaterialize(MachineBasicBlock &MBB,
657 MachineBasicBlock::iterator &MII,
658 unsigned DestReg, unsigned Reg,
659 const TargetInstrInfo *TII,
660 const TargetRegisterInfo *TRI,
662 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
664 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
665 assert(TID.getNumDefs() == 1 &&
666 "Don't know how to remat instructions that define > 1 values!");
668 TII->reMaterialize(MBB, MII, DestReg,
669 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
670 MachineInstr *NewMI = prior(MII);
671 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
672 MachineOperand &MO = NewMI->getOperand(i);
673 if (!MO.isReg() || MO.getReg() == 0)
675 unsigned VirtReg = MO.getReg();
676 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
679 unsigned Phys = VRM.getPhys(VirtReg);
680 assert(Phys && "Virtual register is not assigned a register?");
681 substitutePhysReg(MO, Phys, *TRI);
686 /// findSuperReg - Find the SubReg's super-register of given register class
687 /// where its SubIdx sub-register is SubReg.
688 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
689 unsigned SubIdx, const TargetRegisterInfo *TRI) {
690 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
693 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
699 // ******************************** //
700 // Available Spills Implementation //
701 // ******************************** //
703 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
704 /// stackslot register. The register is still available but is no longer
705 /// allowed to be modifed.
706 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
707 std::multimap<unsigned, int>::iterator I =
708 PhysRegsAvailable.lower_bound(PhysReg);
709 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
710 int SlotOrReMat = I->second;
712 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
713 "Bidirectional map mismatch!");
714 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
715 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
716 << " copied, it is available for use but can no longer be modified\n");
720 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
721 /// stackslot register and its aliases. The register and its aliases may
722 /// still available but is no longer allowed to be modifed.
723 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
724 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
725 disallowClobberPhysRegOnly(*AS);
726 disallowClobberPhysRegOnly(PhysReg);
729 /// ClobberPhysRegOnly - This is called when the specified physreg changes
730 /// value. We use this to invalidate any info about stuff we thing lives in it.
731 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
732 std::multimap<unsigned, int>::iterator I =
733 PhysRegsAvailable.lower_bound(PhysReg);
734 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
735 int SlotOrReMat = I->second;
736 PhysRegsAvailable.erase(I++);
737 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
738 "Bidirectional map mismatch!");
739 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
740 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
741 << " clobbered, invalidating ");
742 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
743 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
745 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
749 /// ClobberPhysReg - This is called when the specified physreg changes
750 /// value. We use this to invalidate any info about stuff we thing lives in
751 /// it and any of its aliases.
752 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
753 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
754 ClobberPhysRegOnly(*AS);
755 ClobberPhysRegOnly(PhysReg);
758 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
759 /// into the specified MBB. Add available physical registers as potential
760 /// live-in's. If they are reused in the MBB, they will be added to the
761 /// live-in set to make register scavenger and post-allocation scheduler.
762 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
764 std::vector<MachineOperand*> &KillOps) {
765 std::set<unsigned> NotAvailable;
766 for (std::multimap<unsigned, int>::iterator
767 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
769 unsigned Reg = I->first;
770 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
771 // FIXME: A temporary workaround. We can't reuse available value if it's
772 // not safe to move the def of the virtual register's class. e.g.
773 // X86::RFP* register classes. Do not add it as a live-in.
774 if (!TII->isSafeToMoveRegClassDefs(RC))
775 // This is no longer available.
776 NotAvailable.insert(Reg);
779 InvalidateKill(Reg, TRI, RegKills, KillOps);
782 // Skip over the same register.
783 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
784 while (NI != E && NI->first == Reg) {
790 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
791 E = NotAvailable.end(); I != E; ++I) {
793 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
795 ClobberPhysReg(*SubRegs);
799 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
800 /// slot changes. This removes information about which register the previous
801 /// value for this slot lives in (as the previous value is dead now).
802 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
803 std::map<int, unsigned>::iterator It =
804 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
805 if (It == SpillSlotsOrReMatsAvailable.end()) return;
806 unsigned Reg = It->second >> 1;
807 SpillSlotsOrReMatsAvailable.erase(It);
809 // This register may hold the value of multiple stack slots, only remove this
810 // stack slot from the set of values the register contains.
811 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
813 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
814 "Map inverse broken!");
815 if (I->second == SlotOrReMat) break;
817 PhysRegsAvailable.erase(I);
820 // ************************** //
821 // Reuse Info Implementation //
822 // ************************** //
824 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
825 /// is some other operand that is using the specified register, either pick
826 /// a new register to use, or evict the previous reload and use this reg.
827 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
830 MachineInstr *MI, AvailableSpills &Spills,
831 std::vector<MachineInstr*> &MaybeDeadStores,
832 SmallSet<unsigned, 8> &Rejected,
834 std::vector<MachineOperand*> &KillOps,
836 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
837 const TargetRegisterInfo *TRI = Spills.getRegInfo();
839 if (Reuses.empty()) return PhysReg; // This is most often empty.
841 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
842 ReusedOp &Op = Reuses[ro];
843 // If we find some other reuse that was supposed to use this register
844 // exactly for its reload, we can change this reload to use ITS reload
845 // register. That is, unless its reload register has already been
846 // considered and subsequently rejected because it has also been reused
847 // by another operand.
848 if (Op.PhysRegReused == PhysReg &&
849 Rejected.count(Op.AssignedPhysReg) == 0 &&
850 RC->contains(Op.AssignedPhysReg)) {
851 // Yup, use the reload register that we didn't use before.
852 unsigned NewReg = Op.AssignedPhysReg;
853 Rejected.insert(PhysReg);
854 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
855 RegKills, KillOps, VRM);
857 // Otherwise, we might also have a problem if a previously reused
858 // value aliases the new register. If so, codegen the previous reload
860 unsigned PRRU = Op.PhysRegReused;
861 if (TRI->regsOverlap(PRRU, PhysReg)) {
862 // Okay, we found out that an alias of a reused register
863 // was used. This isn't good because it means we have
864 // to undo a previous reuse.
865 MachineBasicBlock *MBB = MI->getParent();
866 const TargetRegisterClass *AliasRC =
867 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
869 // Copy Op out of the vector and remove it, we're going to insert an
870 // explicit load for it.
872 Reuses.erase(Reuses.begin()+ro);
874 // MI may be using only a sub-register of PhysRegUsed.
875 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
877 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
878 "A reuse cannot be a virtual register");
879 if (PRRU != RealPhysRegUsed) {
880 // What was the sub-register index?
881 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
883 "Operand physreg is not a sub-register of PhysRegUsed");
886 // Ok, we're going to try to reload the assigned physreg into the
887 // slot that we were supposed to in the first place. However, that
888 // register could hold a reuse. Check to see if it conflicts or
889 // would prefer us to use a different register.
890 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
891 MF, MI, Spills, MaybeDeadStores,
892 Rejected, RegKills, KillOps, VRM);
894 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
895 int SSorRMId = DoReMat
896 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
898 // Back-schedule reloads and remats.
899 MachineBasicBlock::iterator InsertLoc =
900 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
901 DoReMat, SSorRMId, TII, MF);
904 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
907 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
908 NewOp.StackSlotOrReMat, AliasRC);
909 MachineInstr *LoadMI = prior(InsertLoc);
910 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
911 // Any stores to this stack slot are not dead anymore.
912 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
915 Spills.ClobberPhysReg(NewPhysReg);
916 Spills.ClobberPhysReg(NewOp.PhysRegReused);
918 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
919 MI->getOperand(NewOp.Operand).setReg(RReg);
920 MI->getOperand(NewOp.Operand).setSubReg(0);
922 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
923 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
924 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
926 DEBUG(dbgs() << "Reuse undone!\n");
929 // Finally, PhysReg is now available, go ahead and use it.
937 // ************************************************************************ //
939 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
940 /// stack slot mod/ref. It also checks if it's possible to unfold the
941 /// instruction by having it define a specified physical register instead.
942 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
943 const TargetInstrInfo *TII,
944 const TargetRegisterInfo *TRI,
946 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
950 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
951 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
952 unsigned VirtReg = I->second.first;
953 VirtRegMap::ModRef MR = I->second.second;
954 if (MR & VirtRegMap::isModRef)
955 if (VRM.getStackSlot(VirtReg) == SS) {
956 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
963 // Does the instruction uses a register that overlaps the scratch register?
964 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
965 MachineOperand &MO = MI.getOperand(i);
966 if (!MO.isReg() || MO.getReg() == 0)
968 unsigned Reg = MO.getReg();
969 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
970 if (!VRM.hasPhys(Reg))
972 Reg = VRM.getPhys(Reg);
974 if (TRI->regsOverlap(PhysReg, Reg))
980 /// FindFreeRegister - Find a free register of a given register class by looking
981 /// at (at most) the last two machine instructions.
982 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
983 MachineBasicBlock &MBB,
984 const TargetRegisterClass *RC,
985 const TargetRegisterInfo *TRI,
986 BitVector &AllocatableRegs) {
987 BitVector Defs(TRI->getNumRegs());
988 BitVector Uses(TRI->getNumRegs());
989 SmallVector<unsigned, 4> LocalUses;
990 SmallVector<unsigned, 4> Kills;
992 // Take a look at 2 instructions at most.
993 for (unsigned Count = 0; Count < 2; ++Count) {
994 if (MII == MBB.begin())
996 MachineInstr *PrevMI = prior(MII);
997 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
998 MachineOperand &MO = PrevMI->getOperand(i);
999 if (!MO.isReg() || MO.getReg() == 0)
1001 unsigned Reg = MO.getReg();
1004 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1007 LocalUses.push_back(Reg);
1008 if (MO.isKill() && AllocatableRegs[Reg])
1009 Kills.push_back(Reg);
1013 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1014 unsigned Kill = Kills[i];
1015 if (!Defs[Kill] && !Uses[Kill] &&
1016 TRI->getPhysicalRegisterRegClass(Kill) == RC)
1019 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1020 unsigned Reg = LocalUses[i];
1022 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1033 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1034 const TargetRegisterInfo &TRI) {
1035 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1036 MachineOperand &MO = MI->getOperand(i);
1037 if (MO.isReg() && MO.getReg() == VirtReg)
1038 substitutePhysReg(MO, PhysReg, TRI);
1045 bool operator()(const std::pair<MachineInstr*, int> &A,
1046 const std::pair<MachineInstr*, int> &B) {
1047 return A.second < B.second;
1051 // ***************************** //
1052 // Local Spiller Implementation //
1053 // ***************************** //
1055 class LocalRewriter : public VirtRegRewriter {
1056 MachineRegisterInfo *MRI;
1057 const TargetRegisterInfo *TRI;
1058 const TargetInstrInfo *TII;
1060 BitVector AllocatableRegs;
1061 DenseMap<MachineInstr*, unsigned> DistanceMap;
1063 MachineBasicBlock *MBB; // Basic block currently being processed.
1067 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1068 LiveIntervals* LIs);
1072 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1073 MachineBasicBlock::iterator &MII,
1074 std::vector<MachineInstr*> &MaybeDeadStores,
1075 AvailableSpills &Spills,
1076 BitVector &RegKills,
1077 std::vector<MachineOperand*> &KillOps);
1079 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1080 std::vector<MachineInstr*> &MaybeDeadStores,
1081 AvailableSpills &Spills,
1082 BitVector &RegKills,
1083 std::vector<MachineOperand*> &KillOps);
1085 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1086 unsigned VirtReg, unsigned SrcReg, int SS,
1087 AvailableSpills &Spills,
1088 BitVector &RegKills,
1089 std::vector<MachineOperand*> &KillOps,
1090 const TargetRegisterInfo *TRI);
1092 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1093 int Idx, unsigned PhysReg, int StackSlot,
1094 const TargetRegisterClass *RC,
1095 bool isAvailable, MachineInstr *&LastStore,
1096 AvailableSpills &Spills,
1097 SmallSet<MachineInstr*, 4> &ReMatDefs,
1098 BitVector &RegKills,
1099 std::vector<MachineOperand*> &KillOps);
1101 void TransferDeadness(unsigned Reg, BitVector &RegKills,
1102 std::vector<MachineOperand*> &KillOps);
1104 bool InsertEmergencySpills(MachineInstr *MI);
1106 bool InsertRestores(MachineInstr *MI,
1107 AvailableSpills &Spills,
1108 BitVector &RegKills,
1109 std::vector<MachineOperand*> &KillOps);
1111 bool InsertSpills(MachineInstr *MI);
1113 void RewriteMBB(LiveIntervals *LIs,
1114 AvailableSpills &Spills, BitVector &RegKills,
1115 std::vector<MachineOperand*> &KillOps);
1119 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1120 LiveIntervals* LIs) {
1121 MRI = &MF.getRegInfo();
1122 TRI = MF.getTarget().getRegisterInfo();
1123 TII = MF.getTarget().getInstrInfo();
1125 AllocatableRegs = TRI->getAllocatableSet(MF);
1126 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1127 << MF.getFunction()->getName() << "':\n");
1128 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1129 " reloads!) ****\n");
1132 // Spills - Keep track of which spilled values are available in physregs
1133 // so that we can choose to reuse the physregs instead of emitting
1134 // reloads. This is usually refreshed per basic block.
1135 AvailableSpills Spills(TRI, TII);
1137 // Keep track of kill information.
1138 BitVector RegKills(TRI->getNumRegs());
1139 std::vector<MachineOperand*> KillOps;
1140 KillOps.resize(TRI->getNumRegs(), NULL);
1142 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1143 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1144 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1146 // Traverse the basic blocks depth first.
1147 MachineBasicBlock *Entry = MF.begin();
1148 SmallPtrSet<MachineBasicBlock*,16> Visited;
1149 for (df_ext_iterator<MachineBasicBlock*,
1150 SmallPtrSet<MachineBasicBlock*,16> >
1151 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1154 if (!EarlyVisited.count(MBB))
1155 RewriteMBB(LIs, Spills, RegKills, KillOps);
1157 // If this MBB is the only predecessor of a successor. Keep the
1158 // availability information and visit it next.
1160 // Keep visiting single predecessor successor as long as possible.
1161 SinglePredSuccs.clear();
1162 findSinglePredSuccessor(MBB, SinglePredSuccs);
1163 if (SinglePredSuccs.empty())
1166 // FIXME: More than one successors, each of which has MBB has
1167 // the only predecessor.
1168 MBB = SinglePredSuccs[0];
1169 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1170 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1171 RewriteMBB(LIs, Spills, RegKills, KillOps);
1176 // Clear the availability info.
1180 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1183 // Mark unused spill slots.
1184 MachineFrameInfo *MFI = MF.getFrameInfo();
1185 int SS = VRM->getLowSpillSlot();
1186 if (SS != VirtRegMap::NO_STACK_SLOT)
1187 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS)
1188 if (!VRM->isSpillSlotUsed(SS)) {
1189 MFI->RemoveStackObject(SS);
1196 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1197 /// a scratch register is available.
1198 /// xorq %r12<kill>, %r13
1199 /// addq %rax, -184(%rbp)
1200 /// addq %r13, -184(%rbp)
1202 /// xorq %r12<kill>, %r13
1203 /// movq -184(%rbp), %r12
1206 /// movq %r12, -184(%rbp)
1207 bool LocalRewriter::
1208 OptimizeByUnfold2(unsigned VirtReg, int SS,
1209 MachineBasicBlock::iterator &MII,
1210 std::vector<MachineInstr*> &MaybeDeadStores,
1211 AvailableSpills &Spills,
1212 BitVector &RegKills,
1213 std::vector<MachineOperand*> &KillOps) {
1215 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1216 if (NextMII == MBB->end())
1219 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1222 // Now let's see if the last couple of instructions happens to have freed up
1224 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1225 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1229 MachineFunction &MF = *MBB->getParent();
1230 TRI = MF.getTarget().getRegisterInfo();
1231 MachineInstr &MI = *MII;
1232 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1235 // If the next instruction also folds the same SS modref and can be unfoled,
1236 // then it's worthwhile to issue a load from SS into the free register and
1237 // then unfold these instructions.
1238 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1241 // Back-schedule reloads and remats.
1242 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1244 // Load from SS to the spare physical register.
1245 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC);
1246 // This invalidates Phys.
1247 Spills.ClobberPhysReg(PhysReg);
1248 // Remember it's available.
1249 Spills.addAvailable(SS, PhysReg);
1250 MaybeDeadStores[SS] = NULL;
1252 // Unfold current MI.
1253 SmallVector<MachineInstr*, 4> NewMIs;
1254 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1255 llvm_unreachable("Unable unfold the load / store folding instruction!");
1256 assert(NewMIs.size() == 1);
1257 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1258 VRM->transferRestorePts(&MI, NewMIs[0]);
1259 MII = MBB->insert(MII, NewMIs[0]);
1260 InvalidateKills(MI, TRI, RegKills, KillOps);
1261 VRM->RemoveMachineInstrFromMaps(&MI);
1265 // Unfold next instructions that fold the same SS.
1267 MachineInstr &NextMI = *NextMII;
1268 NextMII = llvm::next(NextMII);
1270 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1271 llvm_unreachable("Unable unfold the load / store folding instruction!");
1272 assert(NewMIs.size() == 1);
1273 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1274 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1275 MBB->insert(NextMII, NewMIs[0]);
1276 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1277 VRM->RemoveMachineInstrFromMaps(&NextMI);
1278 MBB->erase(&NextMI);
1280 if (NextMII == MBB->end())
1282 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1284 // Store the value back into SS.
1285 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC);
1286 MachineInstr *StoreMI = prior(NextMII);
1287 VRM->addSpillSlotUse(SS, StoreMI);
1288 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1293 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1294 /// instruction. e.g.
1296 /// movl %eax, -32(%ebp)
1297 /// movl -36(%ebp), %eax
1298 /// orl %eax, -32(%ebp)
1301 /// orl -36(%ebp), %eax
1302 /// mov %eax, -32(%ebp)
1303 /// This enables unfolding optimization for a subsequent instruction which will
1304 /// also eliminate the newly introduced store instruction.
1305 bool LocalRewriter::
1306 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1307 std::vector<MachineInstr*> &MaybeDeadStores,
1308 AvailableSpills &Spills,
1309 BitVector &RegKills,
1310 std::vector<MachineOperand*> &KillOps) {
1311 MachineFunction &MF = *MBB->getParent();
1312 MachineInstr &MI = *MII;
1313 unsigned UnfoldedOpc = 0;
1314 unsigned UnfoldPR = 0;
1315 unsigned UnfoldVR = 0;
1316 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1317 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1318 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1319 // Only transform a MI that folds a single register.
1322 UnfoldVR = I->second.first;
1323 VirtRegMap::ModRef MR = I->second.second;
1324 // MI2VirtMap be can updated which invalidate the iterator.
1325 // Increment the iterator first.
1327 if (VRM->isAssignedReg(UnfoldVR))
1329 // If this reference is not a use, any previous store is now dead.
1330 // Otherwise, the store to this stack slot is not dead anymore.
1331 FoldedSS = VRM->getStackSlot(UnfoldVR);
1332 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1333 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1334 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1335 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1338 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1347 // Look for other unfolding opportunities.
1348 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1352 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1353 MachineOperand &MO = MI.getOperand(i);
1354 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1356 unsigned VirtReg = MO.getReg();
1357 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1359 if (VRM->isAssignedReg(VirtReg)) {
1360 unsigned PhysReg = VRM->getPhys(VirtReg);
1361 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1363 } else if (VRM->isReMaterialized(VirtReg))
1365 int SS = VRM->getStackSlot(VirtReg);
1366 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1368 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1372 if (VRM->hasPhys(VirtReg)) {
1373 PhysReg = VRM->getPhys(VirtReg);
1374 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1378 // Ok, we'll need to reload the value into a register which makes
1379 // it impossible to perform the store unfolding optimization later.
1380 // Let's see if it is possible to fold the load if the store is
1381 // unfolded. This allows us to perform the store unfolding
1383 SmallVector<MachineInstr*, 4> NewMIs;
1384 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1385 assert(NewMIs.size() == 1);
1386 MachineInstr *NewMI = NewMIs.back();
1388 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1390 SmallVector<unsigned, 1> Ops;
1392 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1394 VRM->addSpillSlotUse(SS, FoldedMI);
1395 if (!VRM->hasPhys(UnfoldVR))
1396 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1397 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1398 MII = MBB->insert(MII, FoldedMI);
1399 InvalidateKills(MI, TRI, RegKills, KillOps);
1400 VRM->RemoveMachineInstrFromMaps(&MI);
1402 MF.DeleteMachineInstr(NewMI);
1405 MF.DeleteMachineInstr(NewMI);
1412 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1413 /// where SrcReg is r1 and it is tied to r0. Return true if after
1414 /// commuting this instruction it will be r0 = op r2, r1.
1415 static bool CommuteChangesDestination(MachineInstr *DefMI,
1416 const TargetInstrDesc &TID,
1418 const TargetInstrInfo *TII,
1420 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1422 if (!DefMI->getOperand(1).isReg() ||
1423 DefMI->getOperand(1).getReg() != SrcReg)
1426 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1428 unsigned SrcIdx1, SrcIdx2;
1429 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1431 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1438 /// CommuteToFoldReload -
1441 /// r1 = op r1, r2<kill>
1444 /// If op is commutable and r2 is killed, then we can xform these to
1445 /// r2 = op r2, fi#1
1447 bool LocalRewriter::
1448 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1449 unsigned VirtReg, unsigned SrcReg, int SS,
1450 AvailableSpills &Spills,
1451 BitVector &RegKills,
1452 std::vector<MachineOperand*> &KillOps,
1453 const TargetRegisterInfo *TRI) {
1454 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1457 MachineFunction &MF = *MBB->getParent();
1458 MachineInstr &MI = *MII;
1459 MachineBasicBlock::iterator DefMII = prior(MII);
1460 MachineInstr *DefMI = DefMII;
1461 const TargetInstrDesc &TID = DefMI->getDesc();
1463 if (DefMII != MBB->begin() &&
1464 TID.isCommutable() &&
1465 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1466 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1467 unsigned NewReg = NewDstMO.getReg();
1468 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1470 MachineInstr *ReloadMI = prior(DefMII);
1472 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1473 if (DestReg != SrcReg || FrameIdx != SS)
1475 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1479 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1481 assert(DefMI->getOperand(DefIdx).isReg() &&
1482 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1484 // Now commute def instruction.
1485 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1488 SmallVector<unsigned, 1> Ops;
1489 Ops.push_back(NewDstIdx);
1490 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1491 // Not needed since foldMemoryOperand returns new MI.
1492 MF.DeleteMachineInstr(CommutedMI);
1496 VRM->addSpillSlotUse(SS, FoldedMI);
1497 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1498 // Insert new def MI and spill MI.
1499 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1500 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC);
1502 MachineInstr *StoreMI = MII;
1503 VRM->addSpillSlotUse(SS, StoreMI);
1504 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1505 MII = MBB->insert(MII, FoldedMI); // Update MII to backtrack.
1507 // Delete all 3 old instructions.
1508 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1509 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1510 MBB->erase(ReloadMI);
1511 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1512 VRM->RemoveMachineInstrFromMaps(DefMI);
1514 InvalidateKills(MI, TRI, RegKills, KillOps);
1515 VRM->RemoveMachineInstrFromMaps(&MI);
1518 // If NewReg was previously holding value of some SS, it's now clobbered.
1519 // This has to be done now because it's a physical register. When this
1520 // instruction is re-visited, it's ignored.
1521 Spills.ClobberPhysReg(NewReg);
1530 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1531 /// the last store to the same slot is now dead. If so, remove the last store.
1532 void LocalRewriter::
1533 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1534 int Idx, unsigned PhysReg, int StackSlot,
1535 const TargetRegisterClass *RC,
1536 bool isAvailable, MachineInstr *&LastStore,
1537 AvailableSpills &Spills,
1538 SmallSet<MachineInstr*, 4> &ReMatDefs,
1539 BitVector &RegKills,
1540 std::vector<MachineOperand*> &KillOps) {
1542 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1543 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC);
1544 MachineInstr *StoreMI = prior(oldNextMII);
1545 VRM->addSpillSlotUse(StackSlot, StoreMI);
1546 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1548 // If there is a dead store to this stack slot, nuke it now.
1550 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1552 SmallVector<unsigned, 2> KillRegs;
1553 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1554 MachineBasicBlock::iterator PrevMII = LastStore;
1555 bool CheckDef = PrevMII != MBB->begin();
1558 VRM->RemoveMachineInstrFromMaps(LastStore);
1559 MBB->erase(LastStore);
1561 // Look at defs of killed registers on the store. Mark the defs
1562 // as dead since the store has been deleted and they aren't
1564 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1565 bool HasOtherDef = false;
1566 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1567 MachineInstr *DeadDef = PrevMII;
1568 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1569 // FIXME: This assumes a remat def does not have side effects.
1570 VRM->RemoveMachineInstrFromMaps(DeadDef);
1571 MBB->erase(DeadDef);
1579 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1580 // the last of multiple instructions is the actual store.
1581 LastStore = prior(oldNextMII);
1583 // If the stack slot value was previously available in some other
1584 // register, change it now. Otherwise, make the register available,
1586 Spills.ModifyStackSlotOrReMat(StackSlot);
1587 Spills.ClobberPhysReg(PhysReg);
1588 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1592 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1593 /// effect and all of its defs are dead.
1594 static bool isSafeToDelete(MachineInstr &MI) {
1595 const TargetInstrDesc &TID = MI.getDesc();
1596 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1597 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1598 TID.hasUnmodeledSideEffects())
1600 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1601 MachineOperand &MO = MI.getOperand(i);
1602 if (!MO.isReg() || !MO.getReg())
1604 if (MO.isDef() && !MO.isDead())
1606 if (MO.isUse() && MO.isKill())
1607 // FIXME: We can't remove kill markers or else the scavenger will assert.
1608 // An alternative is to add a ADD pseudo instruction to replace kill
1615 /// TransferDeadness - A identity copy definition is dead and it's being
1616 /// removed. Find the last def or use and mark it as dead / kill.
1617 void LocalRewriter::
1618 TransferDeadness(unsigned Reg, BitVector &RegKills,
1619 std::vector<MachineOperand*> &KillOps) {
1620 SmallPtrSet<MachineInstr*, 4> Seens;
1621 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1622 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1623 RE = MRI->reg_end(); RI != RE; ++RI) {
1624 MachineInstr *UDMI = &*RI;
1625 if (UDMI->getParent() != MBB)
1627 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1628 if (DI == DistanceMap.end())
1630 if (Seens.insert(UDMI))
1631 Refs.push_back(std::make_pair(UDMI, DI->second));
1636 std::sort(Refs.begin(), Refs.end(), RefSorter());
1638 while (!Refs.empty()) {
1639 MachineInstr *LastUDMI = Refs.back().first;
1642 MachineOperand *LastUD = NULL;
1643 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1644 MachineOperand &MO = LastUDMI->getOperand(i);
1645 if (!MO.isReg() || MO.getReg() != Reg)
1647 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1649 if (LastUDMI->isRegTiedToDefOperand(i))
1652 if (LastUD->isDef()) {
1653 // If the instruction has no side effect, delete it and propagate
1654 // backward further. Otherwise, mark is dead and we are done.
1655 if (!isSafeToDelete(*LastUDMI)) {
1656 LastUD->setIsDead();
1659 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1660 MBB->erase(LastUDMI);
1662 LastUD->setIsKill();
1664 KillOps[Reg] = LastUD;
1670 /// InsertEmergencySpills - Insert emergency spills before MI if requested by
1671 /// VRM. Return true if spills were inserted.
1672 bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1673 if (!VRM->hasEmergencySpills(MI))
1675 MachineBasicBlock::iterator MII = MI;
1676 SmallSet<int, 4> UsedSS;
1677 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1678 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1679 unsigned PhysReg = EmSpills[i];
1680 const TargetRegisterClass *RC = TRI->getPhysicalRegisterRegClass(PhysReg);
1681 assert(RC && "Unable to determine register class!");
1682 int SS = VRM->getEmergencySpillSlot(RC);
1683 if (UsedSS.count(SS))
1684 llvm_unreachable("Need to spill more than one physical registers!");
1686 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC);
1687 MachineInstr *StoreMI = prior(MII);
1688 VRM->addSpillSlotUse(SS, StoreMI);
1690 // Back-schedule reloads and remats.
1691 MachineBasicBlock::iterator InsertLoc =
1692 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1693 TII, *MBB->getParent());
1695 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC);
1697 MachineInstr *LoadMI = prior(InsertLoc);
1698 VRM->addSpillSlotUse(SS, LoadMI);
1700 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1705 /// InsertRestores - Restore registers before MI is requested by VRM. Return
1706 /// true is any instructions were inserted.
1707 bool LocalRewriter::InsertRestores(MachineInstr *MI,
1708 AvailableSpills &Spills,
1709 BitVector &RegKills,
1710 std::vector<MachineOperand*> &KillOps) {
1711 if (!VRM->isRestorePt(MI))
1713 MachineBasicBlock::iterator MII = MI;
1714 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1715 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1716 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1717 if (!VRM->getPreSplitReg(VirtReg))
1718 continue; // Split interval spilled again.
1719 unsigned Phys = VRM->getPhys(VirtReg);
1720 MRI->setPhysRegUsed(Phys);
1722 // Check if the value being restored if available. If so, it must be
1723 // from a predecessor BB that fallthrough into this BB. We do not
1729 // ... # r1 not clobbered
1732 bool DoReMat = VRM->isReMaterialized(VirtReg);
1733 int SSorRMId = DoReMat
1734 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1735 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1736 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1737 if (InReg == Phys) {
1738 // If the value is already available in the expected register, save
1739 // a reload / remat.
1741 DEBUG(dbgs() << "Reusing RM#"
1742 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1744 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1745 DEBUG(dbgs() << " from physreg "
1746 << TRI->getName(InReg) << " for vreg"
1747 << VirtReg <<" instead of reloading into physreg "
1748 << TRI->getName(Phys) << '\n');
1751 } else if (InReg && InReg != Phys) {
1753 DEBUG(dbgs() << "Reusing RM#"
1754 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1756 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1757 DEBUG(dbgs() << " from physreg "
1758 << TRI->getName(InReg) << " for vreg"
1759 << VirtReg <<" by copying it into physreg "
1760 << TRI->getName(Phys) << '\n');
1762 // If the reloaded / remat value is available in another register,
1763 // copy it to the desired register.
1765 // Back-schedule reloads and remats.
1766 MachineBasicBlock::iterator InsertLoc =
1767 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1770 TII->copyRegToReg(*MBB, InsertLoc, Phys, InReg, RC, RC);
1772 // This invalidates Phys.
1773 Spills.ClobberPhysReg(Phys);
1774 // Remember it's available.
1775 Spills.addAvailable(SSorRMId, Phys);
1778 MachineInstr *CopyMI = prior(InsertLoc);
1779 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1780 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1781 KillOpnd->setIsKill();
1782 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1784 DEBUG(dbgs() << '\t' << *CopyMI);
1789 // Back-schedule reloads and remats.
1790 MachineBasicBlock::iterator InsertLoc =
1791 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1794 if (VRM->isReMaterialized(VirtReg)) {
1795 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1797 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1798 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC);
1799 MachineInstr *LoadMI = prior(InsertLoc);
1800 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1802 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1805 // This invalidates Phys.
1806 Spills.ClobberPhysReg(Phys);
1807 // Remember it's available.
1808 Spills.addAvailable(SSorRMId, Phys);
1810 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1811 DEBUG(dbgs() << '\t' << *prior(MII));
1816 /// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1817 /// true if spills were inserted.
1818 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1819 if (!VRM->isSpillPt(MI))
1821 MachineBasicBlock::iterator MII = MI;
1822 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1823 VRM->getSpillPtSpills(MI);
1824 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1825 unsigned VirtReg = SpillRegs[i].first;
1826 bool isKill = SpillRegs[i].second;
1827 if (!VRM->getPreSplitReg(VirtReg))
1828 continue; // Split interval spilled again.
1829 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1830 unsigned Phys = VRM->getPhys(VirtReg);
1831 int StackSlot = VRM->getStackSlot(VirtReg);
1832 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1833 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1835 MachineInstr *StoreMI = prior(oldNextMII);
1836 VRM->addSpillSlotUse(StackSlot, StoreMI);
1837 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1838 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1844 /// rewriteMBB - Keep track of which spills are available even after the
1845 /// register allocator is done with them. If possible, avid reloading vregs.
1847 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1848 AvailableSpills &Spills, BitVector &RegKills,
1849 std::vector<MachineOperand*> &KillOps) {
1851 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1852 << MBB->getName() << "':\n");
1854 MachineFunction &MF = *MBB->getParent();
1856 // MaybeDeadStores - When we need to write a value back into a stack slot,
1857 // keep track of the inserted store. If the stack slot value is never read
1858 // (because the value was used from some available register, for example), and
1859 // subsequently stored to, the original store is dead. This map keeps track
1860 // of inserted stores that are not used. If we see a subsequent store to the
1861 // same stack slot, the original store is deleted.
1862 std::vector<MachineInstr*> MaybeDeadStores;
1863 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1865 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1866 SmallSet<MachineInstr*, 4> ReMatDefs;
1869 SmallSet<unsigned, 2> KilledMIRegs;
1872 KillOps.resize(TRI->getNumRegs(), NULL);
1874 DistanceMap.clear();
1875 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1877 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1879 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1880 NextMII = llvm::next(MII);
1882 if (InsertEmergencySpills(MII))
1883 NextMII = llvm::next(MII);
1885 InsertRestores(MII, Spills, RegKills, KillOps);
1887 if (InsertSpills(MII))
1888 NextMII = llvm::next(MII);
1890 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1891 bool Erased = false;
1892 bool BackTracked = false;
1893 MachineInstr &MI = *MII;
1895 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1897 ReuseInfo ReusedOperands(MI, TRI);
1898 SmallVector<unsigned, 4> VirtUseOps;
1899 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1900 MachineOperand &MO = MI.getOperand(i);
1901 if (!MO.isReg() || MO.getReg() == 0)
1902 continue; // Ignore non-register operands.
1904 unsigned VirtReg = MO.getReg();
1905 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1906 // Ignore physregs for spilling, but remember that it is used by this
1908 MRI->setPhysRegUsed(VirtReg);
1912 // We want to process implicit virtual register uses first.
1913 if (MO.isImplicit())
1914 // If the virtual register is implicitly defined, emit a implicit_def
1915 // before so scavenger knows it's "defined".
1916 // FIXME: This is a horrible hack done the by register allocator to
1917 // remat a definition with virtual register operand.
1918 VirtUseOps.insert(VirtUseOps.begin(), i);
1920 VirtUseOps.push_back(i);
1923 // Process all of the spilled uses and all non spilled reg references.
1924 SmallVector<int, 2> PotentialDeadStoreSlots;
1925 KilledMIRegs.clear();
1926 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1927 unsigned i = VirtUseOps[j];
1928 unsigned VirtReg = MI.getOperand(i).getReg();
1929 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1930 "Not a virtual register?");
1932 unsigned SubIdx = MI.getOperand(i).getSubReg();
1933 if (VRM->isAssignedReg(VirtReg)) {
1934 // This virtual register was assigned a physreg!
1935 unsigned Phys = VRM->getPhys(VirtReg);
1936 MRI->setPhysRegUsed(Phys);
1937 if (MI.getOperand(i).isDef())
1938 ReusedOperands.markClobbered(Phys);
1939 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1940 if (VRM->isImplicitlyDefined(VirtReg))
1941 // FIXME: Is this needed?
1942 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1943 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1947 // This virtual register is now known to be a spilled value.
1948 if (!MI.getOperand(i).isUse())
1949 continue; // Handle defs in the loop below (handle use&def here though)
1951 bool AvoidReload = MI.getOperand(i).isUndef();
1952 // Check if it is defined by an implicit def. It should not be spilled.
1953 // Note, this is for correctness reason. e.g.
1954 // 8 %reg1024<def> = IMPLICIT_DEF
1955 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1956 // The live range [12, 14) are not part of the r1024 live interval since
1957 // it's defined by an implicit def. It will not conflicts with live
1958 // interval of r1025. Now suppose both registers are spilled, you can
1959 // easily see a situation where both registers are reloaded before
1960 // the INSERT_SUBREG and both target registers that would overlap.
1961 bool DoReMat = VRM->isReMaterialized(VirtReg);
1962 int SSorRMId = DoReMat
1963 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1964 int ReuseSlot = SSorRMId;
1966 // Check to see if this stack slot is available.
1967 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1969 // If this is a sub-register use, make sure the reuse register is in the
1970 // right register class. For example, for x86 not all of the 32-bit
1971 // registers have accessible sub-registers.
1972 // Similarly so for EXTRACT_SUBREG. Consider this:
1974 // MOV32_mr fi#1, EDI
1976 // = EXTRACT_SUBREG fi#1
1977 // fi#1 is available in EDI, but it cannot be reused because it's not in
1978 // the right register file.
1979 if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
1980 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1981 if (!RC->contains(PhysReg))
1985 if (PhysReg && !AvoidReload) {
1986 // This spilled operand might be part of a two-address operand. If this
1987 // is the case, then changing it will necessarily require changing the
1988 // def part of the instruction as well. However, in some cases, we
1989 // aren't allowed to modify the reused register. If none of these cases
1991 bool CanReuse = true;
1992 bool isTied = MI.isRegTiedToDefOperand(i);
1994 // Okay, we have a two address operand. We can reuse this physreg as
1995 // long as we are allowed to clobber the value and there isn't an
1996 // earlier def that has already clobbered the physreg.
1997 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1998 Spills.canClobberPhysReg(PhysReg);
2002 // If this stack slot value is already available, reuse it!
2003 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2004 DEBUG(dbgs() << "Reusing RM#"
2005 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2007 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2008 DEBUG(dbgs() << " from physreg "
2009 << TRI->getName(PhysReg) << " for vreg"
2010 << VirtReg <<" instead of reloading into physreg "
2011 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2012 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2013 MI.getOperand(i).setReg(RReg);
2014 MI.getOperand(i).setSubReg(0);
2016 // The only technical detail we have is that we don't know that
2017 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2018 // later in the instruction. In particular, consider 'op V1, V2'.
2019 // If V1 is available in physreg R0, we would choose to reuse it
2020 // here, instead of reloading it into the register the allocator
2021 // indicated (say R1). However, V2 might have to be reloaded
2022 // later, and it might indicate that it needs to live in R0. When
2023 // this occurs, we need to have information available that
2024 // indicates it is safe to use R1 for the reload instead of R0.
2026 // To further complicate matters, we might conflict with an alias,
2027 // or R0 and R1 might not be compatible with each other. In this
2028 // case, we actually insert a reload for V1 in R1, ensuring that
2029 // we can get at R0 or its alias.
2030 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2031 VRM->getPhys(VirtReg), VirtReg);
2033 // Only mark it clobbered if this is a use&def operand.
2034 ReusedOperands.markClobbered(PhysReg);
2037 if (MI.getOperand(i).isKill() &&
2038 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2040 // The store of this spilled value is potentially dead, but we
2041 // won't know for certain until we've confirmed that the re-use
2042 // above is valid, which means waiting until the other operands
2043 // are processed. For now we just track the spill slot, we'll
2044 // remove it after the other operands are processed if valid.
2046 PotentialDeadStoreSlots.push_back(ReuseSlot);
2049 // Mark is isKill if it's there no other uses of the same virtual
2050 // register and it's not a two-address operand. IsKill will be
2051 // unset if reg is reused.
2052 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2053 MI.getOperand(i).setIsKill();
2054 KilledMIRegs.insert(VirtReg);
2060 // Otherwise we have a situation where we have a two-address instruction
2061 // whose mod/ref operand needs to be reloaded. This reload is already
2062 // available in some register "PhysReg", but if we used PhysReg as the
2063 // operand to our 2-addr instruction, the instruction would modify
2064 // PhysReg. This isn't cool if something later uses PhysReg and expects
2065 // to get its initial value.
2067 // To avoid this problem, and to avoid doing a load right after a store,
2068 // we emit a copy from PhysReg into the designated register for this
2070 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2071 assert(DesignatedReg && "Must map virtreg to physreg!");
2073 // Note that, if we reused a register for a previous operand, the
2074 // register we want to reload into might not actually be
2075 // available. If this occurs, use the register indicated by the
2077 if (ReusedOperands.hasReuses())
2078 DesignatedReg = ReusedOperands.
2079 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2080 MaybeDeadStores, RegKills, KillOps, *VRM);
2082 // If the mapped designated register is actually the physreg we have
2083 // incoming, we don't need to inserted a dead copy.
2084 if (DesignatedReg == PhysReg) {
2085 // If this stack slot value is already available, reuse it!
2086 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2087 DEBUG(dbgs() << "Reusing RM#"
2088 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2090 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2091 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2092 << " for vreg" << VirtReg
2093 << " instead of reloading into same physreg.\n");
2094 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2095 MI.getOperand(i).setReg(RReg);
2096 MI.getOperand(i).setSubReg(0);
2097 ReusedOperands.markClobbered(RReg);
2102 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2103 MRI->setPhysRegUsed(DesignatedReg);
2104 ReusedOperands.markClobbered(DesignatedReg);
2106 // Back-schedule reloads and remats.
2107 MachineBasicBlock::iterator InsertLoc =
2108 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2111 TII->copyRegToReg(*MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2113 MachineInstr *CopyMI = prior(InsertLoc);
2114 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2115 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2117 // This invalidates DesignatedReg.
2118 Spills.ClobberPhysReg(DesignatedReg);
2120 Spills.addAvailable(ReuseSlot, DesignatedReg);
2122 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2123 MI.getOperand(i).setReg(RReg);
2124 MI.getOperand(i).setSubReg(0);
2125 DEBUG(dbgs() << '\t' << *prior(MII));
2130 // Otherwise, reload it and remember that we have it.
2131 PhysReg = VRM->getPhys(VirtReg);
2132 assert(PhysReg && "Must map virtreg to physreg!");
2134 // Note that, if we reused a register for a previous operand, the
2135 // register we want to reload into might not actually be
2136 // available. If this occurs, use the register indicated by the
2138 if (ReusedOperands.hasReuses())
2139 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2140 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2142 MRI->setPhysRegUsed(PhysReg);
2143 ReusedOperands.markClobbered(PhysReg);
2147 // Back-schedule reloads and remats.
2148 MachineBasicBlock::iterator InsertLoc =
2149 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2153 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2155 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2156 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC);
2157 MachineInstr *LoadMI = prior(InsertLoc);
2158 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2160 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2162 // This invalidates PhysReg.
2163 Spills.ClobberPhysReg(PhysReg);
2165 // Any stores to this stack slot are not dead anymore.
2167 MaybeDeadStores[SSorRMId] = NULL;
2168 Spills.addAvailable(SSorRMId, PhysReg);
2169 // Assumes this is the last use. IsKill will be unset if reg is reused
2170 // unless it's a two-address operand.
2171 if (!MI.isRegTiedToDefOperand(i) &&
2172 KilledMIRegs.count(VirtReg) == 0) {
2173 MI.getOperand(i).setIsKill();
2174 KilledMIRegs.insert(VirtReg);
2177 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2178 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2180 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2181 MI.getOperand(i).setReg(RReg);
2182 MI.getOperand(i).setSubReg(0);
2185 // Ok - now we can remove stores that have been confirmed dead.
2186 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2187 // This was the last use and the spilled value is still available
2188 // for reuse. That means the spill was unnecessary!
2189 int PDSSlot = PotentialDeadStoreSlots[j];
2190 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2192 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2193 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2194 VRM->RemoveMachineInstrFromMaps(DeadStore);
2195 MBB->erase(DeadStore);
2196 MaybeDeadStores[PDSSlot] = NULL;
2202 DEBUG(dbgs() << '\t' << MI);
2205 // If we have folded references to memory operands, make sure we clear all
2206 // physical registers that may contain the value of the spilled virtual
2208 SmallSet<int, 2> FoldedSS;
2209 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
2210 unsigned VirtReg = I->second.first;
2211 VirtRegMap::ModRef MR = I->second.second;
2212 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2214 // MI2VirtMap be can updated which invalidate the iterator.
2215 // Increment the iterator first.
2217 int SS = VRM->getStackSlot(VirtReg);
2218 if (SS == VirtRegMap::NO_STACK_SLOT)
2220 FoldedSS.insert(SS);
2221 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2223 // If this folded instruction is just a use, check to see if it's a
2224 // straight load from the virt reg slot.
2225 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2227 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2228 if (DestReg && FrameIdx == SS) {
2229 // If this spill slot is available, turn it into a copy (or nothing)
2230 // instead of leaving it as a load!
2231 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2232 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2233 if (DestReg != InReg) {
2234 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2235 TII->copyRegToReg(*MBB, &MI, DestReg, InReg, RC, RC);
2236 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2237 unsigned SubIdx = DefMO->getSubReg();
2238 // Revisit the copy so we make sure to notice the effects of the
2239 // operation on the destreg (either needing to RA it if it's
2240 // virtual or needing to clobber any values if it's physical).
2242 --NextMII; // backtrack to the copy.
2243 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2244 // Propagate the sub-register index over.
2246 DefMO = NextMII->findRegisterDefOperand(DestReg);
2247 DefMO->setSubReg(SubIdx);
2251 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2252 KillOpnd->setIsKill();
2256 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2257 // Unset last kill since it's being reused.
2258 InvalidateKill(InReg, TRI, RegKills, KillOps);
2259 Spills.disallowClobberPhysReg(InReg);
2262 InvalidateKills(MI, TRI, RegKills, KillOps);
2263 VRM->RemoveMachineInstrFromMaps(&MI);
2266 goto ProcessNextInst;
2269 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2270 SmallVector<MachineInstr*, 4> NewMIs;
2272 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2273 MBB->insert(MII, NewMIs[0]);
2274 InvalidateKills(MI, TRI, RegKills, KillOps);
2275 VRM->RemoveMachineInstrFromMaps(&MI);
2278 --NextMII; // backtrack to the unfolded instruction.
2280 goto ProcessNextInst;
2285 // If this reference is not a use, any previous store is now dead.
2286 // Otherwise, the store to this stack slot is not dead anymore.
2287 MachineInstr* DeadStore = MaybeDeadStores[SS];
2289 bool isDead = !(MR & VirtRegMap::isRef);
2290 MachineInstr *NewStore = NULL;
2291 if (MR & VirtRegMap::isModRef) {
2292 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2293 SmallVector<MachineInstr*, 4> NewMIs;
2294 // We can reuse this physreg as long as we are allowed to clobber
2295 // the value and there isn't an earlier def that has already clobbered
2298 !ReusedOperands.isClobbered(PhysReg) &&
2299 Spills.canClobberPhysReg(PhysReg) &&
2300 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2301 MachineOperand *KillOpnd =
2302 DeadStore->findRegisterUseOperand(PhysReg, true);
2303 // Note, if the store is storing a sub-register, it's possible the
2304 // super-register is needed below.
2305 if (KillOpnd && !KillOpnd->getSubReg() &&
2306 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2307 MBB->insert(MII, NewMIs[0]);
2308 NewStore = NewMIs[1];
2309 MBB->insert(MII, NewStore);
2310 VRM->addSpillSlotUse(SS, NewStore);
2311 InvalidateKills(MI, TRI, RegKills, KillOps);
2312 VRM->RemoveMachineInstrFromMaps(&MI);
2316 --NextMII; // backtrack to the unfolded instruction.
2324 if (isDead) { // Previous store is dead.
2325 // If we get here, the store is dead, nuke it now.
2326 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2327 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2328 VRM->RemoveMachineInstrFromMaps(DeadStore);
2329 MBB->erase(DeadStore);
2334 MaybeDeadStores[SS] = NULL;
2336 // Treat this store as a spill merged into a copy. That makes the
2337 // stack slot value available.
2338 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2339 goto ProcessNextInst;
2343 // If the spill slot value is available, and this is a new definition of
2344 // the value, the value is not available anymore.
2345 if (MR & VirtRegMap::isMod) {
2346 // Notice that the value in this stack slot has been modified.
2347 Spills.ModifyStackSlotOrReMat(SS);
2349 // If this is *just* a mod of the value, check to see if this is just a
2350 // store to the spill slot (i.e. the spill got merged into the copy). If
2351 // so, realize that the vreg is available now, and add the store to the
2352 // MaybeDeadStore info.
2354 if (!(MR & VirtRegMap::isRef)) {
2355 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2356 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2357 "Src hasn't been allocated yet?");
2359 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2360 Spills, RegKills, KillOps, TRI)) {
2361 NextMII = llvm::next(MII);
2363 goto ProcessNextInst;
2366 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2367 // this as a potentially dead store in case there is a subsequent
2368 // store into the stack slot without a read from it.
2369 MaybeDeadStores[StackSlot] = &MI;
2371 // If the stack slot value was previously available in some other
2372 // register, change it now. Otherwise, make the register
2373 // available in PhysReg.
2374 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2380 // Process all of the spilled defs.
2381 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2382 MachineOperand &MO = MI.getOperand(i);
2383 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2386 unsigned VirtReg = MO.getReg();
2387 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2388 // Check to see if this is a noop copy. If so, eliminate the
2389 // instruction before considering the dest reg to be changed.
2390 // Also check if it's copying from an "undef", if so, we can't
2391 // eliminate this or else the undef marker is lost and it will
2392 // confuses the scavenger. This is extremely rare.
2393 unsigned Src, Dst, SrcSR, DstSR;
2394 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2395 !MI.findRegisterUseOperand(Src)->isUndef()) {
2397 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2398 SmallVector<unsigned, 2> KillRegs;
2399 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2400 if (MO.isDead() && !KillRegs.empty()) {
2401 // Source register or an implicit super/sub-register use is killed.
2402 assert(KillRegs[0] == Dst ||
2403 TRI->isSubRegister(KillRegs[0], Dst) ||
2404 TRI->isSuperRegister(KillRegs[0], Dst));
2405 // Last def is now dead.
2406 TransferDeadness(Src, RegKills, KillOps);
2408 VRM->RemoveMachineInstrFromMaps(&MI);
2411 Spills.disallowClobberPhysReg(VirtReg);
2412 goto ProcessNextInst;
2415 // If it's not a no-op copy, it clobbers the value in the destreg.
2416 Spills.ClobberPhysReg(VirtReg);
2417 ReusedOperands.markClobbered(VirtReg);
2419 // Check to see if this instruction is a load from a stack slot into
2420 // a register. If so, this provides the stack slot value in the reg.
2422 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2423 assert(DestReg == VirtReg && "Unknown load situation!");
2425 // If it is a folded reference, then it's not safe to clobber.
2426 bool Folded = FoldedSS.count(FrameIdx);
2427 // Otherwise, if it wasn't available, remember that it is now!
2428 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2429 goto ProcessNextInst;
2435 unsigned SubIdx = MO.getSubReg();
2436 bool DoReMat = VRM->isReMaterialized(VirtReg);
2438 ReMatDefs.insert(&MI);
2440 // The only vregs left are stack slot definitions.
2441 int StackSlot = VRM->getStackSlot(VirtReg);
2442 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2444 // If this def is part of a two-address operand, make sure to execute
2445 // the store from the correct physical register.
2448 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2449 PhysReg = MI.getOperand(TiedOp).getReg();
2451 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2452 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2453 "Can't find corresponding super-register!");
2457 PhysReg = VRM->getPhys(VirtReg);
2458 if (ReusedOperands.isClobbered(PhysReg)) {
2459 // Another def has taken the assigned physreg. It must have been a
2460 // use&def which got it due to reuse. Undo the reuse!
2461 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2462 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2466 assert(PhysReg && "VR not assigned a physical register?");
2467 MRI->setPhysRegUsed(PhysReg);
2468 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2469 ReusedOperands.markClobbered(RReg);
2470 MI.getOperand(i).setReg(RReg);
2471 MI.getOperand(i).setSubReg(0);
2474 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2475 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2476 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2477 NextMII = llvm::next(MII);
2479 // Check to see if this is a noop copy. If so, eliminate the
2480 // instruction before considering the dest reg to be changed.
2482 unsigned Src, Dst, SrcSR, DstSR;
2483 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2485 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2486 InvalidateKills(MI, TRI, RegKills, KillOps);
2487 VRM->RemoveMachineInstrFromMaps(&MI);
2490 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2491 goto ProcessNextInst;
2497 // Delete dead instructions without side effects.
2498 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2499 InvalidateKills(MI, TRI, RegKills, KillOps);
2500 VRM->RemoveMachineInstrFromMaps(&MI);
2505 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2506 if (!Erased && !BackTracked) {
2507 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2508 UpdateKills(*II, TRI, RegKills, KillOps);
2515 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2516 switch (RewriterOpt) {
2517 default: llvm_unreachable("Unreachable!");
2519 return new LocalRewriter();
2521 return new TrivialRewriter();