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(NumStores, "Number of stores added");
39 STATISTIC(NumLoads , "Number of loads added");
40 STATISTIC(NumReused, "Number of values reused");
41 STATISTIC(NumDSE , "Number of dead stores elided");
42 STATISTIC(NumDCE , "Number of copies elided");
45 enum SpillerName { simple, local };
47 static cl::opt<SpillerName>
49 cl::desc("Spiller to use: (default: local)"),
51 cl::values(clEnumVal(simple, " simple spiller"),
52 clEnumVal(local, " local spiller"),
57 //===----------------------------------------------------------------------===//
58 // VirtRegMap implementation
59 //===----------------------------------------------------------------------===//
61 VirtRegMap::VirtRegMap(MachineFunction &mf)
62 : TII(*mf.getTarget().getInstrInfo()), MF(mf),
63 Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT) {
67 void VirtRegMap::grow() {
68 Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
69 Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
72 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
73 assert(MRegisterInfo::isVirtualRegister(virtReg));
74 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
75 "attempt to assign stack slot to already spilled register");
76 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
77 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
79 Virt2StackSlotMap[virtReg] = frameIndex;
84 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
85 assert(MRegisterInfo::isVirtualRegister(virtReg));
86 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
87 "attempt to assign stack slot to already spilled register");
88 Virt2StackSlotMap[virtReg] = frameIndex;
91 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
92 unsigned OpNo, MachineInstr *NewMI) {
93 // Move previous memory references folded to new instruction.
94 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
95 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
96 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
97 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
98 MI2VirtMap.erase(I++);
102 const TargetInstrDescriptor *TID = OldMI->getInstrDescriptor();
103 if (TID->getOperandConstraint(OpNo, TOI::TIED_TO) != -1 ||
104 TID->findTiedToSrcOperand(OpNo) != -1) {
105 // Folded a two-address operand.
107 } else if (OldMI->getOperand(OpNo).isDef()) {
113 // add new memory reference
114 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
117 void VirtRegMap::print(std::ostream &OS) const {
118 const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
120 OS << "********** REGISTER MAP **********\n";
121 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
122 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
123 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
124 OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
128 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
129 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
130 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
131 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
135 void VirtRegMap::dump() const {
140 //===----------------------------------------------------------------------===//
141 // Simple Spiller Implementation
142 //===----------------------------------------------------------------------===//
144 Spiller::~Spiller() {}
147 struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
148 bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
152 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
153 DOUT << "********** REWRITE MACHINE CODE **********\n";
154 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
155 const TargetMachine &TM = MF.getTarget();
156 const MRegisterInfo &MRI = *TM.getRegisterInfo();
157 bool *PhysRegsUsed = MF.getUsedPhysregs();
159 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
160 // each vreg once (in the case where a spilled vreg is used by multiple
161 // operands). This is always smaller than the number of operands to the
162 // current machine instr, so it should be small.
163 std::vector<unsigned> LoadedRegs;
165 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
167 DOUT << MBBI->getBasicBlock()->getName() << ":\n";
168 MachineBasicBlock &MBB = *MBBI;
169 for (MachineBasicBlock::iterator MII = MBB.begin(),
170 E = MBB.end(); MII != E; ++MII) {
171 MachineInstr &MI = *MII;
172 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
173 MachineOperand &MO = MI.getOperand(i);
174 if (MO.isRegister() && MO.getReg())
175 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
176 unsigned VirtReg = MO.getReg();
177 unsigned PhysReg = VRM.getPhys(VirtReg);
178 if (VRM.hasStackSlot(VirtReg)) {
179 int StackSlot = VRM.getStackSlot(VirtReg);
180 const TargetRegisterClass* RC =
181 MF.getSSARegMap()->getRegClass(VirtReg);
184 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
185 == LoadedRegs.end()) {
186 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
187 LoadedRegs.push_back(VirtReg);
189 DOUT << '\t' << *prior(MII);
193 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
197 PhysRegsUsed[PhysReg] = true;
198 MI.getOperand(i).setReg(PhysReg);
200 PhysRegsUsed[MO.getReg()] = true;
211 //===----------------------------------------------------------------------===//
212 // Local Spiller Implementation
213 //===----------------------------------------------------------------------===//
216 /// LocalSpiller - This spiller does a simple pass over the machine basic
217 /// block to attempt to keep spills in registers as much as possible for
218 /// blocks that have low register pressure (the vreg may be spilled due to
219 /// register pressure in other blocks).
220 class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
221 const MRegisterInfo *MRI;
222 const TargetInstrInfo *TII;
224 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
225 MRI = MF.getTarget().getRegisterInfo();
226 TII = MF.getTarget().getInstrInfo();
227 DOUT << "\n**** Local spiller rewriting function '"
228 << MF.getFunction()->getName() << "':\n";
230 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
232 RewriteMBB(*MBB, VRM);
236 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
240 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
241 /// top down, keep track of which spills slots are available in each register.
243 /// Note that not all physregs are created equal here. In particular, some
244 /// physregs are reloads that we are allowed to clobber or ignore at any time.
245 /// Other physregs are values that the register allocated program is using that
246 /// we cannot CHANGE, but we can read if we like. We keep track of this on a
247 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
248 /// entries. The predicate 'canClobberPhysReg()' checks this bit and
249 /// addAvailable sets it if.
251 class VISIBILITY_HIDDEN AvailableSpills {
252 const MRegisterInfo *MRI;
253 const TargetInstrInfo *TII;
255 // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
256 // register values that are still available, due to being loaded or stored to,
257 // but not invalidated yet.
258 std::map<int, unsigned> SpillSlotsAvailable;
260 // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
261 // which stack slot values are currently held by a physreg. This is used to
262 // invalidate entries in SpillSlotsAvailable when a physreg is modified.
263 std::multimap<unsigned, int> PhysRegsAvailable;
265 void disallowClobberPhysRegOnly(unsigned PhysReg);
267 void ClobberPhysRegOnly(unsigned PhysReg);
269 AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
270 : MRI(mri), TII(tii) {
273 /// getSpillSlotPhysReg - If the specified stack slot is available in a
274 /// physical register, return that PhysReg, otherwise return 0.
275 unsigned getSpillSlotPhysReg(int Slot) const {
276 std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
277 if (I != SpillSlotsAvailable.end())
278 return I->second >> 1; // Remove the CanClobber bit.
282 const MRegisterInfo *getRegInfo() const { return MRI; }
284 /// addAvailable - Mark that the specified stack slot is available in the
285 /// specified physreg. If CanClobber is true, the physreg can be modified at
286 /// any time without changing the semantics of the program.
287 void addAvailable(int Slot, unsigned Reg, bool CanClobber = true) {
288 // If this stack slot is thought to be available in some other physreg,
289 // remove its record.
290 ModifyStackSlot(Slot);
292 PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
293 SpillSlotsAvailable[Slot] = (Reg << 1) | (unsigned)CanClobber;
295 DOUT << "Remembering SS#" << Slot << " in physreg "
296 << MRI->getName(Reg) << "\n";
299 /// canClobberPhysReg - Return true if the spiller is allowed to change the
300 /// value of the specified stackslot register if it desires. The specified
301 /// stack slot must be available in a physreg for this query to make sense.
302 bool canClobberPhysReg(int Slot) const {
303 assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
304 return SpillSlotsAvailable.find(Slot)->second & 1;
307 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
308 /// stackslot register. The register is still available but is no longer
309 /// allowed to be modifed.
310 void disallowClobberPhysReg(unsigned PhysReg);
312 /// ClobberPhysReg - This is called when the specified physreg changes
313 /// value. We use this to invalidate any info about stuff we thing lives in
314 /// it and any of its aliases.
315 void ClobberPhysReg(unsigned PhysReg);
317 /// ModifyStackSlot - This method is called when the value in a stack slot
318 /// changes. This removes information about which register the previous value
319 /// for this slot lives in (as the previous value is dead now).
320 void ModifyStackSlot(int Slot);
324 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
325 /// stackslot register. The register is still available but is no longer
326 /// allowed to be modifed.
327 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
328 std::multimap<unsigned, int>::iterator I =
329 PhysRegsAvailable.lower_bound(PhysReg);
330 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
331 int Slot = I->second;
333 assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
334 "Bidirectional map mismatch!");
335 SpillSlotsAvailable[Slot] &= ~1;
336 DOUT << "PhysReg " << MRI->getName(PhysReg)
337 << " copied, it is available for use but can no longer be modified\n";
341 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
342 /// stackslot register and its aliases. The register and its aliases may
343 /// still available but is no longer allowed to be modifed.
344 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
345 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
346 disallowClobberPhysRegOnly(*AS);
347 disallowClobberPhysRegOnly(PhysReg);
350 /// ClobberPhysRegOnly - This is called when the specified physreg changes
351 /// value. We use this to invalidate any info about stuff we thing lives in it.
352 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
353 std::multimap<unsigned, int>::iterator I =
354 PhysRegsAvailable.lower_bound(PhysReg);
355 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
356 int Slot = I->second;
357 PhysRegsAvailable.erase(I++);
358 assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
359 "Bidirectional map mismatch!");
360 SpillSlotsAvailable.erase(Slot);
361 DOUT << "PhysReg " << MRI->getName(PhysReg)
362 << " clobbered, invalidating SS#" << Slot << "\n";
366 /// ClobberPhysReg - This is called when the specified physreg changes
367 /// value. We use this to invalidate any info about stuff we thing lives in
368 /// it and any of its aliases.
369 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
370 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
371 ClobberPhysRegOnly(*AS);
372 ClobberPhysRegOnly(PhysReg);
375 /// ModifyStackSlot - This method is called when the value in a stack slot
376 /// changes. This removes information about which register the previous value
377 /// for this slot lives in (as the previous value is dead now).
378 void AvailableSpills::ModifyStackSlot(int Slot) {
379 std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
380 if (It == SpillSlotsAvailable.end()) return;
381 unsigned Reg = It->second >> 1;
382 SpillSlotsAvailable.erase(It);
384 // This register may hold the value of multiple stack slots, only remove this
385 // stack slot from the set of values the register contains.
386 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
388 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
389 "Map inverse broken!");
390 if (I->second == Slot) break;
392 PhysRegsAvailable.erase(I);
397 // ReusedOp - For each reused operand, we keep track of a bit of information, in
398 // case we need to rollback upon processing a new operand. See comments below.
401 // The MachineInstr operand that reused an available value.
404 // StackSlot - The spill slot of the value being reused.
407 // PhysRegReused - The physical register the value was available in.
408 unsigned PhysRegReused;
410 // AssignedPhysReg - The physreg that was assigned for use by the reload.
411 unsigned AssignedPhysReg;
413 // VirtReg - The virtual register itself.
416 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
418 : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
422 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
423 /// is reused instead of reloaded.
424 class VISIBILITY_HIDDEN ReuseInfo {
426 std::vector<ReusedOp> Reuses;
427 BitVector PhysRegsClobbered;
429 ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
430 PhysRegsClobbered.resize(mri->getNumRegs());
433 bool hasReuses() const {
434 return !Reuses.empty();
437 /// addReuse - If we choose to reuse a virtual register that is already
438 /// available instead of reloading it, remember that we did so.
439 void addReuse(unsigned OpNo, unsigned StackSlot,
440 unsigned PhysRegReused, unsigned AssignedPhysReg,
442 // If the reload is to the assigned register anyway, no undo will be
444 if (PhysRegReused == AssignedPhysReg) return;
446 // Otherwise, remember this.
447 Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused,
448 AssignedPhysReg, VirtReg));
451 void markClobbered(unsigned PhysReg) {
452 PhysRegsClobbered.set(PhysReg);
455 bool isClobbered(unsigned PhysReg) const {
456 return PhysRegsClobbered.test(PhysReg);
459 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
460 /// is some other operand that is using the specified register, either pick
461 /// a new register to use, or evict the previous reload and use this reg.
462 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
463 AvailableSpills &Spills,
464 std::map<int, MachineInstr*> &MaybeDeadStores,
465 SmallSet<unsigned, 8> &Rejected) {
466 if (Reuses.empty()) return PhysReg; // This is most often empty.
468 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
469 ReusedOp &Op = Reuses[ro];
470 // If we find some other reuse that was supposed to use this register
471 // exactly for its reload, we can change this reload to use ITS reload
472 // register. That is, unless its reload register has already been
473 // considered and subsequently rejected because it has also been reused
474 // by another operand.
475 if (Op.PhysRegReused == PhysReg &&
476 Rejected.count(Op.AssignedPhysReg) == 0) {
477 // Yup, use the reload register that we didn't use before.
478 unsigned NewReg = Op.AssignedPhysReg;
479 Rejected.insert(PhysReg);
480 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected);
482 // Otherwise, we might also have a problem if a previously reused
483 // value aliases the new register. If so, codegen the previous reload
485 unsigned PRRU = Op.PhysRegReused;
486 const MRegisterInfo *MRI = Spills.getRegInfo();
487 if (MRI->areAliases(PRRU, PhysReg)) {
488 // Okay, we found out that an alias of a reused register
489 // was used. This isn't good because it means we have
490 // to undo a previous reuse.
491 MachineBasicBlock *MBB = MI->getParent();
492 const TargetRegisterClass *AliasRC =
493 MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
495 // Copy Op out of the vector and remove it, we're going to insert an
496 // explicit load for it.
498 Reuses.erase(Reuses.begin()+ro);
500 // Ok, we're going to try to reload the assigned physreg into the
501 // slot that we were supposed to in the first place. However, that
502 // register could hold a reuse. Check to see if it conflicts or
503 // would prefer us to use a different register.
504 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
505 MI, Spills, MaybeDeadStores, Rejected);
507 MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
508 NewOp.StackSlot, AliasRC);
509 Spills.ClobberPhysReg(NewPhysReg);
510 Spills.ClobberPhysReg(NewOp.PhysRegReused);
512 // Any stores to this stack slot are not dead anymore.
513 MaybeDeadStores.erase(NewOp.StackSlot);
515 MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
517 Spills.addAvailable(NewOp.StackSlot, NewPhysReg);
519 DEBUG(MachineBasicBlock::iterator MII = MI;
520 DOUT << '\t' << *prior(MII));
522 DOUT << "Reuse undone!\n";
525 // Finally, PhysReg is now available, go ahead and use it.
533 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
534 /// 'Rejected' set to remember which registers have been considered and
535 /// rejected for the reload. This avoids infinite looping in case like
538 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
539 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
541 /// sees r1 is taken by t2, tries t2's reload register r0
542 /// sees r0 is taken by t3, tries t3's reload register r1
543 /// sees r1 is taken by t2, tries t2's reload register r0 ...
544 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
545 AvailableSpills &Spills,
546 std::map<int, MachineInstr*> &MaybeDeadStores) {
547 SmallSet<unsigned, 8> Rejected;
548 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected);
554 /// rewriteMBB - Keep track of which spills are available even after the
555 /// register allocator is done with them. If possible, avoid reloading vregs.
556 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
558 DOUT << MBB.getBasicBlock()->getName() << ":\n";
560 // Spills - Keep track of which spilled values are available in physregs so
561 // that we can choose to reuse the physregs instead of emitting reloads.
562 AvailableSpills Spills(MRI, TII);
564 // MaybeDeadStores - When we need to write a value back into a stack slot,
565 // keep track of the inserted store. If the stack slot value is never read
566 // (because the value was used from some available register, for example), and
567 // subsequently stored to, the original store is dead. This map keeps track
568 // of inserted stores that are not used. If we see a subsequent store to the
569 // same stack slot, the original store is deleted.
570 std::map<int, MachineInstr*> MaybeDeadStores;
572 bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
574 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
576 MachineInstr &MI = *MII;
577 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
579 /// ReusedOperands - Keep track of operand reuse in case we need to undo
581 ReuseInfo ReusedOperands(MI, MRI);
583 // Loop over all of the implicit defs, clearing them from our available
585 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
586 const unsigned *ImpDef = TID->ImplicitDefs;
588 for ( ; *ImpDef; ++ImpDef) {
589 PhysRegsUsed[*ImpDef] = true;
590 ReusedOperands.markClobbered(*ImpDef);
591 Spills.ClobberPhysReg(*ImpDef);
595 // Process all of the spilled uses and all non spilled reg references.
596 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
597 MachineOperand &MO = MI.getOperand(i);
598 if (!MO.isRegister() || MO.getReg() == 0)
599 continue; // Ignore non-register operands.
601 if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
602 // Ignore physregs for spilling, but remember that it is used by this
604 PhysRegsUsed[MO.getReg()] = true;
605 ReusedOperands.markClobbered(MO.getReg());
609 assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
610 "Not a virtual or a physical register?");
612 unsigned VirtReg = MO.getReg();
613 if (!VRM.hasStackSlot(VirtReg)) {
614 // This virtual register was assigned a physreg!
615 unsigned Phys = VRM.getPhys(VirtReg);
616 PhysRegsUsed[Phys] = true;
618 ReusedOperands.markClobbered(Phys);
619 MI.getOperand(i).setReg(Phys);
623 // This virtual register is now known to be a spilled value.
625 continue; // Handle defs in the loop below (handle use&def here though)
627 int StackSlot = VRM.getStackSlot(VirtReg);
630 // Check to see if this stack slot is available.
631 if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot))) {
633 // This spilled operand might be part of a two-address operand. If this
634 // is the case, then changing it will necessarily require changing the
635 // def part of the instruction as well. However, in some cases, we
636 // aren't allowed to modify the reused register. If none of these cases
638 bool CanReuse = true;
639 int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
641 MI.getOperand(ti).isReg() &&
642 MI.getOperand(ti).getReg() == VirtReg) {
643 // Okay, we have a two address operand. We can reuse this physreg as
644 // long as we are allowed to clobber the value and there isn't an
645 // earlier def that has already clobbered the physreg.
646 CanReuse = Spills.canClobberPhysReg(StackSlot) &&
647 !ReusedOperands.isClobbered(PhysReg);
651 // If this stack slot value is already available, reuse it!
652 DOUT << "Reusing SS#" << StackSlot << " from physreg "
653 << MRI->getName(PhysReg) << " for vreg"
654 << VirtReg <<" instead of reloading into physreg "
655 << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
656 MI.getOperand(i).setReg(PhysReg);
658 // The only technical detail we have is that we don't know that
659 // PhysReg won't be clobbered by a reloaded stack slot that occurs
660 // later in the instruction. In particular, consider 'op V1, V2'.
661 // If V1 is available in physreg R0, we would choose to reuse it
662 // here, instead of reloading it into the register the allocator
663 // indicated (say R1). However, V2 might have to be reloaded
664 // later, and it might indicate that it needs to live in R0. When
665 // this occurs, we need to have information available that
666 // indicates it is safe to use R1 for the reload instead of R0.
668 // To further complicate matters, we might conflict with an alias,
669 // or R0 and R1 might not be compatible with each other. In this
670 // case, we actually insert a reload for V1 in R1, ensuring that
671 // we can get at R0 or its alias.
672 ReusedOperands.addReuse(i, StackSlot, PhysReg,
673 VRM.getPhys(VirtReg), VirtReg);
675 // Only mark it clobbered if this is a use&def operand.
676 ReusedOperands.markClobbered(PhysReg);
681 // Otherwise we have a situation where we have a two-address instruction
682 // whose mod/ref operand needs to be reloaded. This reload is already
683 // available in some register "PhysReg", but if we used PhysReg as the
684 // operand to our 2-addr instruction, the instruction would modify
685 // PhysReg. This isn't cool if something later uses PhysReg and expects
686 // to get its initial value.
688 // To avoid this problem, and to avoid doing a load right after a store,
689 // we emit a copy from PhysReg into the designated register for this
691 unsigned DesignatedReg = VRM.getPhys(VirtReg);
692 assert(DesignatedReg && "Must map virtreg to physreg!");
694 // Note that, if we reused a register for a previous operand, the
695 // register we want to reload into might not actually be
696 // available. If this occurs, use the register indicated by the
698 if (ReusedOperands.hasReuses())
699 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
700 Spills, MaybeDeadStores);
702 // If the mapped designated register is actually the physreg we have
703 // incoming, we don't need to inserted a dead copy.
704 if (DesignatedReg == PhysReg) {
705 // If this stack slot value is already available, reuse it!
706 DOUT << "Reusing SS#" << StackSlot << " from physreg "
707 << MRI->getName(PhysReg) << " for vreg"
709 << " instead of reloading into same physreg.\n";
710 MI.getOperand(i).setReg(PhysReg);
711 ReusedOperands.markClobbered(PhysReg);
716 const TargetRegisterClass* RC =
717 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
719 PhysRegsUsed[DesignatedReg] = true;
720 ReusedOperands.markClobbered(DesignatedReg);
721 MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
723 // This invalidates DesignatedReg.
724 Spills.ClobberPhysReg(DesignatedReg);
726 Spills.addAvailable(StackSlot, DesignatedReg);
727 MI.getOperand(i).setReg(DesignatedReg);
728 DOUT << '\t' << *prior(MII);
733 // Otherwise, reload it and remember that we have it.
734 PhysReg = VRM.getPhys(VirtReg);
735 assert(PhysReg && "Must map virtreg to physreg!");
736 const TargetRegisterClass* RC =
737 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
739 // Note that, if we reused a register for a previous operand, the
740 // register we want to reload into might not actually be
741 // available. If this occurs, use the register indicated by the
743 if (ReusedOperands.hasReuses())
744 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
745 Spills, MaybeDeadStores);
747 PhysRegsUsed[PhysReg] = true;
748 ReusedOperands.markClobbered(PhysReg);
749 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
750 // This invalidates PhysReg.
751 Spills.ClobberPhysReg(PhysReg);
753 // Any stores to this stack slot are not dead anymore.
754 MaybeDeadStores.erase(StackSlot);
755 Spills.addAvailable(StackSlot, PhysReg);
757 MI.getOperand(i).setReg(PhysReg);
758 DOUT << '\t' << *prior(MII);
763 // If we have folded references to memory operands, make sure we clear all
764 // physical registers that may contain the value of the spilled virtual
766 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
767 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
768 DOUT << "Folded vreg: " << I->second.first << " MR: "
770 unsigned VirtReg = I->second.first;
771 VirtRegMap::ModRef MR = I->second.second;
772 if (!VRM.hasStackSlot(VirtReg)) {
773 DOUT << ": No stack slot!\n";
776 int SS = VRM.getStackSlot(VirtReg);
777 DOUT << " - StackSlot: " << SS << "\n";
779 // If this folded instruction is just a use, check to see if it's a
780 // straight load from the virt reg slot.
781 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
783 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
784 if (FrameIdx == SS) {
785 // If this spill slot is available, turn it into a copy (or nothing)
786 // instead of leaving it as a load!
787 if (unsigned InReg = Spills.getSpillSlotPhysReg(SS)) {
788 DOUT << "Promoted Load To Copy: " << MI;
789 MachineFunction &MF = *MBB.getParent();
790 if (DestReg != InReg) {
791 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
792 MF.getSSARegMap()->getRegClass(VirtReg));
793 // Revisit the copy so we make sure to notice the effects of the
794 // operation on the destreg (either needing to RA it if it's
795 // virtual or needing to clobber any values if it's physical).
797 --NextMII; // backtrack to the copy.
799 VRM.RemoveFromFoldedVirtMap(&MI);
801 goto ProcessNextInst;
807 // If this reference is not a use, any previous store is now dead.
808 // Otherwise, the store to this stack slot is not dead anymore.
809 std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
810 if (MDSI != MaybeDeadStores.end()) {
811 if (MR & VirtRegMap::isRef) // Previous store is not dead.
812 MaybeDeadStores.erase(MDSI);
814 // If we get here, the store is dead, nuke it now.
815 assert(VirtRegMap::isMod && "Can't be modref!");
816 DOUT << "Removed dead store:\t" << *MDSI->second;
817 MBB.erase(MDSI->second);
818 VRM.RemoveFromFoldedVirtMap(MDSI->second);
819 MaybeDeadStores.erase(MDSI);
824 // If the spill slot value is available, and this is a new definition of
825 // the value, the value is not available anymore.
826 if (MR & VirtRegMap::isMod) {
827 // Notice that the value in this stack slot has been modified.
828 Spills.ModifyStackSlot(SS);
830 // If this is *just* a mod of the value, check to see if this is just a
831 // store to the spill slot (i.e. the spill got merged into the copy). If
832 // so, realize that the vreg is available now, and add the store to the
833 // MaybeDeadStore info.
835 if (!(MR & VirtRegMap::isRef)) {
836 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
837 assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
838 "Src hasn't been allocated yet?");
839 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
840 // this as a potentially dead store in case there is a subsequent
841 // store into the stack slot without a read from it.
842 MaybeDeadStores[StackSlot] = &MI;
844 // If the stack slot value was previously available in some other
845 // register, change it now. Otherwise, make the register available,
847 Spills.addAvailable(StackSlot, SrcReg, false /*don't clobber*/);
853 // Process all of the spilled defs.
854 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
855 MachineOperand &MO = MI.getOperand(i);
856 if (MO.isRegister() && MO.getReg() && MO.isDef()) {
857 unsigned VirtReg = MO.getReg();
859 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
860 // Check to see if this is a noop copy. If so, eliminate the
861 // instruction before considering the dest reg to be changed.
863 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
865 DOUT << "Removing now-noop copy: " << MI;
867 VRM.RemoveFromFoldedVirtMap(&MI);
868 Spills.disallowClobberPhysReg(VirtReg);
869 goto ProcessNextInst;
872 // If it's not a no-op copy, it clobbers the value in the destreg.
873 Spills.ClobberPhysReg(VirtReg);
874 ReusedOperands.markClobbered(VirtReg);
876 // Check to see if this instruction is a load from a stack slot into
877 // a register. If so, this provides the stack slot value in the reg.
879 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
880 assert(DestReg == VirtReg && "Unknown load situation!");
882 // Otherwise, if it wasn't available, remember that it is now!
883 Spills.addAvailable(FrameIdx, DestReg);
884 goto ProcessNextInst;
890 // The only vregs left are stack slot definitions.
891 int StackSlot = VRM.getStackSlot(VirtReg);
892 const TargetRegisterClass *RC =
893 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
895 // If this def is part of a two-address operand, make sure to execute
896 // the store from the correct physical register.
898 int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
900 PhysReg = MI.getOperand(TiedOp).getReg();
902 PhysReg = VRM.getPhys(VirtReg);
903 if (ReusedOperands.isClobbered(PhysReg)) {
904 // Another def has taken the assigned physreg. It must have been a
905 // use&def which got it due to reuse. Undo the reuse!
906 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
907 Spills, MaybeDeadStores);
911 PhysRegsUsed[PhysReg] = true;
912 ReusedOperands.markClobbered(PhysReg);
913 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
914 DOUT << "Store:\t" << *next(MII);
915 MI.getOperand(i).setReg(PhysReg);
917 // If there is a dead store to this stack slot, nuke it now.
918 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
920 DOUT << "Removed dead store:\t" << *LastStore;
922 MBB.erase(LastStore);
923 VRM.RemoveFromFoldedVirtMap(LastStore);
925 LastStore = next(MII);
927 // If the stack slot value was previously available in some other
928 // register, change it now. Otherwise, make the register available,
930 Spills.ModifyStackSlot(StackSlot);
931 Spills.ClobberPhysReg(PhysReg);
932 Spills.addAvailable(StackSlot, PhysReg);
935 // Check to see if this is a noop copy. If so, eliminate the
936 // instruction before considering the dest reg to be changed.
939 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
941 DOUT << "Removing now-noop copy: " << MI;
943 VRM.RemoveFromFoldedVirtMap(&MI);
944 goto ProcessNextInst;
956 llvm::Spiller* llvm::createSpiller() {
957 switch (SpillerOpt) {
958 default: assert(0 && "Unreachable!");
960 return new LocalSpiller();
962 return new SimpleSpiller();