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() {}
65 /// This class is intended for use with the new spilling framework only. It
66 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
68 struct TrivialRewriter : public VirtRegRewriter {
70 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
72 DEBUG(errs() << "********** REWRITE MACHINE CODE **********\n");
73 DEBUG(errs() << "********** Function: "
74 << MF.getFunction()->getName() << '\n');
75 DEBUG(errs() << "**** Machine Instrs"
76 << "(NOTE! Does not include spills and reloads!) ****\n");
79 MachineRegisterInfo *mri = &MF.getRegInfo();
80 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
84 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
85 liItr != liEnd; ++liItr) {
87 const LiveInterval *li = liItr->second;
88 unsigned reg = li->reg;
90 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
92 mri->setPhysRegUsed(reg);
95 if (!VRM.hasPhys(reg))
97 unsigned pReg = VRM.getPhys(reg);
98 mri->setPhysRegUsed(pReg);
99 for (MachineRegisterInfo::reg_iterator regItr = mri->reg_begin(reg),
100 regEnd = mri->reg_end(); regItr != regEnd;) {
101 MachineOperand &mop = regItr.getOperand();
102 assert(mop.isReg() && mop.getReg() == reg && "reg_iterator broken?");
104 unsigned subRegIdx = mop.getSubReg();
105 unsigned pRegOp = subRegIdx ? tri->getSubReg(pReg, subRegIdx) : pReg;
113 DEBUG(errs() << "**** Post Machine Instrs ****\n");
123 // ************************************************************************ //
127 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
128 /// from top down, keep track of which spill slots or remat are available in
131 /// Note that not all physregs are created equal here. In particular, some
132 /// physregs are reloads that we are allowed to clobber or ignore at any time.
133 /// Other physregs are values that the register allocated program is using
134 /// that we cannot CHANGE, but we can read if we like. We keep track of this
135 /// on a per-stack-slot / remat id basis as the low bit in the value of the
136 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
137 /// this bit and addAvailable sets it if.
138 class AvailableSpills {
139 const TargetRegisterInfo *TRI;
140 const TargetInstrInfo *TII;
142 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
143 // or remat'ed virtual register values that are still available, due to
144 // being loaded or stored to, but not invalidated yet.
145 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
147 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
148 // indicating which stack slot values are currently held by a physreg. This
149 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
150 // physreg is modified.
151 std::multimap<unsigned, int> PhysRegsAvailable;
153 void disallowClobberPhysRegOnly(unsigned PhysReg);
155 void ClobberPhysRegOnly(unsigned PhysReg);
157 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
158 : TRI(tri), TII(tii) {
161 /// clear - Reset the state.
163 SpillSlotsOrReMatsAvailable.clear();
164 PhysRegsAvailable.clear();
167 const TargetRegisterInfo *getRegInfo() const { return TRI; }
169 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
170 /// available in a physical register, return that PhysReg, otherwise
172 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
173 std::map<int, unsigned>::const_iterator I =
174 SpillSlotsOrReMatsAvailable.find(Slot);
175 if (I != SpillSlotsOrReMatsAvailable.end()) {
176 return I->second >> 1; // Remove the CanClobber bit.
181 /// addAvailable - Mark that the specified stack slot / remat is available
182 /// in the specified physreg. If CanClobber is true, the physreg can be
183 /// modified at any time without changing the semantics of the program.
184 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
185 // If this stack slot is thought to be available in some other physreg,
186 // remove its record.
187 ModifyStackSlotOrReMat(SlotOrReMat);
189 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
190 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
191 (unsigned)CanClobber;
193 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
194 DEBUG(errs() << "Remembering RM#"
195 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
197 DEBUG(errs() << "Remembering SS#" << SlotOrReMat);
198 DEBUG(errs() << " in physreg " << TRI->getName(Reg) << "\n");
201 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
202 /// the value of the specified stackslot register if it desires. The
203 /// specified stack slot must be available in a physreg for this query to
205 bool canClobberPhysRegForSS(int SlotOrReMat) const {
206 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
207 "Value not available!");
208 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
211 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
212 /// physical register where values for some stack slot(s) might be
214 bool canClobberPhysReg(unsigned PhysReg) const {
215 std::multimap<unsigned, int>::const_iterator I =
216 PhysRegsAvailable.lower_bound(PhysReg);
217 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
218 int SlotOrReMat = I->second;
220 if (!canClobberPhysRegForSS(SlotOrReMat))
226 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
227 /// stackslot register. The register is still available but is no longer
228 /// allowed to be modifed.
229 void disallowClobberPhysReg(unsigned PhysReg);
231 /// ClobberPhysReg - This is called when the specified physreg changes
232 /// value. We use this to invalidate any info about stuff that lives in
233 /// it and any of its aliases.
234 void ClobberPhysReg(unsigned PhysReg);
236 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
237 /// slot changes. This removes information about which register the
238 /// previous value for this slot lives in (as the previous value is dead
240 void ModifyStackSlotOrReMat(int SlotOrReMat);
242 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
243 /// into the specified MBB. Add available physical registers as potential
244 /// live-in's. If they are reused in the MBB, they will be added to the
245 /// live-in set to make register scavenger and post-allocation scheduler.
246 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
247 std::vector<MachineOperand*> &KillOps);
252 // ************************************************************************ //
254 // Given a location where a reload of a spilled register or a remat of
255 // a constant is to be inserted, attempt to find a safe location to
256 // insert the load at an earlier point in the basic-block, to hide
257 // latency of the load and to avoid address-generation interlock
259 static MachineBasicBlock::iterator
260 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
261 MachineBasicBlock::iterator const Begin,
263 const TargetRegisterInfo *TRI,
266 const TargetInstrInfo *TII,
267 const MachineFunction &MF)
272 // Spill backscheduling is of primary interest to addresses, so
273 // don't do anything if the register isn't in the register class
274 // used for pointers.
276 const TargetLowering *TL = MF.getTarget().getTargetLowering();
278 if (!TL->isTypeLegal(TL->getPointerTy()))
279 // Believe it or not, this is true on PIC16.
282 const TargetRegisterClass *ptrRegClass =
283 TL->getRegClassFor(TL->getPointerTy());
284 if (!ptrRegClass->contains(PhysReg))
287 // Scan upwards through the preceding instructions. If an instruction doesn't
288 // reference the stack slot or the register we're loading, we can
289 // backschedule the reload up past it.
290 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
291 while (NewInsertLoc != Begin) {
292 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
293 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
294 MachineOperand &Op = Prev->getOperand(i);
295 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
298 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
299 Prev->findRegisterDefOperand(PhysReg))
301 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
302 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
303 Prev->findRegisterDefOperand(*Alias))
309 // If we made it to the beginning of the block, turn around and move back
310 // down just past any existing reloads. They're likely to be reloads/remats
311 // for instructions earlier than what our current reload/remat is for, so
312 // they should be scheduled earlier.
313 if (NewInsertLoc == Begin) {
315 while (InsertLoc != NewInsertLoc &&
316 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
317 TII->isTriviallyReMaterializable(NewInsertLoc)))
326 // ReusedOp - For each reused operand, we keep track of a bit of information,
327 // in case we need to rollback upon processing a new operand. See comments
330 // The MachineInstr operand that reused an available value.
333 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
334 unsigned StackSlotOrReMat;
336 // PhysRegReused - The physical register the value was available in.
337 unsigned PhysRegReused;
339 // AssignedPhysReg - The physreg that was assigned for use by the reload.
340 unsigned AssignedPhysReg;
342 // VirtReg - The virtual register itself.
345 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
347 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
348 AssignedPhysReg(apr), VirtReg(vreg) {}
351 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
352 /// is reused instead of reloaded.
355 std::vector<ReusedOp> Reuses;
356 BitVector PhysRegsClobbered;
358 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
359 PhysRegsClobbered.resize(tri->getNumRegs());
362 bool hasReuses() const {
363 return !Reuses.empty();
366 /// addReuse - If we choose to reuse a virtual register that is already
367 /// available instead of reloading it, remember that we did so.
368 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
369 unsigned PhysRegReused, unsigned AssignedPhysReg,
371 // If the reload is to the assigned register anyway, no undo will be
373 if (PhysRegReused == AssignedPhysReg) return;
375 // Otherwise, remember this.
376 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
377 AssignedPhysReg, VirtReg));
380 void markClobbered(unsigned PhysReg) {
381 PhysRegsClobbered.set(PhysReg);
384 bool isClobbered(unsigned PhysReg) const {
385 return PhysRegsClobbered.test(PhysReg);
388 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
389 /// is some other operand that is using the specified register, either pick
390 /// a new register to use, or evict the previous reload and use this reg.
391 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
392 MachineFunction &MF, MachineInstr *MI,
393 AvailableSpills &Spills,
394 std::vector<MachineInstr*> &MaybeDeadStores,
395 SmallSet<unsigned, 8> &Rejected,
397 std::vector<MachineOperand*> &KillOps,
400 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
401 /// 'Rejected' set to remember which registers have been considered and
402 /// rejected for the reload. This avoids infinite looping in case like
405 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
406 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
408 /// sees r1 is taken by t2, tries t2's reload register r0
409 /// sees r0 is taken by t3, tries t3's reload register r1
410 /// sees r1 is taken by t2, tries t2's reload register r0 ...
411 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
412 AvailableSpills &Spills,
413 std::vector<MachineInstr*> &MaybeDeadStores,
415 std::vector<MachineOperand*> &KillOps,
417 SmallSet<unsigned, 8> Rejected;
418 MachineFunction &MF = *MI->getParent()->getParent();
419 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
420 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
421 Rejected, RegKills, KillOps, VRM);
427 // ****************** //
428 // Utility Functions //
429 // ****************** //
431 /// findSinglePredSuccessor - Return via reference a vector of machine basic
432 /// blocks each of which is a successor of the specified BB and has no other
434 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
435 SmallVectorImpl<MachineBasicBlock *> &Succs) {
436 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
437 SE = MBB->succ_end(); SI != SE; ++SI) {
438 MachineBasicBlock *SuccMBB = *SI;
439 if (SuccMBB->pred_size() == 1)
440 Succs.push_back(SuccMBB);
444 /// InvalidateKill - Invalidate register kill information for a specific
445 /// register. This also unsets the kills marker on the last kill operand.
446 static void InvalidateKill(unsigned Reg,
447 const TargetRegisterInfo* TRI,
449 std::vector<MachineOperand*> &KillOps) {
451 KillOps[Reg]->setIsKill(false);
452 // KillOps[Reg] might be a def of a super-register.
453 unsigned KReg = KillOps[Reg]->getReg();
454 KillOps[KReg] = NULL;
455 RegKills.reset(KReg);
456 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
458 KillOps[*SR]->setIsKill(false);
466 /// InvalidateKills - MI is going to be deleted. If any of its operands are
467 /// marked kill, then invalidate the information.
468 static void InvalidateKills(MachineInstr &MI,
469 const TargetRegisterInfo* TRI,
471 std::vector<MachineOperand*> &KillOps,
472 SmallVector<unsigned, 2> *KillRegs = NULL) {
473 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
474 MachineOperand &MO = MI.getOperand(i);
475 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
477 unsigned Reg = MO.getReg();
478 if (TargetRegisterInfo::isVirtualRegister(Reg))
481 KillRegs->push_back(Reg);
482 assert(Reg < KillOps.size());
483 if (KillOps[Reg] == &MO) {
486 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
496 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
497 /// (since its spill instruction is removed), mark it isDead. Also checks if
498 /// the def MI has other definition operands that are not dead. Returns it by
500 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
501 MachineInstr &NewDef, unsigned Reg,
503 const TargetRegisterInfo *TRI) {
504 // Due to remat, it's possible this reg isn't being reused. That is,
505 // the def of this reg (by prev MI) is now dead.
506 MachineInstr *DefMI = I;
507 MachineOperand *DefOp = NULL;
508 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
509 MachineOperand &MO = DefMI->getOperand(i);
510 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
512 if (MO.getReg() == Reg)
514 else if (!MO.isDead())
520 bool FoundUse = false, Done = false;
521 MachineBasicBlock::iterator E = &NewDef;
523 for (; !Done && I != E; ++I) {
524 MachineInstr *NMI = I;
525 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
526 MachineOperand &MO = NMI->getOperand(j);
527 if (!MO.isReg() || MO.getReg() == 0 ||
528 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
532 Done = true; // Stop after scanning all the operands of this MI.
543 /// UpdateKills - Track and update kill info. If a MI reads a register that is
544 /// marked kill, then it must be due to register reuse. Transfer the kill info
546 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
548 std::vector<MachineOperand*> &KillOps) {
549 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
550 MachineOperand &MO = MI.getOperand(i);
551 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
553 unsigned Reg = MO.getReg();
557 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
558 // That can't be right. Register is killed but not re-defined and it's
559 // being reused. Let's fix that.
560 KillOps[Reg]->setIsKill(false);
561 // KillOps[Reg] might be a def of a super-register.
562 unsigned KReg = KillOps[Reg]->getReg();
563 KillOps[KReg] = NULL;
564 RegKills.reset(KReg);
566 // Must be a def of a super-register. Its other sub-regsters are no
567 // longer killed as well.
568 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
573 // Check for subreg kills as well.
579 // = d4 <avoiding reload>
580 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
582 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
583 KillOps[SReg]->setIsKill(false);
584 unsigned KReg = KillOps[SReg]->getReg();
585 KillOps[KReg] = NULL;
586 RegKills.reset(KReg);
588 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
589 KillOps[*SSR] = NULL;
590 RegKills.reset(*SSR);
599 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
606 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
607 const MachineOperand &MO = MI.getOperand(i);
608 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
610 unsigned Reg = MO.getReg();
613 // It also defines (or partially define) aliases.
614 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
618 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
625 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
627 static void ReMaterialize(MachineBasicBlock &MBB,
628 MachineBasicBlock::iterator &MII,
629 unsigned DestReg, unsigned Reg,
630 const TargetInstrInfo *TII,
631 const TargetRegisterInfo *TRI,
633 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
635 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
636 assert(TID.getNumDefs() == 1 &&
637 "Don't know how to remat instructions that define > 1 values!");
639 TII->reMaterialize(MBB, MII, DestReg,
640 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
641 MachineInstr *NewMI = prior(MII);
642 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
643 MachineOperand &MO = NewMI->getOperand(i);
644 if (!MO.isReg() || MO.getReg() == 0)
646 unsigned VirtReg = MO.getReg();
647 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
650 unsigned SubIdx = MO.getSubReg();
651 unsigned Phys = VRM.getPhys(VirtReg);
652 assert(Phys && "Virtual register is not assigned a register?");
653 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
660 /// findSuperReg - Find the SubReg's super-register of given register class
661 /// where its SubIdx sub-register is SubReg.
662 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
663 unsigned SubIdx, const TargetRegisterInfo *TRI) {
664 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
667 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
673 // ******************************** //
674 // Available Spills Implementation //
675 // ******************************** //
677 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
678 /// stackslot register. The register is still available but is no longer
679 /// allowed to be modifed.
680 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
681 std::multimap<unsigned, int>::iterator I =
682 PhysRegsAvailable.lower_bound(PhysReg);
683 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
684 int SlotOrReMat = I->second;
686 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
687 "Bidirectional map mismatch!");
688 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
689 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
690 << " copied, it is available for use but can no longer be modified\n");
694 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
695 /// stackslot register and its aliases. The register and its aliases may
696 /// still available but is no longer allowed to be modifed.
697 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
698 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
699 disallowClobberPhysRegOnly(*AS);
700 disallowClobberPhysRegOnly(PhysReg);
703 /// ClobberPhysRegOnly - This is called when the specified physreg changes
704 /// value. We use this to invalidate any info about stuff we thing lives in it.
705 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
706 std::multimap<unsigned, int>::iterator I =
707 PhysRegsAvailable.lower_bound(PhysReg);
708 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
709 int SlotOrReMat = I->second;
710 PhysRegsAvailable.erase(I++);
711 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
712 "Bidirectional map mismatch!");
713 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
714 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
715 << " clobbered, invalidating ");
716 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
717 DEBUG(errs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
719 DEBUG(errs() << "SS#" << SlotOrReMat << "\n");
723 /// ClobberPhysReg - This is called when the specified physreg changes
724 /// value. We use this to invalidate any info about stuff we thing lives in
725 /// it and any of its aliases.
726 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
727 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
728 ClobberPhysRegOnly(*AS);
729 ClobberPhysRegOnly(PhysReg);
732 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
733 /// into the specified MBB. Add available physical registers as potential
734 /// live-in's. If they are reused in the MBB, they will be added to the
735 /// live-in set to make register scavenger and post-allocation scheduler.
736 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
738 std::vector<MachineOperand*> &KillOps) {
739 std::set<unsigned> NotAvailable;
740 for (std::multimap<unsigned, int>::iterator
741 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
743 unsigned Reg = I->first;
744 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
745 // FIXME: A temporary workaround. We can't reuse available value if it's
746 // not safe to move the def of the virtual register's class. e.g.
747 // X86::RFP* register classes. Do not add it as a live-in.
748 if (!TII->isSafeToMoveRegClassDefs(RC))
749 // This is no longer available.
750 NotAvailable.insert(Reg);
753 InvalidateKill(Reg, TRI, RegKills, KillOps);
756 // Skip over the same register.
757 std::multimap<unsigned, int>::iterator NI = next(I);
758 while (NI != E && NI->first == Reg) {
764 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
765 E = NotAvailable.end(); I != E; ++I) {
767 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
769 ClobberPhysReg(*SubRegs);
773 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
774 /// slot changes. This removes information about which register the previous
775 /// value for this slot lives in (as the previous value is dead now).
776 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
777 std::map<int, unsigned>::iterator It =
778 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
779 if (It == SpillSlotsOrReMatsAvailable.end()) return;
780 unsigned Reg = It->second >> 1;
781 SpillSlotsOrReMatsAvailable.erase(It);
783 // This register may hold the value of multiple stack slots, only remove this
784 // stack slot from the set of values the register contains.
785 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
787 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
788 "Map inverse broken!");
789 if (I->second == SlotOrReMat) break;
791 PhysRegsAvailable.erase(I);
794 // ************************** //
795 // Reuse Info Implementation //
796 // ************************** //
798 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
799 /// is some other operand that is using the specified register, either pick
800 /// a new register to use, or evict the previous reload and use this reg.
801 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
804 MachineInstr *MI, AvailableSpills &Spills,
805 std::vector<MachineInstr*> &MaybeDeadStores,
806 SmallSet<unsigned, 8> &Rejected,
808 std::vector<MachineOperand*> &KillOps,
810 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
811 const TargetRegisterInfo *TRI = Spills.getRegInfo();
813 if (Reuses.empty()) return PhysReg; // This is most often empty.
815 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
816 ReusedOp &Op = Reuses[ro];
817 // If we find some other reuse that was supposed to use this register
818 // exactly for its reload, we can change this reload to use ITS reload
819 // register. That is, unless its reload register has already been
820 // considered and subsequently rejected because it has also been reused
821 // by another operand.
822 if (Op.PhysRegReused == PhysReg &&
823 Rejected.count(Op.AssignedPhysReg) == 0 &&
824 RC->contains(Op.AssignedPhysReg)) {
825 // Yup, use the reload register that we didn't use before.
826 unsigned NewReg = Op.AssignedPhysReg;
827 Rejected.insert(PhysReg);
828 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
829 RegKills, KillOps, VRM);
831 // Otherwise, we might also have a problem if a previously reused
832 // value aliases the new register. If so, codegen the previous reload
834 unsigned PRRU = Op.PhysRegReused;
835 if (TRI->regsOverlap(PRRU, PhysReg)) {
836 // Okay, we found out that an alias of a reused register
837 // was used. This isn't good because it means we have
838 // to undo a previous reuse.
839 MachineBasicBlock *MBB = MI->getParent();
840 const TargetRegisterClass *AliasRC =
841 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
843 // Copy Op out of the vector and remove it, we're going to insert an
844 // explicit load for it.
846 Reuses.erase(Reuses.begin()+ro);
848 // MI may be using only a sub-register of PhysRegUsed.
849 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
851 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
852 "A reuse cannot be a virtual register");
853 if (PRRU != RealPhysRegUsed) {
854 // What was the sub-register index?
855 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
857 "Operand physreg is not a sub-register of PhysRegUsed");
860 // Ok, we're going to try to reload the assigned physreg into the
861 // slot that we were supposed to in the first place. However, that
862 // register could hold a reuse. Check to see if it conflicts or
863 // would prefer us to use a different register.
864 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
865 MF, MI, Spills, MaybeDeadStores,
866 Rejected, RegKills, KillOps, VRM);
868 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
869 int SSorRMId = DoReMat
870 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
872 // Back-schedule reloads and remats.
873 MachineBasicBlock::iterator InsertLoc =
874 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
875 DoReMat, SSorRMId, TII, MF);
878 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
881 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
882 NewOp.StackSlotOrReMat, AliasRC);
883 MachineInstr *LoadMI = prior(InsertLoc);
884 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
885 // Any stores to this stack slot are not dead anymore.
886 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
889 Spills.ClobberPhysReg(NewPhysReg);
890 Spills.ClobberPhysReg(NewOp.PhysRegReused);
892 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
893 MI->getOperand(NewOp.Operand).setReg(RReg);
894 MI->getOperand(NewOp.Operand).setSubReg(0);
896 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
897 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
898 DEBUG(errs() << '\t' << *prior(InsertLoc));
900 DEBUG(errs() << "Reuse undone!\n");
903 // Finally, PhysReg is now available, go ahead and use it.
911 // ************************************************************************ //
913 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
914 /// stack slot mod/ref. It also checks if it's possible to unfold the
915 /// instruction by having it define a specified physical register instead.
916 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
917 const TargetInstrInfo *TII,
918 const TargetRegisterInfo *TRI,
920 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
924 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
925 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
926 unsigned VirtReg = I->second.first;
927 VirtRegMap::ModRef MR = I->second.second;
928 if (MR & VirtRegMap::isModRef)
929 if (VRM.getStackSlot(VirtReg) == SS) {
930 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
937 // Does the instruction uses a register that overlaps the scratch register?
938 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
939 MachineOperand &MO = MI.getOperand(i);
940 if (!MO.isReg() || MO.getReg() == 0)
942 unsigned Reg = MO.getReg();
943 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
944 if (!VRM.hasPhys(Reg))
946 Reg = VRM.getPhys(Reg);
948 if (TRI->regsOverlap(PhysReg, Reg))
954 /// FindFreeRegister - Find a free register of a given register class by looking
955 /// at (at most) the last two machine instructions.
956 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
957 MachineBasicBlock &MBB,
958 const TargetRegisterClass *RC,
959 const TargetRegisterInfo *TRI,
960 BitVector &AllocatableRegs) {
961 BitVector Defs(TRI->getNumRegs());
962 BitVector Uses(TRI->getNumRegs());
963 SmallVector<unsigned, 4> LocalUses;
964 SmallVector<unsigned, 4> Kills;
966 // Take a look at 2 instructions at most.
967 for (unsigned Count = 0; Count < 2; ++Count) {
968 if (MII == MBB.begin())
970 MachineInstr *PrevMI = prior(MII);
971 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
972 MachineOperand &MO = PrevMI->getOperand(i);
973 if (!MO.isReg() || MO.getReg() == 0)
975 unsigned Reg = MO.getReg();
978 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
981 LocalUses.push_back(Reg);
982 if (MO.isKill() && AllocatableRegs[Reg])
983 Kills.push_back(Reg);
987 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
988 unsigned Kill = Kills[i];
989 if (!Defs[Kill] && !Uses[Kill] &&
990 TRI->getPhysicalRegisterRegClass(Kill) == RC)
993 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
994 unsigned Reg = LocalUses[i];
996 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1007 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
1008 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1009 MachineOperand &MO = MI->getOperand(i);
1010 if (MO.isReg() && MO.getReg() == VirtReg)
1017 bool operator()(const std::pair<MachineInstr*, int> &A,
1018 const std::pair<MachineInstr*, int> &B) {
1019 return A.second < B.second;
1024 // ***************************** //
1025 // Local Spiller Implementation //
1026 // ***************************** //
1030 class LocalRewriter : public VirtRegRewriter {
1031 MachineRegisterInfo *RegInfo;
1032 const TargetRegisterInfo *TRI;
1033 const TargetInstrInfo *TII;
1034 BitVector AllocatableRegs;
1035 DenseMap<MachineInstr*, unsigned> DistanceMap;
1038 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1039 LiveIntervals* LIs) {
1040 RegInfo = &MF.getRegInfo();
1041 TRI = MF.getTarget().getRegisterInfo();
1042 TII = MF.getTarget().getInstrInfo();
1043 AllocatableRegs = TRI->getAllocatableSet(MF);
1044 DEBUG(errs() << "\n**** Local spiller rewriting function '"
1045 << MF.getFunction()->getName() << "':\n");
1046 DEBUG(errs() << "**** Machine Instrs (NOTE! Does not include spills and"
1047 " reloads!) ****\n");
1050 // Spills - Keep track of which spilled values are available in physregs
1051 // so that we can choose to reuse the physregs instead of emitting
1052 // reloads. This is usually refreshed per basic block.
1053 AvailableSpills Spills(TRI, TII);
1055 // Keep track of kill information.
1056 BitVector RegKills(TRI->getNumRegs());
1057 std::vector<MachineOperand*> KillOps;
1058 KillOps.resize(TRI->getNumRegs(), NULL);
1060 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1061 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1062 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1064 // Traverse the basic blocks depth first.
1065 MachineBasicBlock *Entry = MF.begin();
1066 SmallPtrSet<MachineBasicBlock*,16> Visited;
1067 for (df_ext_iterator<MachineBasicBlock*,
1068 SmallPtrSet<MachineBasicBlock*,16> >
1069 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1071 MachineBasicBlock *MBB = *DFI;
1072 if (!EarlyVisited.count(MBB))
1073 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1075 // If this MBB is the only predecessor of a successor. Keep the
1076 // availability information and visit it next.
1078 // Keep visiting single predecessor successor as long as possible.
1079 SinglePredSuccs.clear();
1080 findSinglePredSuccessor(MBB, SinglePredSuccs);
1081 if (SinglePredSuccs.empty())
1084 // FIXME: More than one successors, each of which has MBB has
1085 // the only predecessor.
1086 MBB = SinglePredSuccs[0];
1087 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1088 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1089 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1094 // Clear the availability info.
1098 DEBUG(errs() << "**** Post Machine Instrs ****\n");
1101 // Mark unused spill slots.
1102 MachineFrameInfo *MFI = MF.getFrameInfo();
1103 int SS = VRM.getLowSpillSlot();
1104 if (SS != VirtRegMap::NO_STACK_SLOT)
1105 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1106 if (!VRM.isSpillSlotUsed(SS)) {
1107 MFI->RemoveStackObject(SS);
1116 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1117 /// a scratch register is available.
1118 /// xorq %r12<kill>, %r13
1119 /// addq %rax, -184(%rbp)
1120 /// addq %r13, -184(%rbp)
1122 /// xorq %r12<kill>, %r13
1123 /// movq -184(%rbp), %r12
1126 /// movq %r12, -184(%rbp)
1127 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1128 MachineBasicBlock &MBB,
1129 MachineBasicBlock::iterator &MII,
1130 std::vector<MachineInstr*> &MaybeDeadStores,
1131 AvailableSpills &Spills,
1132 BitVector &RegKills,
1133 std::vector<MachineOperand*> &KillOps,
1136 MachineBasicBlock::iterator NextMII = next(MII);
1137 if (NextMII == MBB.end())
1140 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1143 // Now let's see if the last couple of instructions happens to have freed up
1145 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1146 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1150 MachineFunction &MF = *MBB.getParent();
1151 TRI = MF.getTarget().getRegisterInfo();
1152 MachineInstr &MI = *MII;
1153 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1156 // If the next instruction also folds the same SS modref and can be unfoled,
1157 // then it's worthwhile to issue a load from SS into the free register and
1158 // then unfold these instructions.
1159 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1162 // Back-schedule reloads and remats.
1163 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
1165 // Load from SS to the spare physical register.
1166 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1167 // This invalidates Phys.
1168 Spills.ClobberPhysReg(PhysReg);
1169 // Remember it's available.
1170 Spills.addAvailable(SS, PhysReg);
1171 MaybeDeadStores[SS] = NULL;
1173 // Unfold current MI.
1174 SmallVector<MachineInstr*, 4> NewMIs;
1175 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1176 llvm_unreachable("Unable unfold the load / store folding instruction!");
1177 assert(NewMIs.size() == 1);
1178 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1179 VRM.transferRestorePts(&MI, NewMIs[0]);
1180 MII = MBB.insert(MII, NewMIs[0]);
1181 InvalidateKills(MI, TRI, RegKills, KillOps);
1182 VRM.RemoveMachineInstrFromMaps(&MI);
1186 // Unfold next instructions that fold the same SS.
1188 MachineInstr &NextMI = *NextMII;
1189 NextMII = next(NextMII);
1191 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1192 llvm_unreachable("Unable unfold the load / store folding instruction!");
1193 assert(NewMIs.size() == 1);
1194 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1195 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1196 MBB.insert(NextMII, NewMIs[0]);
1197 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1198 VRM.RemoveMachineInstrFromMaps(&NextMI);
1201 if (NextMII == MBB.end())
1203 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1205 // Store the value back into SS.
1206 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1207 MachineInstr *StoreMI = prior(NextMII);
1208 VRM.addSpillSlotUse(SS, StoreMI);
1209 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1214 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1215 /// instruction. e.g.
1217 /// movl %eax, -32(%ebp)
1218 /// movl -36(%ebp), %eax
1219 /// orl %eax, -32(%ebp)
1222 /// orl -36(%ebp), %eax
1223 /// mov %eax, -32(%ebp)
1224 /// This enables unfolding optimization for a subsequent instruction which will
1225 /// also eliminate the newly introduced store instruction.
1226 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1227 MachineBasicBlock::iterator &MII,
1228 std::vector<MachineInstr*> &MaybeDeadStores,
1229 AvailableSpills &Spills,
1230 BitVector &RegKills,
1231 std::vector<MachineOperand*> &KillOps,
1233 MachineFunction &MF = *MBB.getParent();
1234 MachineInstr &MI = *MII;
1235 unsigned UnfoldedOpc = 0;
1236 unsigned UnfoldPR = 0;
1237 unsigned UnfoldVR = 0;
1238 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1239 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1240 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1241 // Only transform a MI that folds a single register.
1244 UnfoldVR = I->second.first;
1245 VirtRegMap::ModRef MR = I->second.second;
1246 // MI2VirtMap be can updated which invalidate the iterator.
1247 // Increment the iterator first.
1249 if (VRM.isAssignedReg(UnfoldVR))
1251 // If this reference is not a use, any previous store is now dead.
1252 // Otherwise, the store to this stack slot is not dead anymore.
1253 FoldedSS = VRM.getStackSlot(UnfoldVR);
1254 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1255 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1256 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1257 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1260 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1269 // Look for other unfolding opportunities.
1270 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1271 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1274 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1275 MachineOperand &MO = MI.getOperand(i);
1276 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1278 unsigned VirtReg = MO.getReg();
1279 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1281 if (VRM.isAssignedReg(VirtReg)) {
1282 unsigned PhysReg = VRM.getPhys(VirtReg);
1283 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1285 } else if (VRM.isReMaterialized(VirtReg))
1287 int SS = VRM.getStackSlot(VirtReg);
1288 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1290 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1294 if (VRM.hasPhys(VirtReg)) {
1295 PhysReg = VRM.getPhys(VirtReg);
1296 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1300 // Ok, we'll need to reload the value into a register which makes
1301 // it impossible to perform the store unfolding optimization later.
1302 // Let's see if it is possible to fold the load if the store is
1303 // unfolded. This allows us to perform the store unfolding
1305 SmallVector<MachineInstr*, 4> NewMIs;
1306 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1307 assert(NewMIs.size() == 1);
1308 MachineInstr *NewMI = NewMIs.back();
1310 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1312 SmallVector<unsigned, 1> Ops;
1314 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1316 VRM.addSpillSlotUse(SS, FoldedMI);
1317 if (!VRM.hasPhys(UnfoldVR))
1318 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1319 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1320 MII = MBB.insert(MII, FoldedMI);
1321 InvalidateKills(MI, TRI, RegKills, KillOps);
1322 VRM.RemoveMachineInstrFromMaps(&MI);
1324 MF.DeleteMachineInstr(NewMI);
1327 MF.DeleteMachineInstr(NewMI);
1334 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1335 /// where SrcReg is r1 and it is tied to r0. Return true if after
1336 /// commuting this instruction it will be r0 = op r2, r1.
1337 static bool CommuteChangesDestination(MachineInstr *DefMI,
1338 const TargetInstrDesc &TID,
1340 const TargetInstrInfo *TII,
1342 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1344 if (!DefMI->getOperand(1).isReg() ||
1345 DefMI->getOperand(1).getReg() != SrcReg)
1348 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1350 unsigned SrcIdx1, SrcIdx2;
1351 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1353 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1360 /// CommuteToFoldReload -
1363 /// r1 = op r1, r2<kill>
1366 /// If op is commutable and r2 is killed, then we can xform these to
1367 /// r2 = op r2, fi#1
1369 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1370 MachineBasicBlock::iterator &MII,
1371 unsigned VirtReg, unsigned SrcReg, int SS,
1372 AvailableSpills &Spills,
1373 BitVector &RegKills,
1374 std::vector<MachineOperand*> &KillOps,
1375 const TargetRegisterInfo *TRI,
1377 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1380 MachineFunction &MF = *MBB.getParent();
1381 MachineInstr &MI = *MII;
1382 MachineBasicBlock::iterator DefMII = prior(MII);
1383 MachineInstr *DefMI = DefMII;
1384 const TargetInstrDesc &TID = DefMI->getDesc();
1386 if (DefMII != MBB.begin() &&
1387 TID.isCommutable() &&
1388 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1389 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1390 unsigned NewReg = NewDstMO.getReg();
1391 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1393 MachineInstr *ReloadMI = prior(DefMII);
1395 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1396 if (DestReg != SrcReg || FrameIdx != SS)
1398 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1402 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1404 assert(DefMI->getOperand(DefIdx).isReg() &&
1405 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1407 // Now commute def instruction.
1408 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1411 SmallVector<unsigned, 1> Ops;
1412 Ops.push_back(NewDstIdx);
1413 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1414 // Not needed since foldMemoryOperand returns new MI.
1415 MF.DeleteMachineInstr(CommutedMI);
1419 VRM.addSpillSlotUse(SS, FoldedMI);
1420 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1421 // Insert new def MI and spill MI.
1422 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1423 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1425 MachineInstr *StoreMI = MII;
1426 VRM.addSpillSlotUse(SS, StoreMI);
1427 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1428 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1430 // Delete all 3 old instructions.
1431 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1432 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1433 MBB.erase(ReloadMI);
1434 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1435 VRM.RemoveMachineInstrFromMaps(DefMI);
1437 InvalidateKills(MI, TRI, RegKills, KillOps);
1438 VRM.RemoveMachineInstrFromMaps(&MI);
1441 // If NewReg was previously holding value of some SS, it's now clobbered.
1442 // This has to be done now because it's a physical register. When this
1443 // instruction is re-visited, it's ignored.
1444 Spills.ClobberPhysReg(NewReg);
1453 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1454 /// the last store to the same slot is now dead. If so, remove the last store.
1455 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1456 MachineBasicBlock::iterator &MII,
1457 int Idx, unsigned PhysReg, int StackSlot,
1458 const TargetRegisterClass *RC,
1459 bool isAvailable, MachineInstr *&LastStore,
1460 AvailableSpills &Spills,
1461 SmallSet<MachineInstr*, 4> &ReMatDefs,
1462 BitVector &RegKills,
1463 std::vector<MachineOperand*> &KillOps,
1466 MachineBasicBlock::iterator oldNextMII = next(MII);
1467 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1468 MachineInstr *StoreMI = prior(oldNextMII);
1469 VRM.addSpillSlotUse(StackSlot, StoreMI);
1470 DEBUG(errs() << "Store:\t" << *StoreMI);
1472 // If there is a dead store to this stack slot, nuke it now.
1474 DEBUG(errs() << "Removed dead store:\t" << *LastStore);
1476 SmallVector<unsigned, 2> KillRegs;
1477 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1478 MachineBasicBlock::iterator PrevMII = LastStore;
1479 bool CheckDef = PrevMII != MBB.begin();
1482 VRM.RemoveMachineInstrFromMaps(LastStore);
1483 MBB.erase(LastStore);
1485 // Look at defs of killed registers on the store. Mark the defs
1486 // as dead since the store has been deleted and they aren't
1488 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1489 bool HasOtherDef = false;
1490 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1491 MachineInstr *DeadDef = PrevMII;
1492 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1493 // FIXME: This assumes a remat def does not have side effects.
1494 VRM.RemoveMachineInstrFromMaps(DeadDef);
1503 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1504 // the last of multiple instructions is the actual store.
1505 LastStore = prior(oldNextMII);
1507 // If the stack slot value was previously available in some other
1508 // register, change it now. Otherwise, make the register available,
1510 Spills.ModifyStackSlotOrReMat(StackSlot);
1511 Spills.ClobberPhysReg(PhysReg);
1512 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1516 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1517 /// effect and all of its defs are dead.
1518 static bool isSafeToDelete(MachineInstr &MI) {
1519 const TargetInstrDesc &TID = MI.getDesc();
1520 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1521 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1522 TID.hasUnmodeledSideEffects())
1524 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1525 MachineOperand &MO = MI.getOperand(i);
1526 if (!MO.isReg() || !MO.getReg())
1528 if (MO.isDef() && !MO.isDead())
1530 if (MO.isUse() && MO.isKill())
1531 // FIXME: We can't remove kill markers or else the scavenger will assert.
1532 // An alternative is to add a ADD pseudo instruction to replace kill
1539 /// TransferDeadness - A identity copy definition is dead and it's being
1540 /// removed. Find the last def or use and mark it as dead / kill.
1541 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1542 unsigned Reg, BitVector &RegKills,
1543 std::vector<MachineOperand*> &KillOps,
1545 SmallPtrSet<MachineInstr*, 4> Seens;
1546 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1547 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1548 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1549 MachineInstr *UDMI = &*RI;
1550 if (UDMI->getParent() != MBB)
1552 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1553 if (DI == DistanceMap.end() || DI->second > CurDist)
1555 if (Seens.insert(UDMI))
1556 Refs.push_back(std::make_pair(UDMI, DI->second));
1561 std::sort(Refs.begin(), Refs.end(), RefSorter());
1563 while (!Refs.empty()) {
1564 MachineInstr *LastUDMI = Refs.back().first;
1567 MachineOperand *LastUD = NULL;
1568 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1569 MachineOperand &MO = LastUDMI->getOperand(i);
1570 if (!MO.isReg() || MO.getReg() != Reg)
1572 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1574 if (LastUDMI->isRegTiedToDefOperand(i))
1577 if (LastUD->isDef()) {
1578 // If the instruction has no side effect, delete it and propagate
1579 // backward further. Otherwise, mark is dead and we are done.
1580 if (!isSafeToDelete(*LastUDMI)) {
1581 LastUD->setIsDead();
1584 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1585 MBB->erase(LastUDMI);
1587 LastUD->setIsKill();
1589 KillOps[Reg] = LastUD;
1595 /// rewriteMBB - Keep track of which spills are available even after the
1596 /// register allocator is done with them. If possible, avid reloading vregs.
1597 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1599 AvailableSpills &Spills, BitVector &RegKills,
1600 std::vector<MachineOperand*> &KillOps) {
1602 DEBUG(errs() << "\n**** Local spiller rewriting MBB '"
1603 << MBB.getName() << "':\n");
1605 MachineFunction &MF = *MBB.getParent();
1607 // MaybeDeadStores - When we need to write a value back into a stack slot,
1608 // keep track of the inserted store. If the stack slot value is never read
1609 // (because the value was used from some available register, for example), and
1610 // subsequently stored to, the original store is dead. This map keeps track
1611 // of inserted stores that are not used. If we see a subsequent store to the
1612 // same stack slot, the original store is deleted.
1613 std::vector<MachineInstr*> MaybeDeadStores;
1614 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1616 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1617 SmallSet<MachineInstr*, 4> ReMatDefs;
1620 SmallSet<unsigned, 2> KilledMIRegs;
1623 KillOps.resize(TRI->getNumRegs(), NULL);
1626 DistanceMap.clear();
1627 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1629 MachineBasicBlock::iterator NextMII = next(MII);
1631 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1632 bool Erased = false;
1633 bool BackTracked = false;
1634 if (OptimizeByUnfold(MBB, MII,
1635 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1636 NextMII = next(MII);
1638 MachineInstr &MI = *MII;
1640 if (VRM.hasEmergencySpills(&MI)) {
1641 // Spill physical register(s) in the rare case the allocator has run out
1642 // of registers to allocate.
1643 SmallSet<int, 4> UsedSS;
1644 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1645 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1646 unsigned PhysReg = EmSpills[i];
1647 const TargetRegisterClass *RC =
1648 TRI->getPhysicalRegisterRegClass(PhysReg);
1649 assert(RC && "Unable to determine register class!");
1650 int SS = VRM.getEmergencySpillSlot(RC);
1651 if (UsedSS.count(SS))
1652 llvm_unreachable("Need to spill more than one physical registers!");
1654 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1655 MachineInstr *StoreMI = prior(MII);
1656 VRM.addSpillSlotUse(SS, StoreMI);
1658 // Back-schedule reloads and remats.
1659 MachineBasicBlock::iterator InsertLoc =
1660 ComputeReloadLoc(next(MII), MBB.begin(), PhysReg, TRI, false,
1663 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1665 MachineInstr *LoadMI = prior(InsertLoc);
1666 VRM.addSpillSlotUse(SS, LoadMI);
1668 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1670 NextMII = next(MII);
1673 // Insert restores here if asked to.
1674 if (VRM.isRestorePt(&MI)) {
1675 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1676 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1677 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1678 if (!VRM.getPreSplitReg(VirtReg))
1679 continue; // Split interval spilled again.
1680 unsigned Phys = VRM.getPhys(VirtReg);
1681 RegInfo->setPhysRegUsed(Phys);
1683 // Check if the value being restored if available. If so, it must be
1684 // from a predecessor BB that fallthrough into this BB. We do not
1690 // ... # r1 not clobbered
1693 bool DoReMat = VRM.isReMaterialized(VirtReg);
1694 int SSorRMId = DoReMat
1695 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1696 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1697 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1698 if (InReg == Phys) {
1699 // If the value is already available in the expected register, save
1700 // a reload / remat.
1702 DEBUG(errs() << "Reusing RM#"
1703 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1705 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1706 DEBUG(errs() << " from physreg "
1707 << TRI->getName(InReg) << " for vreg"
1708 << VirtReg <<" instead of reloading into physreg "
1709 << TRI->getName(Phys) << '\n');
1712 } else if (InReg && InReg != Phys) {
1714 DEBUG(errs() << "Reusing RM#"
1715 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1717 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1718 DEBUG(errs() << " from physreg "
1719 << TRI->getName(InReg) << " for vreg"
1720 << VirtReg <<" by copying it into physreg "
1721 << TRI->getName(Phys) << '\n');
1723 // If the reloaded / remat value is available in another register,
1724 // copy it to the desired register.
1726 // Back-schedule reloads and remats.
1727 MachineBasicBlock::iterator InsertLoc =
1728 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1731 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
1733 // This invalidates Phys.
1734 Spills.ClobberPhysReg(Phys);
1735 // Remember it's available.
1736 Spills.addAvailable(SSorRMId, Phys);
1739 MachineInstr *CopyMI = prior(InsertLoc);
1740 CopyMI->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
1741 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1742 KillOpnd->setIsKill();
1743 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1745 DEBUG(errs() << '\t' << *CopyMI);
1750 // Back-schedule reloads and remats.
1751 MachineBasicBlock::iterator InsertLoc =
1752 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1755 if (VRM.isReMaterialized(VirtReg)) {
1756 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
1758 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1759 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1760 MachineInstr *LoadMI = prior(InsertLoc);
1761 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1763 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1766 // This invalidates Phys.
1767 Spills.ClobberPhysReg(Phys);
1768 // Remember it's available.
1769 Spills.addAvailable(SSorRMId, Phys);
1771 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1772 DEBUG(errs() << '\t' << *prior(MII));
1776 // Insert spills here if asked to.
1777 if (VRM.isSpillPt(&MI)) {
1778 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1779 VRM.getSpillPtSpills(&MI);
1780 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1781 unsigned VirtReg = SpillRegs[i].first;
1782 bool isKill = SpillRegs[i].second;
1783 if (!VRM.getPreSplitReg(VirtReg))
1784 continue; // Split interval spilled again.
1785 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1786 unsigned Phys = VRM.getPhys(VirtReg);
1787 int StackSlot = VRM.getStackSlot(VirtReg);
1788 MachineBasicBlock::iterator oldNextMII = next(MII);
1789 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1790 MachineInstr *StoreMI = prior(oldNextMII);
1791 VRM.addSpillSlotUse(StackSlot, StoreMI);
1792 DEBUG(errs() << "Store:\t" << *StoreMI);
1793 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1795 NextMII = next(MII);
1798 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1800 ReuseInfo ReusedOperands(MI, TRI);
1801 SmallVector<unsigned, 4> VirtUseOps;
1802 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1803 MachineOperand &MO = MI.getOperand(i);
1804 if (!MO.isReg() || MO.getReg() == 0)
1805 continue; // Ignore non-register operands.
1807 unsigned VirtReg = MO.getReg();
1808 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1809 // Ignore physregs for spilling, but remember that it is used by this
1811 RegInfo->setPhysRegUsed(VirtReg);
1815 // We want to process implicit virtual register uses first.
1816 if (MO.isImplicit())
1817 // If the virtual register is implicitly defined, emit a implicit_def
1818 // before so scavenger knows it's "defined".
1819 // FIXME: This is a horrible hack done the by register allocator to
1820 // remat a definition with virtual register operand.
1821 VirtUseOps.insert(VirtUseOps.begin(), i);
1823 VirtUseOps.push_back(i);
1826 // Process all of the spilled uses and all non spilled reg references.
1827 SmallVector<int, 2> PotentialDeadStoreSlots;
1828 KilledMIRegs.clear();
1829 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1830 unsigned i = VirtUseOps[j];
1831 MachineOperand &MO = MI.getOperand(i);
1832 unsigned VirtReg = MO.getReg();
1833 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1834 "Not a virtual register?");
1836 unsigned SubIdx = MO.getSubReg();
1837 if (VRM.isAssignedReg(VirtReg)) {
1838 // This virtual register was assigned a physreg!
1839 unsigned Phys = VRM.getPhys(VirtReg);
1840 RegInfo->setPhysRegUsed(Phys);
1842 ReusedOperands.markClobbered(Phys);
1843 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1844 MI.getOperand(i).setReg(RReg);
1845 MI.getOperand(i).setSubReg(0);
1846 if (VRM.isImplicitlyDefined(VirtReg))
1847 // FIXME: Is this needed?
1848 BuildMI(MBB, &MI, MI.getDebugLoc(),
1849 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1853 // This virtual register is now known to be a spilled value.
1855 continue; // Handle defs in the loop below (handle use&def here though)
1857 bool AvoidReload = MO.isUndef();
1858 // Check if it is defined by an implicit def. It should not be spilled.
1859 // Note, this is for correctness reason. e.g.
1860 // 8 %reg1024<def> = IMPLICIT_DEF
1861 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1862 // The live range [12, 14) are not part of the r1024 live interval since
1863 // it's defined by an implicit def. It will not conflicts with live
1864 // interval of r1025. Now suppose both registers are spilled, you can
1865 // easily see a situation where both registers are reloaded before
1866 // the INSERT_SUBREG and both target registers that would overlap.
1867 bool DoReMat = VRM.isReMaterialized(VirtReg);
1868 int SSorRMId = DoReMat
1869 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1870 int ReuseSlot = SSorRMId;
1872 // Check to see if this stack slot is available.
1873 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1875 // If this is a sub-register use, make sure the reuse register is in the
1876 // right register class. For example, for x86 not all of the 32-bit
1877 // registers have accessible sub-registers.
1878 // Similarly so for EXTRACT_SUBREG. Consider this:
1880 // MOV32_mr fi#1, EDI
1882 // = EXTRACT_SUBREG fi#1
1883 // fi#1 is available in EDI, but it cannot be reused because it's not in
1884 // the right register file.
1885 if (PhysReg && !AvoidReload &&
1886 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1887 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1888 if (!RC->contains(PhysReg))
1892 if (PhysReg && !AvoidReload) {
1893 // This spilled operand might be part of a two-address operand. If this
1894 // is the case, then changing it will necessarily require changing the
1895 // def part of the instruction as well. However, in some cases, we
1896 // aren't allowed to modify the reused register. If none of these cases
1898 bool CanReuse = true;
1899 bool isTied = MI.isRegTiedToDefOperand(i);
1901 // Okay, we have a two address operand. We can reuse this physreg as
1902 // long as we are allowed to clobber the value and there isn't an
1903 // earlier def that has already clobbered the physreg.
1904 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1905 Spills.canClobberPhysReg(PhysReg);
1909 // If this stack slot value is already available, reuse it!
1910 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1911 DEBUG(errs() << "Reusing RM#"
1912 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1914 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1915 DEBUG(errs() << " from physreg "
1916 << TRI->getName(PhysReg) << " for vreg"
1917 << VirtReg <<" instead of reloading into physreg "
1918 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
1919 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1920 MI.getOperand(i).setReg(RReg);
1921 MI.getOperand(i).setSubReg(0);
1923 // The only technical detail we have is that we don't know that
1924 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1925 // later in the instruction. In particular, consider 'op V1, V2'.
1926 // If V1 is available in physreg R0, we would choose to reuse it
1927 // here, instead of reloading it into the register the allocator
1928 // indicated (say R1). However, V2 might have to be reloaded
1929 // later, and it might indicate that it needs to live in R0. When
1930 // this occurs, we need to have information available that
1931 // indicates it is safe to use R1 for the reload instead of R0.
1933 // To further complicate matters, we might conflict with an alias,
1934 // or R0 and R1 might not be compatible with each other. In this
1935 // case, we actually insert a reload for V1 in R1, ensuring that
1936 // we can get at R0 or its alias.
1937 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1938 VRM.getPhys(VirtReg), VirtReg);
1940 // Only mark it clobbered if this is a use&def operand.
1941 ReusedOperands.markClobbered(PhysReg);
1944 if (MI.getOperand(i).isKill() &&
1945 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1947 // The store of this spilled value is potentially dead, but we
1948 // won't know for certain until we've confirmed that the re-use
1949 // above is valid, which means waiting until the other operands
1950 // are processed. For now we just track the spill slot, we'll
1951 // remove it after the other operands are processed if valid.
1953 PotentialDeadStoreSlots.push_back(ReuseSlot);
1956 // Mark is isKill if it's there no other uses of the same virtual
1957 // register and it's not a two-address operand. IsKill will be
1958 // unset if reg is reused.
1959 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1960 MI.getOperand(i).setIsKill();
1961 KilledMIRegs.insert(VirtReg);
1967 // Otherwise we have a situation where we have a two-address instruction
1968 // whose mod/ref operand needs to be reloaded. This reload is already
1969 // available in some register "PhysReg", but if we used PhysReg as the
1970 // operand to our 2-addr instruction, the instruction would modify
1971 // PhysReg. This isn't cool if something later uses PhysReg and expects
1972 // to get its initial value.
1974 // To avoid this problem, and to avoid doing a load right after a store,
1975 // we emit a copy from PhysReg into the designated register for this
1977 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1978 assert(DesignatedReg && "Must map virtreg to physreg!");
1980 // Note that, if we reused a register for a previous operand, the
1981 // register we want to reload into might not actually be
1982 // available. If this occurs, use the register indicated by the
1984 if (ReusedOperands.hasReuses())
1985 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
1987 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1989 // If the mapped designated register is actually the physreg we have
1990 // incoming, we don't need to inserted a dead copy.
1991 if (DesignatedReg == PhysReg) {
1992 // If this stack slot value is already available, reuse it!
1993 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1994 DEBUG(errs() << "Reusing RM#"
1995 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1997 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1998 DEBUG(errs() << " from physreg " << TRI->getName(PhysReg)
1999 << " for vreg" << VirtReg
2000 << " instead of reloading into same physreg.\n");
2001 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2002 MI.getOperand(i).setReg(RReg);
2003 MI.getOperand(i).setSubReg(0);
2004 ReusedOperands.markClobbered(RReg);
2009 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
2010 RegInfo->setPhysRegUsed(DesignatedReg);
2011 ReusedOperands.markClobbered(DesignatedReg);
2013 // Back-schedule reloads and remats.
2014 MachineBasicBlock::iterator InsertLoc =
2015 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
2018 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2020 MachineInstr *CopyMI = prior(InsertLoc);
2021 CopyMI->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
2022 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2024 // This invalidates DesignatedReg.
2025 Spills.ClobberPhysReg(DesignatedReg);
2027 Spills.addAvailable(ReuseSlot, DesignatedReg);
2029 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2030 MI.getOperand(i).setReg(RReg);
2031 MI.getOperand(i).setSubReg(0);
2032 DEBUG(errs() << '\t' << *prior(MII));
2037 // Otherwise, reload it and remember that we have it.
2038 PhysReg = VRM.getPhys(VirtReg);
2039 assert(PhysReg && "Must map virtreg to physreg!");
2041 // Note that, if we reused a register for a previous operand, the
2042 // register we want to reload into might not actually be
2043 // available. If this occurs, use the register indicated by the
2045 if (ReusedOperands.hasReuses())
2046 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2047 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2049 RegInfo->setPhysRegUsed(PhysReg);
2050 ReusedOperands.markClobbered(PhysReg);
2054 // Back-schedule reloads and remats.
2055 MachineBasicBlock::iterator InsertLoc =
2056 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
2060 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
2062 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
2063 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
2064 MachineInstr *LoadMI = prior(InsertLoc);
2065 VRM.addSpillSlotUse(SSorRMId, LoadMI);
2067 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
2069 // This invalidates PhysReg.
2070 Spills.ClobberPhysReg(PhysReg);
2072 // Any stores to this stack slot are not dead anymore.
2074 MaybeDeadStores[SSorRMId] = NULL;
2075 Spills.addAvailable(SSorRMId, PhysReg);
2076 // Assumes this is the last use. IsKill will be unset if reg is reused
2077 // unless it's a two-address operand.
2078 if (!MI.isRegTiedToDefOperand(i) &&
2079 KilledMIRegs.count(VirtReg) == 0) {
2080 MI.getOperand(i).setIsKill();
2081 KilledMIRegs.insert(VirtReg);
2084 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2085 DEBUG(errs() << '\t' << *prior(InsertLoc));
2087 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2088 MI.getOperand(i).setReg(RReg);
2089 MI.getOperand(i).setSubReg(0);
2092 // Ok - now we can remove stores that have been confirmed dead.
2093 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2094 // This was the last use and the spilled value is still available
2095 // for reuse. That means the spill was unnecessary!
2096 int PDSSlot = PotentialDeadStoreSlots[j];
2097 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2099 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
2100 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2101 VRM.RemoveMachineInstrFromMaps(DeadStore);
2102 MBB.erase(DeadStore);
2103 MaybeDeadStores[PDSSlot] = NULL;
2109 DEBUG(errs() << '\t' << MI);
2112 // If we have folded references to memory operands, make sure we clear all
2113 // physical registers that may contain the value of the spilled virtual
2115 SmallSet<int, 2> FoldedSS;
2116 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2117 unsigned VirtReg = I->second.first;
2118 VirtRegMap::ModRef MR = I->second.second;
2119 DEBUG(errs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2121 // MI2VirtMap be can updated which invalidate the iterator.
2122 // Increment the iterator first.
2124 int SS = VRM.getStackSlot(VirtReg);
2125 if (SS == VirtRegMap::NO_STACK_SLOT)
2127 FoldedSS.insert(SS);
2128 DEBUG(errs() << " - StackSlot: " << SS << "\n");
2130 // If this folded instruction is just a use, check to see if it's a
2131 // straight load from the virt reg slot.
2132 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2134 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2135 if (DestReg && FrameIdx == SS) {
2136 // If this spill slot is available, turn it into a copy (or nothing)
2137 // instead of leaving it as a load!
2138 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2139 DEBUG(errs() << "Promoted Load To Copy: " << MI);
2140 if (DestReg != InReg) {
2141 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2142 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2143 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2144 unsigned SubIdx = DefMO->getSubReg();
2145 // Revisit the copy so we make sure to notice the effects of the
2146 // operation on the destreg (either needing to RA it if it's
2147 // virtual or needing to clobber any values if it's physical).
2149 --NextMII; // backtrack to the copy.
2150 NextMII->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
2151 // Propagate the sub-register index over.
2153 DefMO = NextMII->findRegisterDefOperand(DestReg);
2154 DefMO->setSubReg(SubIdx);
2158 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2159 KillOpnd->setIsKill();
2163 DEBUG(errs() << "Removing now-noop copy: " << MI);
2164 // Unset last kill since it's being reused.
2165 InvalidateKill(InReg, TRI, RegKills, KillOps);
2166 Spills.disallowClobberPhysReg(InReg);
2169 InvalidateKills(MI, TRI, RegKills, KillOps);
2170 VRM.RemoveMachineInstrFromMaps(&MI);
2173 goto ProcessNextInst;
2176 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2177 SmallVector<MachineInstr*, 4> NewMIs;
2179 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2180 MBB.insert(MII, NewMIs[0]);
2181 InvalidateKills(MI, TRI, RegKills, KillOps);
2182 VRM.RemoveMachineInstrFromMaps(&MI);
2185 --NextMII; // backtrack to the unfolded instruction.
2187 goto ProcessNextInst;
2192 // If this reference is not a use, any previous store is now dead.
2193 // Otherwise, the store to this stack slot is not dead anymore.
2194 MachineInstr* DeadStore = MaybeDeadStores[SS];
2196 bool isDead = !(MR & VirtRegMap::isRef);
2197 MachineInstr *NewStore = NULL;
2198 if (MR & VirtRegMap::isModRef) {
2199 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2200 SmallVector<MachineInstr*, 4> NewMIs;
2201 // We can reuse this physreg as long as we are allowed to clobber
2202 // the value and there isn't an earlier def that has already clobbered
2205 !ReusedOperands.isClobbered(PhysReg) &&
2206 Spills.canClobberPhysReg(PhysReg) &&
2207 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2208 MachineOperand *KillOpnd =
2209 DeadStore->findRegisterUseOperand(PhysReg, true);
2210 // Note, if the store is storing a sub-register, it's possible the
2211 // super-register is needed below.
2212 if (KillOpnd && !KillOpnd->getSubReg() &&
2213 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2214 MBB.insert(MII, NewMIs[0]);
2215 NewStore = NewMIs[1];
2216 MBB.insert(MII, NewStore);
2217 VRM.addSpillSlotUse(SS, NewStore);
2218 InvalidateKills(MI, TRI, RegKills, KillOps);
2219 VRM.RemoveMachineInstrFromMaps(&MI);
2223 --NextMII; // backtrack to the unfolded instruction.
2231 if (isDead) { // Previous store is dead.
2232 // If we get here, the store is dead, nuke it now.
2233 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
2234 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2235 VRM.RemoveMachineInstrFromMaps(DeadStore);
2236 MBB.erase(DeadStore);
2241 MaybeDeadStores[SS] = NULL;
2243 // Treat this store as a spill merged into a copy. That makes the
2244 // stack slot value available.
2245 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2246 goto ProcessNextInst;
2250 // If the spill slot value is available, and this is a new definition of
2251 // the value, the value is not available anymore.
2252 if (MR & VirtRegMap::isMod) {
2253 // Notice that the value in this stack slot has been modified.
2254 Spills.ModifyStackSlotOrReMat(SS);
2256 // If this is *just* a mod of the value, check to see if this is just a
2257 // store to the spill slot (i.e. the spill got merged into the copy). If
2258 // so, realize that the vreg is available now, and add the store to the
2259 // MaybeDeadStore info.
2261 if (!(MR & VirtRegMap::isRef)) {
2262 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2263 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2264 "Src hasn't been allocated yet?");
2266 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2267 Spills, RegKills, KillOps, TRI, VRM)) {
2268 NextMII = next(MII);
2270 goto ProcessNextInst;
2273 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2274 // this as a potentially dead store in case there is a subsequent
2275 // store into the stack slot without a read from it.
2276 MaybeDeadStores[StackSlot] = &MI;
2278 // If the stack slot value was previously available in some other
2279 // register, change it now. Otherwise, make the register
2280 // available in PhysReg.
2281 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2287 // Process all of the spilled defs.
2288 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2289 MachineOperand &MO = MI.getOperand(i);
2290 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2293 unsigned VirtReg = MO.getReg();
2294 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2295 // Check to see if this is a noop copy. If so, eliminate the
2296 // instruction before considering the dest reg to be changed.
2297 // Also check if it's copying from an "undef", if so, we can't
2298 // eliminate this or else the undef marker is lost and it will
2299 // confuses the scavenger. This is extremely rare.
2300 unsigned Src, Dst, SrcSR, DstSR;
2301 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2302 !MI.findRegisterUseOperand(Src)->isUndef()) {
2304 DEBUG(errs() << "Removing now-noop copy: " << MI);
2305 SmallVector<unsigned, 2> KillRegs;
2306 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2307 if (MO.isDead() && !KillRegs.empty()) {
2308 // Source register or an implicit super/sub-register use is killed.
2309 assert(KillRegs[0] == Dst ||
2310 TRI->isSubRegister(KillRegs[0], Dst) ||
2311 TRI->isSuperRegister(KillRegs[0], Dst));
2312 // Last def is now dead.
2313 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2315 VRM.RemoveMachineInstrFromMaps(&MI);
2318 Spills.disallowClobberPhysReg(VirtReg);
2319 goto ProcessNextInst;
2322 // If it's not a no-op copy, it clobbers the value in the destreg.
2323 Spills.ClobberPhysReg(VirtReg);
2324 ReusedOperands.markClobbered(VirtReg);
2326 // Check to see if this instruction is a load from a stack slot into
2327 // a register. If so, this provides the stack slot value in the reg.
2329 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2330 assert(DestReg == VirtReg && "Unknown load situation!");
2332 // If it is a folded reference, then it's not safe to clobber.
2333 bool Folded = FoldedSS.count(FrameIdx);
2334 // Otherwise, if it wasn't available, remember that it is now!
2335 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2336 goto ProcessNextInst;
2342 unsigned SubIdx = MO.getSubReg();
2343 bool DoReMat = VRM.isReMaterialized(VirtReg);
2345 ReMatDefs.insert(&MI);
2347 // The only vregs left are stack slot definitions.
2348 int StackSlot = VRM.getStackSlot(VirtReg);
2349 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2351 // If this def is part of a two-address operand, make sure to execute
2352 // the store from the correct physical register.
2355 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2356 PhysReg = MI.getOperand(TiedOp).getReg();
2358 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2359 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2360 "Can't find corresponding super-register!");
2364 PhysReg = VRM.getPhys(VirtReg);
2365 if (ReusedOperands.isClobbered(PhysReg)) {
2366 // Another def has taken the assigned physreg. It must have been a
2367 // use&def which got it due to reuse. Undo the reuse!
2368 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2369 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2373 assert(PhysReg && "VR not assigned a physical register?");
2374 RegInfo->setPhysRegUsed(PhysReg);
2375 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2376 ReusedOperands.markClobbered(RReg);
2377 MI.getOperand(i).setReg(RReg);
2378 MI.getOperand(i).setSubReg(0);
2381 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2382 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2383 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2384 NextMII = next(MII);
2386 // Check to see if this is a noop copy. If so, eliminate the
2387 // instruction before considering the dest reg to be changed.
2389 unsigned Src, Dst, SrcSR, DstSR;
2390 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2392 DEBUG(errs() << "Removing now-noop copy: " << MI);
2393 InvalidateKills(MI, TRI, RegKills, KillOps);
2394 VRM.RemoveMachineInstrFromMaps(&MI);
2397 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2398 goto ProcessNextInst;
2404 // Delete dead instructions without side effects.
2405 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2406 InvalidateKills(MI, TRI, RegKills, KillOps);
2407 VRM.RemoveMachineInstrFromMaps(&MI);
2412 DistanceMap.insert(std::make_pair(&MI, Dist++));
2413 if (!Erased && !BackTracked) {
2414 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2415 UpdateKills(*II, TRI, RegKills, KillOps);
2426 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2427 switch (RewriterOpt) {
2428 default: llvm_unreachable("Unreachable!");
2430 return new LocalRewriter();
2432 return new TrivialRewriter();