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/SmallSet.h"
26 #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) {
71 MO.substPhysReg(Reg, TRI);
73 // Any kill flags apply to the full virtual register, so they also apply to
74 // the full physical register.
75 // We assume that partial defs have already been decorated with a super-reg
76 // <imp-def> operand by LiveIntervals.
77 MachineInstr &MI = *MO.getParent();
78 if (MO.isUse() && !MO.isUndef() &&
79 (MO.isKill() || MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
80 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
88 /// This class is intended for use with the new spilling framework only. It
89 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
91 struct TrivialRewriter : public VirtRegRewriter {
93 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
95 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
96 DEBUG(dbgs() << "********** Function: "
97 << MF.getFunction()->getName() << '\n');
98 DEBUG(dbgs() << "**** Machine Instrs"
99 << "(NOTE! Does not include spills and reloads!) ****\n");
102 MachineRegisterInfo *mri = &MF.getRegInfo();
103 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
105 bool changed = false;
107 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
108 liItr != liEnd; ++liItr) {
110 const LiveInterval *li = liItr->second;
111 unsigned reg = li->reg;
113 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
115 mri->setPhysRegUsed(reg);
118 if (!VRM.hasPhys(reg))
120 unsigned pReg = VRM.getPhys(reg);
121 mri->setPhysRegUsed(pReg);
122 // Copy the register use-list before traversing it.
123 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
124 for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
125 E = mri->reg_end(); I != E; ++I)
126 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
127 for (unsigned N=0; N != reglist.size(); ++N)
128 substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
130 changed |= !reglist.empty();
134 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
144 // ************************************************************************ //
148 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
149 /// from top down, keep track of which spill slots or remat are available in
152 /// Note that not all physregs are created equal here. In particular, some
153 /// physregs are reloads that we are allowed to clobber or ignore at any time.
154 /// Other physregs are values that the register allocated program is using
155 /// that we cannot CHANGE, but we can read if we like. We keep track of this
156 /// on a per-stack-slot / remat id basis as the low bit in the value of the
157 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
158 /// this bit and addAvailable sets it if.
159 class AvailableSpills {
160 const TargetRegisterInfo *TRI;
161 const TargetInstrInfo *TII;
163 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
164 // or remat'ed virtual register values that are still available, due to
165 // being loaded or stored to, but not invalidated yet.
166 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
168 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
169 // indicating which stack slot values are currently held by a physreg. This
170 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
171 // physreg is modified.
172 std::multimap<unsigned, int> PhysRegsAvailable;
174 void disallowClobberPhysRegOnly(unsigned PhysReg);
176 void ClobberPhysRegOnly(unsigned PhysReg);
178 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
179 : TRI(tri), TII(tii) {
182 /// clear - Reset the state.
184 SpillSlotsOrReMatsAvailable.clear();
185 PhysRegsAvailable.clear();
188 const TargetRegisterInfo *getRegInfo() const { return TRI; }
190 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
191 /// available in a physical register, return that PhysReg, otherwise
193 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
194 std::map<int, unsigned>::const_iterator I =
195 SpillSlotsOrReMatsAvailable.find(Slot);
196 if (I != SpillSlotsOrReMatsAvailable.end()) {
197 return I->second >> 1; // Remove the CanClobber bit.
202 /// addAvailable - Mark that the specified stack slot / remat is available
203 /// in the specified physreg. If CanClobber is true, the physreg can be
204 /// modified at any time without changing the semantics of the program.
205 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
206 // If this stack slot is thought to be available in some other physreg,
207 // remove its record.
208 ModifyStackSlotOrReMat(SlotOrReMat);
210 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
211 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
212 (unsigned)CanClobber;
214 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
215 DEBUG(dbgs() << "Remembering RM#"
216 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
218 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
219 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
222 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
223 /// the value of the specified stackslot register if it desires. The
224 /// specified stack slot must be available in a physreg for this query to
226 bool canClobberPhysRegForSS(int SlotOrReMat) const {
227 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
228 "Value not available!");
229 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
232 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
233 /// physical register where values for some stack slot(s) might be
235 bool canClobberPhysReg(unsigned PhysReg) const {
236 std::multimap<unsigned, int>::const_iterator I =
237 PhysRegsAvailable.lower_bound(PhysReg);
238 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
239 int SlotOrReMat = I->second;
241 if (!canClobberPhysRegForSS(SlotOrReMat))
247 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
248 /// stackslot register. The register is still available but is no longer
249 /// allowed to be modifed.
250 void disallowClobberPhysReg(unsigned PhysReg);
252 /// ClobberPhysReg - This is called when the specified physreg changes
253 /// value. We use this to invalidate any info about stuff that lives in
254 /// it and any of its aliases.
255 void ClobberPhysReg(unsigned PhysReg);
257 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
258 /// slot changes. This removes information about which register the
259 /// previous value for this slot lives in (as the previous value is dead
261 void ModifyStackSlotOrReMat(int SlotOrReMat);
263 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
264 /// into the specified MBB. Add available physical registers as potential
265 /// live-in's. If they are reused in the MBB, they will be added to the
266 /// live-in set to make register scavenger and post-allocation scheduler.
267 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
268 std::vector<MachineOperand*> &KillOps);
273 // ************************************************************************ //
275 // Given a location where a reload of a spilled register or a remat of
276 // a constant is to be inserted, attempt to find a safe location to
277 // insert the load at an earlier point in the basic-block, to hide
278 // latency of the load and to avoid address-generation interlock
280 static MachineBasicBlock::iterator
281 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
282 MachineBasicBlock::iterator const Begin,
284 const TargetRegisterInfo *TRI,
287 const TargetInstrInfo *TII,
288 const MachineFunction &MF)
293 // Spill backscheduling is of primary interest to addresses, so
294 // don't do anything if the register isn't in the register class
295 // used for pointers.
297 const TargetLowering *TL = MF.getTarget().getTargetLowering();
299 if (!TL->isTypeLegal(TL->getPointerTy()))
300 // Believe it or not, this is true on 16-bit targets like PIC16.
303 const TargetRegisterClass *ptrRegClass =
304 TL->getRegClassFor(TL->getPointerTy());
305 if (!ptrRegClass->contains(PhysReg))
308 // Scan upwards through the preceding instructions. If an instruction doesn't
309 // reference the stack slot or the register we're loading, we can
310 // backschedule the reload up past it.
311 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
312 while (NewInsertLoc != Begin) {
313 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
314 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
315 MachineOperand &Op = Prev->getOperand(i);
316 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
319 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
320 Prev->findRegisterDefOperand(PhysReg))
322 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
323 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
324 Prev->findRegisterDefOperand(*Alias))
330 // If we made it to the beginning of the block, turn around and move back
331 // down just past any existing reloads. They're likely to be reloads/remats
332 // for instructions earlier than what our current reload/remat is for, so
333 // they should be scheduled earlier.
334 if (NewInsertLoc == Begin) {
336 while (InsertLoc != NewInsertLoc &&
337 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
338 TII->isTriviallyReMaterializable(NewInsertLoc)))
347 // ReusedOp - For each reused operand, we keep track of a bit of information,
348 // in case we need to rollback upon processing a new operand. See comments
351 // The MachineInstr operand that reused an available value.
354 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
355 unsigned StackSlotOrReMat;
357 // PhysRegReused - The physical register the value was available in.
358 unsigned PhysRegReused;
360 // AssignedPhysReg - The physreg that was assigned for use by the reload.
361 unsigned AssignedPhysReg;
363 // VirtReg - The virtual register itself.
366 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
368 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
369 AssignedPhysReg(apr), VirtReg(vreg) {}
372 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
373 /// is reused instead of reloaded.
376 std::vector<ReusedOp> Reuses;
377 BitVector PhysRegsClobbered;
379 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
380 PhysRegsClobbered.resize(tri->getNumRegs());
383 bool hasReuses() const {
384 return !Reuses.empty();
387 /// addReuse - If we choose to reuse a virtual register that is already
388 /// available instead of reloading it, remember that we did so.
389 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
390 unsigned PhysRegReused, unsigned AssignedPhysReg,
392 // If the reload is to the assigned register anyway, no undo will be
394 if (PhysRegReused == AssignedPhysReg) return;
396 // Otherwise, remember this.
397 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
398 AssignedPhysReg, VirtReg));
401 void markClobbered(unsigned PhysReg) {
402 PhysRegsClobbered.set(PhysReg);
405 bool isClobbered(unsigned PhysReg) const {
406 return PhysRegsClobbered.test(PhysReg);
409 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
410 /// is some other operand that is using the specified register, either pick
411 /// a new register to use, or evict the previous reload and use this reg.
412 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
413 MachineFunction &MF, MachineInstr *MI,
414 AvailableSpills &Spills,
415 std::vector<MachineInstr*> &MaybeDeadStores,
416 SmallSet<unsigned, 8> &Rejected,
418 std::vector<MachineOperand*> &KillOps,
421 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
422 /// 'Rejected' set to remember which registers have been considered and
423 /// rejected for the reload. This avoids infinite looping in case like
426 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
427 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
429 /// sees r1 is taken by t2, tries t2's reload register r0
430 /// sees r0 is taken by t3, tries t3's reload register r1
431 /// sees r1 is taken by t2, tries t2's reload register r0 ...
432 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
433 AvailableSpills &Spills,
434 std::vector<MachineInstr*> &MaybeDeadStores,
436 std::vector<MachineOperand*> &KillOps,
438 SmallSet<unsigned, 8> Rejected;
439 MachineFunction &MF = *MI->getParent()->getParent();
440 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
441 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
442 Rejected, RegKills, KillOps, VRM);
448 // ****************** //
449 // Utility Functions //
450 // ****************** //
452 /// findSinglePredSuccessor - Return via reference a vector of machine basic
453 /// blocks each of which is a successor of the specified BB and has no other
455 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
456 SmallVectorImpl<MachineBasicBlock *> &Succs){
457 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
458 SE = MBB->succ_end(); SI != SE; ++SI) {
459 MachineBasicBlock *SuccMBB = *SI;
460 if (SuccMBB->pred_size() == 1)
461 Succs.push_back(SuccMBB);
465 /// InvalidateKill - Invalidate register kill information for a specific
466 /// register. This also unsets the kills marker on the last kill operand.
467 static void InvalidateKill(unsigned Reg,
468 const TargetRegisterInfo* TRI,
470 std::vector<MachineOperand*> &KillOps) {
472 KillOps[Reg]->setIsKill(false);
473 // KillOps[Reg] might be a def of a super-register.
474 unsigned KReg = KillOps[Reg]->getReg();
475 KillOps[KReg] = NULL;
476 RegKills.reset(KReg);
477 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
479 KillOps[*SR]->setIsKill(false);
487 /// InvalidateKills - MI is going to be deleted. If any of its operands are
488 /// marked kill, then invalidate the information.
489 static void InvalidateKills(MachineInstr &MI,
490 const TargetRegisterInfo* TRI,
492 std::vector<MachineOperand*> &KillOps,
493 SmallVector<unsigned, 2> *KillRegs = NULL) {
494 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
495 MachineOperand &MO = MI.getOperand(i);
496 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
498 unsigned Reg = MO.getReg();
499 if (TargetRegisterInfo::isVirtualRegister(Reg))
502 KillRegs->push_back(Reg);
503 assert(Reg < KillOps.size());
504 if (KillOps[Reg] == &MO) {
507 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
517 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
518 /// (since its spill instruction is removed), mark it isDead. Also checks if
519 /// the def MI has other definition operands that are not dead. Returns it by
521 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
522 MachineInstr &NewDef, unsigned Reg,
524 const TargetRegisterInfo *TRI) {
525 // Due to remat, it's possible this reg isn't being reused. That is,
526 // the def of this reg (by prev MI) is now dead.
527 MachineInstr *DefMI = I;
528 MachineOperand *DefOp = NULL;
529 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
530 MachineOperand &MO = DefMI->getOperand(i);
531 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
533 if (MO.getReg() == Reg)
535 else if (!MO.isDead())
541 bool FoundUse = false, Done = false;
542 MachineBasicBlock::iterator E = &NewDef;
544 for (; !Done && I != E; ++I) {
545 MachineInstr *NMI = I;
546 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
547 MachineOperand &MO = NMI->getOperand(j);
548 if (!MO.isReg() || MO.getReg() == 0 ||
549 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
553 Done = true; // Stop after scanning all the operands of this MI.
564 /// UpdateKills - Track and update kill info. If a MI reads a register that is
565 /// marked kill, then it must be due to register reuse. Transfer the kill info
567 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
569 std::vector<MachineOperand*> &KillOps) {
570 // These do not affect kill info at all.
571 if (MI.isDebugValue())
573 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
574 MachineOperand &MO = MI.getOperand(i);
575 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
577 unsigned Reg = MO.getReg();
581 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
582 // That can't be right. Register is killed but not re-defined and it's
583 // being reused. Let's fix that.
584 KillOps[Reg]->setIsKill(false);
585 // KillOps[Reg] might be a def of a super-register.
586 unsigned KReg = KillOps[Reg]->getReg();
587 KillOps[KReg] = NULL;
588 RegKills.reset(KReg);
590 // Must be a def of a super-register. Its other sub-regsters are no
591 // longer killed as well.
592 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
597 // Check for subreg kills as well.
603 // = d4 <avoiding reload>
604 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
606 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
607 KillOps[SReg]->setIsKill(false);
608 unsigned KReg = KillOps[SReg]->getReg();
609 KillOps[KReg] = NULL;
610 RegKills.reset(KReg);
612 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
613 KillOps[*SSR] = NULL;
614 RegKills.reset(*SSR);
623 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
630 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
631 const MachineOperand &MO = MI.getOperand(i);
632 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
634 unsigned Reg = MO.getReg();
637 // It also defines (or partially define) aliases.
638 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
642 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
649 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
651 static void ReMaterialize(MachineBasicBlock &MBB,
652 MachineBasicBlock::iterator &MII,
653 unsigned DestReg, unsigned Reg,
654 const TargetInstrInfo *TII,
655 const TargetRegisterInfo *TRI,
657 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
659 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
660 assert(TID.getNumDefs() == 1 &&
661 "Don't know how to remat instructions that define > 1 values!");
663 TII->reMaterialize(MBB, MII, DestReg, 0, ReMatDefMI, *TRI);
664 MachineInstr *NewMI = prior(MII);
665 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
666 MachineOperand &MO = NewMI->getOperand(i);
667 if (!MO.isReg() || MO.getReg() == 0)
669 unsigned VirtReg = MO.getReg();
670 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
673 unsigned Phys = VRM.getPhys(VirtReg);
674 assert(Phys && "Virtual register is not assigned a register?");
675 substitutePhysReg(MO, Phys, *TRI);
680 /// findSuperReg - Find the SubReg's super-register of given register class
681 /// where its SubIdx sub-register is SubReg.
682 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
683 unsigned SubIdx, const TargetRegisterInfo *TRI) {
684 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
687 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
693 // ******************************** //
694 // Available Spills Implementation //
695 // ******************************** //
697 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
698 /// stackslot register. The register is still available but is no longer
699 /// allowed to be modifed.
700 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
701 std::multimap<unsigned, int>::iterator I =
702 PhysRegsAvailable.lower_bound(PhysReg);
703 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
704 int SlotOrReMat = I->second;
706 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
707 "Bidirectional map mismatch!");
708 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
709 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
710 << " copied, it is available for use but can no longer be modified\n");
714 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
715 /// stackslot register and its aliases. The register and its aliases may
716 /// still available but is no longer allowed to be modifed.
717 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
718 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
719 disallowClobberPhysRegOnly(*AS);
720 disallowClobberPhysRegOnly(PhysReg);
723 /// ClobberPhysRegOnly - This is called when the specified physreg changes
724 /// value. We use this to invalidate any info about stuff we thing lives in it.
725 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
726 std::multimap<unsigned, int>::iterator I =
727 PhysRegsAvailable.lower_bound(PhysReg);
728 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
729 int SlotOrReMat = I->second;
730 PhysRegsAvailable.erase(I++);
731 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
732 "Bidirectional map mismatch!");
733 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
734 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
735 << " clobbered, invalidating ");
736 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
737 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
739 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
743 /// ClobberPhysReg - This is called when the specified physreg changes
744 /// value. We use this to invalidate any info about stuff we thing lives in
745 /// it and any of its aliases.
746 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
747 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
748 ClobberPhysRegOnly(*AS);
749 ClobberPhysRegOnly(PhysReg);
752 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
753 /// into the specified MBB. Add available physical registers as potential
754 /// live-in's. If they are reused in the MBB, they will be added to the
755 /// live-in set to make register scavenger and post-allocation scheduler.
756 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
758 std::vector<MachineOperand*> &KillOps) {
759 std::set<unsigned> NotAvailable;
760 for (std::multimap<unsigned, int>::iterator
761 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
763 unsigned Reg = I->first;
764 const TargetRegisterClass* RC = TRI->getMinimalPhysRegClass(Reg);
765 // FIXME: A temporary workaround. We can't reuse available value if it's
766 // not safe to move the def of the virtual register's class. e.g.
767 // X86::RFP* register classes. Do not add it as a live-in.
768 if (!TII->isSafeToMoveRegClassDefs(RC))
769 // This is no longer available.
770 NotAvailable.insert(Reg);
773 InvalidateKill(Reg, TRI, RegKills, KillOps);
776 // Skip over the same register.
777 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
778 while (NI != E && NI->first == Reg) {
784 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
785 E = NotAvailable.end(); I != E; ++I) {
787 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
789 ClobberPhysReg(*SubRegs);
793 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
794 /// slot changes. This removes information about which register the previous
795 /// value for this slot lives in (as the previous value is dead now).
796 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
797 std::map<int, unsigned>::iterator It =
798 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
799 if (It == SpillSlotsOrReMatsAvailable.end()) return;
800 unsigned Reg = It->second >> 1;
801 SpillSlotsOrReMatsAvailable.erase(It);
803 // This register may hold the value of multiple stack slots, only remove this
804 // stack slot from the set of values the register contains.
805 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
807 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
808 "Map inverse broken!");
809 if (I->second == SlotOrReMat) break;
811 PhysRegsAvailable.erase(I);
814 // ************************** //
815 // Reuse Info Implementation //
816 // ************************** //
818 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
819 /// is some other operand that is using the specified register, either pick
820 /// a new register to use, or evict the previous reload and use this reg.
821 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
824 MachineInstr *MI, AvailableSpills &Spills,
825 std::vector<MachineInstr*> &MaybeDeadStores,
826 SmallSet<unsigned, 8> &Rejected,
828 std::vector<MachineOperand*> &KillOps,
830 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
831 const TargetRegisterInfo *TRI = Spills.getRegInfo();
833 if (Reuses.empty()) return PhysReg; // This is most often empty.
835 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
836 ReusedOp &Op = Reuses[ro];
837 // If we find some other reuse that was supposed to use this register
838 // exactly for its reload, we can change this reload to use ITS reload
839 // register. That is, unless its reload register has already been
840 // considered and subsequently rejected because it has also been reused
841 // by another operand.
842 if (Op.PhysRegReused == PhysReg &&
843 Rejected.count(Op.AssignedPhysReg) == 0 &&
844 RC->contains(Op.AssignedPhysReg)) {
845 // Yup, use the reload register that we didn't use before.
846 unsigned NewReg = Op.AssignedPhysReg;
847 Rejected.insert(PhysReg);
848 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores,
849 Rejected, RegKills, KillOps, VRM);
851 // Otherwise, we might also have a problem if a previously reused
852 // value aliases the new register. If so, codegen the previous reload
854 unsigned PRRU = Op.PhysRegReused;
855 if (TRI->regsOverlap(PRRU, PhysReg)) {
856 // Okay, we found out that an alias of a reused register
857 // was used. This isn't good because it means we have
858 // to undo a previous reuse.
859 MachineBasicBlock *MBB = MI->getParent();
860 const TargetRegisterClass *AliasRC =
861 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
863 // Copy Op out of the vector and remove it, we're going to insert an
864 // explicit load for it.
866 Reuses.erase(Reuses.begin()+ro);
868 // MI may be using only a sub-register of PhysRegUsed.
869 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
871 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
872 "A reuse cannot be a virtual register");
873 if (PRRU != RealPhysRegUsed) {
874 // What was the sub-register index?
875 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
877 "Operand physreg is not a sub-register of PhysRegUsed");
880 // Ok, we're going to try to reload the assigned physreg into the
881 // slot that we were supposed to in the first place. However, that
882 // register could hold a reuse. Check to see if it conflicts or
883 // would prefer us to use a different register.
884 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
885 MF, MI, Spills, MaybeDeadStores,
886 Rejected, RegKills, KillOps, VRM);
888 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
889 int SSorRMId = DoReMat
890 ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
892 // Back-schedule reloads and remats.
893 MachineBasicBlock::iterator InsertLoc =
894 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
895 DoReMat, SSorRMId, TII, MF);
898 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
901 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
902 NewOp.StackSlotOrReMat, AliasRC, TRI);
903 MachineInstr *LoadMI = prior(InsertLoc);
904 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
905 // Any stores to this stack slot are not dead anymore.
906 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
909 Spills.ClobberPhysReg(NewPhysReg);
910 Spills.ClobberPhysReg(NewOp.PhysRegReused);
912 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
913 MI->getOperand(NewOp.Operand).setReg(RReg);
914 MI->getOperand(NewOp.Operand).setSubReg(0);
916 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
917 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
918 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
920 DEBUG(dbgs() << "Reuse undone!\n");
923 // Finally, PhysReg is now available, go ahead and use it.
931 // ************************************************************************ //
933 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
934 /// stack slot mod/ref. It also checks if it's possible to unfold the
935 /// instruction by having it define a specified physical register instead.
936 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
937 const TargetInstrInfo *TII,
938 const TargetRegisterInfo *TRI,
940 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
944 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
945 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
946 unsigned VirtReg = I->second.first;
947 VirtRegMap::ModRef MR = I->second.second;
948 if (MR & VirtRegMap::isModRef)
949 if (VRM.getStackSlot(VirtReg) == SS) {
950 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
957 // Does the instruction uses a register that overlaps the scratch register?
958 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
959 MachineOperand &MO = MI.getOperand(i);
960 if (!MO.isReg() || MO.getReg() == 0)
962 unsigned Reg = MO.getReg();
963 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
964 if (!VRM.hasPhys(Reg))
966 Reg = VRM.getPhys(Reg);
968 if (TRI->regsOverlap(PhysReg, Reg))
974 /// FindFreeRegister - Find a free register of a given register class by looking
975 /// at (at most) the last two machine instructions.
976 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
977 MachineBasicBlock &MBB,
978 const TargetRegisterClass *RC,
979 const TargetRegisterInfo *TRI,
980 BitVector &AllocatableRegs) {
981 BitVector Defs(TRI->getNumRegs());
982 BitVector Uses(TRI->getNumRegs());
983 SmallVector<unsigned, 4> LocalUses;
984 SmallVector<unsigned, 4> Kills;
986 // Take a look at 2 instructions at most.
989 if (MII == MBB.begin())
991 MachineInstr *PrevMI = prior(MII);
994 if (PrevMI->isDebugValue())
995 continue; // Skip over dbg_value instructions.
998 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
999 MachineOperand &MO = PrevMI->getOperand(i);
1000 if (!MO.isReg() || MO.getReg() == 0)
1002 unsigned Reg = MO.getReg();
1005 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1008 LocalUses.push_back(Reg);
1009 if (MO.isKill() && AllocatableRegs[Reg])
1010 Kills.push_back(Reg);
1014 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1015 unsigned Kill = Kills[i];
1016 if (!Defs[Kill] && !Uses[Kill] &&
1020 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1021 unsigned Reg = LocalUses[i];
1023 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1032 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1033 const TargetRegisterInfo &TRI) {
1034 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1035 MachineOperand &MO = MI->getOperand(i);
1036 if (MO.isReg() && MO.getReg() == VirtReg)
1037 substitutePhysReg(MO, PhysReg, TRI);
1044 bool operator()(const std::pair<MachineInstr*, int> &A,
1045 const std::pair<MachineInstr*, int> &B) {
1046 return A.second < B.second;
1050 // ***************************** //
1051 // Local Spiller Implementation //
1052 // ***************************** //
1054 class LocalRewriter : public VirtRegRewriter {
1055 MachineRegisterInfo *MRI;
1056 const TargetRegisterInfo *TRI;
1057 const TargetInstrInfo *TII;
1059 BitVector AllocatableRegs;
1060 DenseMap<MachineInstr*, unsigned> DistanceMap;
1061 DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
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 ProcessUses(MachineInstr &MI, AvailableSpills &Spills,
1114 std::vector<MachineInstr*> &MaybeDeadStores,
1115 BitVector &RegKills,
1116 ReuseInfo &ReusedOperands,
1117 std::vector<MachineOperand*> &KillOps);
1119 void RewriteMBB(LiveIntervals *LIs,
1120 AvailableSpills &Spills, BitVector &RegKills,
1121 std::vector<MachineOperand*> &KillOps);
1125 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1126 LiveIntervals* LIs) {
1127 MRI = &MF.getRegInfo();
1128 TRI = MF.getTarget().getRegisterInfo();
1129 TII = MF.getTarget().getInstrInfo();
1131 AllocatableRegs = TRI->getAllocatableSet(MF);
1132 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1133 << MF.getFunction()->getName() << "':\n");
1134 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1135 " reloads!) ****\n");
1138 // Spills - Keep track of which spilled values are available in physregs
1139 // so that we can choose to reuse the physregs instead of emitting
1140 // reloads. This is usually refreshed per basic block.
1141 AvailableSpills Spills(TRI, TII);
1143 // Keep track of kill information.
1144 BitVector RegKills(TRI->getNumRegs());
1145 std::vector<MachineOperand*> KillOps;
1146 KillOps.resize(TRI->getNumRegs(), NULL);
1148 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1149 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1150 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1152 // Traverse the basic blocks depth first.
1153 MachineBasicBlock *Entry = MF.begin();
1154 SmallPtrSet<MachineBasicBlock*,16> Visited;
1155 for (df_ext_iterator<MachineBasicBlock*,
1156 SmallPtrSet<MachineBasicBlock*,16> >
1157 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1160 if (!EarlyVisited.count(MBB))
1161 RewriteMBB(LIs, Spills, RegKills, KillOps);
1163 // If this MBB is the only predecessor of a successor. Keep the
1164 // availability information and visit it next.
1166 // Keep visiting single predecessor successor as long as possible.
1167 SinglePredSuccs.clear();
1168 findSinglePredSuccessor(MBB, SinglePredSuccs);
1169 if (SinglePredSuccs.empty())
1172 // FIXME: More than one successors, each of which has MBB has
1173 // the only predecessor.
1174 MBB = SinglePredSuccs[0];
1175 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1176 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1177 RewriteMBB(LIs, Spills, RegKills, KillOps);
1182 // Clear the availability info.
1186 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1189 // Mark unused spill slots.
1190 MachineFrameInfo *MFI = MF.getFrameInfo();
1191 int SS = VRM->getLowSpillSlot();
1192 if (SS != VirtRegMap::NO_STACK_SLOT) {
1193 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1194 SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
1195 if (!VRM->isSpillSlotUsed(SS)) {
1196 MFI->RemoveStackObject(SS);
1197 for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1198 MachineInstr *DVMI = DbgValues[j];
1199 MachineBasicBlock *DVMBB = DVMI->getParent();
1200 DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1201 VRM->RemoveMachineInstrFromMaps(DVMI);
1209 Slot2DbgValues.clear();
1214 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1215 /// a scratch register is available.
1216 /// xorq %r12<kill>, %r13
1217 /// addq %rax, -184(%rbp)
1218 /// addq %r13, -184(%rbp)
1220 /// xorq %r12<kill>, %r13
1221 /// movq -184(%rbp), %r12
1224 /// movq %r12, -184(%rbp)
1225 bool LocalRewriter::
1226 OptimizeByUnfold2(unsigned VirtReg, int SS,
1227 MachineBasicBlock::iterator &MII,
1228 std::vector<MachineInstr*> &MaybeDeadStores,
1229 AvailableSpills &Spills,
1230 BitVector &RegKills,
1231 std::vector<MachineOperand*> &KillOps) {
1233 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1234 // Skip over dbg_value instructions.
1235 while (NextMII != MBB->end() && NextMII->isDebugValue())
1236 NextMII = llvm::next(NextMII);
1237 if (NextMII == MBB->end())
1240 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1243 // Now let's see if the last couple of instructions happens to have freed up
1245 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1246 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1250 MachineFunction &MF = *MBB->getParent();
1251 TRI = MF.getTarget().getRegisterInfo();
1252 MachineInstr &MI = *MII;
1253 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1256 // If the next instruction also folds the same SS modref and can be unfoled,
1257 // then it's worthwhile to issue a load from SS into the free register and
1258 // then unfold these instructions.
1259 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1262 // Back-schedule reloads and remats.
1263 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1265 // Load from SS to the spare physical register.
1266 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
1267 // This invalidates Phys.
1268 Spills.ClobberPhysReg(PhysReg);
1269 // Remember it's available.
1270 Spills.addAvailable(SS, PhysReg);
1271 MaybeDeadStores[SS] = NULL;
1273 // Unfold current MI.
1274 SmallVector<MachineInstr*, 4> NewMIs;
1275 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1276 llvm_unreachable("Unable unfold the load / store folding instruction!");
1277 assert(NewMIs.size() == 1);
1278 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1279 VRM->transferRestorePts(&MI, NewMIs[0]);
1280 MII = MBB->insert(MII, NewMIs[0]);
1281 InvalidateKills(MI, TRI, RegKills, KillOps);
1282 VRM->RemoveMachineInstrFromMaps(&MI);
1286 // Unfold next instructions that fold the same SS.
1288 MachineInstr &NextMI = *NextMII;
1289 NextMII = llvm::next(NextMII);
1291 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1292 llvm_unreachable("Unable unfold the load / store folding instruction!");
1293 assert(NewMIs.size() == 1);
1294 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1295 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1296 MBB->insert(NextMII, NewMIs[0]);
1297 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1298 VRM->RemoveMachineInstrFromMaps(&NextMI);
1299 MBB->erase(&NextMI);
1301 // Skip over dbg_value instructions.
1302 while (NextMII != MBB->end() && NextMII->isDebugValue())
1303 NextMII = llvm::next(NextMII);
1304 if (NextMII == MBB->end())
1306 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1308 // Store the value back into SS.
1309 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
1310 MachineInstr *StoreMI = prior(NextMII);
1311 VRM->addSpillSlotUse(SS, StoreMI);
1312 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1317 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1318 /// instruction. e.g.
1320 /// movl %eax, -32(%ebp)
1321 /// movl -36(%ebp), %eax
1322 /// orl %eax, -32(%ebp)
1325 /// orl -36(%ebp), %eax
1326 /// mov %eax, -32(%ebp)
1327 /// This enables unfolding optimization for a subsequent instruction which will
1328 /// also eliminate the newly introduced store instruction.
1329 bool LocalRewriter::
1330 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1331 std::vector<MachineInstr*> &MaybeDeadStores,
1332 AvailableSpills &Spills,
1333 BitVector &RegKills,
1334 std::vector<MachineOperand*> &KillOps) {
1335 MachineFunction &MF = *MBB->getParent();
1336 MachineInstr &MI = *MII;
1337 unsigned UnfoldedOpc = 0;
1338 unsigned UnfoldPR = 0;
1339 unsigned UnfoldVR = 0;
1340 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1341 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1342 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1343 // Only transform a MI that folds a single register.
1346 UnfoldVR = I->second.first;
1347 VirtRegMap::ModRef MR = I->second.second;
1348 // MI2VirtMap be can updated which invalidate the iterator.
1349 // Increment the iterator first.
1351 if (VRM->isAssignedReg(UnfoldVR))
1353 // If this reference is not a use, any previous store is now dead.
1354 // Otherwise, the store to this stack slot is not dead anymore.
1355 FoldedSS = VRM->getStackSlot(UnfoldVR);
1356 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1357 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1358 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1359 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1362 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1371 // Look for other unfolding opportunities.
1372 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1376 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1377 MachineOperand &MO = MI.getOperand(i);
1378 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1380 unsigned VirtReg = MO.getReg();
1381 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1383 if (VRM->isAssignedReg(VirtReg)) {
1384 unsigned PhysReg = VRM->getPhys(VirtReg);
1385 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1387 } else if (VRM->isReMaterialized(VirtReg))
1389 int SS = VRM->getStackSlot(VirtReg);
1390 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1392 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1396 if (VRM->hasPhys(VirtReg)) {
1397 PhysReg = VRM->getPhys(VirtReg);
1398 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1402 // Ok, we'll need to reload the value into a register which makes
1403 // it impossible to perform the store unfolding optimization later.
1404 // Let's see if it is possible to fold the load if the store is
1405 // unfolded. This allows us to perform the store unfolding
1407 SmallVector<MachineInstr*, 4> NewMIs;
1408 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1409 assert(NewMIs.size() == 1);
1410 MachineInstr *NewMI = NewMIs.back();
1411 MBB->insert(MII, NewMI);
1413 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1415 SmallVector<unsigned, 1> Ops;
1417 MachineInstr *FoldedMI = TII->foldMemoryOperand(NewMI, Ops, SS);
1418 NewMI->eraseFromParent();
1420 VRM->addSpillSlotUse(SS, FoldedMI);
1421 if (!VRM->hasPhys(UnfoldVR))
1422 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1423 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1425 InvalidateKills(MI, TRI, RegKills, KillOps);
1426 VRM->RemoveMachineInstrFromMaps(&MI);
1436 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1437 /// where SrcReg is r1 and it is tied to r0. Return true if after
1438 /// commuting this instruction it will be r0 = op r2, r1.
1439 static bool CommuteChangesDestination(MachineInstr *DefMI,
1440 const TargetInstrDesc &TID,
1442 const TargetInstrInfo *TII,
1444 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1446 if (!DefMI->getOperand(1).isReg() ||
1447 DefMI->getOperand(1).getReg() != SrcReg)
1450 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1452 unsigned SrcIdx1, SrcIdx2;
1453 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1455 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1462 /// CommuteToFoldReload -
1465 /// r1 = op r1, r2<kill>
1468 /// If op is commutable and r2 is killed, then we can xform these to
1469 /// r2 = op r2, fi#1
1471 bool LocalRewriter::
1472 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1473 unsigned VirtReg, unsigned SrcReg, int SS,
1474 AvailableSpills &Spills,
1475 BitVector &RegKills,
1476 std::vector<MachineOperand*> &KillOps,
1477 const TargetRegisterInfo *TRI) {
1478 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1481 MachineInstr &MI = *MII;
1482 MachineBasicBlock::iterator DefMII = prior(MII);
1483 MachineInstr *DefMI = DefMII;
1484 const TargetInstrDesc &TID = DefMI->getDesc();
1486 if (DefMII != MBB->begin() &&
1487 TID.isCommutable() &&
1488 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1489 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1490 unsigned NewReg = NewDstMO.getReg();
1491 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1493 MachineInstr *ReloadMI = prior(DefMII);
1495 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1496 if (DestReg != SrcReg || FrameIdx != SS)
1498 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1502 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1504 assert(DefMI->getOperand(DefIdx).isReg() &&
1505 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1507 // Now commute def instruction.
1508 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1511 MBB->insert(MII, CommutedMI);
1512 SmallVector<unsigned, 1> Ops;
1513 Ops.push_back(NewDstIdx);
1514 MachineInstr *FoldedMI = TII->foldMemoryOperand(CommutedMI, Ops, SS);
1515 // Not needed since foldMemoryOperand returns new MI.
1516 CommutedMI->eraseFromParent();
1520 VRM->addSpillSlotUse(SS, FoldedMI);
1521 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1522 // Insert new def MI and spill MI.
1523 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1524 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
1526 MachineInstr *StoreMI = MII;
1527 VRM->addSpillSlotUse(SS, StoreMI);
1528 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1529 MII = FoldedMI; // Update MII to backtrack.
1531 // Delete all 3 old instructions.
1532 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1533 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1534 MBB->erase(ReloadMI);
1535 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1536 VRM->RemoveMachineInstrFromMaps(DefMI);
1538 InvalidateKills(MI, TRI, RegKills, KillOps);
1539 VRM->RemoveMachineInstrFromMaps(&MI);
1542 // If NewReg was previously holding value of some SS, it's now clobbered.
1543 // This has to be done now because it's a physical register. When this
1544 // instruction is re-visited, it's ignored.
1545 Spills.ClobberPhysReg(NewReg);
1554 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1555 /// the last store to the same slot is now dead. If so, remove the last store.
1556 void LocalRewriter::
1557 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1558 int Idx, unsigned PhysReg, int StackSlot,
1559 const TargetRegisterClass *RC,
1560 bool isAvailable, MachineInstr *&LastStore,
1561 AvailableSpills &Spills,
1562 SmallSet<MachineInstr*, 4> &ReMatDefs,
1563 BitVector &RegKills,
1564 std::vector<MachineOperand*> &KillOps) {
1566 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1567 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1569 MachineInstr *StoreMI = prior(oldNextMII);
1570 VRM->addSpillSlotUse(StackSlot, StoreMI);
1571 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1573 // If there is a dead store to this stack slot, nuke it now.
1575 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1577 SmallVector<unsigned, 2> KillRegs;
1578 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1579 MachineBasicBlock::iterator PrevMII = LastStore;
1580 bool CheckDef = PrevMII != MBB->begin();
1583 VRM->RemoveMachineInstrFromMaps(LastStore);
1584 MBB->erase(LastStore);
1586 // Look at defs of killed registers on the store. Mark the defs
1587 // as dead since the store has been deleted and they aren't
1589 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1590 bool HasOtherDef = false;
1591 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1592 MachineInstr *DeadDef = PrevMII;
1593 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1594 // FIXME: This assumes a remat def does not have side effects.
1595 VRM->RemoveMachineInstrFromMaps(DeadDef);
1596 MBB->erase(DeadDef);
1604 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1605 // the last of multiple instructions is the actual store.
1606 LastStore = prior(oldNextMII);
1608 // If the stack slot value was previously available in some other
1609 // register, change it now. Otherwise, make the register available,
1611 Spills.ModifyStackSlotOrReMat(StackSlot);
1612 Spills.ClobberPhysReg(PhysReg);
1613 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1617 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1618 /// effect and all of its defs are dead.
1619 static bool isSafeToDelete(MachineInstr &MI) {
1620 const TargetInstrDesc &TID = MI.getDesc();
1621 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1622 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1623 TID.hasUnmodeledSideEffects() ||
1624 MI.isLabel() || MI.isDebugValue())
1626 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1627 MachineOperand &MO = MI.getOperand(i);
1628 if (!MO.isReg() || !MO.getReg())
1630 if (MO.isDef() && !MO.isDead())
1632 if (MO.isUse() && MO.isKill())
1633 // FIXME: We can't remove kill markers or else the scavenger will assert.
1634 // An alternative is to add a ADD pseudo instruction to replace kill
1641 /// TransferDeadness - A identity copy definition is dead and it's being
1642 /// removed. Find the last def or use and mark it as dead / kill.
1643 void LocalRewriter::
1644 TransferDeadness(unsigned Reg, BitVector &RegKills,
1645 std::vector<MachineOperand*> &KillOps) {
1646 SmallPtrSet<MachineInstr*, 4> Seens;
1647 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1648 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1649 RE = MRI->reg_end(); RI != RE; ++RI) {
1650 MachineInstr *UDMI = &*RI;
1651 if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
1653 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1654 if (DI == DistanceMap.end())
1656 if (Seens.insert(UDMI))
1657 Refs.push_back(std::make_pair(UDMI, DI->second));
1662 std::sort(Refs.begin(), Refs.end(), RefSorter());
1664 while (!Refs.empty()) {
1665 MachineInstr *LastUDMI = Refs.back().first;
1668 MachineOperand *LastUD = NULL;
1669 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1670 MachineOperand &MO = LastUDMI->getOperand(i);
1671 if (!MO.isReg() || MO.getReg() != Reg)
1673 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1675 if (LastUDMI->isRegTiedToDefOperand(i))
1678 if (LastUD->isDef()) {
1679 // If the instruction has no side effect, delete it and propagate
1680 // backward further. Otherwise, mark is dead and we are done.
1681 if (!isSafeToDelete(*LastUDMI)) {
1682 LastUD->setIsDead();
1685 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1686 MBB->erase(LastUDMI);
1688 LastUD->setIsKill();
1690 KillOps[Reg] = LastUD;
1696 /// InsertEmergencySpills - Insert emergency spills before MI if requested by
1697 /// VRM. Return true if spills were inserted.
1698 bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1699 if (!VRM->hasEmergencySpills(MI))
1701 MachineBasicBlock::iterator MII = MI;
1702 SmallSet<int, 4> UsedSS;
1703 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1704 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1705 unsigned PhysReg = EmSpills[i];
1706 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
1707 assert(RC && "Unable to determine register class!");
1708 int SS = VRM->getEmergencySpillSlot(RC);
1709 if (UsedSS.count(SS))
1710 llvm_unreachable("Need to spill more than one physical registers!");
1712 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
1713 MachineInstr *StoreMI = prior(MII);
1714 VRM->addSpillSlotUse(SS, StoreMI);
1716 // Back-schedule reloads and remats.
1717 MachineBasicBlock::iterator InsertLoc =
1718 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1719 TII, *MBB->getParent());
1721 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
1723 MachineInstr *LoadMI = prior(InsertLoc);
1724 VRM->addSpillSlotUse(SS, LoadMI);
1726 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1731 /// InsertRestores - Restore registers before MI is requested by VRM. Return
1732 /// true is any instructions were inserted.
1733 bool LocalRewriter::InsertRestores(MachineInstr *MI,
1734 AvailableSpills &Spills,
1735 BitVector &RegKills,
1736 std::vector<MachineOperand*> &KillOps) {
1737 if (!VRM->isRestorePt(MI))
1739 MachineBasicBlock::iterator MII = MI;
1740 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1741 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1742 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1743 if (!VRM->getPreSplitReg(VirtReg))
1744 continue; // Split interval spilled again.
1745 unsigned Phys = VRM->getPhys(VirtReg);
1746 MRI->setPhysRegUsed(Phys);
1748 // Check if the value being restored if available. If so, it must be
1749 // from a predecessor BB that fallthrough into this BB. We do not
1755 // ... # r1 not clobbered
1758 bool DoReMat = VRM->isReMaterialized(VirtReg);
1759 int SSorRMId = DoReMat
1760 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1761 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1762 if (InReg == Phys) {
1763 // If the value is already available in the expected register, save
1764 // a reload / remat.
1766 DEBUG(dbgs() << "Reusing RM#"
1767 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1769 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1770 DEBUG(dbgs() << " from physreg "
1771 << TRI->getName(InReg) << " for vreg"
1772 << VirtReg <<" instead of reloading into physreg "
1773 << TRI->getName(Phys) << '\n');
1776 } else if (InReg && InReg != Phys) {
1778 DEBUG(dbgs() << "Reusing RM#"
1779 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1781 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1782 DEBUG(dbgs() << " from physreg "
1783 << TRI->getName(InReg) << " for vreg"
1784 << VirtReg <<" by copying it into physreg "
1785 << TRI->getName(Phys) << '\n');
1787 // If the reloaded / remat value is available in another register,
1788 // copy it to the desired register.
1790 // Back-schedule reloads and remats.
1791 MachineBasicBlock::iterator InsertLoc =
1792 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1794 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI->getDebugLoc(),
1795 TII->get(TargetOpcode::COPY), Phys)
1796 .addReg(InReg, RegState::Kill);
1798 // This invalidates Phys.
1799 Spills.ClobberPhysReg(Phys);
1800 // Remember it's available.
1801 Spills.addAvailable(SSorRMId, Phys);
1803 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1804 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1806 DEBUG(dbgs() << '\t' << *CopyMI);
1811 // Back-schedule reloads and remats.
1812 MachineBasicBlock::iterator InsertLoc =
1813 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1816 if (VRM->isReMaterialized(VirtReg)) {
1817 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1819 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1820 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
1821 MachineInstr *LoadMI = prior(InsertLoc);
1822 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1824 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1827 // This invalidates Phys.
1828 Spills.ClobberPhysReg(Phys);
1829 // Remember it's available.
1830 Spills.addAvailable(SSorRMId, Phys);
1832 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1833 DEBUG(dbgs() << '\t' << *prior(MII));
1838 /// InsertSpills - Insert spills after MI if requested by VRM. Return
1839 /// true if spills were inserted.
1840 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1841 if (!VRM->isSpillPt(MI))
1843 MachineBasicBlock::iterator MII = MI;
1844 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1845 VRM->getSpillPtSpills(MI);
1846 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1847 unsigned VirtReg = SpillRegs[i].first;
1848 bool isKill = SpillRegs[i].second;
1849 if (!VRM->getPreSplitReg(VirtReg))
1850 continue; // Split interval spilled again.
1851 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1852 unsigned Phys = VRM->getPhys(VirtReg);
1853 int StackSlot = VRM->getStackSlot(VirtReg);
1854 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1855 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1857 MachineInstr *StoreMI = prior(oldNextMII);
1858 VRM->addSpillSlotUse(StackSlot, StoreMI);
1859 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1860 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1866 /// ProcessUses - Process all of MI's spilled operands and all available
1868 void LocalRewriter::ProcessUses(MachineInstr &MI, AvailableSpills &Spills,
1869 std::vector<MachineInstr*> &MaybeDeadStores,
1870 BitVector &RegKills,
1871 ReuseInfo &ReusedOperands,
1872 std::vector<MachineOperand*> &KillOps) {
1874 SmallSet<unsigned, 2> KilledMIRegs;
1875 SmallVector<unsigned, 4> VirtUseOps;
1876 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1877 MachineOperand &MO = MI.getOperand(i);
1878 if (!MO.isReg() || MO.getReg() == 0)
1879 continue; // Ignore non-register operands.
1881 unsigned VirtReg = MO.getReg();
1882 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1883 // Ignore physregs for spilling, but remember that it is used by this
1885 MRI->setPhysRegUsed(VirtReg);
1889 // We want to process implicit virtual register uses first.
1890 if (MO.isImplicit())
1891 // If the virtual register is implicitly defined, emit a implicit_def
1892 // before so scavenger knows it's "defined".
1893 // FIXME: This is a horrible hack done the by register allocator to
1894 // remat a definition with virtual register operand.
1895 VirtUseOps.insert(VirtUseOps.begin(), i);
1897 VirtUseOps.push_back(i);
1899 // A partial def causes problems because the same operand both reads and
1900 // writes the register. This rewriter is designed to rewrite uses and defs
1901 // separately, so a partial def would already have been rewritten to a
1902 // physreg by the time we get to processing defs.
1903 // Add an implicit use operand to model the partial def.
1904 if (MO.isDef() && MO.getSubReg() && MI.readsVirtualRegister(VirtReg) &&
1905 MI.findRegisterUseOperandIdx(VirtReg) == -1) {
1906 VirtUseOps.insert(VirtUseOps.begin(), MI.getNumOperands());
1907 MI.addOperand(MachineOperand::CreateReg(VirtReg,
1909 true)); // isImplicit
1910 DEBUG(dbgs() << "Partial redef: " << MI);
1914 // Process all of the spilled uses and all non spilled reg references.
1915 SmallVector<int, 2> PotentialDeadStoreSlots;
1916 KilledMIRegs.clear();
1917 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1918 unsigned i = VirtUseOps[j];
1919 unsigned VirtReg = MI.getOperand(i).getReg();
1920 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1921 "Not a virtual register?");
1923 unsigned SubIdx = MI.getOperand(i).getSubReg();
1924 if (VRM->isAssignedReg(VirtReg)) {
1925 // This virtual register was assigned a physreg!
1926 unsigned Phys = VRM->getPhys(VirtReg);
1927 MRI->setPhysRegUsed(Phys);
1928 if (MI.getOperand(i).isDef())
1929 ReusedOperands.markClobbered(Phys);
1930 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1931 if (VRM->isImplicitlyDefined(VirtReg))
1932 // FIXME: Is this needed?
1933 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1934 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1938 // This virtual register is now known to be a spilled value.
1939 if (!MI.getOperand(i).isUse())
1940 continue; // Handle defs in the loop below (handle use&def here though)
1942 bool AvoidReload = MI.getOperand(i).isUndef();
1943 // Check if it is defined by an implicit def. It should not be spilled.
1944 // Note, this is for correctness reason. e.g.
1945 // 8 %reg1024<def> = IMPLICIT_DEF
1946 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1947 // The live range [12, 14) are not part of the r1024 live interval since
1948 // it's defined by an implicit def. It will not conflicts with live
1949 // interval of r1025. Now suppose both registers are spilled, you can
1950 // easily see a situation where both registers are reloaded before
1951 // the INSERT_SUBREG and both target registers that would overlap.
1952 bool DoReMat = VRM->isReMaterialized(VirtReg);
1953 int SSorRMId = DoReMat
1954 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1955 int ReuseSlot = SSorRMId;
1957 // Check to see if this stack slot is available.
1958 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1960 // If this is a sub-register use, make sure the reuse register is in the
1961 // right register class. For example, for x86 not all of the 32-bit
1962 // registers have accessible sub-registers.
1963 // Similarly so for EXTRACT_SUBREG. Consider this:
1965 // MOV32_mr fi#1, EDI
1967 // = EXTRACT_SUBREG fi#1
1968 // fi#1 is available in EDI, but it cannot be reused because it's not in
1969 // the right register file.
1970 if (PhysReg && !AvoidReload && SubIdx) {
1971 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1972 if (!RC->contains(PhysReg))
1976 if (PhysReg && !AvoidReload) {
1977 // This spilled operand might be part of a two-address operand. If this
1978 // is the case, then changing it will necessarily require changing the
1979 // def part of the instruction as well. However, in some cases, we
1980 // aren't allowed to modify the reused register. If none of these cases
1982 bool CanReuse = true;
1983 bool isTied = MI.isRegTiedToDefOperand(i);
1985 // Okay, we have a two address operand. We can reuse this physreg as
1986 // long as we are allowed to clobber the value and there isn't an
1987 // earlier def that has already clobbered the physreg.
1988 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1989 Spills.canClobberPhysReg(PhysReg);
1991 // If this is an asm, and a PhysReg alias is used elsewhere as an
1992 // earlyclobber operand, we can't also use it as an input.
1993 if (MI.isInlineAsm()) {
1994 for (unsigned k = 0, e = MI.getNumOperands(); k != e; ++k) {
1995 MachineOperand &MOk = MI.getOperand(k);
1996 if (MOk.isReg() && MOk.isEarlyClobber() &&
1997 TRI->regsOverlap(MOk.getReg(), PhysReg)) {
1999 DEBUG(dbgs() << "Not reusing physreg " << TRI->getName(PhysReg)
2000 << " for vreg" << VirtReg << ": " << MOk << '\n');
2007 // If this stack slot value is already available, reuse it!
2008 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2009 DEBUG(dbgs() << "Reusing RM#"
2010 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2012 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2013 DEBUG(dbgs() << " from physreg "
2014 << TRI->getName(PhysReg) << " for vreg"
2015 << VirtReg <<" instead of reloading into physreg "
2016 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2017 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2018 MI.getOperand(i).setReg(RReg);
2019 MI.getOperand(i).setSubReg(0);
2021 // The only technical detail we have is that we don't know that
2022 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2023 // later in the instruction. In particular, consider 'op V1, V2'.
2024 // If V1 is available in physreg R0, we would choose to reuse it
2025 // here, instead of reloading it into the register the allocator
2026 // indicated (say R1). However, V2 might have to be reloaded
2027 // later, and it might indicate that it needs to live in R0. When
2028 // this occurs, we need to have information available that
2029 // indicates it is safe to use R1 for the reload instead of R0.
2031 // To further complicate matters, we might conflict with an alias,
2032 // or R0 and R1 might not be compatible with each other. In this
2033 // case, we actually insert a reload for V1 in R1, ensuring that
2034 // we can get at R0 or its alias.
2035 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2036 VRM->getPhys(VirtReg), VirtReg);
2038 // Only mark it clobbered if this is a use&def operand.
2039 ReusedOperands.markClobbered(PhysReg);
2042 if (MI.getOperand(i).isKill() &&
2043 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2045 // The store of this spilled value is potentially dead, but we
2046 // won't know for certain until we've confirmed that the re-use
2047 // above is valid, which means waiting until the other operands
2048 // are processed. For now we just track the spill slot, we'll
2049 // remove it after the other operands are processed if valid.
2051 PotentialDeadStoreSlots.push_back(ReuseSlot);
2054 // Mark is isKill if it's there no other uses of the same virtual
2055 // register and it's not a two-address operand. IsKill will be
2056 // unset if reg is reused.
2057 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2058 MI.getOperand(i).setIsKill();
2059 KilledMIRegs.insert(VirtReg);
2065 // Otherwise we have a situation where we have a two-address instruction
2066 // whose mod/ref operand needs to be reloaded. This reload is already
2067 // available in some register "PhysReg", but if we used PhysReg as the
2068 // operand to our 2-addr instruction, the instruction would modify
2069 // PhysReg. This isn't cool if something later uses PhysReg and expects
2070 // to get its initial value.
2072 // To avoid this problem, and to avoid doing a load right after a store,
2073 // we emit a copy from PhysReg into the designated register for this
2076 // This case also applies to an earlyclobber'd PhysReg.
2077 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2078 assert(DesignatedReg && "Must map virtreg to physreg!");
2080 // Note that, if we reused a register for a previous operand, the
2081 // register we want to reload into might not actually be
2082 // available. If this occurs, use the register indicated by the
2084 if (ReusedOperands.hasReuses())
2085 DesignatedReg = ReusedOperands.
2086 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2087 MaybeDeadStores, RegKills, KillOps, *VRM);
2089 // If the mapped designated register is actually the physreg we have
2090 // incoming, we don't need to inserted a dead copy.
2091 if (DesignatedReg == PhysReg) {
2092 // If this stack slot value is already available, reuse it!
2093 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2094 DEBUG(dbgs() << "Reusing RM#"
2095 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2097 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2098 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2099 << " for vreg" << VirtReg
2100 << " instead of reloading into same physreg.\n");
2101 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2102 MI.getOperand(i).setReg(RReg);
2103 MI.getOperand(i).setSubReg(0);
2104 ReusedOperands.markClobbered(RReg);
2109 MRI->setPhysRegUsed(DesignatedReg);
2110 ReusedOperands.markClobbered(DesignatedReg);
2112 // Back-schedule reloads and remats.
2113 MachineBasicBlock::iterator InsertLoc =
2114 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2115 SSorRMId, TII, *MBB->getParent());
2116 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI.getDebugLoc(),
2117 TII->get(TargetOpcode::COPY),
2118 DesignatedReg).addReg(PhysReg);
2119 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2120 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2122 // This invalidates DesignatedReg.
2123 Spills.ClobberPhysReg(DesignatedReg);
2125 Spills.addAvailable(ReuseSlot, DesignatedReg);
2127 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2128 MI.getOperand(i).setReg(RReg);
2129 MI.getOperand(i).setSubReg(0);
2130 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2135 // Otherwise, reload it and remember that we have it.
2136 PhysReg = VRM->getPhys(VirtReg);
2137 assert(PhysReg && "Must map virtreg to physreg!");
2139 // Note that, if we reused a register for a previous operand, the
2140 // register we want to reload into might not actually be
2141 // available. If this occurs, use the register indicated by the
2143 if (ReusedOperands.hasReuses())
2144 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2145 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2147 MRI->setPhysRegUsed(PhysReg);
2148 ReusedOperands.markClobbered(PhysReg);
2152 // Back-schedule reloads and remats.
2153 MachineBasicBlock::iterator InsertLoc =
2154 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI, DoReMat,
2155 SSorRMId, TII, *MBB->getParent());
2158 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2160 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2161 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2162 MachineInstr *LoadMI = prior(InsertLoc);
2163 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2165 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2167 // This invalidates PhysReg.
2168 Spills.ClobberPhysReg(PhysReg);
2170 // Any stores to this stack slot are not dead anymore.
2172 MaybeDeadStores[SSorRMId] = NULL;
2173 Spills.addAvailable(SSorRMId, PhysReg);
2174 // Assumes this is the last use. IsKill will be unset if reg is reused
2175 // unless it's a two-address operand.
2176 if (!MI.isRegTiedToDefOperand(i) &&
2177 KilledMIRegs.count(VirtReg) == 0) {
2178 MI.getOperand(i).setIsKill();
2179 KilledMIRegs.insert(VirtReg);
2182 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2183 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2185 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2186 MI.getOperand(i).setReg(RReg);
2187 MI.getOperand(i).setSubReg(0);
2190 // Ok - now we can remove stores that have been confirmed dead.
2191 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2192 // This was the last use and the spilled value is still available
2193 // for reuse. That means the spill was unnecessary!
2194 int PDSSlot = PotentialDeadStoreSlots[j];
2195 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2197 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2198 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2199 VRM->RemoveMachineInstrFromMaps(DeadStore);
2200 MBB->erase(DeadStore);
2201 MaybeDeadStores[PDSSlot] = NULL;
2208 /// rewriteMBB - Keep track of which spills are available even after the
2209 /// register allocator is done with them. If possible, avoid reloading vregs.
2211 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
2212 AvailableSpills &Spills, BitVector &RegKills,
2213 std::vector<MachineOperand*> &KillOps) {
2215 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
2216 << MBB->getName() << "':\n");
2218 MachineFunction &MF = *MBB->getParent();
2220 // MaybeDeadStores - When we need to write a value back into a stack slot,
2221 // keep track of the inserted store. If the stack slot value is never read
2222 // (because the value was used from some available register, for example), and
2223 // subsequently stored to, the original store is dead. This map keeps track
2224 // of inserted stores that are not used. If we see a subsequent store to the
2225 // same stack slot, the original store is deleted.
2226 std::vector<MachineInstr*> MaybeDeadStores;
2227 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
2229 // ReMatDefs - These are rematerializable def MIs which are not deleted.
2230 SmallSet<MachineInstr*, 4> ReMatDefs;
2232 // Keep track of the registers we have already spilled in case there are
2233 // multiple defs of the same register in MI.
2234 SmallSet<unsigned, 8> SpilledMIRegs;
2238 KillOps.resize(TRI->getNumRegs(), NULL);
2240 DistanceMap.clear();
2241 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2243 MachineBasicBlock::iterator NextMII = llvm::next(MII);
2245 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
2246 NextMII = llvm::next(MII);
2248 if (InsertEmergencySpills(MII))
2249 NextMII = llvm::next(MII);
2251 InsertRestores(MII, Spills, RegKills, KillOps);
2253 if (InsertSpills(MII))
2254 NextMII = llvm::next(MII);
2256 bool Erased = false;
2257 bool BackTracked = false;
2258 MachineInstr &MI = *MII;
2260 // Remember DbgValue's which reference stack slots.
2261 if (MI.isDebugValue() && MI.getOperand(0).isFI())
2262 Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
2264 /// ReusedOperands - Keep track of operand reuse in case we need to undo
2266 ReuseInfo ReusedOperands(MI, TRI);
2268 ProcessUses(MI, Spills, MaybeDeadStores, RegKills, ReusedOperands, KillOps);
2270 DEBUG(dbgs() << '\t' << MI);
2273 // If we have folded references to memory operands, make sure we clear all
2274 // physical registers that may contain the value of the spilled virtual
2277 // Copy the folded virts to a small vector, we may change MI2VirtMap.
2278 SmallVector<std::pair<unsigned, VirtRegMap::ModRef>, 4> FoldedVirts;
2280 for (std::pair<VirtRegMap::MI2VirtMapTy::const_iterator,
2281 VirtRegMap::MI2VirtMapTy::const_iterator> FVRange =
2282 VRM->getFoldedVirts(&MI);
2283 FVRange.first != FVRange.second; ++FVRange.first)
2284 FoldedVirts.push_back(FVRange.first->second);
2286 SmallSet<int, 2> FoldedSS;
2287 for (unsigned FVI = 0, FVE = FoldedVirts.size(); FVI != FVE; ++FVI) {
2288 unsigned VirtReg = FoldedVirts[FVI].first;
2289 VirtRegMap::ModRef MR = FoldedVirts[FVI].second;
2290 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2292 int SS = VRM->getStackSlot(VirtReg);
2293 if (SS == VirtRegMap::NO_STACK_SLOT)
2295 FoldedSS.insert(SS);
2296 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2298 // If this folded instruction is just a use, check to see if it's a
2299 // straight load from the virt reg slot.
2300 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2302 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2303 if (DestReg && FrameIdx == SS) {
2304 // If this spill slot is available, turn it into a copy (or nothing)
2305 // instead of leaving it as a load!
2306 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2307 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2308 if (DestReg != InReg) {
2309 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2310 MachineInstr *CopyMI = BuildMI(*MBB, &MI, MI.getDebugLoc(),
2311 TII->get(TargetOpcode::COPY))
2312 .addReg(DestReg, RegState::Define, DefMO->getSubReg())
2313 .addReg(InReg, RegState::Kill);
2314 // Revisit the copy so we make sure to notice the effects of the
2315 // operation on the destreg (either needing to RA it if it's
2316 // virtual or needing to clobber any values if it's physical).
2318 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2321 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2322 // Unset last kill since it's being reused.
2323 InvalidateKill(InReg, TRI, RegKills, KillOps);
2324 Spills.disallowClobberPhysReg(InReg);
2327 InvalidateKills(MI, TRI, RegKills, KillOps);
2328 VRM->RemoveMachineInstrFromMaps(&MI);
2331 goto ProcessNextInst;
2334 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2335 SmallVector<MachineInstr*, 4> NewMIs;
2337 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)){
2338 MBB->insert(MII, NewMIs[0]);
2339 InvalidateKills(MI, TRI, RegKills, KillOps);
2340 VRM->RemoveMachineInstrFromMaps(&MI);
2343 --NextMII; // backtrack to the unfolded instruction.
2345 goto ProcessNextInst;
2350 // If this reference is not a use, any previous store is now dead.
2351 // Otherwise, the store to this stack slot is not dead anymore.
2352 MachineInstr* DeadStore = MaybeDeadStores[SS];
2354 bool isDead = !(MR & VirtRegMap::isRef);
2355 MachineInstr *NewStore = NULL;
2356 if (MR & VirtRegMap::isModRef) {
2357 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2358 SmallVector<MachineInstr*, 4> NewMIs;
2359 // We can reuse this physreg as long as we are allowed to clobber
2360 // the value and there isn't an earlier def that has already clobbered
2363 !ReusedOperands.isClobbered(PhysReg) &&
2364 Spills.canClobberPhysReg(PhysReg) &&
2365 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2366 MachineOperand *KillOpnd =
2367 DeadStore->findRegisterUseOperand(PhysReg, true);
2368 // Note, if the store is storing a sub-register, it's possible the
2369 // super-register is needed below.
2370 if (KillOpnd && !KillOpnd->getSubReg() &&
2371 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2372 MBB->insert(MII, NewMIs[0]);
2373 NewStore = NewMIs[1];
2374 MBB->insert(MII, NewStore);
2375 VRM->addSpillSlotUse(SS, NewStore);
2376 InvalidateKills(MI, TRI, RegKills, KillOps);
2377 VRM->RemoveMachineInstrFromMaps(&MI);
2381 --NextMII; // backtrack to the unfolded instruction.
2389 if (isDead) { // Previous store is dead.
2390 // If we get here, the store is dead, nuke it now.
2391 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2392 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2393 VRM->RemoveMachineInstrFromMaps(DeadStore);
2394 MBB->erase(DeadStore);
2399 MaybeDeadStores[SS] = NULL;
2401 // Treat this store as a spill merged into a copy. That makes the
2402 // stack slot value available.
2403 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2404 goto ProcessNextInst;
2408 // If the spill slot value is available, and this is a new definition of
2409 // the value, the value is not available anymore.
2410 if (MR & VirtRegMap::isMod) {
2411 // Notice that the value in this stack slot has been modified.
2412 Spills.ModifyStackSlotOrReMat(SS);
2414 // If this is *just* a mod of the value, check to see if this is just a
2415 // store to the spill slot (i.e. the spill got merged into the copy). If
2416 // so, realize that the vreg is available now, and add the store to the
2417 // MaybeDeadStore info.
2419 if (!(MR & VirtRegMap::isRef)) {
2420 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2421 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2422 "Src hasn't been allocated yet?");
2424 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2425 Spills, RegKills, KillOps, TRI)) {
2426 NextMII = llvm::next(MII);
2428 goto ProcessNextInst;
2431 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2432 // this as a potentially dead store in case there is a subsequent
2433 // store into the stack slot without a read from it.
2434 MaybeDeadStores[StackSlot] = &MI;
2436 // If the stack slot value was previously available in some other
2437 // register, change it now. Otherwise, make the register
2438 // available in PhysReg.
2439 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2445 // Process all of the spilled defs.
2446 SpilledMIRegs.clear();
2447 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2448 MachineOperand &MO = MI.getOperand(i);
2449 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2452 unsigned VirtReg = MO.getReg();
2453 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2454 // Check to see if this is a noop copy. If so, eliminate the
2455 // instruction before considering the dest reg to be changed.
2456 // Also check if it's copying from an "undef", if so, we can't
2457 // eliminate this or else the undef marker is lost and it will
2458 // confuses the scavenger. This is extremely rare.
2459 if (MI.isIdentityCopy() && !MI.getOperand(1).isUndef() &&
2460 MI.getNumOperands() == 2) {
2462 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2463 SmallVector<unsigned, 2> KillRegs;
2464 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2465 if (MO.isDead() && !KillRegs.empty()) {
2466 // Source register or an implicit super/sub-register use is killed.
2467 assert(TRI->regsOverlap(KillRegs[0], MI.getOperand(0).getReg()));
2468 // Last def is now dead.
2469 TransferDeadness(MI.getOperand(1).getReg(), RegKills, KillOps);
2471 VRM->RemoveMachineInstrFromMaps(&MI);
2474 Spills.disallowClobberPhysReg(VirtReg);
2475 goto ProcessNextInst;
2478 // If it's not a no-op copy, it clobbers the value in the destreg.
2479 Spills.ClobberPhysReg(VirtReg);
2480 ReusedOperands.markClobbered(VirtReg);
2482 // Check to see if this instruction is a load from a stack slot into
2483 // a register. If so, this provides the stack slot value in the reg.
2485 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2486 assert(DestReg == VirtReg && "Unknown load situation!");
2488 // If it is a folded reference, then it's not safe to clobber.
2489 bool Folded = FoldedSS.count(FrameIdx);
2490 // Otherwise, if it wasn't available, remember that it is now!
2491 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2492 goto ProcessNextInst;
2498 unsigned SubIdx = MO.getSubReg();
2499 bool DoReMat = VRM->isReMaterialized(VirtReg);
2501 ReMatDefs.insert(&MI);
2503 // The only vregs left are stack slot definitions.
2504 int StackSlot = VRM->getStackSlot(VirtReg);
2505 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2507 // If this def is part of a two-address operand, make sure to execute
2508 // the store from the correct physical register.
2511 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2512 PhysReg = MI.getOperand(TiedOp).getReg();
2514 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2515 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2516 "Can't find corresponding super-register!");
2520 PhysReg = VRM->getPhys(VirtReg);
2521 if (ReusedOperands.isClobbered(PhysReg)) {
2522 // Another def has taken the assigned physreg. It must have been a
2523 // use&def which got it due to reuse. Undo the reuse!
2524 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2525 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2529 assert(PhysReg && "VR not assigned a physical register?");
2530 MRI->setPhysRegUsed(PhysReg);
2531 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2532 ReusedOperands.markClobbered(RReg);
2533 MI.getOperand(i).setReg(RReg);
2534 MI.getOperand(i).setSubReg(0);
2536 if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
2537 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2538 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2539 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2540 NextMII = llvm::next(MII);
2542 // Check to see if this is a noop copy. If so, eliminate the
2543 // instruction before considering the dest reg to be changed.
2544 if (MI.isIdentityCopy()) {
2546 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2547 InvalidateKills(MI, TRI, RegKills, KillOps);
2548 VRM->RemoveMachineInstrFromMaps(&MI);
2551 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2552 goto ProcessNextInst;
2557 // Delete dead instructions without side effects.
2558 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2559 InvalidateKills(MI, TRI, RegKills, KillOps);
2560 VRM->RemoveMachineInstrFromMaps(&MI);
2565 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2566 if (!Erased && !BackTracked) {
2567 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2568 UpdateKills(*II, TRI, RegKills, KillOps);
2575 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2576 switch (RewriterOpt) {
2577 default: llvm_unreachable("Unreachable!");
2579 return new LocalRewriter();
2581 return new TrivialRewriter();