Add AVX SSE2 packed integer extract/insert instructions
[llvm.git] / lib / CodeGen / VirtRegRewriter.cpp
blob11bd3cde707fe9d55cde18033cd710a288adebbc
1 //===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "virtregrewriter"
11 #include "VirtRegRewriter.h"
12 #include "VirtRegMap.h"
13 #include "llvm/Function.h"
14 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
26 #include <algorithm>
27 using namespace llvm;
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");
45 namespace {
46 enum RewriterName { local, trivial };
49 static cl::opt<RewriterName>
50 RewriterOpt("rewriter",
51 cl::desc("Rewriter to use (default=local)"),
52 cl::Prefix,
53 cl::values(clEnumVal(local, "local rewriter"),
54 clEnumVal(trivial, "trivial rewriter"),
55 clEnumValEnd),
56 cl::init(local));
58 static cl::opt<bool>
59 ScheduleSpills("schedule-spills",
60 cl::desc("Schedule spill code"),
61 cl::init(false));
63 VirtRegRewriter::~VirtRegRewriter() {}
65 /// substitutePhysReg - Replace virtual register in MachineOperand with a
66 /// physical register. Do the right thing with the sub-register index.
67 /// Note that operands may be added, so the MO reference is no longer valid.
68 static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
69 const TargetRegisterInfo &TRI) {
70 if (unsigned SubIdx = MO.getSubReg()) {
71 // Insert the physical subreg and reset the subreg field.
72 MO.setReg(TRI.getSubReg(Reg, SubIdx));
73 MO.setSubReg(0);
75 // Any def, dead, and kill flags apply to the full virtual register, so they
76 // also apply to the full physical register. Add imp-def/dead and imp-kill
77 // as needed.
78 MachineInstr &MI = *MO.getParent();
79 if (MO.isDef())
80 if (MO.isDead())
81 MI.addRegisterDead(Reg, &TRI, /*AddIfNotFound=*/ true);
82 else
83 MI.addRegisterDefined(Reg, &TRI);
84 else if (!MO.isUndef() &&
85 (MO.isKill() ||
86 MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
87 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
88 } else {
89 MO.setReg(Reg);
93 namespace {
95 /// This class is intended for use with the new spilling framework only. It
96 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
97 /// spill code.
98 struct TrivialRewriter : public VirtRegRewriter {
100 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
101 LiveIntervals* LIs) {
102 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
103 DEBUG(dbgs() << "********** Function: "
104 << MF.getFunction()->getName() << '\n');
105 DEBUG(dbgs() << "**** Machine Instrs"
106 << "(NOTE! Does not include spills and reloads!) ****\n");
107 DEBUG(MF.dump());
109 MachineRegisterInfo *mri = &MF.getRegInfo();
110 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
112 bool changed = false;
114 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
115 liItr != liEnd; ++liItr) {
117 const LiveInterval *li = liItr->second;
118 unsigned reg = li->reg;
120 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
121 if (!li->empty())
122 mri->setPhysRegUsed(reg);
124 else {
125 if (!VRM.hasPhys(reg))
126 continue;
127 unsigned pReg = VRM.getPhys(reg);
128 mri->setPhysRegUsed(pReg);
129 // Copy the register use-list before traversing it.
130 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
131 for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
132 E = mri->reg_end(); I != E; ++I)
133 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
134 for (unsigned N=0; N != reglist.size(); ++N)
135 substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
136 pReg, *tri);
137 changed |= !reglist.empty();
141 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
142 DEBUG(MF.dump());
144 return changed;
151 // ************************************************************************ //
153 namespace {
155 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
156 /// from top down, keep track of which spill slots or remat are available in
157 /// each register.
159 /// Note that not all physregs are created equal here. In particular, some
160 /// physregs are reloads that we are allowed to clobber or ignore at any time.
161 /// Other physregs are values that the register allocated program is using
162 /// that we cannot CHANGE, but we can read if we like. We keep track of this
163 /// on a per-stack-slot / remat id basis as the low bit in the value of the
164 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
165 /// this bit and addAvailable sets it if.
166 class AvailableSpills {
167 const TargetRegisterInfo *TRI;
168 const TargetInstrInfo *TII;
170 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
171 // or remat'ed virtual register values that are still available, due to
172 // being loaded or stored to, but not invalidated yet.
173 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
175 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
176 // indicating which stack slot values are currently held by a physreg. This
177 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
178 // physreg is modified.
179 std::multimap<unsigned, int> PhysRegsAvailable;
181 void disallowClobberPhysRegOnly(unsigned PhysReg);
183 void ClobberPhysRegOnly(unsigned PhysReg);
184 public:
185 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
186 : TRI(tri), TII(tii) {
189 /// clear - Reset the state.
190 void clear() {
191 SpillSlotsOrReMatsAvailable.clear();
192 PhysRegsAvailable.clear();
195 const TargetRegisterInfo *getRegInfo() const { return TRI; }
197 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
198 /// available in a physical register, return that PhysReg, otherwise
199 /// return 0.
200 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
201 std::map<int, unsigned>::const_iterator I =
202 SpillSlotsOrReMatsAvailable.find(Slot);
203 if (I != SpillSlotsOrReMatsAvailable.end()) {
204 return I->second >> 1; // Remove the CanClobber bit.
206 return 0;
209 /// addAvailable - Mark that the specified stack slot / remat is available
210 /// in the specified physreg. If CanClobber is true, the physreg can be
211 /// modified at any time without changing the semantics of the program.
212 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
213 // If this stack slot is thought to be available in some other physreg,
214 // remove its record.
215 ModifyStackSlotOrReMat(SlotOrReMat);
217 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
218 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
219 (unsigned)CanClobber;
221 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
222 DEBUG(dbgs() << "Remembering RM#"
223 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
224 else
225 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
226 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
229 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
230 /// the value of the specified stackslot register if it desires. The
231 /// specified stack slot must be available in a physreg for this query to
232 /// make sense.
233 bool canClobberPhysRegForSS(int SlotOrReMat) const {
234 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
235 "Value not available!");
236 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
239 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
240 /// physical register where values for some stack slot(s) might be
241 /// available.
242 bool canClobberPhysReg(unsigned PhysReg) const {
243 std::multimap<unsigned, int>::const_iterator I =
244 PhysRegsAvailable.lower_bound(PhysReg);
245 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
246 int SlotOrReMat = I->second;
247 I++;
248 if (!canClobberPhysRegForSS(SlotOrReMat))
249 return false;
251 return true;
254 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
255 /// stackslot register. The register is still available but is no longer
256 /// allowed to be modifed.
257 void disallowClobberPhysReg(unsigned PhysReg);
259 /// ClobberPhysReg - This is called when the specified physreg changes
260 /// value. We use this to invalidate any info about stuff that lives in
261 /// it and any of its aliases.
262 void ClobberPhysReg(unsigned PhysReg);
264 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
265 /// slot changes. This removes information about which register the
266 /// previous value for this slot lives in (as the previous value is dead
267 /// now).
268 void ModifyStackSlotOrReMat(int SlotOrReMat);
270 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
271 /// into the specified MBB. Add available physical registers as potential
272 /// live-in's. If they are reused in the MBB, they will be added to the
273 /// live-in set to make register scavenger and post-allocation scheduler.
274 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
275 std::vector<MachineOperand*> &KillOps);
280 // ************************************************************************ //
282 // Given a location where a reload of a spilled register or a remat of
283 // a constant is to be inserted, attempt to find a safe location to
284 // insert the load at an earlier point in the basic-block, to hide
285 // latency of the load and to avoid address-generation interlock
286 // issues.
287 static MachineBasicBlock::iterator
288 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
289 MachineBasicBlock::iterator const Begin,
290 unsigned PhysReg,
291 const TargetRegisterInfo *TRI,
292 bool DoReMat,
293 int SSorRMId,
294 const TargetInstrInfo *TII,
295 const MachineFunction &MF)
297 if (!ScheduleSpills)
298 return InsertLoc;
300 // Spill backscheduling is of primary interest to addresses, so
301 // don't do anything if the register isn't in the register class
302 // used for pointers.
304 const TargetLowering *TL = MF.getTarget().getTargetLowering();
306 if (!TL->isTypeLegal(TL->getPointerTy()))
307 // Believe it or not, this is true on PIC16.
308 return InsertLoc;
310 const TargetRegisterClass *ptrRegClass =
311 TL->getRegClassFor(TL->getPointerTy());
312 if (!ptrRegClass->contains(PhysReg))
313 return InsertLoc;
315 // Scan upwards through the preceding instructions. If an instruction doesn't
316 // reference the stack slot or the register we're loading, we can
317 // backschedule the reload up past it.
318 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
319 while (NewInsertLoc != Begin) {
320 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
321 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
322 MachineOperand &Op = Prev->getOperand(i);
323 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
324 goto stop;
326 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
327 Prev->findRegisterDefOperand(PhysReg))
328 goto stop;
329 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
330 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
331 Prev->findRegisterDefOperand(*Alias))
332 goto stop;
333 NewInsertLoc = Prev;
335 stop:;
337 // If we made it to the beginning of the block, turn around and move back
338 // down just past any existing reloads. They're likely to be reloads/remats
339 // for instructions earlier than what our current reload/remat is for, so
340 // they should be scheduled earlier.
341 if (NewInsertLoc == Begin) {
342 int FrameIdx;
343 while (InsertLoc != NewInsertLoc &&
344 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
345 TII->isTriviallyReMaterializable(NewInsertLoc)))
346 ++NewInsertLoc;
349 return NewInsertLoc;
352 namespace {
354 // ReusedOp - For each reused operand, we keep track of a bit of information,
355 // in case we need to rollback upon processing a new operand. See comments
356 // below.
357 struct ReusedOp {
358 // The MachineInstr operand that reused an available value.
359 unsigned Operand;
361 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
362 unsigned StackSlotOrReMat;
364 // PhysRegReused - The physical register the value was available in.
365 unsigned PhysRegReused;
367 // AssignedPhysReg - The physreg that was assigned for use by the reload.
368 unsigned AssignedPhysReg;
370 // VirtReg - The virtual register itself.
371 unsigned VirtReg;
373 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
374 unsigned vreg)
375 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
376 AssignedPhysReg(apr), VirtReg(vreg) {}
379 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
380 /// is reused instead of reloaded.
381 class ReuseInfo {
382 MachineInstr &MI;
383 std::vector<ReusedOp> Reuses;
384 BitVector PhysRegsClobbered;
385 public:
386 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
387 PhysRegsClobbered.resize(tri->getNumRegs());
390 bool hasReuses() const {
391 return !Reuses.empty();
394 /// addReuse - If we choose to reuse a virtual register that is already
395 /// available instead of reloading it, remember that we did so.
396 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
397 unsigned PhysRegReused, unsigned AssignedPhysReg,
398 unsigned VirtReg) {
399 // If the reload is to the assigned register anyway, no undo will be
400 // required.
401 if (PhysRegReused == AssignedPhysReg) return;
403 // Otherwise, remember this.
404 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
405 AssignedPhysReg, VirtReg));
408 void markClobbered(unsigned PhysReg) {
409 PhysRegsClobbered.set(PhysReg);
412 bool isClobbered(unsigned PhysReg) const {
413 return PhysRegsClobbered.test(PhysReg);
416 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
417 /// is some other operand that is using the specified register, either pick
418 /// a new register to use, or evict the previous reload and use this reg.
419 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
420 MachineFunction &MF, MachineInstr *MI,
421 AvailableSpills &Spills,
422 std::vector<MachineInstr*> &MaybeDeadStores,
423 SmallSet<unsigned, 8> &Rejected,
424 BitVector &RegKills,
425 std::vector<MachineOperand*> &KillOps,
426 VirtRegMap &VRM);
428 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
429 /// 'Rejected' set to remember which registers have been considered and
430 /// rejected for the reload. This avoids infinite looping in case like
431 /// this:
432 /// t1 := op t2, t3
433 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
434 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
435 /// t1 <- desires r1
436 /// sees r1 is taken by t2, tries t2's reload register r0
437 /// sees r0 is taken by t3, tries t3's reload register r1
438 /// sees r1 is taken by t2, tries t2's reload register r0 ...
439 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
440 AvailableSpills &Spills,
441 std::vector<MachineInstr*> &MaybeDeadStores,
442 BitVector &RegKills,
443 std::vector<MachineOperand*> &KillOps,
444 VirtRegMap &VRM) {
445 SmallSet<unsigned, 8> Rejected;
446 MachineFunction &MF = *MI->getParent()->getParent();
447 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
448 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
449 Rejected, RegKills, KillOps, VRM);
455 // ****************** //
456 // Utility Functions //
457 // ****************** //
459 /// findSinglePredSuccessor - Return via reference a vector of machine basic
460 /// blocks each of which is a successor of the specified BB and has no other
461 /// predecessor.
462 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
463 SmallVectorImpl<MachineBasicBlock *> &Succs) {
464 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
465 SE = MBB->succ_end(); SI != SE; ++SI) {
466 MachineBasicBlock *SuccMBB = *SI;
467 if (SuccMBB->pred_size() == 1)
468 Succs.push_back(SuccMBB);
472 /// InvalidateKill - Invalidate register kill information for a specific
473 /// register. This also unsets the kills marker on the last kill operand.
474 static void InvalidateKill(unsigned Reg,
475 const TargetRegisterInfo* TRI,
476 BitVector &RegKills,
477 std::vector<MachineOperand*> &KillOps) {
478 if (RegKills[Reg]) {
479 KillOps[Reg]->setIsKill(false);
480 // KillOps[Reg] might be a def of a super-register.
481 unsigned KReg = KillOps[Reg]->getReg();
482 KillOps[KReg] = NULL;
483 RegKills.reset(KReg);
484 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
485 if (RegKills[*SR]) {
486 KillOps[*SR]->setIsKill(false);
487 KillOps[*SR] = NULL;
488 RegKills.reset(*SR);
494 /// InvalidateKills - MI is going to be deleted. If any of its operands are
495 /// marked kill, then invalidate the information.
496 static void InvalidateKills(MachineInstr &MI,
497 const TargetRegisterInfo* TRI,
498 BitVector &RegKills,
499 std::vector<MachineOperand*> &KillOps,
500 SmallVector<unsigned, 2> *KillRegs = NULL) {
501 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
502 MachineOperand &MO = MI.getOperand(i);
503 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
504 continue;
505 unsigned Reg = MO.getReg();
506 if (TargetRegisterInfo::isVirtualRegister(Reg))
507 continue;
508 if (KillRegs)
509 KillRegs->push_back(Reg);
510 assert(Reg < KillOps.size());
511 if (KillOps[Reg] == &MO) {
512 KillOps[Reg] = NULL;
513 RegKills.reset(Reg);
514 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
515 if (RegKills[*SR]) {
516 KillOps[*SR] = NULL;
517 RegKills.reset(*SR);
524 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
525 /// (since its spill instruction is removed), mark it isDead. Also checks if
526 /// the def MI has other definition operands that are not dead. Returns it by
527 /// reference.
528 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
529 MachineInstr &NewDef, unsigned Reg,
530 bool &HasLiveDef,
531 const TargetRegisterInfo *TRI) {
532 // Due to remat, it's possible this reg isn't being reused. That is,
533 // the def of this reg (by prev MI) is now dead.
534 MachineInstr *DefMI = I;
535 MachineOperand *DefOp = NULL;
536 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
537 MachineOperand &MO = DefMI->getOperand(i);
538 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
539 continue;
540 if (MO.getReg() == Reg)
541 DefOp = &MO;
542 else if (!MO.isDead())
543 HasLiveDef = true;
545 if (!DefOp)
546 return false;
548 bool FoundUse = false, Done = false;
549 MachineBasicBlock::iterator E = &NewDef;
550 ++I; ++E;
551 for (; !Done && I != E; ++I) {
552 MachineInstr *NMI = I;
553 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
554 MachineOperand &MO = NMI->getOperand(j);
555 if (!MO.isReg() || MO.getReg() == 0 ||
556 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
557 continue;
558 if (MO.isUse())
559 FoundUse = true;
560 Done = true; // Stop after scanning all the operands of this MI.
563 if (!FoundUse) {
564 // Def is dead!
565 DefOp->setIsDead();
566 return true;
568 return false;
571 /// UpdateKills - Track and update kill info. If a MI reads a register that is
572 /// marked kill, then it must be due to register reuse. Transfer the kill info
573 /// over.
574 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
575 BitVector &RegKills,
576 std::vector<MachineOperand*> &KillOps) {
577 // These do not affect kill info at all.
578 if (MI.isDebugValue())
579 return;
580 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
581 MachineOperand &MO = MI.getOperand(i);
582 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
583 continue;
584 unsigned Reg = MO.getReg();
585 if (Reg == 0)
586 continue;
588 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
589 // That can't be right. Register is killed but not re-defined and it's
590 // being reused. Let's fix that.
591 KillOps[Reg]->setIsKill(false);
592 // KillOps[Reg] might be a def of a super-register.
593 unsigned KReg = KillOps[Reg]->getReg();
594 KillOps[KReg] = NULL;
595 RegKills.reset(KReg);
597 // Must be a def of a super-register. Its other sub-regsters are no
598 // longer killed as well.
599 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
600 KillOps[*SR] = NULL;
601 RegKills.reset(*SR);
603 } else {
604 // Check for subreg kills as well.
605 // d4 =
606 // store d4, fi#0
607 // ...
608 // = s8<kill>
609 // ...
610 // = d4 <avoiding reload>
611 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
612 unsigned SReg = *SR;
613 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
614 KillOps[SReg]->setIsKill(false);
615 unsigned KReg = KillOps[SReg]->getReg();
616 KillOps[KReg] = NULL;
617 RegKills.reset(KReg);
619 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
620 KillOps[*SSR] = NULL;
621 RegKills.reset(*SSR);
627 if (MO.isKill()) {
628 RegKills.set(Reg);
629 KillOps[Reg] = &MO;
630 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
631 RegKills.set(*SR);
632 KillOps[*SR] = &MO;
637 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI.getOperand(i);
639 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
640 continue;
641 unsigned Reg = MO.getReg();
642 RegKills.reset(Reg);
643 KillOps[Reg] = NULL;
644 // It also defines (or partially define) aliases.
645 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
646 RegKills.reset(*SR);
647 KillOps[*SR] = NULL;
649 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
650 RegKills.reset(*SR);
651 KillOps[*SR] = NULL;
656 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
658 static void ReMaterialize(MachineBasicBlock &MBB,
659 MachineBasicBlock::iterator &MII,
660 unsigned DestReg, unsigned Reg,
661 const TargetInstrInfo *TII,
662 const TargetRegisterInfo *TRI,
663 VirtRegMap &VRM) {
664 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
665 #ifndef NDEBUG
666 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
667 assert(TID.getNumDefs() == 1 &&
668 "Don't know how to remat instructions that define > 1 values!");
669 #endif
670 TII->reMaterialize(MBB, MII, DestReg, 0, ReMatDefMI, *TRI);
671 MachineInstr *NewMI = prior(MII);
672 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
673 MachineOperand &MO = NewMI->getOperand(i);
674 if (!MO.isReg() || MO.getReg() == 0)
675 continue;
676 unsigned VirtReg = MO.getReg();
677 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
678 continue;
679 assert(MO.isUse());
680 unsigned Phys = VRM.getPhys(VirtReg);
681 assert(Phys && "Virtual register is not assigned a register?");
682 substitutePhysReg(MO, Phys, *TRI);
684 ++NumReMats;
687 /// findSuperReg - Find the SubReg's super-register of given register class
688 /// where its SubIdx sub-register is SubReg.
689 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
690 unsigned SubIdx, const TargetRegisterInfo *TRI) {
691 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
692 I != E; ++I) {
693 unsigned Reg = *I;
694 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
695 return Reg;
697 return 0;
700 // ******************************** //
701 // Available Spills Implementation //
702 // ******************************** //
704 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
705 /// stackslot register. The register is still available but is no longer
706 /// allowed to be modifed.
707 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
708 std::multimap<unsigned, int>::iterator I =
709 PhysRegsAvailable.lower_bound(PhysReg);
710 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
711 int SlotOrReMat = I->second;
712 I++;
713 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
714 "Bidirectional map mismatch!");
715 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
716 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
717 << " copied, it is available for use but can no longer be modified\n");
721 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
722 /// stackslot register and its aliases. The register and its aliases may
723 /// still available but is no longer allowed to be modifed.
724 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
725 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
726 disallowClobberPhysRegOnly(*AS);
727 disallowClobberPhysRegOnly(PhysReg);
730 /// ClobberPhysRegOnly - This is called when the specified physreg changes
731 /// value. We use this to invalidate any info about stuff we thing lives in it.
732 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
733 std::multimap<unsigned, int>::iterator I =
734 PhysRegsAvailable.lower_bound(PhysReg);
735 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
736 int SlotOrReMat = I->second;
737 PhysRegsAvailable.erase(I++);
738 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
739 "Bidirectional map mismatch!");
740 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
741 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
742 << " clobbered, invalidating ");
743 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
744 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
745 else
746 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
750 /// ClobberPhysReg - This is called when the specified physreg changes
751 /// value. We use this to invalidate any info about stuff we thing lives in
752 /// it and any of its aliases.
753 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
754 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
755 ClobberPhysRegOnly(*AS);
756 ClobberPhysRegOnly(PhysReg);
759 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
760 /// into the specified MBB. Add available physical registers as potential
761 /// live-in's. If they are reused in the MBB, they will be added to the
762 /// live-in set to make register scavenger and post-allocation scheduler.
763 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
764 BitVector &RegKills,
765 std::vector<MachineOperand*> &KillOps) {
766 std::set<unsigned> NotAvailable;
767 for (std::multimap<unsigned, int>::iterator
768 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
769 I != E; ++I) {
770 unsigned Reg = I->first;
771 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
772 // FIXME: A temporary workaround. We can't reuse available value if it's
773 // not safe to move the def of the virtual register's class. e.g.
774 // X86::RFP* register classes. Do not add it as a live-in.
775 if (!TII->isSafeToMoveRegClassDefs(RC))
776 // This is no longer available.
777 NotAvailable.insert(Reg);
778 else {
779 MBB.addLiveIn(Reg);
780 InvalidateKill(Reg, TRI, RegKills, KillOps);
783 // Skip over the same register.
784 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
785 while (NI != E && NI->first == Reg) {
786 ++I;
787 ++NI;
791 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
792 E = NotAvailable.end(); I != E; ++I) {
793 ClobberPhysReg(*I);
794 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
795 *SubRegs; ++SubRegs)
796 ClobberPhysReg(*SubRegs);
800 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
801 /// slot changes. This removes information about which register the previous
802 /// value for this slot lives in (as the previous value is dead now).
803 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
804 std::map<int, unsigned>::iterator It =
805 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
806 if (It == SpillSlotsOrReMatsAvailable.end()) return;
807 unsigned Reg = It->second >> 1;
808 SpillSlotsOrReMatsAvailable.erase(It);
810 // This register may hold the value of multiple stack slots, only remove this
811 // stack slot from the set of values the register contains.
812 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
813 for (; ; ++I) {
814 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
815 "Map inverse broken!");
816 if (I->second == SlotOrReMat) break;
818 PhysRegsAvailable.erase(I);
821 // ************************** //
822 // Reuse Info Implementation //
823 // ************************** //
825 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
826 /// is some other operand that is using the specified register, either pick
827 /// a new register to use, or evict the previous reload and use this reg.
828 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
829 unsigned PhysReg,
830 MachineFunction &MF,
831 MachineInstr *MI, AvailableSpills &Spills,
832 std::vector<MachineInstr*> &MaybeDeadStores,
833 SmallSet<unsigned, 8> &Rejected,
834 BitVector &RegKills,
835 std::vector<MachineOperand*> &KillOps,
836 VirtRegMap &VRM) {
837 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
838 const TargetRegisterInfo *TRI = Spills.getRegInfo();
840 if (Reuses.empty()) return PhysReg; // This is most often empty.
842 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
843 ReusedOp &Op = Reuses[ro];
844 // If we find some other reuse that was supposed to use this register
845 // exactly for its reload, we can change this reload to use ITS reload
846 // register. That is, unless its reload register has already been
847 // considered and subsequently rejected because it has also been reused
848 // by another operand.
849 if (Op.PhysRegReused == PhysReg &&
850 Rejected.count(Op.AssignedPhysReg) == 0 &&
851 RC->contains(Op.AssignedPhysReg)) {
852 // Yup, use the reload register that we didn't use before.
853 unsigned NewReg = Op.AssignedPhysReg;
854 Rejected.insert(PhysReg);
855 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
856 RegKills, KillOps, VRM);
857 } else {
858 // Otherwise, we might also have a problem if a previously reused
859 // value aliases the new register. If so, codegen the previous reload
860 // and use this one.
861 unsigned PRRU = Op.PhysRegReused;
862 if (TRI->regsOverlap(PRRU, PhysReg)) {
863 // Okay, we found out that an alias of a reused register
864 // was used. This isn't good because it means we have
865 // to undo a previous reuse.
866 MachineBasicBlock *MBB = MI->getParent();
867 const TargetRegisterClass *AliasRC =
868 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
870 // Copy Op out of the vector and remove it, we're going to insert an
871 // explicit load for it.
872 ReusedOp NewOp = Op;
873 Reuses.erase(Reuses.begin()+ro);
875 // MI may be using only a sub-register of PhysRegUsed.
876 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
877 unsigned SubIdx = 0;
878 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
879 "A reuse cannot be a virtual register");
880 if (PRRU != RealPhysRegUsed) {
881 // What was the sub-register index?
882 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
883 assert(SubIdx &&
884 "Operand physreg is not a sub-register of PhysRegUsed");
887 // Ok, we're going to try to reload the assigned physreg into the
888 // slot that we were supposed to in the first place. However, that
889 // register could hold a reuse. Check to see if it conflicts or
890 // would prefer us to use a different register.
891 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
892 MF, MI, Spills, MaybeDeadStores,
893 Rejected, RegKills, KillOps, VRM);
895 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
896 int SSorRMId = DoReMat
897 ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
899 // Back-schedule reloads and remats.
900 MachineBasicBlock::iterator InsertLoc =
901 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
902 DoReMat, SSorRMId, TII, MF);
904 if (DoReMat) {
905 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
906 TRI, VRM);
907 } else {
908 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
909 NewOp.StackSlotOrReMat, AliasRC, TRI);
910 MachineInstr *LoadMI = prior(InsertLoc);
911 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
912 // Any stores to this stack slot are not dead anymore.
913 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
914 ++NumLoads;
916 Spills.ClobberPhysReg(NewPhysReg);
917 Spills.ClobberPhysReg(NewOp.PhysRegReused);
919 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
920 MI->getOperand(NewOp.Operand).setReg(RReg);
921 MI->getOperand(NewOp.Operand).setSubReg(0);
923 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
924 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
925 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
927 DEBUG(dbgs() << "Reuse undone!\n");
928 --NumReused;
930 // Finally, PhysReg is now available, go ahead and use it.
931 return PhysReg;
935 return PhysReg;
938 // ************************************************************************ //
940 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
941 /// stack slot mod/ref. It also checks if it's possible to unfold the
942 /// instruction by having it define a specified physical register instead.
943 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
944 const TargetInstrInfo *TII,
945 const TargetRegisterInfo *TRI,
946 VirtRegMap &VRM) {
947 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
948 return false;
950 bool Found = false;
951 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
952 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
953 unsigned VirtReg = I->second.first;
954 VirtRegMap::ModRef MR = I->second.second;
955 if (MR & VirtRegMap::isModRef)
956 if (VRM.getStackSlot(VirtReg) == SS) {
957 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
958 break;
961 if (!Found)
962 return false;
964 // Does the instruction uses a register that overlaps the scratch register?
965 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
966 MachineOperand &MO = MI.getOperand(i);
967 if (!MO.isReg() || MO.getReg() == 0)
968 continue;
969 unsigned Reg = MO.getReg();
970 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
971 if (!VRM.hasPhys(Reg))
972 continue;
973 Reg = VRM.getPhys(Reg);
975 if (TRI->regsOverlap(PhysReg, Reg))
976 return false;
978 return true;
981 /// FindFreeRegister - Find a free register of a given register class by looking
982 /// at (at most) the last two machine instructions.
983 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
984 MachineBasicBlock &MBB,
985 const TargetRegisterClass *RC,
986 const TargetRegisterInfo *TRI,
987 BitVector &AllocatableRegs) {
988 BitVector Defs(TRI->getNumRegs());
989 BitVector Uses(TRI->getNumRegs());
990 SmallVector<unsigned, 4> LocalUses;
991 SmallVector<unsigned, 4> Kills;
993 // Take a look at 2 instructions at most.
994 unsigned Count = 0;
995 while (Count < 2) {
996 if (MII == MBB.begin())
997 break;
998 MachineInstr *PrevMI = prior(MII);
999 MII = PrevMI;
1001 if (PrevMI->isDebugValue())
1002 continue; // Skip over dbg_value instructions.
1003 ++Count;
1005 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
1006 MachineOperand &MO = PrevMI->getOperand(i);
1007 if (!MO.isReg() || MO.getReg() == 0)
1008 continue;
1009 unsigned Reg = MO.getReg();
1010 if (MO.isDef()) {
1011 Defs.set(Reg);
1012 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1013 Defs.set(*AS);
1014 } else {
1015 LocalUses.push_back(Reg);
1016 if (MO.isKill() && AllocatableRegs[Reg])
1017 Kills.push_back(Reg);
1021 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1022 unsigned Kill = Kills[i];
1023 if (!Defs[Kill] && !Uses[Kill] &&
1024 TRI->getPhysicalRegisterRegClass(Kill) == RC)
1025 return Kill;
1027 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1028 unsigned Reg = LocalUses[i];
1029 Uses.set(Reg);
1030 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1031 Uses.set(*AS);
1035 return 0;
1038 static
1039 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1040 const TargetRegisterInfo &TRI) {
1041 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1042 MachineOperand &MO = MI->getOperand(i);
1043 if (MO.isReg() && MO.getReg() == VirtReg)
1044 substitutePhysReg(MO, PhysReg, TRI);
1048 namespace {
1050 struct RefSorter {
1051 bool operator()(const std::pair<MachineInstr*, int> &A,
1052 const std::pair<MachineInstr*, int> &B) {
1053 return A.second < B.second;
1057 // ***************************** //
1058 // Local Spiller Implementation //
1059 // ***************************** //
1061 class LocalRewriter : public VirtRegRewriter {
1062 MachineRegisterInfo *MRI;
1063 const TargetRegisterInfo *TRI;
1064 const TargetInstrInfo *TII;
1065 VirtRegMap *VRM;
1066 BitVector AllocatableRegs;
1067 DenseMap<MachineInstr*, unsigned> DistanceMap;
1068 DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
1070 MachineBasicBlock *MBB; // Basic block currently being processed.
1072 public:
1074 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1075 LiveIntervals* LIs);
1077 private:
1079 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1080 MachineBasicBlock::iterator &MII,
1081 std::vector<MachineInstr*> &MaybeDeadStores,
1082 AvailableSpills &Spills,
1083 BitVector &RegKills,
1084 std::vector<MachineOperand*> &KillOps);
1086 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1087 std::vector<MachineInstr*> &MaybeDeadStores,
1088 AvailableSpills &Spills,
1089 BitVector &RegKills,
1090 std::vector<MachineOperand*> &KillOps);
1092 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1093 unsigned VirtReg, unsigned SrcReg, int SS,
1094 AvailableSpills &Spills,
1095 BitVector &RegKills,
1096 std::vector<MachineOperand*> &KillOps,
1097 const TargetRegisterInfo *TRI);
1099 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1100 int Idx, unsigned PhysReg, int StackSlot,
1101 const TargetRegisterClass *RC,
1102 bool isAvailable, MachineInstr *&LastStore,
1103 AvailableSpills &Spills,
1104 SmallSet<MachineInstr*, 4> &ReMatDefs,
1105 BitVector &RegKills,
1106 std::vector<MachineOperand*> &KillOps);
1108 void TransferDeadness(unsigned Reg, BitVector &RegKills,
1109 std::vector<MachineOperand*> &KillOps);
1111 bool InsertEmergencySpills(MachineInstr *MI);
1113 bool InsertRestores(MachineInstr *MI,
1114 AvailableSpills &Spills,
1115 BitVector &RegKills,
1116 std::vector<MachineOperand*> &KillOps);
1118 bool InsertSpills(MachineInstr *MI);
1120 void RewriteMBB(LiveIntervals *LIs,
1121 AvailableSpills &Spills, BitVector &RegKills,
1122 std::vector<MachineOperand*> &KillOps);
1126 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1127 LiveIntervals* LIs) {
1128 MRI = &MF.getRegInfo();
1129 TRI = MF.getTarget().getRegisterInfo();
1130 TII = MF.getTarget().getInstrInfo();
1131 VRM = &vrm;
1132 AllocatableRegs = TRI->getAllocatableSet(MF);
1133 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1134 << MF.getFunction()->getName() << "':\n");
1135 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1136 " reloads!) ****\n");
1137 DEBUG(MF.dump());
1139 // Spills - Keep track of which spilled values are available in physregs
1140 // so that we can choose to reuse the physregs instead of emitting
1141 // reloads. This is usually refreshed per basic block.
1142 AvailableSpills Spills(TRI, TII);
1144 // Keep track of kill information.
1145 BitVector RegKills(TRI->getNumRegs());
1146 std::vector<MachineOperand*> KillOps;
1147 KillOps.resize(TRI->getNumRegs(), NULL);
1149 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1150 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1151 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1153 // Traverse the basic blocks depth first.
1154 MachineBasicBlock *Entry = MF.begin();
1155 SmallPtrSet<MachineBasicBlock*,16> Visited;
1156 for (df_ext_iterator<MachineBasicBlock*,
1157 SmallPtrSet<MachineBasicBlock*,16> >
1158 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1159 DFI != E; ++DFI) {
1160 MBB = *DFI;
1161 if (!EarlyVisited.count(MBB))
1162 RewriteMBB(LIs, Spills, RegKills, KillOps);
1164 // If this MBB is the only predecessor of a successor. Keep the
1165 // availability information and visit it next.
1166 do {
1167 // Keep visiting single predecessor successor as long as possible.
1168 SinglePredSuccs.clear();
1169 findSinglePredSuccessor(MBB, SinglePredSuccs);
1170 if (SinglePredSuccs.empty())
1171 MBB = 0;
1172 else {
1173 // FIXME: More than one successors, each of which has MBB has
1174 // the only predecessor.
1175 MBB = SinglePredSuccs[0];
1176 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1177 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1178 RewriteMBB(LIs, Spills, RegKills, KillOps);
1181 } while (MBB);
1183 // Clear the availability info.
1184 Spills.clear();
1187 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1188 DEBUG(MF.dump());
1190 // Mark unused spill slots.
1191 MachineFrameInfo *MFI = MF.getFrameInfo();
1192 int SS = VRM->getLowSpillSlot();
1193 if (SS != VirtRegMap::NO_STACK_SLOT) {
1194 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1195 SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
1196 if (!VRM->isSpillSlotUsed(SS)) {
1197 MFI->RemoveStackObject(SS);
1198 for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1199 MachineInstr *DVMI = DbgValues[j];
1200 MachineBasicBlock *DVMBB = DVMI->getParent();
1201 DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1202 VRM->RemoveMachineInstrFromMaps(DVMI);
1203 DVMBB->erase(DVMI);
1205 ++NumDSS;
1207 DbgValues.clear();
1210 Slot2DbgValues.clear();
1212 return true;
1215 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1216 /// a scratch register is available.
1217 /// xorq %r12<kill>, %r13
1218 /// addq %rax, -184(%rbp)
1219 /// addq %r13, -184(%rbp)
1220 /// ==>
1221 /// xorq %r12<kill>, %r13
1222 /// movq -184(%rbp), %r12
1223 /// addq %rax, %r12
1224 /// addq %r13, %r12
1225 /// movq %r12, -184(%rbp)
1226 bool LocalRewriter::
1227 OptimizeByUnfold2(unsigned VirtReg, int SS,
1228 MachineBasicBlock::iterator &MII,
1229 std::vector<MachineInstr*> &MaybeDeadStores,
1230 AvailableSpills &Spills,
1231 BitVector &RegKills,
1232 std::vector<MachineOperand*> &KillOps) {
1234 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1235 // Skip over dbg_value instructions.
1236 while (NextMII != MBB->end() && NextMII->isDebugValue())
1237 NextMII = llvm::next(NextMII);
1238 if (NextMII == MBB->end())
1239 return false;
1241 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1242 return false;
1244 // Now let's see if the last couple of instructions happens to have freed up
1245 // a register.
1246 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1247 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1248 if (!PhysReg)
1249 return false;
1251 MachineFunction &MF = *MBB->getParent();
1252 TRI = MF.getTarget().getRegisterInfo();
1253 MachineInstr &MI = *MII;
1254 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1255 return false;
1257 // If the next instruction also folds the same SS modref and can be unfoled,
1258 // then it's worthwhile to issue a load from SS into the free register and
1259 // then unfold these instructions.
1260 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1261 return false;
1263 // Back-schedule reloads and remats.
1264 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1266 // Load from SS to the spare physical register.
1267 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
1268 // This invalidates Phys.
1269 Spills.ClobberPhysReg(PhysReg);
1270 // Remember it's available.
1271 Spills.addAvailable(SS, PhysReg);
1272 MaybeDeadStores[SS] = NULL;
1274 // Unfold current MI.
1275 SmallVector<MachineInstr*, 4> NewMIs;
1276 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1277 llvm_unreachable("Unable unfold the load / store folding instruction!");
1278 assert(NewMIs.size() == 1);
1279 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1280 VRM->transferRestorePts(&MI, NewMIs[0]);
1281 MII = MBB->insert(MII, NewMIs[0]);
1282 InvalidateKills(MI, TRI, RegKills, KillOps);
1283 VRM->RemoveMachineInstrFromMaps(&MI);
1284 MBB->erase(&MI);
1285 ++NumModRefUnfold;
1287 // Unfold next instructions that fold the same SS.
1288 do {
1289 MachineInstr &NextMI = *NextMII;
1290 NextMII = llvm::next(NextMII);
1291 NewMIs.clear();
1292 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1293 llvm_unreachable("Unable unfold the load / store folding instruction!");
1294 assert(NewMIs.size() == 1);
1295 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1296 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1297 MBB->insert(NextMII, NewMIs[0]);
1298 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1299 VRM->RemoveMachineInstrFromMaps(&NextMI);
1300 MBB->erase(&NextMI);
1301 ++NumModRefUnfold;
1302 // Skip over dbg_value instructions.
1303 while (NextMII != MBB->end() && NextMII->isDebugValue())
1304 NextMII = llvm::next(NextMII);
1305 if (NextMII == MBB->end())
1306 break;
1307 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1309 // Store the value back into SS.
1310 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
1311 MachineInstr *StoreMI = prior(NextMII);
1312 VRM->addSpillSlotUse(SS, StoreMI);
1313 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1315 return true;
1318 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1319 /// instruction. e.g.
1320 /// xorl %edi, %eax
1321 /// movl %eax, -32(%ebp)
1322 /// movl -36(%ebp), %eax
1323 /// orl %eax, -32(%ebp)
1324 /// ==>
1325 /// xorl %edi, %eax
1326 /// orl -36(%ebp), %eax
1327 /// mov %eax, -32(%ebp)
1328 /// This enables unfolding optimization for a subsequent instruction which will
1329 /// also eliminate the newly introduced store instruction.
1330 bool LocalRewriter::
1331 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1332 std::vector<MachineInstr*> &MaybeDeadStores,
1333 AvailableSpills &Spills,
1334 BitVector &RegKills,
1335 std::vector<MachineOperand*> &KillOps) {
1336 MachineFunction &MF = *MBB->getParent();
1337 MachineInstr &MI = *MII;
1338 unsigned UnfoldedOpc = 0;
1339 unsigned UnfoldPR = 0;
1340 unsigned UnfoldVR = 0;
1341 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1342 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1343 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1344 // Only transform a MI that folds a single register.
1345 if (UnfoldedOpc)
1346 return false;
1347 UnfoldVR = I->second.first;
1348 VirtRegMap::ModRef MR = I->second.second;
1349 // MI2VirtMap be can updated which invalidate the iterator.
1350 // Increment the iterator first.
1351 ++I;
1352 if (VRM->isAssignedReg(UnfoldVR))
1353 continue;
1354 // If this reference is not a use, any previous store is now dead.
1355 // Otherwise, the store to this stack slot is not dead anymore.
1356 FoldedSS = VRM->getStackSlot(UnfoldVR);
1357 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1358 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1359 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1360 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1361 continue;
1362 UnfoldPR = PhysReg;
1363 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1364 false, true);
1368 if (!UnfoldedOpc) {
1369 if (!UnfoldVR)
1370 return false;
1372 // Look for other unfolding opportunities.
1373 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1374 RegKills, KillOps);
1377 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1378 MachineOperand &MO = MI.getOperand(i);
1379 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1380 continue;
1381 unsigned VirtReg = MO.getReg();
1382 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1383 continue;
1384 if (VRM->isAssignedReg(VirtReg)) {
1385 unsigned PhysReg = VRM->getPhys(VirtReg);
1386 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1387 return false;
1388 } else if (VRM->isReMaterialized(VirtReg))
1389 continue;
1390 int SS = VRM->getStackSlot(VirtReg);
1391 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1392 if (PhysReg) {
1393 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1394 return false;
1395 continue;
1397 if (VRM->hasPhys(VirtReg)) {
1398 PhysReg = VRM->getPhys(VirtReg);
1399 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1400 continue;
1403 // Ok, we'll need to reload the value into a register which makes
1404 // it impossible to perform the store unfolding optimization later.
1405 // Let's see if it is possible to fold the load if the store is
1406 // unfolded. This allows us to perform the store unfolding
1407 // optimization.
1408 SmallVector<MachineInstr*, 4> NewMIs;
1409 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1410 assert(NewMIs.size() == 1);
1411 MachineInstr *NewMI = NewMIs.back();
1412 NewMIs.clear();
1413 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1414 assert(Idx != -1);
1415 SmallVector<unsigned, 1> Ops;
1416 Ops.push_back(Idx);
1417 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1418 if (FoldedMI) {
1419 VRM->addSpillSlotUse(SS, FoldedMI);
1420 if (!VRM->hasPhys(UnfoldVR))
1421 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1422 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1423 MII = MBB->insert(MII, FoldedMI);
1424 InvalidateKills(MI, TRI, RegKills, KillOps);
1425 VRM->RemoveMachineInstrFromMaps(&MI);
1426 MBB->erase(&MI);
1427 MF.DeleteMachineInstr(NewMI);
1428 return true;
1430 MF.DeleteMachineInstr(NewMI);
1434 return false;
1437 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1438 /// where SrcReg is r1 and it is tied to r0. Return true if after
1439 /// commuting this instruction it will be r0 = op r2, r1.
1440 static bool CommuteChangesDestination(MachineInstr *DefMI,
1441 const TargetInstrDesc &TID,
1442 unsigned SrcReg,
1443 const TargetInstrInfo *TII,
1444 unsigned &DstIdx) {
1445 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1446 return false;
1447 if (!DefMI->getOperand(1).isReg() ||
1448 DefMI->getOperand(1).getReg() != SrcReg)
1449 return false;
1450 unsigned DefIdx;
1451 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1452 return false;
1453 unsigned SrcIdx1, SrcIdx2;
1454 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1455 return false;
1456 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1457 DstIdx = 2;
1458 return true;
1460 return false;
1463 /// CommuteToFoldReload -
1464 /// Look for
1465 /// r1 = load fi#1
1466 /// r1 = op r1, r2<kill>
1467 /// store r1, fi#1
1469 /// If op is commutable and r2 is killed, then we can xform these to
1470 /// r2 = op r2, fi#1
1471 /// store r2, fi#1
1472 bool LocalRewriter::
1473 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1474 unsigned VirtReg, unsigned SrcReg, int SS,
1475 AvailableSpills &Spills,
1476 BitVector &RegKills,
1477 std::vector<MachineOperand*> &KillOps,
1478 const TargetRegisterInfo *TRI) {
1479 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1480 return false;
1482 MachineFunction &MF = *MBB->getParent();
1483 MachineInstr &MI = *MII;
1484 MachineBasicBlock::iterator DefMII = prior(MII);
1485 MachineInstr *DefMI = DefMII;
1486 const TargetInstrDesc &TID = DefMI->getDesc();
1487 unsigned NewDstIdx;
1488 if (DefMII != MBB->begin() &&
1489 TID.isCommutable() &&
1490 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1491 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1492 unsigned NewReg = NewDstMO.getReg();
1493 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1494 return false;
1495 MachineInstr *ReloadMI = prior(DefMII);
1496 int FrameIdx;
1497 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1498 if (DestReg != SrcReg || FrameIdx != SS)
1499 return false;
1500 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1501 if (UseIdx == -1)
1502 return false;
1503 unsigned DefIdx;
1504 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1505 return false;
1506 assert(DefMI->getOperand(DefIdx).isReg() &&
1507 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1509 // Now commute def instruction.
1510 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1511 if (!CommutedMI)
1512 return false;
1513 SmallVector<unsigned, 1> Ops;
1514 Ops.push_back(NewDstIdx);
1515 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1516 // Not needed since foldMemoryOperand returns new MI.
1517 MF.DeleteMachineInstr(CommutedMI);
1518 if (!FoldedMI)
1519 return false;
1521 VRM->addSpillSlotUse(SS, FoldedMI);
1522 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1523 // Insert new def MI and spill MI.
1524 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1525 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
1526 MII = prior(MII);
1527 MachineInstr *StoreMI = MII;
1528 VRM->addSpillSlotUse(SS, StoreMI);
1529 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1530 MII = MBB->insert(MII, FoldedMI); // Update MII to backtrack.
1532 // Delete all 3 old instructions.
1533 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1534 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1535 MBB->erase(ReloadMI);
1536 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1537 VRM->RemoveMachineInstrFromMaps(DefMI);
1538 MBB->erase(DefMI);
1539 InvalidateKills(MI, TRI, RegKills, KillOps);
1540 VRM->RemoveMachineInstrFromMaps(&MI);
1541 MBB->erase(&MI);
1543 // If NewReg was previously holding value of some SS, it's now clobbered.
1544 // This has to be done now because it's a physical register. When this
1545 // instruction is re-visited, it's ignored.
1546 Spills.ClobberPhysReg(NewReg);
1548 ++NumCommutes;
1549 return true;
1552 return false;
1555 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1556 /// the last store to the same slot is now dead. If so, remove the last store.
1557 void LocalRewriter::
1558 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1559 int Idx, unsigned PhysReg, int StackSlot,
1560 const TargetRegisterClass *RC,
1561 bool isAvailable, MachineInstr *&LastStore,
1562 AvailableSpills &Spills,
1563 SmallSet<MachineInstr*, 4> &ReMatDefs,
1564 BitVector &RegKills,
1565 std::vector<MachineOperand*> &KillOps) {
1567 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1568 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1569 TRI);
1570 MachineInstr *StoreMI = prior(oldNextMII);
1571 VRM->addSpillSlotUse(StackSlot, StoreMI);
1572 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1574 // If there is a dead store to this stack slot, nuke it now.
1575 if (LastStore) {
1576 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1577 ++NumDSE;
1578 SmallVector<unsigned, 2> KillRegs;
1579 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1580 MachineBasicBlock::iterator PrevMII = LastStore;
1581 bool CheckDef = PrevMII != MBB->begin();
1582 if (CheckDef)
1583 --PrevMII;
1584 VRM->RemoveMachineInstrFromMaps(LastStore);
1585 MBB->erase(LastStore);
1586 if (CheckDef) {
1587 // Look at defs of killed registers on the store. Mark the defs
1588 // as dead since the store has been deleted and they aren't
1589 // being reused.
1590 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1591 bool HasOtherDef = false;
1592 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1593 MachineInstr *DeadDef = PrevMII;
1594 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1595 // FIXME: This assumes a remat def does not have side effects.
1596 VRM->RemoveMachineInstrFromMaps(DeadDef);
1597 MBB->erase(DeadDef);
1598 ++NumDRM;
1605 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1606 // the last of multiple instructions is the actual store.
1607 LastStore = prior(oldNextMII);
1609 // If the stack slot value was previously available in some other
1610 // register, change it now. Otherwise, make the register available,
1611 // in PhysReg.
1612 Spills.ModifyStackSlotOrReMat(StackSlot);
1613 Spills.ClobberPhysReg(PhysReg);
1614 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1615 ++NumStores;
1618 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1619 /// effect and all of its defs are dead.
1620 static bool isSafeToDelete(MachineInstr &MI) {
1621 const TargetInstrDesc &TID = MI.getDesc();
1622 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1623 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1624 TID.hasUnmodeledSideEffects())
1625 return false;
1626 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1627 MachineOperand &MO = MI.getOperand(i);
1628 if (!MO.isReg() || !MO.getReg())
1629 continue;
1630 if (MO.isDef() && !MO.isDead())
1631 return false;
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
1635 // markers.
1636 return false;
1638 return true;
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)
1652 continue;
1653 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1654 if (DI == DistanceMap.end())
1655 continue;
1656 if (Seens.insert(UDMI))
1657 Refs.push_back(std::make_pair(UDMI, DI->second));
1660 if (Refs.empty())
1661 return;
1662 std::sort(Refs.begin(), Refs.end(), RefSorter());
1664 while (!Refs.empty()) {
1665 MachineInstr *LastUDMI = Refs.back().first;
1666 Refs.pop_back();
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)
1672 continue;
1673 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1674 LastUD = &MO;
1675 if (LastUDMI->isRegTiedToDefOperand(i))
1676 break;
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();
1683 break;
1685 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1686 MBB->erase(LastUDMI);
1687 } else {
1688 LastUD->setIsKill();
1689 RegKills.set(Reg);
1690 KillOps[Reg] = LastUD;
1691 break;
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))
1700 return false;
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->getPhysicalRegisterRegClass(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!");
1711 UsedSS.insert(SS);
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);
1725 ++NumPSpills;
1726 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1728 return true;
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))
1738 return false;
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
1750 // expect:
1751 // BB1:
1752 // r1 = load fi#1
1753 // ...
1754 // = r1<kill>
1755 // ... # r1 not clobbered
1756 // ...
1757 // = load fi#1
1758 bool DoReMat = VRM->isReMaterialized(VirtReg);
1759 int SSorRMId = DoReMat
1760 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1761 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1762 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1763 if (InReg == Phys) {
1764 // If the value is already available in the expected register, save
1765 // a reload / remat.
1766 if (SSorRMId)
1767 DEBUG(dbgs() << "Reusing RM#"
1768 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1769 else
1770 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1771 DEBUG(dbgs() << " from physreg "
1772 << TRI->getName(InReg) << " for vreg"
1773 << VirtReg <<" instead of reloading into physreg "
1774 << TRI->getName(Phys) << '\n');
1775 ++NumOmitted;
1776 continue;
1777 } else if (InReg && InReg != Phys) {
1778 if (SSorRMId)
1779 DEBUG(dbgs() << "Reusing RM#"
1780 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1781 else
1782 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1783 DEBUG(dbgs() << " from physreg "
1784 << TRI->getName(InReg) << " for vreg"
1785 << VirtReg <<" by copying it into physreg "
1786 << TRI->getName(Phys) << '\n');
1788 // If the reloaded / remat value is available in another register,
1789 // copy it to the desired register.
1791 // Back-schedule reloads and remats.
1792 MachineBasicBlock::iterator InsertLoc =
1793 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1794 *MBB->getParent());
1796 TII->copyRegToReg(*MBB, InsertLoc, Phys, InReg, RC, RC,
1797 MI->getDebugLoc());
1799 // This invalidates Phys.
1800 Spills.ClobberPhysReg(Phys);
1801 // Remember it's available.
1802 Spills.addAvailable(SSorRMId, Phys);
1804 // Mark is killed.
1805 MachineInstr *CopyMI = prior(InsertLoc);
1806 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1807 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1808 KillOpnd->setIsKill();
1809 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1811 DEBUG(dbgs() << '\t' << *CopyMI);
1812 ++NumCopified;
1813 continue;
1816 // Back-schedule reloads and remats.
1817 MachineBasicBlock::iterator InsertLoc =
1818 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1819 *MBB->getParent());
1821 if (VRM->isReMaterialized(VirtReg)) {
1822 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1823 } else {
1824 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1825 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
1826 MachineInstr *LoadMI = prior(InsertLoc);
1827 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1828 ++NumLoads;
1829 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1832 // This invalidates Phys.
1833 Spills.ClobberPhysReg(Phys);
1834 // Remember it's available.
1835 Spills.addAvailable(SSorRMId, Phys);
1837 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1838 DEBUG(dbgs() << '\t' << *prior(MII));
1840 return true;
1843 /// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1844 /// true if spills were inserted.
1845 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1846 if (!VRM->isSpillPt(MI))
1847 return false;
1848 MachineBasicBlock::iterator MII = MI;
1849 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1850 VRM->getSpillPtSpills(MI);
1851 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1852 unsigned VirtReg = SpillRegs[i].first;
1853 bool isKill = SpillRegs[i].second;
1854 if (!VRM->getPreSplitReg(VirtReg))
1855 continue; // Split interval spilled again.
1856 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1857 unsigned Phys = VRM->getPhys(VirtReg);
1858 int StackSlot = VRM->getStackSlot(VirtReg);
1859 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1860 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1861 RC, TRI);
1862 MachineInstr *StoreMI = prior(oldNextMII);
1863 VRM->addSpillSlotUse(StackSlot, StoreMI);
1864 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1865 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1867 return true;
1871 /// rewriteMBB - Keep track of which spills are available even after the
1872 /// register allocator is done with them. If possible, avid reloading vregs.
1873 void
1874 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1875 AvailableSpills &Spills, BitVector &RegKills,
1876 std::vector<MachineOperand*> &KillOps) {
1878 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1879 << MBB->getName() << "':\n");
1881 MachineFunction &MF = *MBB->getParent();
1883 // MaybeDeadStores - When we need to write a value back into a stack slot,
1884 // keep track of the inserted store. If the stack slot value is never read
1885 // (because the value was used from some available register, for example), and
1886 // subsequently stored to, the original store is dead. This map keeps track
1887 // of inserted stores that are not used. If we see a subsequent store to the
1888 // same stack slot, the original store is deleted.
1889 std::vector<MachineInstr*> MaybeDeadStores;
1890 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1892 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1893 SmallSet<MachineInstr*, 4> ReMatDefs;
1895 // Clear kill info.
1896 SmallSet<unsigned, 2> KilledMIRegs;
1898 // Keep track of the registers we have already spilled in case there are
1899 // multiple defs of the same register in MI.
1900 SmallSet<unsigned, 8> SpilledMIRegs;
1902 RegKills.reset();
1903 KillOps.clear();
1904 KillOps.resize(TRI->getNumRegs(), NULL);
1906 DistanceMap.clear();
1907 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1908 MII != E; ) {
1909 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1911 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1912 NextMII = llvm::next(MII);
1914 if (InsertEmergencySpills(MII))
1915 NextMII = llvm::next(MII);
1917 InsertRestores(MII, Spills, RegKills, KillOps);
1919 if (InsertSpills(MII))
1920 NextMII = llvm::next(MII);
1922 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1923 bool Erased = false;
1924 bool BackTracked = false;
1925 MachineInstr &MI = *MII;
1927 // Remember DbgValue's which reference stack slots.
1928 if (MI.isDebugValue() && MI.getOperand(0).isFI())
1929 Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
1931 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1932 /// reuse.
1933 ReuseInfo ReusedOperands(MI, TRI);
1934 SmallVector<unsigned, 4> VirtUseOps;
1935 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1936 MachineOperand &MO = MI.getOperand(i);
1937 if (!MO.isReg() || MO.getReg() == 0)
1938 continue; // Ignore non-register operands.
1940 unsigned VirtReg = MO.getReg();
1941 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1942 // Ignore physregs for spilling, but remember that it is used by this
1943 // function.
1944 MRI->setPhysRegUsed(VirtReg);
1945 continue;
1948 // We want to process implicit virtual register uses first.
1949 if (MO.isImplicit())
1950 // If the virtual register is implicitly defined, emit a implicit_def
1951 // before so scavenger knows it's "defined".
1952 // FIXME: This is a horrible hack done the by register allocator to
1953 // remat a definition with virtual register operand.
1954 VirtUseOps.insert(VirtUseOps.begin(), i);
1955 else
1956 VirtUseOps.push_back(i);
1959 // Process all of the spilled uses and all non spilled reg references.
1960 SmallVector<int, 2> PotentialDeadStoreSlots;
1961 KilledMIRegs.clear();
1962 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1963 unsigned i = VirtUseOps[j];
1964 unsigned VirtReg = MI.getOperand(i).getReg();
1965 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1966 "Not a virtual register?");
1968 unsigned SubIdx = MI.getOperand(i).getSubReg();
1969 if (VRM->isAssignedReg(VirtReg)) {
1970 // This virtual register was assigned a physreg!
1971 unsigned Phys = VRM->getPhys(VirtReg);
1972 MRI->setPhysRegUsed(Phys);
1973 if (MI.getOperand(i).isDef())
1974 ReusedOperands.markClobbered(Phys);
1975 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1976 if (VRM->isImplicitlyDefined(VirtReg))
1977 // FIXME: Is this needed?
1978 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1979 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1980 continue;
1983 // This virtual register is now known to be a spilled value.
1984 if (!MI.getOperand(i).isUse())
1985 continue; // Handle defs in the loop below (handle use&def here though)
1987 bool AvoidReload = MI.getOperand(i).isUndef();
1988 // Check if it is defined by an implicit def. It should not be spilled.
1989 // Note, this is for correctness reason. e.g.
1990 // 8 %reg1024<def> = IMPLICIT_DEF
1991 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1992 // The live range [12, 14) are not part of the r1024 live interval since
1993 // it's defined by an implicit def. It will not conflicts with live
1994 // interval of r1025. Now suppose both registers are spilled, you can
1995 // easily see a situation where both registers are reloaded before
1996 // the INSERT_SUBREG and both target registers that would overlap.
1997 bool DoReMat = VRM->isReMaterialized(VirtReg);
1998 int SSorRMId = DoReMat
1999 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
2000 int ReuseSlot = SSorRMId;
2002 // Check to see if this stack slot is available.
2003 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
2005 // If this is a sub-register use, make sure the reuse register is in the
2006 // right register class. For example, for x86 not all of the 32-bit
2007 // registers have accessible sub-registers.
2008 // Similarly so for EXTRACT_SUBREG. Consider this:
2009 // EDI = op
2010 // MOV32_mr fi#1, EDI
2011 // ...
2012 // = EXTRACT_SUBREG fi#1
2013 // fi#1 is available in EDI, but it cannot be reused because it's not in
2014 // the right register file.
2015 if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
2016 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2017 if (!RC->contains(PhysReg))
2018 PhysReg = 0;
2021 if (PhysReg && !AvoidReload) {
2022 // This spilled operand might be part of a two-address operand. If this
2023 // is the case, then changing it will necessarily require changing the
2024 // def part of the instruction as well. However, in some cases, we
2025 // aren't allowed to modify the reused register. If none of these cases
2026 // apply, reuse it.
2027 bool CanReuse = true;
2028 bool isTied = MI.isRegTiedToDefOperand(i);
2029 if (isTied) {
2030 // Okay, we have a two address operand. We can reuse this physreg as
2031 // long as we are allowed to clobber the value and there isn't an
2032 // earlier def that has already clobbered the physreg.
2033 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
2034 Spills.canClobberPhysReg(PhysReg);
2036 // If this is an asm, and PhysReg is used elsewhere as an earlyclobber
2037 // operand, we can't also use it as an input. (Outputs always come
2038 // before inputs, so we can stop looking at i.)
2039 if (MI.isInlineAsm()) {
2040 for (unsigned k=0; k<i; ++k) {
2041 MachineOperand &MOk = MI.getOperand(k);
2042 if (MOk.isReg() && MOk.getReg()==PhysReg && MOk.isEarlyClobber()) {
2043 CanReuse = false;
2044 break;
2049 if (CanReuse) {
2050 // If this stack slot value is already available, reuse it!
2051 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2052 DEBUG(dbgs() << "Reusing RM#"
2053 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2054 else
2055 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2056 DEBUG(dbgs() << " from physreg "
2057 << TRI->getName(PhysReg) << " for vreg"
2058 << VirtReg <<" instead of reloading into physreg "
2059 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2060 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2061 MI.getOperand(i).setReg(RReg);
2062 MI.getOperand(i).setSubReg(0);
2064 // The only technical detail we have is that we don't know that
2065 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2066 // later in the instruction. In particular, consider 'op V1, V2'.
2067 // If V1 is available in physreg R0, we would choose to reuse it
2068 // here, instead of reloading it into the register the allocator
2069 // indicated (say R1). However, V2 might have to be reloaded
2070 // later, and it might indicate that it needs to live in R0. When
2071 // this occurs, we need to have information available that
2072 // indicates it is safe to use R1 for the reload instead of R0.
2074 // To further complicate matters, we might conflict with an alias,
2075 // or R0 and R1 might not be compatible with each other. In this
2076 // case, we actually insert a reload for V1 in R1, ensuring that
2077 // we can get at R0 or its alias.
2078 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2079 VRM->getPhys(VirtReg), VirtReg);
2080 if (isTied)
2081 // Only mark it clobbered if this is a use&def operand.
2082 ReusedOperands.markClobbered(PhysReg);
2083 ++NumReused;
2085 if (MI.getOperand(i).isKill() &&
2086 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2088 // The store of this spilled value is potentially dead, but we
2089 // won't know for certain until we've confirmed that the re-use
2090 // above is valid, which means waiting until the other operands
2091 // are processed. For now we just track the spill slot, we'll
2092 // remove it after the other operands are processed if valid.
2094 PotentialDeadStoreSlots.push_back(ReuseSlot);
2097 // Mark is isKill if it's there no other uses of the same virtual
2098 // register and it's not a two-address operand. IsKill will be
2099 // unset if reg is reused.
2100 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2101 MI.getOperand(i).setIsKill();
2102 KilledMIRegs.insert(VirtReg);
2105 continue;
2106 } // CanReuse
2108 // Otherwise we have a situation where we have a two-address instruction
2109 // whose mod/ref operand needs to be reloaded. This reload is already
2110 // available in some register "PhysReg", but if we used PhysReg as the
2111 // operand to our 2-addr instruction, the instruction would modify
2112 // PhysReg. This isn't cool if something later uses PhysReg and expects
2113 // to get its initial value.
2115 // To avoid this problem, and to avoid doing a load right after a store,
2116 // we emit a copy from PhysReg into the designated register for this
2117 // operand.
2119 // This case also applies to an earlyclobber'd PhysReg.
2120 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2121 assert(DesignatedReg && "Must map virtreg to physreg!");
2123 // Note that, if we reused a register for a previous operand, the
2124 // register we want to reload into might not actually be
2125 // available. If this occurs, use the register indicated by the
2126 // reuser.
2127 if (ReusedOperands.hasReuses())
2128 DesignatedReg = ReusedOperands.
2129 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2130 MaybeDeadStores, RegKills, KillOps, *VRM);
2132 // If the mapped designated register is actually the physreg we have
2133 // incoming, we don't need to inserted a dead copy.
2134 if (DesignatedReg == PhysReg) {
2135 // If this stack slot value is already available, reuse it!
2136 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2137 DEBUG(dbgs() << "Reusing RM#"
2138 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2139 else
2140 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2141 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2142 << " for vreg" << VirtReg
2143 << " instead of reloading into same physreg.\n");
2144 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2145 MI.getOperand(i).setReg(RReg);
2146 MI.getOperand(i).setSubReg(0);
2147 ReusedOperands.markClobbered(RReg);
2148 ++NumReused;
2149 continue;
2152 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2153 MRI->setPhysRegUsed(DesignatedReg);
2154 ReusedOperands.markClobbered(DesignatedReg);
2156 // Back-schedule reloads and remats.
2157 MachineBasicBlock::iterator InsertLoc =
2158 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2159 SSorRMId, TII, MF);
2161 TII->copyRegToReg(*MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC,
2162 MI.getDebugLoc());
2164 MachineInstr *CopyMI = prior(InsertLoc);
2165 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2166 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2168 // This invalidates DesignatedReg.
2169 Spills.ClobberPhysReg(DesignatedReg);
2171 Spills.addAvailable(ReuseSlot, DesignatedReg);
2172 unsigned RReg =
2173 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2174 MI.getOperand(i).setReg(RReg);
2175 MI.getOperand(i).setSubReg(0);
2176 DEBUG(dbgs() << '\t' << *prior(MII));
2177 ++NumReused;
2178 continue;
2179 } // if (PhysReg)
2181 // Otherwise, reload it and remember that we have it.
2182 PhysReg = VRM->getPhys(VirtReg);
2183 assert(PhysReg && "Must map virtreg to physreg!");
2185 // Note that, if we reused a register for a previous operand, the
2186 // register we want to reload into might not actually be
2187 // available. If this occurs, use the register indicated by the
2188 // reuser.
2189 if (ReusedOperands.hasReuses())
2190 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2191 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2193 MRI->setPhysRegUsed(PhysReg);
2194 ReusedOperands.markClobbered(PhysReg);
2195 if (AvoidReload)
2196 ++NumAvoided;
2197 else {
2198 // Back-schedule reloads and remats.
2199 MachineBasicBlock::iterator InsertLoc =
2200 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2201 SSorRMId, TII, MF);
2203 if (DoReMat) {
2204 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2205 } else {
2206 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2207 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2208 MachineInstr *LoadMI = prior(InsertLoc);
2209 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2210 ++NumLoads;
2211 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2213 // This invalidates PhysReg.
2214 Spills.ClobberPhysReg(PhysReg);
2216 // Any stores to this stack slot are not dead anymore.
2217 if (!DoReMat)
2218 MaybeDeadStores[SSorRMId] = NULL;
2219 Spills.addAvailable(SSorRMId, PhysReg);
2220 // Assumes this is the last use. IsKill will be unset if reg is reused
2221 // unless it's a two-address operand.
2222 if (!MI.isRegTiedToDefOperand(i) &&
2223 KilledMIRegs.count(VirtReg) == 0) {
2224 MI.getOperand(i).setIsKill();
2225 KilledMIRegs.insert(VirtReg);
2228 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2229 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2231 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2232 MI.getOperand(i).setReg(RReg);
2233 MI.getOperand(i).setSubReg(0);
2236 // Ok - now we can remove stores that have been confirmed dead.
2237 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2238 // This was the last use and the spilled value is still available
2239 // for reuse. That means the spill was unnecessary!
2240 int PDSSlot = PotentialDeadStoreSlots[j];
2241 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2242 if (DeadStore) {
2243 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2244 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2245 VRM->RemoveMachineInstrFromMaps(DeadStore);
2246 MBB->erase(DeadStore);
2247 MaybeDeadStores[PDSSlot] = NULL;
2248 ++NumDSE;
2253 DEBUG(dbgs() << '\t' << MI);
2256 // If we have folded references to memory operands, make sure we clear all
2257 // physical registers that may contain the value of the spilled virtual
2258 // register
2259 SmallSet<int, 2> FoldedSS;
2260 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
2261 unsigned VirtReg = I->second.first;
2262 VirtRegMap::ModRef MR = I->second.second;
2263 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2265 // MI2VirtMap be can updated which invalidate the iterator.
2266 // Increment the iterator first.
2267 ++I;
2268 int SS = VRM->getStackSlot(VirtReg);
2269 if (SS == VirtRegMap::NO_STACK_SLOT)
2270 continue;
2271 FoldedSS.insert(SS);
2272 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2274 // If this folded instruction is just a use, check to see if it's a
2275 // straight load from the virt reg slot.
2276 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2277 int FrameIdx;
2278 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2279 if (DestReg && FrameIdx == SS) {
2280 // If this spill slot is available, turn it into a copy (or nothing)
2281 // instead of leaving it as a load!
2282 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2283 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2284 if (DestReg != InReg) {
2285 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2286 TII->copyRegToReg(*MBB, &MI, DestReg, InReg, RC, RC,
2287 MI.getDebugLoc());
2288 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2289 unsigned SubIdx = DefMO->getSubReg();
2290 // Revisit the copy so we make sure to notice the effects of the
2291 // operation on the destreg (either needing to RA it if it's
2292 // virtual or needing to clobber any values if it's physical).
2293 NextMII = &MI;
2294 --NextMII; // backtrack to the copy.
2295 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2296 // Propagate the sub-register index over.
2297 if (SubIdx) {
2298 DefMO = NextMII->findRegisterDefOperand(DestReg);
2299 DefMO->setSubReg(SubIdx);
2302 // Mark is killed.
2303 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2304 KillOpnd->setIsKill();
2306 BackTracked = true;
2307 } else {
2308 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2309 // Unset last kill since it's being reused.
2310 InvalidateKill(InReg, TRI, RegKills, KillOps);
2311 Spills.disallowClobberPhysReg(InReg);
2314 InvalidateKills(MI, TRI, RegKills, KillOps);
2315 VRM->RemoveMachineInstrFromMaps(&MI);
2316 MBB->erase(&MI);
2317 Erased = true;
2318 goto ProcessNextInst;
2320 } else {
2321 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2322 SmallVector<MachineInstr*, 4> NewMIs;
2323 if (PhysReg &&
2324 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2325 MBB->insert(MII, NewMIs[0]);
2326 InvalidateKills(MI, TRI, RegKills, KillOps);
2327 VRM->RemoveMachineInstrFromMaps(&MI);
2328 MBB->erase(&MI);
2329 Erased = true;
2330 --NextMII; // backtrack to the unfolded instruction.
2331 BackTracked = true;
2332 goto ProcessNextInst;
2337 // If this reference is not a use, any previous store is now dead.
2338 // Otherwise, the store to this stack slot is not dead anymore.
2339 MachineInstr* DeadStore = MaybeDeadStores[SS];
2340 if (DeadStore) {
2341 bool isDead = !(MR & VirtRegMap::isRef);
2342 MachineInstr *NewStore = NULL;
2343 if (MR & VirtRegMap::isModRef) {
2344 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2345 SmallVector<MachineInstr*, 4> NewMIs;
2346 // We can reuse this physreg as long as we are allowed to clobber
2347 // the value and there isn't an earlier def that has already clobbered
2348 // the physreg.
2349 if (PhysReg &&
2350 !ReusedOperands.isClobbered(PhysReg) &&
2351 Spills.canClobberPhysReg(PhysReg) &&
2352 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2353 MachineOperand *KillOpnd =
2354 DeadStore->findRegisterUseOperand(PhysReg, true);
2355 // Note, if the store is storing a sub-register, it's possible the
2356 // super-register is needed below.
2357 if (KillOpnd && !KillOpnd->getSubReg() &&
2358 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2359 MBB->insert(MII, NewMIs[0]);
2360 NewStore = NewMIs[1];
2361 MBB->insert(MII, NewStore);
2362 VRM->addSpillSlotUse(SS, NewStore);
2363 InvalidateKills(MI, TRI, RegKills, KillOps);
2364 VRM->RemoveMachineInstrFromMaps(&MI);
2365 MBB->erase(&MI);
2366 Erased = true;
2367 --NextMII;
2368 --NextMII; // backtrack to the unfolded instruction.
2369 BackTracked = true;
2370 isDead = true;
2371 ++NumSUnfold;
2376 if (isDead) { // Previous store is dead.
2377 // If we get here, the store is dead, nuke it now.
2378 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2379 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2380 VRM->RemoveMachineInstrFromMaps(DeadStore);
2381 MBB->erase(DeadStore);
2382 if (!NewStore)
2383 ++NumDSE;
2386 MaybeDeadStores[SS] = NULL;
2387 if (NewStore) {
2388 // Treat this store as a spill merged into a copy. That makes the
2389 // stack slot value available.
2390 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2391 goto ProcessNextInst;
2395 // If the spill slot value is available, and this is a new definition of
2396 // the value, the value is not available anymore.
2397 if (MR & VirtRegMap::isMod) {
2398 // Notice that the value in this stack slot has been modified.
2399 Spills.ModifyStackSlotOrReMat(SS);
2401 // If this is *just* a mod of the value, check to see if this is just a
2402 // store to the spill slot (i.e. the spill got merged into the copy). If
2403 // so, realize that the vreg is available now, and add the store to the
2404 // MaybeDeadStore info.
2405 int StackSlot;
2406 if (!(MR & VirtRegMap::isRef)) {
2407 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2408 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2409 "Src hasn't been allocated yet?");
2411 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2412 Spills, RegKills, KillOps, TRI)) {
2413 NextMII = llvm::next(MII);
2414 BackTracked = true;
2415 goto ProcessNextInst;
2418 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2419 // this as a potentially dead store in case there is a subsequent
2420 // store into the stack slot without a read from it.
2421 MaybeDeadStores[StackSlot] = &MI;
2423 // If the stack slot value was previously available in some other
2424 // register, change it now. Otherwise, make the register
2425 // available in PhysReg.
2426 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2432 // Process all of the spilled defs.
2433 SpilledMIRegs.clear();
2434 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2435 MachineOperand &MO = MI.getOperand(i);
2436 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2437 continue;
2439 unsigned VirtReg = MO.getReg();
2440 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2441 // Check to see if this is a noop copy. If so, eliminate the
2442 // instruction before considering the dest reg to be changed.
2443 // Also check if it's copying from an "undef", if so, we can't
2444 // eliminate this or else the undef marker is lost and it will
2445 // confuses the scavenger. This is extremely rare.
2446 unsigned Src, Dst, SrcSR, DstSR;
2447 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) &&
2448 Src == Dst && SrcSR == DstSR &&
2449 !MI.findRegisterUseOperand(Src)->isUndef()) {
2450 ++NumDCE;
2451 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2452 SmallVector<unsigned, 2> KillRegs;
2453 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2454 if (MO.isDead() && !KillRegs.empty()) {
2455 // Source register or an implicit super/sub-register use is killed.
2456 assert(KillRegs[0] == Dst ||
2457 TRI->isSubRegister(KillRegs[0], Dst) ||
2458 TRI->isSuperRegister(KillRegs[0], Dst));
2459 // Last def is now dead.
2460 TransferDeadness(Src, RegKills, KillOps);
2462 VRM->RemoveMachineInstrFromMaps(&MI);
2463 MBB->erase(&MI);
2464 Erased = true;
2465 Spills.disallowClobberPhysReg(VirtReg);
2466 goto ProcessNextInst;
2469 // If it's not a no-op copy, it clobbers the value in the destreg.
2470 Spills.ClobberPhysReg(VirtReg);
2471 ReusedOperands.markClobbered(VirtReg);
2473 // Check to see if this instruction is a load from a stack slot into
2474 // a register. If so, this provides the stack slot value in the reg.
2475 int FrameIdx;
2476 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2477 assert(DestReg == VirtReg && "Unknown load situation!");
2479 // If it is a folded reference, then it's not safe to clobber.
2480 bool Folded = FoldedSS.count(FrameIdx);
2481 // Otherwise, if it wasn't available, remember that it is now!
2482 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2483 goto ProcessNextInst;
2486 continue;
2489 unsigned SubIdx = MO.getSubReg();
2490 bool DoReMat = VRM->isReMaterialized(VirtReg);
2491 if (DoReMat)
2492 ReMatDefs.insert(&MI);
2494 // The only vregs left are stack slot definitions.
2495 int StackSlot = VRM->getStackSlot(VirtReg);
2496 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2498 // If this def is part of a two-address operand, make sure to execute
2499 // the store from the correct physical register.
2500 unsigned PhysReg;
2501 unsigned TiedOp;
2502 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2503 PhysReg = MI.getOperand(TiedOp).getReg();
2504 if (SubIdx) {
2505 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2506 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2507 "Can't find corresponding super-register!");
2508 PhysReg = SuperReg;
2510 } else {
2511 PhysReg = VRM->getPhys(VirtReg);
2512 if (ReusedOperands.isClobbered(PhysReg)) {
2513 // Another def has taken the assigned physreg. It must have been a
2514 // use&def which got it due to reuse. Undo the reuse!
2515 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2516 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2520 assert(PhysReg && "VR not assigned a physical register?");
2521 MRI->setPhysRegUsed(PhysReg);
2522 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2523 ReusedOperands.markClobbered(RReg);
2524 MI.getOperand(i).setReg(RReg);
2525 MI.getOperand(i).setSubReg(0);
2527 if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
2528 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2529 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2530 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2531 NextMII = llvm::next(MII);
2533 // Check to see if this is a noop copy. If so, eliminate the
2534 // instruction before considering the dest reg to be changed.
2536 unsigned Src, Dst, SrcSR, DstSR;
2537 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) &&
2538 Src == Dst && SrcSR == DstSR) {
2539 ++NumDCE;
2540 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2541 InvalidateKills(MI, TRI, RegKills, KillOps);
2542 VRM->RemoveMachineInstrFromMaps(&MI);
2543 MBB->erase(&MI);
2544 Erased = true;
2545 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2546 goto ProcessNextInst;
2551 ProcessNextInst:
2552 // Delete dead instructions without side effects.
2553 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2554 InvalidateKills(MI, TRI, RegKills, KillOps);
2555 VRM->RemoveMachineInstrFromMaps(&MI);
2556 MBB->erase(&MI);
2557 Erased = true;
2559 if (!Erased)
2560 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2561 if (!Erased && !BackTracked) {
2562 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2563 UpdateKills(*II, TRI, RegKills, KillOps);
2565 MII = NextMII;
2570 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2571 switch (RewriterOpt) {
2572 default: llvm_unreachable("Unreachable!");
2573 case local:
2574 return new LocalRewriter();
2575 case trivial:
2576 return new TrivialRewriter();