1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the VirtRegMap class.
12 // It also contains implementations of the the Spiller interface, which, given a
13 // virtual register map and a machine function, eliminates all virtual
14 // references by replacing them with physical register references - adding spill
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "spiller"
20 #include "VirtRegMap.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallSet.h"
37 STATISTIC(NumSpills, "Number of register spills");
38 STATISTIC(NumReMats, "Number of re-materialization");
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41 STATISTIC(NumReused, "Number of values reused");
42 STATISTIC(NumDSE , "Number of dead stores elided");
43 STATISTIC(NumDCE , "Number of copies elided");
46 enum SpillerName { simple, local };
48 static cl::opt<SpillerName>
50 cl::desc("Spiller to use: (default: local)"),
52 cl::values(clEnumVal(simple, " simple spiller"),
53 clEnumVal(local, " local spiller"),
58 //===----------------------------------------------------------------------===//
59 // VirtRegMap implementation
60 //===----------------------------------------------------------------------===//
62 VirtRegMap::VirtRegMap(MachineFunction &mf)
63 : TII(*mf.getTarget().getInstrInfo()), MF(mf),
64 Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
65 ReMatId(MAX_STACK_SLOT+1) {
69 void VirtRegMap::grow() {
70 Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
71 Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
74 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
75 assert(MRegisterInfo::isVirtualRegister(virtReg));
76 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
77 "attempt to assign stack slot to already spilled register");
78 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
79 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
81 Virt2StackSlotMap[virtReg] = frameIndex;
86 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
87 assert(MRegisterInfo::isVirtualRegister(virtReg));
88 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
89 "attempt to assign stack slot to already spilled register");
90 assert((frameIndex >= 0 ||
91 (frameIndex >= MF.getFrameInfo()->getObjectIndexBegin())) &&
92 "illegal fixed frame index");
93 Virt2StackSlotMap[virtReg] = frameIndex;
96 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
97 assert(MRegisterInfo::isVirtualRegister(virtReg));
98 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
99 "attempt to assign re-mat id to already spilled register");
100 const MachineInstr *DefMI = getReMaterializedMI(virtReg);
102 if (TII.isLoadFromStackSlot((MachineInstr*)DefMI, FrameIdx)) {
103 // Load from stack slot is re-materialize as reload from the stack slot!
104 Virt2StackSlotMap[virtReg] = FrameIdx;
107 Virt2StackSlotMap[virtReg] = ReMatId;
111 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
112 unsigned OpNo, MachineInstr *NewMI) {
113 // Move previous memory references folded to new instruction.
114 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
115 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
116 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
117 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
118 MI2VirtMap.erase(I++);
122 const TargetInstrDescriptor *TID = OldMI->getInstrDescriptor();
123 if (TID->getOperandConstraint(OpNo, TOI::TIED_TO) != -1 ||
124 TID->findTiedToSrcOperand(OpNo) != -1) {
125 // Folded a two-address operand.
127 } else if (OldMI->getOperand(OpNo).isDef()) {
133 // add new memory reference
134 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
137 void VirtRegMap::print(std::ostream &OS) const {
138 const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
140 OS << "********** REGISTER MAP **********\n";
141 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
142 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
143 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
144 OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
148 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
149 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
150 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
151 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
155 void VirtRegMap::dump() const {
160 //===----------------------------------------------------------------------===//
161 // Simple Spiller Implementation
162 //===----------------------------------------------------------------------===//
164 Spiller::~Spiller() {}
167 struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
168 bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
172 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
173 DOUT << "********** REWRITE MACHINE CODE **********\n";
174 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
175 const TargetMachine &TM = MF.getTarget();
176 const MRegisterInfo &MRI = *TM.getRegisterInfo();
177 bool *PhysRegsUsed = MF.getUsedPhysregs();
179 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
180 // each vreg once (in the case where a spilled vreg is used by multiple
181 // operands). This is always smaller than the number of operands to the
182 // current machine instr, so it should be small.
183 std::vector<unsigned> LoadedRegs;
185 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
187 DOUT << MBBI->getBasicBlock()->getName() << ":\n";
188 MachineBasicBlock &MBB = *MBBI;
189 for (MachineBasicBlock::iterator MII = MBB.begin(),
190 E = MBB.end(); MII != E; ++MII) {
191 MachineInstr &MI = *MII;
192 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
193 MachineOperand &MO = MI.getOperand(i);
194 if (MO.isRegister() && MO.getReg())
195 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
196 unsigned VirtReg = MO.getReg();
197 unsigned PhysReg = VRM.getPhys(VirtReg);
198 if (VRM.hasStackSlot(VirtReg)) {
199 int StackSlot = VRM.getStackSlot(VirtReg);
200 const TargetRegisterClass* RC =
201 MF.getSSARegMap()->getRegClass(VirtReg);
204 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
205 == LoadedRegs.end()) {
206 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
207 LoadedRegs.push_back(VirtReg);
209 DOUT << '\t' << *prior(MII);
213 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
217 PhysRegsUsed[PhysReg] = true;
218 MI.getOperand(i).setReg(PhysReg);
220 PhysRegsUsed[MO.getReg()] = true;
231 //===----------------------------------------------------------------------===//
232 // Local Spiller Implementation
233 //===----------------------------------------------------------------------===//
236 /// LocalSpiller - This spiller does a simple pass over the machine basic
237 /// block to attempt to keep spills in registers as much as possible for
238 /// blocks that have low register pressure (the vreg may be spilled due to
239 /// register pressure in other blocks).
240 class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
241 const MRegisterInfo *MRI;
242 const TargetInstrInfo *TII;
244 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
245 MRI = MF.getTarget().getRegisterInfo();
246 TII = MF.getTarget().getInstrInfo();
247 DOUT << "\n**** Local spiller rewriting function '"
248 << MF.getFunction()->getName() << "':\n";
250 std::vector<MachineInstr *> ReMatedMIs;
251 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
253 RewriteMBB(*MBB, VRM, ReMatedMIs);
254 for (unsigned i = 0, e = ReMatedMIs.size(); i != e; ++i)
255 delete ReMatedMIs[i];
259 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
260 std::vector<MachineInstr*> &ReMatedMIs);
264 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
265 /// top down, keep track of which spills slots are available in each register.
267 /// Note that not all physregs are created equal here. In particular, some
268 /// physregs are reloads that we are allowed to clobber or ignore at any time.
269 /// Other physregs are values that the register allocated program is using that
270 /// we cannot CHANGE, but we can read if we like. We keep track of this on a
271 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
272 /// entries. The predicate 'canClobberPhysReg()' checks this bit and
273 /// addAvailable sets it if.
275 class VISIBILITY_HIDDEN AvailableSpills {
276 const MRegisterInfo *MRI;
277 const TargetInstrInfo *TII;
279 // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
280 // register values that are still available, due to being loaded or stored to,
281 // but not invalidated yet. It also tracks the instructions that defined
282 // or used the register.
283 typedef std::pair<unsigned, std::vector<MachineInstr*> > SSInfo;
284 std::map<int, SSInfo> SpillSlotsAvailable;
286 // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
287 // which stack slot values are currently held by a physreg. This is used to
288 // invalidate entries in SpillSlotsAvailable when a physreg is modified.
289 std::multimap<unsigned, int> PhysRegsAvailable;
291 void disallowClobberPhysRegOnly(unsigned PhysReg);
293 void ClobberPhysRegOnly(unsigned PhysReg);
295 AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
296 : MRI(mri), TII(tii) {
299 const MRegisterInfo *getRegInfo() const { return MRI; }
301 /// getSpillSlotPhysReg - If the specified stack slot is available in a
302 /// physical register, return that PhysReg, otherwise return 0. It also
303 /// returns by reference the instruction that either defines or last uses
305 unsigned getSpillSlotPhysReg(int Slot, MachineInstr *&SSMI) const {
306 std::map<int, SSInfo>::const_iterator I = SpillSlotsAvailable.find(Slot);
307 if (I != SpillSlotsAvailable.end()) {
308 if (!I->second.second.empty())
309 SSMI = I->second.second.back();
310 return I->second.first >> 1; // Remove the CanClobber bit.
315 /// addLastUse - Add the last use information of all stack slots whose
316 /// values are available in the specific register.
317 void addLastUse(unsigned PhysReg, MachineInstr *Use) {
318 std::multimap<unsigned, int>::iterator I =
319 PhysRegsAvailable.lower_bound(PhysReg);
320 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
321 int Slot = I->second;
324 std::map<int, SSInfo>::iterator II = SpillSlotsAvailable.find(Slot);
325 assert(II != SpillSlotsAvailable.end() && "Slot not available!");
326 unsigned Val = II->second.first;
327 assert((Val >> 1) == PhysReg && "Bidirectional map mismatch!");
328 // This can be true if there are multiple uses of the same register.
329 if (II->second.second.back() != Use)
330 II->second.second.push_back(Use);
334 /// removeLastUse - Remove the last use information of all stack slots whose
335 /// values are available in the specific register.
336 void removeLastUse(unsigned PhysReg, MachineInstr *Use) {
337 std::multimap<unsigned, int>::iterator I =
338 PhysRegsAvailable.lower_bound(PhysReg);
339 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
340 int Slot = I->second;
343 std::map<int, SSInfo>::iterator II = SpillSlotsAvailable.find(Slot);
344 assert(II != SpillSlotsAvailable.end() && "Slot not available!");
345 unsigned Val = II->second.first;
346 assert((Val >> 1) == PhysReg && "Bidirectional map mismatch!");
347 if (II->second.second.back() == Use)
348 II->second.second.pop_back();
352 /// addAvailable - Mark that the specified stack slot is available in the
353 /// specified physreg. If CanClobber is true, the physreg can be modified at
354 /// any time without changing the semantics of the program.
355 void addAvailable(int Slot, MachineInstr *MI, unsigned Reg,
356 bool CanClobber = true) {
357 // If this stack slot is thought to be available in some other physreg,
358 // remove its record.
359 ModifyStackSlot(Slot);
361 PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
362 std::vector<MachineInstr*> DefUses;
363 DefUses.push_back(MI);
364 SpillSlotsAvailable[Slot] =
365 std::make_pair((Reg << 1) | (unsigned)CanClobber, DefUses);
367 if (Slot > VirtRegMap::MAX_STACK_SLOT)
368 DOUT << "Remembering RM#" << Slot-VirtRegMap::MAX_STACK_SLOT-1;
370 DOUT << "Remembering SS#" << Slot;
371 DOUT << " in physreg " << MRI->getName(Reg) << "\n";
374 /// canClobberPhysReg - Return true if the spiller is allowed to change the
375 /// value of the specified stackslot register if it desires. The specified
376 /// stack slot must be available in a physreg for this query to make sense.
377 bool canClobberPhysReg(int Slot) const {
378 assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
379 return SpillSlotsAvailable.find(Slot)->second.first & 1;
382 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
383 /// stackslot register. The register is still available but is no longer
384 /// allowed to be modifed.
385 void disallowClobberPhysReg(unsigned PhysReg);
387 /// ClobberPhysReg - This is called when the specified physreg changes
388 /// value. We use this to invalidate any info about stuff we thing lives in
389 /// it and any of its aliases.
390 void ClobberPhysReg(unsigned PhysReg);
392 /// ModifyStackSlot - This method is called when the value in a stack slot
393 /// changes. This removes information about which register the previous value
394 /// for this slot lives in (as the previous value is dead now).
395 void ModifyStackSlot(int Slot);
399 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
400 /// stackslot register. The register is still available but is no longer
401 /// allowed to be modifed.
402 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
403 std::multimap<unsigned, int>::iterator I =
404 PhysRegsAvailable.lower_bound(PhysReg);
405 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
406 int Slot = I->second;
408 assert((SpillSlotsAvailable[Slot].first >> 1) == PhysReg &&
409 "Bidirectional map mismatch!");
410 SpillSlotsAvailable[Slot].first &= ~1;
411 DOUT << "PhysReg " << MRI->getName(PhysReg)
412 << " copied, it is available for use but can no longer be modified\n";
416 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
417 /// stackslot register and its aliases. The register and its aliases may
418 /// still available but is no longer allowed to be modifed.
419 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
420 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
421 disallowClobberPhysRegOnly(*AS);
422 disallowClobberPhysRegOnly(PhysReg);
425 /// ClobberPhysRegOnly - This is called when the specified physreg changes
426 /// value. We use this to invalidate any info about stuff we thing lives in it.
427 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
428 std::multimap<unsigned, int>::iterator I =
429 PhysRegsAvailable.lower_bound(PhysReg);
430 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
431 int Slot = I->second;
432 PhysRegsAvailable.erase(I++);
433 assert((SpillSlotsAvailable[Slot].first >> 1) == PhysReg &&
434 "Bidirectional map mismatch!");
435 SpillSlotsAvailable.erase(Slot);
436 DOUT << "PhysReg " << MRI->getName(PhysReg)
437 << " clobbered, invalidating ";
438 if (Slot > VirtRegMap::MAX_STACK_SLOT)
439 DOUT << "RM#" << Slot-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
441 DOUT << "SS#" << Slot << "\n";
445 /// ClobberPhysReg - This is called when the specified physreg changes
446 /// value. We use this to invalidate any info about stuff we thing lives in
447 /// it and any of its aliases.
448 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
449 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
450 ClobberPhysRegOnly(*AS);
451 ClobberPhysRegOnly(PhysReg);
454 /// ModifyStackSlot - This method is called when the value in a stack slot
455 /// changes. This removes information about which register the previous value
456 /// for this slot lives in (as the previous value is dead now).
457 void AvailableSpills::ModifyStackSlot(int Slot) {
458 std::map<int, SSInfo>::iterator It = SpillSlotsAvailable.find(Slot);
459 if (It == SpillSlotsAvailable.end()) return;
460 unsigned Reg = It->second.first >> 1;
461 SpillSlotsAvailable.erase(It);
463 // This register may hold the value of multiple stack slots, only remove this
464 // stack slot from the set of values the register contains.
465 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
467 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
468 "Map inverse broken!");
469 if (I->second == Slot) break;
471 PhysRegsAvailable.erase(I);
476 // ReusedOp - For each reused operand, we keep track of a bit of information, in
477 // case we need to rollback upon processing a new operand. See comments below.
480 // The MachineInstr operand that reused an available value.
483 // StackSlot - The spill slot of the value being reused.
486 // PhysRegReused - The physical register the value was available in.
487 unsigned PhysRegReused;
489 // AssignedPhysReg - The physreg that was assigned for use by the reload.
490 unsigned AssignedPhysReg;
492 // VirtReg - The virtual register itself.
495 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
497 : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
501 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
502 /// is reused instead of reloaded.
503 class VISIBILITY_HIDDEN ReuseInfo {
505 std::vector<ReusedOp> Reuses;
506 BitVector PhysRegsClobbered;
508 ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
509 PhysRegsClobbered.resize(mri->getNumRegs());
512 bool hasReuses() const {
513 return !Reuses.empty();
516 /// addReuse - If we choose to reuse a virtual register that is already
517 /// available instead of reloading it, remember that we did so.
518 void addReuse(unsigned OpNo, unsigned StackSlot,
519 unsigned PhysRegReused, unsigned AssignedPhysReg,
521 // If the reload is to the assigned register anyway, no undo will be
523 if (PhysRegReused == AssignedPhysReg) return;
525 // Otherwise, remember this.
526 Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused,
527 AssignedPhysReg, VirtReg));
530 void markClobbered(unsigned PhysReg) {
531 PhysRegsClobbered.set(PhysReg);
534 bool isClobbered(unsigned PhysReg) const {
535 return PhysRegsClobbered.test(PhysReg);
538 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
539 /// is some other operand that is using the specified register, either pick
540 /// a new register to use, or evict the previous reload and use this reg.
541 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
542 AvailableSpills &Spills,
543 std::map<int, MachineInstr*> &MaybeDeadStores,
544 SmallSet<unsigned, 8> &Rejected) {
545 if (Reuses.empty()) return PhysReg; // This is most often empty.
547 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
548 ReusedOp &Op = Reuses[ro];
549 // If we find some other reuse that was supposed to use this register
550 // exactly for its reload, we can change this reload to use ITS reload
551 // register. That is, unless its reload register has already been
552 // considered and subsequently rejected because it has also been reused
553 // by another operand.
554 if (Op.PhysRegReused == PhysReg &&
555 Rejected.count(Op.AssignedPhysReg) == 0) {
556 // Yup, use the reload register that we didn't use before.
557 unsigned NewReg = Op.AssignedPhysReg;
558 Rejected.insert(PhysReg);
559 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected);
561 // Otherwise, we might also have a problem if a previously reused
562 // value aliases the new register. If so, codegen the previous reload
564 unsigned PRRU = Op.PhysRegReused;
565 const MRegisterInfo *MRI = Spills.getRegInfo();
566 if (MRI->areAliases(PRRU, PhysReg)) {
567 // Okay, we found out that an alias of a reused register
568 // was used. This isn't good because it means we have
569 // to undo a previous reuse.
570 MachineBasicBlock *MBB = MI->getParent();
571 const TargetRegisterClass *AliasRC =
572 MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
574 // Copy Op out of the vector and remove it, we're going to insert an
575 // explicit load for it.
577 Reuses.erase(Reuses.begin()+ro);
579 // Ok, we're going to try to reload the assigned physreg into the
580 // slot that we were supposed to in the first place. However, that
581 // register could hold a reuse. Check to see if it conflicts or
582 // would prefer us to use a different register.
583 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
584 MI, Spills, MaybeDeadStores, Rejected);
586 MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
587 NewOp.StackSlot, AliasRC);
588 Spills.ClobberPhysReg(NewPhysReg);
589 Spills.ClobberPhysReg(NewOp.PhysRegReused);
591 // Any stores to this stack slot are not dead anymore.
592 MaybeDeadStores.erase(NewOp.StackSlot);
594 MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
596 Spills.addAvailable(NewOp.StackSlot, MI, NewPhysReg);
598 DEBUG(MachineBasicBlock::iterator MII = MI;
599 DOUT << '\t' << *prior(MII));
601 DOUT << "Reuse undone!\n";
604 // Finally, PhysReg is now available, go ahead and use it.
612 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
613 /// 'Rejected' set to remember which registers have been considered and
614 /// rejected for the reload. This avoids infinite looping in case like
617 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
618 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
620 /// sees r1 is taken by t2, tries t2's reload register r0
621 /// sees r0 is taken by t3, tries t3's reload register r1
622 /// sees r1 is taken by t2, tries t2's reload register r0 ...
623 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
624 AvailableSpills &Spills,
625 std::map<int, MachineInstr*> &MaybeDeadStores) {
626 SmallSet<unsigned, 8> Rejected;
627 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected);
633 /// rewriteMBB - Keep track of which spills are available even after the
634 /// register allocator is done with them. If possible, avoid reloading vregs.
635 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
636 std::vector<MachineInstr*> &ReMatedMIs) {
637 DOUT << MBB.getBasicBlock()->getName() << ":\n";
639 // Spills - Keep track of which spilled values are available in physregs so
640 // that we can choose to reuse the physregs instead of emitting reloads.
641 AvailableSpills Spills(MRI, TII);
643 // MaybeDeadStores - When we need to write a value back into a stack slot,
644 // keep track of the inserted store. If the stack slot value is never read
645 // (because the value was used from some available register, for example), and
646 // subsequently stored to, the original store is dead. This map keeps track
647 // of inserted stores that are not used. If we see a subsequent store to the
648 // same stack slot, the original store is deleted.
649 std::map<int, MachineInstr*> MaybeDeadStores;
651 bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
653 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
655 MachineInstr &MI = *MII;
656 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
658 /// ReusedOperands - Keep track of operand reuse in case we need to undo
660 ReuseInfo ReusedOperands(MI, MRI);
662 // Loop over all of the implicit defs, clearing them from our available
664 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
666 // If this instruction is being rematerialized, just remove it!
668 if ((TID->Flags & M_REMATERIALIZIBLE) ||
669 TII->isLoadFromStackSlot(&MI, FrameIdx)) {
671 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
672 MachineOperand &MO = MI.getOperand(i);
673 if (!MO.isRegister() || MO.getReg() == 0)
674 continue; // Ignore non-register operands.
675 if (MO.isDef() && !VRM.isReMaterialized(MO.getReg())) {
681 VRM.RemoveFromFoldedVirtMap(&MI);
682 ReMatedMIs.push_back(MI.removeFromParent());
688 const unsigned *ImpDef = TID->ImplicitDefs;
690 for ( ; *ImpDef; ++ImpDef) {
691 PhysRegsUsed[*ImpDef] = true;
692 ReusedOperands.markClobbered(*ImpDef);
693 Spills.ClobberPhysReg(*ImpDef);
697 // Process all of the spilled uses and all non spilled reg references.
698 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
699 MachineOperand &MO = MI.getOperand(i);
700 if (!MO.isRegister() || MO.getReg() == 0)
701 continue; // Ignore non-register operands.
703 if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
704 // Ignore physregs for spilling, but remember that it is used by this
706 PhysRegsUsed[MO.getReg()] = true;
707 ReusedOperands.markClobbered(MO.getReg());
711 assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
712 "Not a virtual or a physical register?");
714 unsigned VirtReg = MO.getReg();
715 if (!VRM.hasStackSlot(VirtReg)) {
716 // This virtual register was assigned a physreg!
717 unsigned Phys = VRM.getPhys(VirtReg);
718 PhysRegsUsed[Phys] = true;
720 ReusedOperands.markClobbered(Phys);
721 MI.getOperand(i).setReg(Phys);
725 // This virtual register is now known to be a spilled value.
727 continue; // Handle defs in the loop below (handle use&def here though)
729 bool doReMat = VRM.isReMaterialized(VirtReg);
730 int StackSlot = VRM.getStackSlot(VirtReg);
733 // Check to see if this stack slot is available.
734 MachineInstr *SSMI = NULL;
735 if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot, SSMI))) {
736 // This spilled operand might be part of a two-address operand. If this
737 // is the case, then changing it will necessarily require changing the
738 // def part of the instruction as well. However, in some cases, we
739 // aren't allowed to modify the reused register. If none of these cases
741 bool CanReuse = true;
742 int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
744 MI.getOperand(ti).isReg() &&
745 MI.getOperand(ti).getReg() == VirtReg) {
746 // Okay, we have a two address operand. We can reuse this physreg as
747 // long as we are allowed to clobber the value and there isn't an
748 // earlier def that has already clobbered the physreg.
749 CanReuse = Spills.canClobberPhysReg(StackSlot) &&
750 !ReusedOperands.isClobbered(PhysReg);
754 // If this stack slot value is already available, reuse it!
755 if (StackSlot > VirtRegMap::MAX_STACK_SLOT)
756 DOUT << "Reusing RM#" << StackSlot-VirtRegMap::MAX_STACK_SLOT-1;
758 DOUT << "Reusing SS#" << StackSlot;
759 DOUT << " from physreg "
760 << MRI->getName(PhysReg) << " for vreg"
761 << VirtReg <<" instead of reloading into physreg "
762 << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
763 MI.getOperand(i).setReg(PhysReg);
765 // Extend the live range of the MI that last kill the register if
767 bool WasKill = false;
769 int UIdx = SSMI->findRegisterUseOperand(PhysReg, true);
771 MachineOperand &MOK = SSMI->getOperand(UIdx);
772 WasKill = MOK.isKill();
777 // Unless it's the use of a two-address code, transfer the kill
778 // of the reused register to this use.
780 MI.getOperand(i).setIsKill();
781 Spills.addLastUse(PhysReg, &MI);
784 // The only technical detail we have is that we don't know that
785 // PhysReg won't be clobbered by a reloaded stack slot that occurs
786 // later in the instruction. In particular, consider 'op V1, V2'.
787 // If V1 is available in physreg R0, we would choose to reuse it
788 // here, instead of reloading it into the register the allocator
789 // indicated (say R1). However, V2 might have to be reloaded
790 // later, and it might indicate that it needs to live in R0. When
791 // this occurs, we need to have information available that
792 // indicates it is safe to use R1 for the reload instead of R0.
794 // To further complicate matters, we might conflict with an alias,
795 // or R0 and R1 might not be compatible with each other. In this
796 // case, we actually insert a reload for V1 in R1, ensuring that
797 // we can get at R0 or its alias.
798 ReusedOperands.addReuse(i, StackSlot, PhysReg,
799 VRM.getPhys(VirtReg), VirtReg);
801 // Only mark it clobbered if this is a use&def operand.
802 ReusedOperands.markClobbered(PhysReg);
807 // Otherwise we have a situation where we have a two-address instruction
808 // whose mod/ref operand needs to be reloaded. This reload is already
809 // available in some register "PhysReg", but if we used PhysReg as the
810 // operand to our 2-addr instruction, the instruction would modify
811 // PhysReg. This isn't cool if something later uses PhysReg and expects
812 // to get its initial value.
814 // To avoid this problem, and to avoid doing a load right after a store,
815 // we emit a copy from PhysReg into the designated register for this
817 unsigned DesignatedReg = VRM.getPhys(VirtReg);
818 assert(DesignatedReg && "Must map virtreg to physreg!");
820 // Note that, if we reused a register for a previous operand, the
821 // register we want to reload into might not actually be
822 // available. If this occurs, use the register indicated by the
824 if (ReusedOperands.hasReuses())
825 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
826 Spills, MaybeDeadStores);
828 // If the mapped designated register is actually the physreg we have
829 // incoming, we don't need to inserted a dead copy.
830 if (DesignatedReg == PhysReg) {
831 // If this stack slot value is already available, reuse it!
832 if (StackSlot > VirtRegMap::MAX_STACK_SLOT)
833 DOUT << "Reusing RM#" << StackSlot-VirtRegMap::MAX_STACK_SLOT-1;
835 DOUT << "Reusing SS#" << StackSlot;
836 DOUT << " from physreg " << MRI->getName(PhysReg) << " for vreg"
838 << " instead of reloading into same physreg.\n";
839 MI.getOperand(i).setReg(PhysReg);
840 ReusedOperands.markClobbered(PhysReg);
845 const TargetRegisterClass* RC =
846 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
848 PhysRegsUsed[DesignatedReg] = true;
849 ReusedOperands.markClobbered(DesignatedReg);
850 MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
852 // Extend the live range of the MI that last kill the register if
854 bool WasKill = false;
856 int UIdx = SSMI->findRegisterUseOperand(PhysReg, true);
858 MachineOperand &MOK = SSMI->getOperand(UIdx);
859 WasKill = MOK.isKill();
863 MachineInstr *CopyMI = prior(MII);
865 // Transfer kill to the next use.
866 int UIdx = CopyMI->findRegisterUseOperand(PhysReg);
868 MachineOperand &MOU = CopyMI->getOperand(UIdx);
871 Spills.addLastUse(PhysReg, CopyMI);
873 // This invalidates DesignatedReg.
874 Spills.ClobberPhysReg(DesignatedReg);
876 Spills.addAvailable(StackSlot, &MI, DesignatedReg);
877 MI.getOperand(i).setReg(DesignatedReg);
878 DOUT << '\t' << *prior(MII);
883 // Otherwise, reload it and remember that we have it.
884 PhysReg = VRM.getPhys(VirtReg);
885 assert(PhysReg && "Must map virtreg to physreg!");
886 const TargetRegisterClass* RC =
887 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
889 // Note that, if we reused a register for a previous operand, the
890 // register we want to reload into might not actually be
891 // available. If this occurs, use the register indicated by the
893 if (ReusedOperands.hasReuses())
894 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
895 Spills, MaybeDeadStores);
897 PhysRegsUsed[PhysReg] = true;
898 ReusedOperands.markClobbered(PhysReg);
900 MRI->reMaterialize(MBB, &MI, PhysReg, VRM.getReMaterializedMI(VirtReg));
903 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
906 // This invalidates PhysReg.
907 Spills.ClobberPhysReg(PhysReg);
909 // Any stores to this stack slot are not dead anymore.
911 MaybeDeadStores.erase(StackSlot);
912 Spills.addAvailable(StackSlot, &MI, PhysReg);
913 // Assumes this is the last use. IsKill will be unset if reg is reused
914 // unless it's a two-address operand.
915 if (TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
916 MI.getOperand(i).setIsKill();
917 MI.getOperand(i).setReg(PhysReg);
918 DOUT << '\t' << *prior(MII);
923 // If we have folded references to memory operands, make sure we clear all
924 // physical registers that may contain the value of the spilled virtual
926 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
927 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
928 DOUT << "Folded vreg: " << I->second.first << " MR: "
930 unsigned VirtReg = I->second.first;
931 VirtRegMap::ModRef MR = I->second.second;
932 if (!VRM.hasStackSlot(VirtReg)) {
933 DOUT << ": No stack slot!\n";
936 int SS = VRM.getStackSlot(VirtReg);
937 DOUT << " - StackSlot: " << SS << "\n";
939 // If this folded instruction is just a use, check to see if it's a
940 // straight load from the virt reg slot.
941 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
943 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
944 if (FrameIdx == SS) {
945 // If this spill slot is available, turn it into a copy (or nothing)
946 // instead of leaving it as a load!
947 MachineInstr *SSMI = NULL;
948 if (unsigned InReg = Spills.getSpillSlotPhysReg(SS, SSMI)) {
949 DOUT << "Promoted Load To Copy: " << MI;
950 MachineFunction &MF = *MBB.getParent();
951 if (DestReg != InReg) {
952 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
953 MF.getSSARegMap()->getRegClass(VirtReg));
954 // Revisit the copy so we make sure to notice the effects of the
955 // operation on the destreg (either needing to RA it if it's
956 // virtual or needing to clobber any values if it's physical).
958 --NextMII; // backtrack to the copy.
960 DOUT << "Removing now-noop copy: " << MI;
962 // Either way, the live range of the last kill of InReg has been
963 // extended. Remove its kill.
964 bool WasKill = false;
966 int UIdx = SSMI->findRegisterUseOperand(InReg, true);
968 MachineOperand &MOK = SSMI->getOperand(UIdx);
969 WasKill = MOK.isKill();
973 if (NextMII != MBB.end()) {
974 // If NextMII uses InReg and the use is not a two address
975 // operand, mark it killed.
976 int UIdx = NextMII->findRegisterUseOperand(InReg);
978 MachineOperand &MOU = NextMII->getOperand(UIdx);
980 const TargetInstrDescriptor *NTID =
981 NextMII->getInstrDescriptor();
982 if (UIdx >= NTID->numOperands ||
983 NTID->getOperandConstraint(UIdx, TOI::TIED_TO) == -1)
986 Spills.addLastUse(InReg, &(*NextMII));
990 VRM.RemoveFromFoldedVirtMap(&MI);
992 goto ProcessNextInst;
998 // If this reference is not a use, any previous store is now dead.
999 // Otherwise, the store to this stack slot is not dead anymore.
1000 std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
1001 if (MDSI != MaybeDeadStores.end()) {
1002 if (MR & VirtRegMap::isRef) // Previous store is not dead.
1003 MaybeDeadStores.erase(MDSI);
1005 // If we get here, the store is dead, nuke it now.
1006 assert(VirtRegMap::isMod && "Can't be modref!");
1007 DOUT << "Removed dead store:\t" << *MDSI->second;
1008 MBB.erase(MDSI->second);
1009 VRM.RemoveFromFoldedVirtMap(MDSI->second);
1010 MaybeDeadStores.erase(MDSI);
1015 // If the spill slot value is available, and this is a new definition of
1016 // the value, the value is not available anymore.
1017 if (MR & VirtRegMap::isMod) {
1018 // Notice that the value in this stack slot has been modified.
1019 Spills.ModifyStackSlot(SS);
1021 // If this is *just* a mod of the value, check to see if this is just a
1022 // store to the spill slot (i.e. the spill got merged into the copy). If
1023 // so, realize that the vreg is available now, and add the store to the
1024 // MaybeDeadStore info.
1026 if (!(MR & VirtRegMap::isRef)) {
1027 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1028 assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
1029 "Src hasn't been allocated yet?");
1030 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
1031 // this as a potentially dead store in case there is a subsequent
1032 // store into the stack slot without a read from it.
1033 MaybeDeadStores[StackSlot] = &MI;
1035 // If the stack slot value was previously available in some other
1036 // register, change it now. Otherwise, make the register available,
1038 Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
1044 // Process all of the spilled defs.
1045 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1046 MachineOperand &MO = MI.getOperand(i);
1047 if (MO.isRegister() && MO.getReg() && MO.isDef()) {
1048 unsigned VirtReg = MO.getReg();
1050 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
1051 // Check to see if this is a noop copy. If so, eliminate the
1052 // instruction before considering the dest reg to be changed.
1054 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1056 DOUT << "Removing now-noop copy: " << MI;
1057 Spills.removeLastUse(Src, &MI);
1059 VRM.RemoveFromFoldedVirtMap(&MI);
1060 Spills.disallowClobberPhysReg(VirtReg);
1061 goto ProcessNextInst;
1064 // If it's not a no-op copy, it clobbers the value in the destreg.
1065 Spills.ClobberPhysReg(VirtReg);
1066 ReusedOperands.markClobbered(VirtReg);
1068 // Check to see if this instruction is a load from a stack slot into
1069 // a register. If so, this provides the stack slot value in the reg.
1071 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1072 assert(DestReg == VirtReg && "Unknown load situation!");
1074 // Otherwise, if it wasn't available, remember that it is now!
1075 Spills.addAvailable(FrameIdx, &MI, DestReg);
1076 goto ProcessNextInst;
1082 // The only vregs left are stack slot definitions.
1083 int StackSlot = VRM.getStackSlot(VirtReg);
1084 const TargetRegisterClass *RC =
1085 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
1087 // If this def is part of a two-address operand, make sure to execute
1088 // the store from the correct physical register.
1090 int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
1092 PhysReg = MI.getOperand(TiedOp).getReg();
1094 PhysReg = VRM.getPhys(VirtReg);
1095 if (ReusedOperands.isClobbered(PhysReg)) {
1096 // Another def has taken the assigned physreg. It must have been a
1097 // use&def which got it due to reuse. Undo the reuse!
1098 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1099 Spills, MaybeDeadStores);
1103 PhysRegsUsed[PhysReg] = true;
1104 ReusedOperands.markClobbered(PhysReg);
1105 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
1106 DOUT << "Store:\t" << *next(MII);
1107 MI.getOperand(i).setReg(PhysReg);
1109 // If there is a dead store to this stack slot, nuke it now.
1110 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1112 DOUT << "Removed dead store:\t" << *LastStore;
1114 MBB.erase(LastStore);
1115 VRM.RemoveFromFoldedVirtMap(LastStore);
1117 LastStore = next(MII);
1119 // If the stack slot value was previously available in some other
1120 // register, change it now. Otherwise, make the register available,
1122 Spills.ModifyStackSlot(StackSlot);
1123 Spills.ClobberPhysReg(PhysReg);
1124 Spills.addAvailable(StackSlot, LastStore, PhysReg);
1127 // Check to see if this is a noop copy. If so, eliminate the
1128 // instruction before considering the dest reg to be changed.
1131 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1133 DOUT << "Removing now-noop copy: " << MI;
1134 Spills.removeLastUse(Src, &MI);
1136 VRM.RemoveFromFoldedVirtMap(&MI);
1137 goto ProcessNextInst;
1149 llvm::Spiller* llvm::createSpiller() {
1150 switch (SpillerOpt) {
1151 default: assert(0 && "Unreachable!");
1153 return new LocalSpiller();
1155 return new SimpleSpiller();