LLVM API Documentation
00001 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the VirtRegMap class. 00011 // 00012 // It also contains implementations of the the Spiller interface, which, given a 00013 // virtual register map and a machine function, eliminates all virtual 00014 // references by replacing them with physical register references - adding spill 00015 // code as necessary. 00016 // 00017 //===----------------------------------------------------------------------===// 00018 00019 #define DEBUG_TYPE "spiller" 00020 #include "VirtRegMap.h" 00021 #include "llvm/Function.h" 00022 #include "llvm/CodeGen/MachineFrameInfo.h" 00023 #include "llvm/CodeGen/MachineFunction.h" 00024 #include "llvm/CodeGen/MachineInstrBuilder.h" 00025 #include "llvm/CodeGen/MachineRegisterInfo.h" 00026 #include "llvm/Target/TargetMachine.h" 00027 #include "llvm/Target/TargetInstrInfo.h" 00028 #include "llvm/Support/CommandLine.h" 00029 #include "llvm/Support/Debug.h" 00030 #include "llvm/Support/Compiler.h" 00031 #include "llvm/ADT/BitVector.h" 00032 #include "llvm/ADT/DenseMap.h" 00033 #include "llvm/ADT/Statistic.h" 00034 #include "llvm/ADT/STLExtras.h" 00035 #include "llvm/ADT/SmallSet.h" 00036 #include <algorithm> 00037 using namespace llvm; 00038 00039 STATISTIC(NumSpills , "Number of register spills"); 00040 STATISTIC(NumPSpills , "Number of physical register spills"); 00041 STATISTIC(NumReMats , "Number of re-materialization"); 00042 STATISTIC(NumDRM , "Number of re-materializable defs elided"); 00043 STATISTIC(NumStores , "Number of stores added"); 00044 STATISTIC(NumLoads , "Number of loads added"); 00045 STATISTIC(NumReused , "Number of values reused"); 00046 STATISTIC(NumDSE , "Number of dead stores elided"); 00047 STATISTIC(NumDCE , "Number of copies elided"); 00048 STATISTIC(NumDSS , "Number of dead spill slots removed"); 00049 STATISTIC(NumCommutes, "Number of instructions commuted"); 00050 00051 namespace { 00052 enum SpillerName { simple, local }; 00053 } 00054 00055 static cl::opt<SpillerName> 00056 SpillerOpt("spiller", 00057 cl::desc("Spiller to use: (default: local)"), 00058 cl::Prefix, 00059 cl::values(clEnumVal(simple, "simple spiller"), 00060 clEnumVal(local, "local spiller"), 00061 clEnumValEnd), 00062 cl::init(local)); 00063 00064 //===----------------------------------------------------------------------===// 00065 // VirtRegMap implementation 00066 //===----------------------------------------------------------------------===// 00067 00068 VirtRegMap::VirtRegMap(MachineFunction &mf) 00069 : TII(*mf.getTarget().getInstrInfo()), MF(mf), 00070 Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT), 00071 Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0), 00072 Virt2SplitKillMap(0), ReMatMap(NULL), ReMatId(MAX_STACK_SLOT+1), 00073 LowSpillSlot(NO_STACK_SLOT), HighSpillSlot(NO_STACK_SLOT) { 00074 SpillSlotToUsesMap.resize(8); 00075 ImplicitDefed.resize(MF.getRegInfo().getLastVirtReg()+1- 00076 TargetRegisterInfo::FirstVirtualRegister); 00077 grow(); 00078 } 00079 00080 void VirtRegMap::grow() { 00081 unsigned LastVirtReg = MF.getRegInfo().getLastVirtReg(); 00082 Virt2PhysMap.grow(LastVirtReg); 00083 Virt2StackSlotMap.grow(LastVirtReg); 00084 Virt2ReMatIdMap.grow(LastVirtReg); 00085 Virt2SplitMap.grow(LastVirtReg); 00086 Virt2SplitKillMap.grow(LastVirtReg); 00087 ReMatMap.grow(LastVirtReg); 00088 ImplicitDefed.resize(LastVirtReg-TargetRegisterInfo::FirstVirtualRegister+1); 00089 } 00090 00091 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) { 00092 assert(TargetRegisterInfo::isVirtualRegister(virtReg)); 00093 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT && 00094 "attempt to assign stack slot to already spilled register"); 00095 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(virtReg); 00096 int SS = MF.getFrameInfo()->CreateStackObject(RC->getSize(), 00097 RC->getAlignment()); 00098 if (LowSpillSlot == NO_STACK_SLOT) 00099 LowSpillSlot = SS; 00100 if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot) 00101 HighSpillSlot = SS; 00102 unsigned Idx = SS-LowSpillSlot; 00103 while (Idx >= SpillSlotToUsesMap.size()) 00104 SpillSlotToUsesMap.resize(SpillSlotToUsesMap.size()*2); 00105 Virt2StackSlotMap[virtReg] = SS; 00106 ++NumSpills; 00107 return SS; 00108 } 00109 00110 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) { 00111 assert(TargetRegisterInfo::isVirtualRegister(virtReg)); 00112 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT && 00113 "attempt to assign stack slot to already spilled register"); 00114 assert((SS >= 0 || 00115 (SS >= MF.getFrameInfo()->getObjectIndexBegin())) && 00116 "illegal fixed frame index"); 00117 Virt2StackSlotMap[virtReg] = SS; 00118 } 00119 00120 int VirtRegMap::assignVirtReMatId(unsigned virtReg) { 00121 assert(TargetRegisterInfo::isVirtualRegister(virtReg)); 00122 assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT && 00123 "attempt to assign re-mat id to already spilled register"); 00124 Virt2ReMatIdMap[virtReg] = ReMatId; 00125 return ReMatId++; 00126 } 00127 00128 void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) { 00129 assert(TargetRegisterInfo::isVirtualRegister(virtReg)); 00130 assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT && 00131 "attempt to assign re-mat id to already spilled register"); 00132 Virt2ReMatIdMap[virtReg] = id; 00133 } 00134 00135 int VirtRegMap::getEmergencySpillSlot(const TargetRegisterClass *RC) { 00136 std::map<const TargetRegisterClass*, int>::iterator I = 00137 EmergencySpillSlots.find(RC); 00138 if (I != EmergencySpillSlots.end()) 00139 return I->second; 00140 int SS = MF.getFrameInfo()->CreateStackObject(RC->getSize(), 00141 RC->getAlignment()); 00142 if (LowSpillSlot == NO_STACK_SLOT) 00143 LowSpillSlot = SS; 00144 if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot) 00145 HighSpillSlot = SS; 00146 EmergencySpillSlots[RC] = SS; 00147 return SS; 00148 } 00149 00150 void VirtRegMap::addSpillSlotUse(int FI, MachineInstr *MI) { 00151 if (!MF.getFrameInfo()->isFixedObjectIndex(FI)) { 00152 // If FI < LowSpillSlot, this stack reference was produced by 00153 // instruction selection and is not a spill 00154 if (FI >= LowSpillSlot) { 00155 assert(FI >= 0 && "Spill slot index should not be negative!"); 00156 assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size() 00157 && "Invalid spill slot"); 00158 SpillSlotToUsesMap[FI-LowSpillSlot].insert(MI); 00159 } 00160 } 00161 } 00162 00163 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI, 00164 MachineInstr *NewMI, ModRef MRInfo) { 00165 // Move previous memory references folded to new instruction. 00166 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI); 00167 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI), 00168 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) { 00169 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second)); 00170 MI2VirtMap.erase(I++); 00171 } 00172 00173 // add new memory reference 00174 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo))); 00175 } 00176 00177 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) { 00178 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI); 00179 MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo))); 00180 } 00181 00182 void VirtRegMap::RemoveMachineInstrFromMaps(MachineInstr *MI) { 00183 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00184 MachineOperand &MO = MI->getOperand(i); 00185 if (!MO.isFI()) 00186 continue; 00187 int FI = MO.getIndex(); 00188 if (MF.getFrameInfo()->isFixedObjectIndex(FI)) 00189 continue; 00190 // This stack reference was produced by instruction selection and 00191 // is not a spill 00192 if (FI < LowSpillSlot) 00193 continue; 00194 assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size() 00195 && "Invalid spill slot"); 00196 SpillSlotToUsesMap[FI-LowSpillSlot].erase(MI); 00197 } 00198 MI2VirtMap.erase(MI); 00199 SpillPt2VirtMap.erase(MI); 00200 RestorePt2VirtMap.erase(MI); 00201 EmergencySpillMap.erase(MI); 00202 } 00203 00204 void VirtRegMap::print(std::ostream &OS) const { 00205 const TargetRegisterInfo* TRI = MF.getTarget().getRegisterInfo(); 00206 00207 OS << "********** REGISTER MAP **********\n"; 00208 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister, 00209 e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i) { 00210 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG) 00211 OS << "[reg" << i << " -> " << TRI->getName(Virt2PhysMap[i]) 00212 << "]\n"; 00213 } 00214 00215 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister, 00216 e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i) 00217 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT) 00218 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n"; 00219 OS << '\n'; 00220 } 00221 00222 void VirtRegMap::dump() const { 00223 print(cerr); 00224 } 00225 00226 00227 //===----------------------------------------------------------------------===// 00228 // Simple Spiller Implementation 00229 //===----------------------------------------------------------------------===// 00230 00231 Spiller::~Spiller() {} 00232 00233 namespace { 00234 struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller { 00235 bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM); 00236 }; 00237 } 00238 00239 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) { 00240 DOUT << "********** REWRITE MACHINE CODE **********\n"; 00241 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n'; 00242 const TargetMachine &TM = MF.getTarget(); 00243 const TargetInstrInfo &TII = *TM.getInstrInfo(); 00244 const TargetRegisterInfo &TRI = *TM.getRegisterInfo(); 00245 00246 00247 // LoadedRegs - Keep track of which vregs are loaded, so that we only load 00248 // each vreg once (in the case where a spilled vreg is used by multiple 00249 // operands). This is always smaller than the number of operands to the 00250 // current machine instr, so it should be small. 00251 std::vector<unsigned> LoadedRegs; 00252 00253 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end(); 00254 MBBI != E; ++MBBI) { 00255 DOUT << MBBI->getBasicBlock()->getName() << ":\n"; 00256 MachineBasicBlock &MBB = *MBBI; 00257 for (MachineBasicBlock::iterator MII = MBB.begin(), 00258 E = MBB.end(); MII != E; ++MII) { 00259 MachineInstr &MI = *MII; 00260 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 00261 MachineOperand &MO = MI.getOperand(i); 00262 if (MO.isReg() && MO.getReg()) { 00263 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 00264 unsigned VirtReg = MO.getReg(); 00265 unsigned SubIdx = MO.getSubReg(); 00266 unsigned PhysReg = VRM.getPhys(VirtReg); 00267 unsigned RReg = SubIdx ? TRI.getSubReg(PhysReg, SubIdx) : PhysReg; 00268 if (!VRM.isAssignedReg(VirtReg)) { 00269 int StackSlot = VRM.getStackSlot(VirtReg); 00270 const TargetRegisterClass* RC = 00271 MF.getRegInfo().getRegClass(VirtReg); 00272 00273 if (MO.isUse() && 00274 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg) 00275 == LoadedRegs.end()) { 00276 TII.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC); 00277 MachineInstr *LoadMI = prior(MII); 00278 VRM.addSpillSlotUse(StackSlot, LoadMI); 00279 LoadedRegs.push_back(VirtReg); 00280 ++NumLoads; 00281 DOUT << '\t' << *LoadMI; 00282 } 00283 00284 if (MO.isDef()) { 00285 TII.storeRegToStackSlot(MBB, next(MII), PhysReg, true, 00286 StackSlot, RC); 00287 MachineInstr *StoreMI = next(MII); 00288 VRM.addSpillSlotUse(StackSlot, StoreMI); 00289 ++NumStores; 00290 } 00291 } 00292 MF.getRegInfo().setPhysRegUsed(RReg); 00293 MI.getOperand(i).setReg(RReg); 00294 } else { 00295 MF.getRegInfo().setPhysRegUsed(MO.getReg()); 00296 } 00297 } 00298 } 00299 00300 DOUT << '\t' << MI; 00301 LoadedRegs.clear(); 00302 } 00303 } 00304 return true; 00305 } 00306 00307 //===----------------------------------------------------------------------===// 00308 // Local Spiller Implementation 00309 //===----------------------------------------------------------------------===// 00310 00311 namespace { 00312 class AvailableSpills; 00313 00314 /// LocalSpiller - This spiller does a simple pass over the machine basic 00315 /// block to attempt to keep spills in registers as much as possible for 00316 /// blocks that have low register pressure (the vreg may be spilled due to 00317 /// register pressure in other blocks). 00318 class VISIBILITY_HIDDEN LocalSpiller : public Spiller { 00319 MachineRegisterInfo *RegInfo; 00320 const TargetRegisterInfo *TRI; 00321 const TargetInstrInfo *TII; 00322 DenseMap<MachineInstr*, unsigned> DistanceMap; 00323 public: 00324 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) { 00325 RegInfo = &MF.getRegInfo(); 00326 TRI = MF.getTarget().getRegisterInfo(); 00327 TII = MF.getTarget().getInstrInfo(); 00328 DOUT << "\n**** Local spiller rewriting function '" 00329 << MF.getFunction()->getName() << "':\n"; 00330 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)" 00331 " ****\n"; 00332 DEBUG(MF.dump()); 00333 00334 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 00335 MBB != E; ++MBB) 00336 RewriteMBB(*MBB, VRM); 00337 00338 // Mark unused spill slots. 00339 MachineFrameInfo *MFI = MF.getFrameInfo(); 00340 int SS = VRM.getLowSpillSlot(); 00341 if (SS != VirtRegMap::NO_STACK_SLOT) 00342 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS) 00343 if (!VRM.isSpillSlotUsed(SS)) { 00344 MFI->RemoveStackObject(SS); 00345 ++NumDSS; 00346 } 00347 00348 DOUT << "**** Post Machine Instrs ****\n"; 00349 DEBUG(MF.dump()); 00350 00351 return true; 00352 } 00353 private: 00354 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist, 00355 unsigned Reg, BitVector &RegKills, 00356 std::vector<MachineOperand*> &KillOps); 00357 bool PrepForUnfoldOpti(MachineBasicBlock &MBB, 00358 MachineBasicBlock::iterator &MII, 00359 std::vector<MachineInstr*> &MaybeDeadStores, 00360 AvailableSpills &Spills, BitVector &RegKills, 00361 std::vector<MachineOperand*> &KillOps, 00362 VirtRegMap &VRM); 00363 bool CommuteToFoldReload(MachineBasicBlock &MBB, 00364 MachineBasicBlock::iterator &MII, 00365 unsigned VirtReg, unsigned SrcReg, int SS, 00366 BitVector &RegKills, 00367 std::vector<MachineOperand*> &KillOps, 00368 const TargetRegisterInfo *TRI, 00369 VirtRegMap &VRM); 00370 void SpillRegToStackSlot(MachineBasicBlock &MBB, 00371 MachineBasicBlock::iterator &MII, 00372 int Idx, unsigned PhysReg, int StackSlot, 00373 const TargetRegisterClass *RC, 00374 bool isAvailable, MachineInstr *&LastStore, 00375 AvailableSpills &Spills, 00376 SmallSet<MachineInstr*, 4> &ReMatDefs, 00377 BitVector &RegKills, 00378 std::vector<MachineOperand*> &KillOps, 00379 VirtRegMap &VRM); 00380 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM); 00381 }; 00382 } 00383 00384 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from 00385 /// top down, keep track of which spills slots or remat are available in each 00386 /// register. 00387 /// 00388 /// Note that not all physregs are created equal here. In particular, some 00389 /// physregs are reloads that we are allowed to clobber or ignore at any time. 00390 /// Other physregs are values that the register allocated program is using that 00391 /// we cannot CHANGE, but we can read if we like. We keep track of this on a 00392 /// per-stack-slot / remat id basis as the low bit in the value of the 00393 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks 00394 /// this bit and addAvailable sets it if. 00395 namespace { 00396 class VISIBILITY_HIDDEN AvailableSpills { 00397 const TargetRegisterInfo *TRI; 00398 const TargetInstrInfo *TII; 00399 00400 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled 00401 // or remat'ed virtual register values that are still available, due to being 00402 // loaded or stored to, but not invalidated yet. 00403 std::map<int, unsigned> SpillSlotsOrReMatsAvailable; 00404 00405 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable, 00406 // indicating which stack slot values are currently held by a physreg. This 00407 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a 00408 // physreg is modified. 00409 std::multimap<unsigned, int> PhysRegsAvailable; 00410 00411 void disallowClobberPhysRegOnly(unsigned PhysReg); 00412 00413 void ClobberPhysRegOnly(unsigned PhysReg); 00414 public: 00415 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii) 00416 : TRI(tri), TII(tii) { 00417 } 00418 00419 const TargetRegisterInfo *getRegInfo() const { return TRI; } 00420 00421 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is 00422 /// available in a physical register, return that PhysReg, otherwise 00423 /// return 0. 00424 unsigned getSpillSlotOrReMatPhysReg(int Slot) const { 00425 std::map<int, unsigned>::const_iterator I = 00426 SpillSlotsOrReMatsAvailable.find(Slot); 00427 if (I != SpillSlotsOrReMatsAvailable.end()) { 00428 return I->second >> 1; // Remove the CanClobber bit. 00429 } 00430 return 0; 00431 } 00432 00433 /// addAvailable - Mark that the specified stack slot / remat is available in 00434 /// the specified physreg. If CanClobber is true, the physreg can be modified 00435 /// at any time without changing the semantics of the program. 00436 void addAvailable(int SlotOrReMat, MachineInstr *MI, unsigned Reg, 00437 bool CanClobber = true) { 00438 // If this stack slot is thought to be available in some other physreg, 00439 // remove its record. 00440 ModifyStackSlotOrReMat(SlotOrReMat); 00441 00442 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat)); 00443 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) | (unsigned)CanClobber; 00444 00445 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT) 00446 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1; 00447 else 00448 DOUT << "Remembering SS#" << SlotOrReMat; 00449 DOUT << " in physreg " << TRI->getName(Reg) << "\n"; 00450 } 00451 00452 /// canClobberPhysReg - Return true if the spiller is allowed to change the 00453 /// value of the specified stackslot register if it desires. The specified 00454 /// stack slot must be available in a physreg for this query to make sense. 00455 bool canClobberPhysReg(int SlotOrReMat) const { 00456 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) && 00457 "Value not available!"); 00458 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1; 00459 } 00460 00461 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified 00462 /// stackslot register. The register is still available but is no longer 00463 /// allowed to be modifed. 00464 void disallowClobberPhysReg(unsigned PhysReg); 00465 00466 /// ClobberPhysReg - This is called when the specified physreg changes 00467 /// value. We use this to invalidate any info about stuff that lives in 00468 /// it and any of its aliases. 00469 void ClobberPhysReg(unsigned PhysReg); 00470 00471 /// ModifyStackSlotOrReMat - This method is called when the value in a stack 00472 /// slot changes. This removes information about which register the previous 00473 /// value for this slot lives in (as the previous value is dead now). 00474 void ModifyStackSlotOrReMat(int SlotOrReMat); 00475 }; 00476 } 00477 00478 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified 00479 /// stackslot register. The register is still available but is no longer 00480 /// allowed to be modifed. 00481 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) { 00482 std::multimap<unsigned, int>::iterator I = 00483 PhysRegsAvailable.lower_bound(PhysReg); 00484 while (I != PhysRegsAvailable.end() && I->first == PhysReg) { 00485 int SlotOrReMat = I->second; 00486 I++; 00487 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg && 00488 "Bidirectional map mismatch!"); 00489 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1; 00490 DOUT << "PhysReg " << TRI->getName(PhysReg) 00491 << " copied, it is available for use but can no longer be modified\n"; 00492 } 00493 } 00494 00495 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified 00496 /// stackslot register and its aliases. The register and its aliases may 00497 /// still available but is no longer allowed to be modifed. 00498 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) { 00499 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS) 00500 disallowClobberPhysRegOnly(*AS); 00501 disallowClobberPhysRegOnly(PhysReg); 00502 } 00503 00504 /// ClobberPhysRegOnly - This is called when the specified physreg changes 00505 /// value. We use this to invalidate any info about stuff we thing lives in it. 00506 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) { 00507 std::multimap<unsigned, int>::iterator I = 00508 PhysRegsAvailable.lower_bound(PhysReg); 00509 while (I != PhysRegsAvailable.end() && I->first == PhysReg) { 00510 int SlotOrReMat = I->second; 00511 PhysRegsAvailable.erase(I++); 00512 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg && 00513 "Bidirectional map mismatch!"); 00514 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat); 00515 DOUT << "PhysReg " << TRI->getName(PhysReg) 00516 << " clobbered, invalidating "; 00517 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT) 00518 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n"; 00519 else 00520 DOUT << "SS#" << SlotOrReMat << "\n"; 00521 } 00522 } 00523 00524 /// ClobberPhysReg - This is called when the specified physreg changes 00525 /// value. We use this to invalidate any info about stuff we thing lives in 00526 /// it and any of its aliases. 00527 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) { 00528 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS) 00529 ClobberPhysRegOnly(*AS); 00530 ClobberPhysRegOnly(PhysReg); 00531 } 00532 00533 /// ModifyStackSlotOrReMat - This method is called when the value in a stack 00534 /// slot changes. This removes information about which register the previous 00535 /// value for this slot lives in (as the previous value is dead now). 00536 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) { 00537 std::map<int, unsigned>::iterator It = 00538 SpillSlotsOrReMatsAvailable.find(SlotOrReMat); 00539 if (It == SpillSlotsOrReMatsAvailable.end()) return; 00540 unsigned Reg = It->second >> 1; 00541 SpillSlotsOrReMatsAvailable.erase(It); 00542 00543 // This register may hold the value of multiple stack slots, only remove this 00544 // stack slot from the set of values the register contains. 00545 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg); 00546 for (; ; ++I) { 00547 assert(I != PhysRegsAvailable.end() && I->first == Reg && 00548 "Map inverse broken!"); 00549 if (I->second == SlotOrReMat) break; 00550 } 00551 PhysRegsAvailable.erase(I); 00552 } 00553 00554 00555 00556 /// InvalidateKills - MI is going to be deleted. If any of its operands are 00557 /// marked kill, then invalidate the information. 00558 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills, 00559 std::vector<MachineOperand*> &KillOps, 00560 SmallVector<unsigned, 2> *KillRegs = NULL) { 00561 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 00562 MachineOperand &MO = MI.getOperand(i); 00563 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 00564 continue; 00565 unsigned Reg = MO.getReg(); 00566 if (TargetRegisterInfo::isVirtualRegister(Reg)) 00567 continue; 00568 if (KillRegs) 00569 KillRegs->push_back(Reg); 00570 assert(Reg < KillOps.size()); 00571 if (KillOps[Reg] == &MO) { 00572 RegKills.reset(Reg); 00573 KillOps[Reg] = NULL; 00574 } 00575 } 00576 } 00577 00578 /// InvalidateKill - A MI that defines the specified register is being deleted, 00579 /// invalidate the register kill information. 00580 static void InvalidateKill(unsigned Reg, BitVector &RegKills, 00581 std::vector<MachineOperand*> &KillOps) { 00582 if (RegKills[Reg]) { 00583 KillOps[Reg]->setIsKill(false); 00584 KillOps[Reg] = NULL; 00585 RegKills.reset(Reg); 00586 } 00587 } 00588 00589 /// InvalidateRegDef - If the def operand of the specified def MI is now dead 00590 /// (since it's spill instruction is removed), mark it isDead. Also checks if 00591 /// the def MI has other definition operands that are not dead. Returns it by 00592 /// reference. 00593 static bool InvalidateRegDef(MachineBasicBlock::iterator I, 00594 MachineInstr &NewDef, unsigned Reg, 00595 bool &HasLiveDef) { 00596 // Due to remat, it's possible this reg isn't being reused. That is, 00597 // the def of this reg (by prev MI) is now dead. 00598 MachineInstr *DefMI = I; 00599 MachineOperand *DefOp = NULL; 00600 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) { 00601 MachineOperand &MO = DefMI->getOperand(i); 00602 if (MO.isReg() && MO.isDef()) { 00603 if (MO.getReg() == Reg) 00604 DefOp = &MO; 00605 else if (!MO.isDead()) 00606 HasLiveDef = true; 00607 } 00608 } 00609 if (!DefOp) 00610 return false; 00611 00612 bool FoundUse = false, Done = false; 00613 MachineBasicBlock::iterator E = &NewDef; 00614 ++I; ++E; 00615 for (; !Done && I != E; ++I) { 00616 MachineInstr *NMI = I; 00617 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) { 00618 MachineOperand &MO = NMI->getOperand(j); 00619 if (!MO.isReg() || MO.getReg() != Reg) 00620 continue; 00621 if (MO.isUse()) 00622 FoundUse = true; 00623 Done = true; // Stop after scanning all the operands of this MI. 00624 } 00625 } 00626 if (!FoundUse) { 00627 // Def is dead! 00628 DefOp->setIsDead(); 00629 return true; 00630 } 00631 return false; 00632 } 00633 00634 /// UpdateKills - Track and update kill info. If a MI reads a register that is 00635 /// marked kill, then it must be due to register reuse. Transfer the kill info 00636 /// over. 00637 static void UpdateKills(MachineInstr &MI, BitVector &RegKills, 00638 std::vector<MachineOperand*> &KillOps, 00639 const TargetRegisterInfo* TRI) { 00640 const TargetInstrDesc &TID = MI.getDesc(); 00641 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 00642 MachineOperand &MO = MI.getOperand(i); 00643 if (!MO.isReg() || !MO.isUse()) 00644 continue; 00645 unsigned Reg = MO.getReg(); 00646 if (Reg == 0) 00647 continue; 00648 00649 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) { 00650 // That can't be right. Register is killed but not re-defined and it's 00651 // being reused. Let's fix that. 00652 KillOps[Reg]->setIsKill(false); 00653 KillOps[Reg] = NULL; 00654 RegKills.reset(Reg); 00655 if (i < TID.getNumOperands() && 00656 TID.getOperandConstraint(i, TOI::TIED_TO) == -1) 00657 // Unless it's a two-address operand, this is the new kill. 00658 MO.setIsKill(); 00659 } 00660 if (MO.isKill()) { 00661 RegKills.set(Reg); 00662 KillOps[Reg] = &MO; 00663 } 00664 } 00665 00666 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 00667 const MachineOperand &MO = MI.getOperand(i); 00668 if (!MO.isReg() || !MO.isDef()) 00669 continue; 00670 unsigned Reg = MO.getReg(); 00671 RegKills.reset(Reg); 00672 KillOps[Reg] = NULL; 00673 // It also defines (or partially define) aliases. 00674 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) { 00675 RegKills.reset(*AS); 00676 KillOps[*AS] = NULL; 00677 } 00678 } 00679 } 00680 00681 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg. 00682 /// 00683 static void ReMaterialize(MachineBasicBlock &MBB, 00684 MachineBasicBlock::iterator &MII, 00685 unsigned DestReg, unsigned Reg, 00686 const TargetInstrInfo *TII, 00687 const TargetRegisterInfo *TRI, 00688 VirtRegMap &VRM) { 00689 TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg)); 00690 MachineInstr *NewMI = prior(MII); 00691 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) { 00692 MachineOperand &MO = NewMI->getOperand(i); 00693 if (!MO.isReg() || MO.getReg() == 0) 00694 continue; 00695 unsigned VirtReg = MO.getReg(); 00696 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) 00697 continue; 00698 assert(MO.isUse()); 00699 unsigned SubIdx = MO.getSubReg(); 00700 unsigned Phys = VRM.getPhys(VirtReg); 00701 assert(Phys); 00702 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys; 00703 MO.setReg(RReg); 00704 } 00705 ++NumReMats; 00706 } 00707 00708 00709 // ReusedOp - For each reused operand, we keep track of a bit of information, in 00710 // case we need to rollback upon processing a new operand. See comments below. 00711 namespace { 00712 struct ReusedOp { 00713 // The MachineInstr operand that reused an available value. 00714 unsigned Operand; 00715 00716 // StackSlotOrReMat - The spill slot or remat id of the value being reused. 00717 unsigned StackSlotOrReMat; 00718 00719 // PhysRegReused - The physical register the value was available in. 00720 unsigned PhysRegReused; 00721 00722 // AssignedPhysReg - The physreg that was assigned for use by the reload. 00723 unsigned AssignedPhysReg; 00724 00725 // VirtReg - The virtual register itself. 00726 unsigned VirtReg; 00727 00728 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr, 00729 unsigned vreg) 00730 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr), 00731 AssignedPhysReg(apr), VirtReg(vreg) {} 00732 }; 00733 00734 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that 00735 /// is reused instead of reloaded. 00736 class VISIBILITY_HIDDEN ReuseInfo { 00737 MachineInstr &MI; 00738 std::vector<ReusedOp> Reuses; 00739 BitVector PhysRegsClobbered; 00740 public: 00741 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) { 00742 PhysRegsClobbered.resize(tri->getNumRegs()); 00743 } 00744 00745 bool hasReuses() const { 00746 return !Reuses.empty(); 00747 } 00748 00749 /// addReuse - If we choose to reuse a virtual register that is already 00750 /// available instead of reloading it, remember that we did so. 00751 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat, 00752 unsigned PhysRegReused, unsigned AssignedPhysReg, 00753 unsigned VirtReg) { 00754 // If the reload is to the assigned register anyway, no undo will be 00755 // required. 00756 if (PhysRegReused == AssignedPhysReg) return; 00757 00758 // Otherwise, remember this. 00759 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused, 00760 AssignedPhysReg, VirtReg)); 00761 } 00762 00763 void markClobbered(unsigned PhysReg) { 00764 PhysRegsClobbered.set(PhysReg); 00765 } 00766 00767 bool isClobbered(unsigned PhysReg) const { 00768 return PhysRegsClobbered.test(PhysReg); 00769 } 00770 00771 /// GetRegForReload - We are about to emit a reload into PhysReg. If there 00772 /// is some other operand that is using the specified register, either pick 00773 /// a new register to use, or evict the previous reload and use this reg. 00774 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI, 00775 AvailableSpills &Spills, 00776 std::vector<MachineInstr*> &MaybeDeadStores, 00777 SmallSet<unsigned, 8> &Rejected, 00778 BitVector &RegKills, 00779 std::vector<MachineOperand*> &KillOps, 00780 VirtRegMap &VRM) { 00781 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget() 00782 .getInstrInfo(); 00783 00784 if (Reuses.empty()) return PhysReg; // This is most often empty. 00785 00786 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) { 00787 ReusedOp &Op = Reuses[ro]; 00788 // If we find some other reuse that was supposed to use this register 00789 // exactly for its reload, we can change this reload to use ITS reload 00790 // register. That is, unless its reload register has already been 00791 // considered and subsequently rejected because it has also been reused 00792 // by another operand. 00793 if (Op.PhysRegReused == PhysReg && 00794 Rejected.count(Op.AssignedPhysReg) == 0) { 00795 // Yup, use the reload register that we didn't use before. 00796 unsigned NewReg = Op.AssignedPhysReg; 00797 Rejected.insert(PhysReg); 00798 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected, 00799 RegKills, KillOps, VRM); 00800 } else { 00801 // Otherwise, we might also have a problem if a previously reused 00802 // value aliases the new register. If so, codegen the previous reload 00803 // and use this one. 00804 unsigned PRRU = Op.PhysRegReused; 00805 const TargetRegisterInfo *TRI = Spills.getRegInfo(); 00806 if (TRI->areAliases(PRRU, PhysReg)) { 00807 // Okay, we found out that an alias of a reused register 00808 // was used. This isn't good because it means we have 00809 // to undo a previous reuse. 00810 MachineBasicBlock *MBB = MI->getParent(); 00811 const TargetRegisterClass *AliasRC = 00812 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg); 00813 00814 // Copy Op out of the vector and remove it, we're going to insert an 00815 // explicit load for it. 00816 ReusedOp NewOp = Op; 00817 Reuses.erase(Reuses.begin()+ro); 00818 00819 // Ok, we're going to try to reload the assigned physreg into the 00820 // slot that we were supposed to in the first place. However, that 00821 // register could hold a reuse. Check to see if it conflicts or 00822 // would prefer us to use a different register. 00823 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg, 00824 MI, Spills, MaybeDeadStores, 00825 Rejected, RegKills, KillOps, VRM); 00826 00827 MachineBasicBlock::iterator MII = MI; 00828 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) { 00829 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM); 00830 } else { 00831 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg, 00832 NewOp.StackSlotOrReMat, AliasRC); 00833 MachineInstr *LoadMI = prior(MII); 00834 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI); 00835 // Any stores to this stack slot are not dead anymore. 00836 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL; 00837 ++NumLoads; 00838 } 00839 Spills.ClobberPhysReg(NewPhysReg); 00840 Spills.ClobberPhysReg(NewOp.PhysRegReused); 00841 00842 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg(); 00843 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg; 00844 MI->getOperand(NewOp.Operand).setReg(RReg); 00845 00846 Spills.addAvailable(NewOp.StackSlotOrReMat, MI, NewPhysReg); 00847 --MII; 00848 UpdateKills(*MII, RegKills, KillOps, TRI); 00849 DOUT << '\t' << *MII; 00850 00851 DOUT << "Reuse undone!\n"; 00852 --NumReused; 00853 00854 // Finally, PhysReg is now available, go ahead and use it. 00855 return PhysReg; 00856 } 00857 } 00858 } 00859 return PhysReg; 00860 } 00861 00862 /// GetRegForReload - Helper for the above GetRegForReload(). Add a 00863 /// 'Rejected' set to remember which registers have been considered and 00864 /// rejected for the reload. This avoids infinite looping in case like 00865 /// this: 00866 /// t1 := op t2, t3 00867 /// t2 <- assigned r0 for use by the reload but ended up reuse r1 00868 /// t3 <- assigned r1 for use by the reload but ended up reuse r0 00869 /// t1 <- desires r1 00870 /// sees r1 is taken by t2, tries t2's reload register r0 00871 /// sees r0 is taken by t3, tries t3's reload register r1 00872 /// sees r1 is taken by t2, tries t2's reload register r0 ... 00873 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI, 00874 AvailableSpills &Spills, 00875 std::vector<MachineInstr*> &MaybeDeadStores, 00876 BitVector &RegKills, 00877 std::vector<MachineOperand*> &KillOps, 00878 VirtRegMap &VRM) { 00879 SmallSet<unsigned, 8> Rejected; 00880 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected, 00881 RegKills, KillOps, VRM); 00882 } 00883 }; 00884 } 00885 00886 /// PrepForUnfoldOpti - Turn a store folding instruction into a load folding 00887 /// instruction. e.g. 00888 /// xorl %edi, %eax 00889 /// movl %eax, -32(%ebp) 00890 /// movl -36(%ebp), %eax 00891 /// orl %eax, -32(%ebp) 00892 /// ==> 00893 /// xorl %edi, %eax 00894 /// orl -36(%ebp), %eax 00895 /// mov %eax, -32(%ebp) 00896 /// This enables unfolding optimization for a subsequent instruction which will 00897 /// also eliminate the newly introduced store instruction. 00898 bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB, 00899 MachineBasicBlock::iterator &MII, 00900 std::vector<MachineInstr*> &MaybeDeadStores, 00901 AvailableSpills &Spills, 00902 BitVector &RegKills, 00903 std::vector<MachineOperand*> &KillOps, 00904 VirtRegMap &VRM) { 00905 MachineFunction &MF = *MBB.getParent(); 00906 MachineInstr &MI = *MII; 00907 unsigned UnfoldedOpc = 0; 00908 unsigned UnfoldPR = 0; 00909 unsigned UnfoldVR = 0; 00910 int FoldedSS = VirtRegMap::NO_STACK_SLOT; 00911 VirtRegMap::MI2VirtMapTy::const_iterator I, End; 00912 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) { 00913 // Only transform a MI that folds a single register. 00914 if (UnfoldedOpc) 00915 return false; 00916 UnfoldVR = I->second.first; 00917 VirtRegMap::ModRef MR = I->second.second; 00918 // MI2VirtMap be can updated which invalidate the iterator. 00919 // Increment the iterator first. 00920 ++I; 00921 if (VRM.isAssignedReg(UnfoldVR)) 00922 continue; 00923 // If this reference is not a use, any previous store is now dead. 00924 // Otherwise, the store to this stack slot is not dead anymore. 00925 FoldedSS = VRM.getStackSlot(UnfoldVR); 00926 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS]; 00927 if (DeadStore && (MR & VirtRegMap::isModRef)) { 00928 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS); 00929 if (!PhysReg || !DeadStore->readsRegister(PhysReg)) 00930 continue; 00931 UnfoldPR = PhysReg; 00932 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), 00933 false, true); 00934 } 00935 } 00936 00937 if (!UnfoldedOpc) 00938 return false; 00939 00940 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 00941 MachineOperand &MO = MI.getOperand(i); 00942 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse()) 00943 continue; 00944 unsigned VirtReg = MO.getReg(); 00945 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg()) 00946 continue; 00947 if (VRM.isAssignedReg(VirtReg)) { 00948 unsigned PhysReg = VRM.getPhys(VirtReg); 00949 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR)) 00950 return false; 00951 } else if (VRM.isReMaterialized(VirtReg)) 00952 continue; 00953 int SS = VRM.getStackSlot(VirtReg); 00954 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS); 00955 if (PhysReg) { 00956 if (TRI->regsOverlap(PhysReg, UnfoldPR)) 00957 return false; 00958 continue; 00959 } 00960 if (VRM.hasPhys(VirtReg)) { 00961 PhysReg = VRM.getPhys(VirtReg); 00962 if (!TRI->regsOverlap(PhysReg, UnfoldPR)) 00963 continue; 00964 } 00965 00966 // Ok, we'll need to reload the value into a register which makes 00967 // it impossible to perform the store unfolding optimization later. 00968 // Let's see if it is possible to fold the load if the store is 00969 // unfolded. This allows us to perform the store unfolding 00970 // optimization. 00971 SmallVector<MachineInstr*, 4> NewMIs; 00972 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) { 00973 assert(NewMIs.size() == 1); 00974 MachineInstr *NewMI = NewMIs.back(); 00975 NewMIs.clear(); 00976 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false); 00977 assert(Idx != -1); 00978 SmallVector<unsigned, 2> Ops; 00979 Ops.push_back(Idx); 00980 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS); 00981 if (FoldedMI) { 00982 VRM.addSpillSlotUse(SS, FoldedMI); 00983 if (!VRM.hasPhys(UnfoldVR)) 00984 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR); 00985 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef); 00986 MII = MBB.insert(MII, FoldedMI); 00987 InvalidateKills(MI, RegKills, KillOps); 00988 VRM.RemoveMachineInstrFromMaps(&MI); 00989 MBB.erase(&MI); 00990 MF.DeleteMachineInstr(NewMI); 00991 return true; 00992 } 00993 MF.DeleteMachineInstr(NewMI); 00994 } 00995 } 00996 return false; 00997 } 00998 00999 /// CommuteToFoldReload - 01000 /// Look for 01001 /// r1 = load fi#1 01002 /// r1 = op r1, r2<kill> 01003 /// store r1, fi#1 01004 /// 01005 /// If op is commutable and r2 is killed, then we can xform these to 01006 /// r2 = op r2, fi#1 01007 /// store r2, fi#1 01008 bool LocalSpiller::CommuteToFoldReload(MachineBasicBlock &MBB, 01009 MachineBasicBlock::iterator &MII, 01010 unsigned VirtReg, unsigned SrcReg, int SS, 01011 BitVector &RegKills, 01012 std::vector<MachineOperand*> &KillOps, 01013 const TargetRegisterInfo *TRI, 01014 VirtRegMap &VRM) { 01015 if (MII == MBB.begin() || !MII->killsRegister(SrcReg)) 01016 return false; 01017 01018 MachineFunction &MF = *MBB.getParent(); 01019 MachineInstr &MI = *MII; 01020 MachineBasicBlock::iterator DefMII = prior(MII); 01021 MachineInstr *DefMI = DefMII; 01022 const TargetInstrDesc &TID = DefMI->getDesc(); 01023 unsigned NewDstIdx; 01024 if (DefMII != MBB.begin() && 01025 TID.isCommutable() && 01026 TII->CommuteChangesDestination(DefMI, NewDstIdx)) { 01027 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); 01028 unsigned NewReg = NewDstMO.getReg(); 01029 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg)) 01030 return false; 01031 MachineInstr *ReloadMI = prior(DefMII); 01032 int FrameIdx; 01033 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx); 01034 if (DestReg != SrcReg || FrameIdx != SS) 01035 return false; 01036 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false); 01037 if (UseIdx == -1) 01038 return false; 01039 int DefIdx = TID.getOperandConstraint(UseIdx, TOI::TIED_TO); 01040 if (DefIdx == -1) 01041 return false; 01042 assert(DefMI->getOperand(DefIdx).isReg() && 01043 DefMI->getOperand(DefIdx).getReg() == SrcReg); 01044 01045 // Now commute def instruction. 01046 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true); 01047 if (!CommutedMI) 01048 return false; 01049 SmallVector<unsigned, 2> Ops; 01050 Ops.push_back(NewDstIdx); 01051 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS); 01052 // Not needed since foldMemoryOperand returns new MI. 01053 MF.DeleteMachineInstr(CommutedMI); 01054 if (!FoldedMI) 01055 return false; 01056 01057 VRM.addSpillSlotUse(SS, FoldedMI); 01058 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef); 01059 // Insert new def MI and spill MI. 01060 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg); 01061 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC); 01062 MII = prior(MII); 01063 MachineInstr *StoreMI = MII; 01064 VRM.addSpillSlotUse(SS, StoreMI); 01065 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod); 01066 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack. 01067 01068 // Delete all 3 old instructions. 01069 InvalidateKills(*ReloadMI, RegKills, KillOps); 01070 VRM.RemoveMachineInstrFromMaps(ReloadMI); 01071 MBB.erase(ReloadMI); 01072 InvalidateKills(*DefMI, RegKills, KillOps); 01073 VRM.RemoveMachineInstrFromMaps(DefMI); 01074 MBB.erase(DefMI); 01075 InvalidateKills(MI, RegKills, KillOps); 01076 VRM.RemoveMachineInstrFromMaps(&MI); 01077 MBB.erase(&MI); 01078 01079 ++NumCommutes; 01080 return true; 01081 } 01082 01083 return false; 01084 } 01085 01086 /// findSuperReg - Find the SubReg's super-register of given register class 01087 /// where its SubIdx sub-register is SubReg. 01088 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg, 01089 unsigned SubIdx, const TargetRegisterInfo *TRI) { 01090 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 01091 I != E; ++I) { 01092 unsigned Reg = *I; 01093 if (TRI->getSubReg(Reg, SubIdx) == SubReg) 01094 return Reg; 01095 } 01096 return 0; 01097 } 01098 01099 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if 01100 /// the last store to the same slot is now dead. If so, remove the last store. 01101 void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB, 01102 MachineBasicBlock::iterator &MII, 01103 int Idx, unsigned PhysReg, int StackSlot, 01104 const TargetRegisterClass *RC, 01105 bool isAvailable, MachineInstr *&LastStore, 01106 AvailableSpills &Spills, 01107 SmallSet<MachineInstr*, 4> &ReMatDefs, 01108 BitVector &RegKills, 01109 std::vector<MachineOperand*> &KillOps, 01110 VirtRegMap &VRM) { 01111 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC); 01112 MachineInstr *StoreMI = next(MII); 01113 VRM.addSpillSlotUse(StackSlot, StoreMI); 01114 DOUT << "Store:\t" << *StoreMI; 01115 01116 // If there is a dead store to this stack slot, nuke it now. 01117 if (LastStore) { 01118 DOUT << "Removed dead store:\t" << *LastStore; 01119 ++NumDSE; 01120 SmallVector<unsigned, 2> KillRegs; 01121 InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs); 01122 MachineBasicBlock::iterator PrevMII = LastStore; 01123 bool CheckDef = PrevMII != MBB.begin(); 01124 if (CheckDef) 01125 --PrevMII; 01126 VRM.RemoveMachineInstrFromMaps(LastStore); 01127 MBB.erase(LastStore); 01128 if (CheckDef) { 01129 // Look at defs of killed registers on the store. Mark the defs 01130 // as dead since the store has been deleted and they aren't 01131 // being reused. 01132 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) { 01133 bool HasOtherDef = false; 01134 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) { 01135 MachineInstr *DeadDef = PrevMII; 01136 if (ReMatDefs.count(DeadDef) && !HasOtherDef) { 01137 // FIXME: This assumes a remat def does not have side 01138 // effects. 01139 VRM.RemoveMachineInstrFromMaps(DeadDef); 01140 MBB.erase(DeadDef); 01141 ++NumDRM; 01142 } 01143 } 01144 } 01145 } 01146 } 01147 01148 LastStore = next(MII); 01149 01150 // If the stack slot value was previously available in some other 01151 // register, change it now. Otherwise, make the register available, 01152 // in PhysReg. 01153 Spills.ModifyStackSlotOrReMat(StackSlot); 01154 Spills.ClobberPhysReg(PhysReg); 01155 Spills.addAvailable(StackSlot, LastStore, PhysReg, isAvailable); 01156 ++NumStores; 01157 } 01158 01159 /// TransferDeadness - A identity copy definition is dead and it's being 01160 /// removed. Find the last def or use and mark it as dead / kill. 01161 void LocalSpiller::TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist, 01162 unsigned Reg, BitVector &RegKills, 01163 std::vector<MachineOperand*> &KillOps) { 01164 int LastUDDist = -1; 01165 MachineInstr *LastUDMI = NULL; 01166 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg), 01167 RE = RegInfo->reg_end(); RI != RE; ++RI) { 01168 MachineInstr *UDMI = &*RI; 01169 if (UDMI->getParent() != MBB) 01170 continue; 01171 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI); 01172 if (DI == DistanceMap.end() || DI->second > CurDist) 01173 continue; 01174 if ((int)DI->second < LastUDDist) 01175 continue; 01176 LastUDDist = DI->second; 01177 LastUDMI = UDMI; 01178 } 01179 01180 if (LastUDMI) { 01181 const TargetInstrDesc &TID = LastUDMI->getDesc(); 01182 MachineOperand *LastUD = NULL; 01183 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) { 01184 MachineOperand &MO = LastUDMI->getOperand(i); 01185 if (!MO.isReg() || MO.getReg() != Reg) 01186 continue; 01187 if (!LastUD || (LastUD->isUse() && MO.isDef())) 01188 LastUD = &MO; 01189 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) 01190 return; 01191 } 01192 if (LastUD->isDef()) 01193 LastUD->setIsDead(); 01194 else { 01195 LastUD->setIsKill(); 01196 RegKills.set(Reg); 01197 KillOps[Reg] = LastUD; 01198 } 01199 } 01200 } 01201 01202 /// rewriteMBB - Keep track of which spills are available even after the 01203 /// register allocator is done with them. If possible, avid reloading vregs. 01204 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) { 01205 DOUT << MBB.getBasicBlock()->getName() << ":\n"; 01206 01207 MachineFunction &MF = *MBB.getParent(); 01208 01209 // Spills - Keep track of which spilled values are available in physregs so 01210 // that we can choose to reuse the physregs instead of emitting reloads. 01211 AvailableSpills Spills(TRI, TII); 01212 01213 // MaybeDeadStores - When we need to write a value back into a stack slot, 01214 // keep track of the inserted store. If the stack slot value is never read 01215 // (because the value was used from some available register, for example), and 01216 // subsequently stored to, the original store is dead. This map keeps track 01217 // of inserted stores that are not used. If we see a subsequent store to the 01218 // same stack slot, the original store is deleted. 01219 std::vector<MachineInstr*> MaybeDeadStores; 01220 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL); 01221 01222 // ReMatDefs - These are rematerializable def MIs which are not deleted. 01223 SmallSet<MachineInstr*, 4> ReMatDefs; 01224 01225 // Keep track of kill information. 01226 BitVector RegKills(TRI->getNumRegs()); 01227 std::vector<MachineOperand*> KillOps; 01228 KillOps.resize(TRI->getNumRegs(), NULL); 01229 01230 unsigned Dist = 0; 01231 DistanceMap.clear(); 01232 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end(); 01233 MII != E; ) { 01234 MachineBasicBlock::iterator NextMII = MII; ++NextMII; 01235 01236 VirtRegMap::MI2VirtMapTy::const_iterator I, End; 01237 bool Erased = false; 01238 bool BackTracked = false; 01239 if (PrepForUnfoldOpti(MBB, MII, 01240 MaybeDeadStores, Spills, RegKills, KillOps, VRM)) 01241 NextMII = next(MII); 01242 01243 MachineInstr &MI = *MII; 01244 const TargetInstrDesc &TID = MI.getDesc(); 01245 01246 if (VRM.hasEmergencySpills(&MI)) { 01247 // Spill physical register(s) in the rare case the allocator has run out 01248 // of registers to allocate. 01249 SmallSet<int, 4> UsedSS; 01250 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI); 01251 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) { 01252 unsigned PhysReg = EmSpills[i]; 01253 const TargetRegisterClass *RC = 01254 TRI->getPhysicalRegisterRegClass(PhysReg); 01255 assert(RC && "Unable to determine register class!"); 01256 int SS = VRM.getEmergencySpillSlot(RC); 01257 if (UsedSS.count(SS)) 01258 assert(0 && "Need to spill more than one physical registers!"); 01259 UsedSS.insert(SS); 01260 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC); 01261 MachineInstr *StoreMI = prior(MII); 01262 VRM.addSpillSlotUse(SS, StoreMI); 01263 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC); 01264 MachineInstr *LoadMI = next(MII); 01265 VRM.addSpillSlotUse(SS, LoadMI); 01266 ++NumPSpills; 01267 } 01268 NextMII = next(MII); 01269 } 01270 01271 // Insert restores here if asked to. 01272 if (VRM.isRestorePt(&MI)) { 01273 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI); 01274 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) { 01275 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order. 01276 if (!VRM.getPreSplitReg(VirtReg)) 01277 continue; // Split interval spilled again. 01278 unsigned Phys = VRM.getPhys(VirtReg); 01279 RegInfo->setPhysRegUsed(Phys); 01280 if (VRM.isReMaterialized(VirtReg)) { 01281 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM); 01282 } else { 01283 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg); 01284 int SS = VRM.getStackSlot(VirtReg); 01285 TII->loadRegFromStackSlot(MBB, &MI, Phys, SS, RC); 01286 MachineInstr *LoadMI = prior(MII); 01287 VRM.addSpillSlotUse(SS, LoadMI); 01288 ++NumLoads; 01289 } 01290 // This invalidates Phys. 01291 Spills.ClobberPhysReg(Phys); 01292 UpdateKills(*prior(MII), RegKills, KillOps, TRI); 01293 DOUT << '\t' << *prior(MII); 01294 } 01295 } 01296 01297 // Insert spills here if asked to. 01298 if (VRM.isSpillPt(&MI)) { 01299 std::vector<std::pair<unsigned,bool> > &SpillRegs = 01300 VRM.getSpillPtSpills(&MI); 01301 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) { 01302 unsigned VirtReg = SpillRegs[i].first; 01303 bool isKill = SpillRegs[i].second; 01304 if (!VRM.getPreSplitReg(VirtReg)) 01305 continue; // Split interval spilled again. 01306 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg); 01307 unsigned Phys = VRM.getPhys(VirtReg); 01308 int StackSlot = VRM.getStackSlot(VirtReg); 01309 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC); 01310 MachineInstr *StoreMI = next(MII); 01311 VRM.addSpillSlotUse(StackSlot, StoreMI); 01312 DOUT << "Store:\t" << *StoreMI; 01313 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod); 01314 } 01315 NextMII = next(MII); 01316 } 01317 01318 /// ReusedOperands - Keep track of operand reuse in case we need to undo 01319 /// reuse. 01320 ReuseInfo ReusedOperands(MI, TRI); 01321 SmallVector<unsigned, 4> VirtUseOps; 01322 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 01323 MachineOperand &MO = MI.getOperand(i); 01324 if (!MO.isReg() || MO.getReg() == 0) 01325 continue; // Ignore non-register operands. 01326 01327 unsigned VirtReg = MO.getReg(); 01328 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) { 01329 // Ignore physregs for spilling, but remember that it is used by this 01330 // function. 01331 RegInfo->setPhysRegUsed(VirtReg); 01332 continue; 01333 } 01334 01335 // We want to process implicit virtual register uses first. 01336 if (MO.isImplicit()) 01337 // If the virtual register is implicitly defined, emit a implicit_def 01338 // before so scavenger knows it's "defined". 01339 VirtUseOps.insert(VirtUseOps.begin(), i); 01340 else 01341 VirtUseOps.push_back(i); 01342 } 01343 01344 // Process all of the spilled uses and all non spilled reg references. 01345 SmallVector<int, 2> PotentialDeadStoreSlots; 01346 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) { 01347 unsigned i = VirtUseOps[j]; 01348 MachineOperand &MO = MI.getOperand(i); 01349 unsigned VirtReg = MO.getReg(); 01350 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && 01351 "Not a virtual register?"); 01352 01353 unsigned SubIdx = MO.getSubReg(); 01354 if (VRM.isAssignedReg(VirtReg)) { 01355 // This virtual register was assigned a physreg! 01356 unsigned Phys = VRM.getPhys(VirtReg); 01357 RegInfo->setPhysRegUsed(Phys); 01358 if (MO.isDef()) 01359 ReusedOperands.markClobbered(Phys); 01360 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys; 01361 MI.getOperand(i).setReg(RReg); 01362 if (VRM.isImplicitlyDefined(VirtReg)) 01363 BuildMI(MBB, &MI, MI.getDebugLoc(), 01364 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg); 01365 continue; 01366 } 01367 01368 // This virtual register is now known to be a spilled value. 01369 if (!MO.isUse()) 01370 continue; // Handle defs in the loop below (handle use&def here though) 01371 01372 bool DoReMat = VRM.isReMaterialized(VirtReg); 01373 int SSorRMId = DoReMat 01374 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg); 01375 int ReuseSlot = SSorRMId; 01376 01377 // Check to see if this stack slot is available. 01378 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId); 01379 01380 // If this is a sub-register use, make sure the reuse register is in the 01381 // right register class. For example, for x86 not all of the 32-bit 01382 // registers have accessible sub-registers. 01383 // Similarly so for EXTRACT_SUBREG. Consider this: 01384 // EDI = op 01385 // MOV32_mr fi#1, EDI 01386 // ... 01387 // = EXTRACT_SUBREG fi#1 01388 // fi#1 is available in EDI, but it cannot be reused because it's not in 01389 // the right register file. 01390 if (PhysReg && 01391 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) { 01392 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg); 01393 if (!RC->contains(PhysReg)) 01394 PhysReg = 0; 01395 } 01396 01397 if (PhysReg) { 01398 // This spilled operand might be part of a two-address operand. If this 01399 // is the case, then changing it will necessarily require changing the 01400 // def part of the instruction as well. However, in some cases, we 01401 // aren't allowed to modify the reused register. If none of these cases 01402 // apply, reuse it. 01403 bool CanReuse = true; 01404 int ti = TID.getOperandConstraint(i, TOI::TIED_TO); 01405 if (ti != -1 && 01406 MI.getOperand(ti).isReg() && 01407 MI.getOperand(ti).getReg() == VirtReg) { 01408 // Okay, we have a two address operand. We can reuse this physreg as 01409 // long as we are allowed to clobber the value and there isn't an 01410 // earlier def that has already clobbered the physreg. 01411 CanReuse = Spills.canClobberPhysReg(ReuseSlot) && 01412 !ReusedOperands.isClobbered(PhysReg); 01413 } 01414 01415 if (CanReuse) { 01416 // If this stack slot value is already available, reuse it! 01417 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT) 01418 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1; 01419 else 01420 DOUT << "Reusing SS#" << ReuseSlot; 01421 DOUT << " from physreg " 01422 << TRI->getName(PhysReg) << " for vreg" 01423 << VirtReg <<" instead of reloading into physreg " 01424 << TRI->getName(VRM.getPhys(VirtReg)) << "\n"; 01425 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg; 01426 MI.getOperand(i).setReg(RReg); 01427 01428 // The only technical detail we have is that we don't know that 01429 // PhysReg won't be clobbered by a reloaded stack slot that occurs 01430 // later in the instruction. In particular, consider 'op V1, V2'. 01431 // If V1 is available in physreg R0, we would choose to reuse it 01432 // here, instead of reloading it into the register the allocator 01433 // indicated (say R1). However, V2 might have to be reloaded 01434 // later, and it might indicate that it needs to live in R0. When 01435 // this occurs, we need to have information available that 01436 // indicates it is safe to use R1 for the reload instead of R0. 01437 // 01438 // To further complicate matters, we might conflict with an alias, 01439 // or R0 and R1 might not be compatible with each other. In this 01440 // case, we actually insert a reload for V1 in R1, ensuring that 01441 // we can get at R0 or its alias. 01442 ReusedOperands.addReuse(i, ReuseSlot, PhysReg, 01443 VRM.getPhys(VirtReg), VirtReg); 01444 if (ti != -1) 01445 // Only mark it clobbered if this is a use&def operand. 01446 ReusedOperands.markClobbered(PhysReg); 01447 ++NumReused; 01448 01449 if (MI.getOperand(i).isKill() && 01450 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) { 01451 01452 // The store of this spilled value is potentially dead, but we 01453 // won't know for certain until we've confirmed that the re-use 01454 // above is valid, which means waiting until the other operands 01455 // are processed. For now we just track the spill slot, we'll 01456 // remove it after the other operands are processed if valid. 01457 01458 PotentialDeadStoreSlots.push_back(ReuseSlot); 01459 } 01460 continue; 01461 } // CanReuse 01462 01463 // Otherwise we have a situation where we have a two-address instruction 01464 // whose mod/ref operand needs to be reloaded. This reload is already 01465 // available in some register "PhysReg", but if we used PhysReg as the 01466 // operand to our 2-addr instruction, the instruction would modify 01467 // PhysReg. This isn't cool if something later uses PhysReg and expects 01468 // to get its initial value. 01469 // 01470 // To avoid this problem, and to avoid doing a load right after a store, 01471 // we emit a copy from PhysReg into the designated register for this 01472 // operand. 01473 unsigned DesignatedReg = VRM.getPhys(VirtReg); 01474 assert(DesignatedReg && "Must map virtreg to physreg!"); 01475 01476 // Note that, if we reused a register for a previous operand, the 01477 // register we want to reload into might not actually be 01478 // available. If this occurs, use the register indicated by the 01479 // reuser. 01480 if (ReusedOperands.hasReuses()) 01481 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 01482 Spills, MaybeDeadStores, RegKills, KillOps, VRM); 01483 01484 // If the mapped designated register is actually the physreg we have 01485 // incoming, we don't need to inserted a dead copy. 01486 if (DesignatedReg == PhysReg) { 01487 // If this stack slot value is already available, reuse it! 01488 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT) 01489 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1; 01490 else 01491 DOUT << "Reusing SS#" << ReuseSlot; 01492 DOUT << " from physreg " << TRI->getName(PhysReg) 01493 << " for vreg" << VirtReg 01494 << " instead of reloading into same physreg.\n"; 01495 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg; 01496 MI.getOperand(i).setReg(RReg); 01497 ReusedOperands.markClobbered(RReg); 01498 ++NumReused; 01499 continue; 01500 } 01501 01502 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg); 01503 RegInfo->setPhysRegUsed(DesignatedReg); 01504 ReusedOperands.markClobbered(DesignatedReg); 01505 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC); 01506 01507 MachineInstr *CopyMI = prior(MII); 01508 UpdateKills(*CopyMI, RegKills, KillOps, TRI); 01509 01510 // This invalidates DesignatedReg. 01511 Spills.ClobberPhysReg(DesignatedReg); 01512 01513 Spills.addAvailable(ReuseSlot, &MI, DesignatedReg); 01514 unsigned RReg = 01515 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg; 01516 MI.getOperand(i).setReg(RReg); 01517 DOUT << '\t' << *prior(MII); 01518 ++NumReused; 01519 continue; 01520 } // if (PhysReg) 01521 01522 // Otherwise, reload it and remember that we have it. 01523 PhysReg = VRM.getPhys(VirtReg); 01524 assert(PhysReg && "Must map virtreg to physreg!"); 01525 01526 // Note that, if we reused a register for a previous operand, the 01527 // register we want to reload into might not actually be 01528 // available. If this occurs, use the register indicated by the 01529 // reuser. 01530 if (ReusedOperands.hasReuses()) 01531 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 01532 Spills, MaybeDeadStores, RegKills, KillOps, VRM); 01533 01534 RegInfo->setPhysRegUsed(PhysReg); 01535 ReusedOperands.markClobbered(PhysReg); 01536 if (DoReMat) { 01537 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM); 01538 } else { 01539 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg); 01540 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC); 01541 MachineInstr *LoadMI = prior(MII); 01542 VRM.addSpillSlotUse(SSorRMId, LoadMI); 01543 ++NumLoads; 01544 } 01545 // This invalidates PhysReg. 01546 Spills.ClobberPhysReg(PhysReg); 01547 01548 // Any stores to this stack slot are not dead anymore. 01549 if (!DoReMat) 01550 MaybeDeadStores[SSorRMId] = NULL; 01551 Spills.addAvailable(SSorRMId, &MI, PhysReg); 01552 // Assumes this is the last use. IsKill will be unset if reg is reused 01553 // unless it's a two-address operand. 01554 if (TID.getOperandConstraint(i, TOI::TIED_TO) == -1) 01555 MI.getOperand(i).setIsKill(); 01556 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg; 01557 MI.getOperand(i).setReg(RReg); 01558 UpdateKills(*prior(MII), RegKills, KillOps, TRI); 01559 DOUT << '\t' << *prior(MII); 01560 } 01561 01562 // Ok - now we can remove stores that have been confirmed dead. 01563 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) { 01564 // This was the last use and the spilled value is still available 01565 // for reuse. That means the spill was unnecessary! 01566 int PDSSlot = PotentialDeadStoreSlots[j]; 01567 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot]; 01568 if (DeadStore) { 01569 DOUT << "Removed dead store:\t" << *DeadStore; 01570 InvalidateKills(*DeadStore, RegKills, KillOps); 01571 VRM.RemoveMachineInstrFromMaps(DeadStore); 01572 MBB.erase(DeadStore); 01573 MaybeDeadStores[PDSSlot] = NULL; 01574 ++NumDSE; 01575 } 01576 } 01577 01578 01579 DOUT << '\t' << MI; 01580 01581 01582 // If we have folded references to memory operands, make sure we clear all 01583 // physical registers that may contain the value of the spilled virtual 01584 // register 01585 SmallSet<int, 2> FoldedSS; 01586 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) { 01587 unsigned VirtReg = I->second.first; 01588 VirtRegMap::ModRef MR = I->second.second; 01589 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR; 01590 01591 // MI2VirtMap be can updated which invalidate the iterator. 01592 // Increment the iterator first. 01593 ++I; 01594 int SS = VRM.getStackSlot(VirtReg); 01595 if (SS == VirtRegMap::NO_STACK_SLOT) 01596 continue; 01597 FoldedSS.insert(SS); 01598 DOUT << " - StackSlot: " << SS << "\n"; 01599 01600 // If this folded instruction is just a use, check to see if it's a 01601 // straight load from the virt reg slot. 01602 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) { 01603 int FrameIdx; 01604 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx); 01605 if (DestReg && FrameIdx == SS) { 01606 // If this spill slot is available, turn it into a copy (or nothing) 01607 // instead of leaving it as a load! 01608 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) { 01609 DOUT << "Promoted Load To Copy: " << MI; 01610 if (DestReg != InReg) { 01611 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg); 01612 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC); 01613 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg); 01614 unsigned SubIdx = DefMO->getSubReg(); 01615 // Revisit the copy so we make sure to notice the effects of the 01616 // operation on the destreg (either needing to RA it if it's 01617 // virtual or needing to clobber any values if it's physical). 01618 NextMII = &MI; 01619 --NextMII; // backtrack to the copy. 01620 // Propagate the sub-register index over. 01621 if (SubIdx) { 01622 DefMO = NextMII->findRegisterDefOperand(DestReg); 01623 DefMO->setSubReg(SubIdx); 01624 } 01625 BackTracked = true; 01626 } else { 01627 DOUT << "Removing now-noop copy: " << MI; 01628 // Unset last kill since it's being reused. 01629 InvalidateKill(InReg, RegKills, KillOps); 01630 } 01631 01632 InvalidateKills(MI, RegKills, KillOps); 01633 VRM.RemoveMachineInstrFromMaps(&MI); 01634 MBB.erase(&MI); 01635 Erased = true; 01636 goto ProcessNextInst; 01637 } 01638 } else { 01639 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS); 01640 SmallVector<MachineInstr*, 4> NewMIs; 01641 if (PhysReg && 01642 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) { 01643 MBB.insert(MII, NewMIs[0]); 01644 InvalidateKills(MI, RegKills, KillOps); 01645 VRM.RemoveMachineInstrFromMaps(&MI); 01646 MBB.erase(&MI); 01647 Erased = true; 01648 --NextMII; // backtrack to the unfolded instruction. 01649 BackTracked = true; 01650 goto ProcessNextInst; 01651 } 01652 } 01653 } 01654 01655 // If this reference is not a use, any previous store is now dead. 01656 // Otherwise, the store to this stack slot is not dead anymore. 01657 MachineInstr* DeadStore = MaybeDeadStores[SS]; 01658 if (DeadStore) { 01659 bool isDead = !(MR & VirtRegMap::isRef); 01660 MachineInstr *NewStore = NULL; 01661 if (MR & VirtRegMap::isModRef) { 01662 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS); 01663 SmallVector<MachineInstr*, 4> NewMIs; 01664 // We can reuse this physreg as long as we are allowed to clobber 01665 // the value and there isn't an earlier def that has already clobbered 01666 // the physreg. 01667 if (PhysReg && 01668 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable! 01669 MachineOperand *KillOpnd = 01670 DeadStore->findRegisterUseOperand(PhysReg, true); 01671 // Note, if the store is storing a sub-register, it's possible the 01672 // super-register is needed below. 01673 if (KillOpnd && !KillOpnd->getSubReg() && 01674 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){ 01675 MBB.insert(MII, NewMIs[0]); 01676 NewStore = NewMIs[1]; 01677 MBB.insert(MII, NewStore); 01678 VRM.addSpillSlotUse(SS, NewStore); 01679 InvalidateKills(MI, RegKills, KillOps); 01680 VRM.RemoveMachineInstrFromMaps(&MI); 01681 MBB.erase(&MI); 01682 Erased = true; 01683 --NextMII; 01684 --NextMII; // backtrack to the unfolded instruction. 01685 BackTracked = true; 01686 isDead = true; 01687 } 01688 } 01689 } 01690 01691 if (isDead) { // Previous store is dead. 01692 // If we get here, the store is dead, nuke it now. 01693 DOUT << "Removed dead store:\t" << *DeadStore; 01694 InvalidateKills(*DeadStore, RegKills, KillOps); 01695 VRM.RemoveMachineInstrFromMaps(DeadStore); 01696 MBB.erase(DeadStore); 01697 if (!NewStore) 01698 ++NumDSE; 01699 } 01700 01701 MaybeDeadStores[SS] = NULL; 01702 if (NewStore) { 01703 // Treat this store as a spill merged into a copy. That makes the 01704 // stack slot value available. 01705 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod); 01706 goto ProcessNextInst; 01707 } 01708 } 01709 01710 // If the spill slot value is available, and this is a new definition of 01711 // the value, the value is not available anymore. 01712 if (MR & VirtRegMap::isMod) { 01713 // Notice that the value in this stack slot has been modified. 01714 Spills.ModifyStackSlotOrReMat(SS); 01715 01716 // If this is *just* a mod of the value, check to see if this is just a 01717 // store to the spill slot (i.e. the spill got merged into the copy). If 01718 // so, realize that the vreg is available now, and add the store to the 01719 // MaybeDeadStore info. 01720 int StackSlot; 01721 if (!(MR & VirtRegMap::isRef)) { 01722 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) { 01723 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) && 01724 "Src hasn't been allocated yet?"); 01725 01726 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot, 01727 RegKills, KillOps, TRI, VRM)) { 01728 NextMII = next(MII); 01729 BackTracked = true; 01730 goto ProcessNextInst; 01731 } 01732 01733 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark 01734 // this as a potentially dead store in case there is a subsequent 01735 // store into the stack slot without a read from it. 01736 MaybeDeadStores[StackSlot] = &MI; 01737 01738 // If the stack slot value was previously available in some other 01739 // register, change it now. Otherwise, make the register 01740 // available in PhysReg. 01741 Spills.addAvailable(StackSlot, &MI, SrcReg, false/*!clobber*/); 01742 } 01743 } 01744 } 01745 } 01746 01747 // Process all of the spilled defs. 01748 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 01749 MachineOperand &MO = MI.getOperand(i); 01750 if (!(MO.isReg() && MO.getReg() && MO.isDef())) 01751 continue; 01752 01753 unsigned VirtReg = MO.getReg(); 01754 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) { 01755 // Check to see if this is a noop copy. If so, eliminate the 01756 // instruction before considering the dest reg to be changed. 01757 unsigned Src, Dst, SrcSR, DstSR; 01758 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) { 01759 ++NumDCE; 01760 DOUT << "Removing now-noop copy: " << MI; 01761 SmallVector<unsigned, 2> KillRegs; 01762 InvalidateKills(MI, RegKills, KillOps, &KillRegs); 01763 if (MO.isDead() && !KillRegs.empty()) { 01764 // Source register or an implicit super/sub-register use is killed. 01765 assert(KillRegs[0] == Dst || 01766 TRI->isSubRegister(KillRegs[0], Dst) || 01767 TRI->isSuperRegister(KillRegs[0], Dst)); 01768 // Last def is now dead. 01769 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps); 01770 } 01771 VRM.RemoveMachineInstrFromMaps(&MI); 01772 MBB.erase(&MI); 01773 Erased = true; 01774 Spills.disallowClobberPhysReg(VirtReg); 01775 goto ProcessNextInst; 01776 } 01777 01778 // If it's not a no-op copy, it clobbers the value in the destreg. 01779 Spills.ClobberPhysReg(VirtReg); 01780 ReusedOperands.markClobbered(VirtReg); 01781 01782 // Check to see if this instruction is a load from a stack slot into 01783 // a register. If so, this provides the stack slot value in the reg. 01784 int FrameIdx; 01785 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) { 01786 assert(DestReg == VirtReg && "Unknown load situation!"); 01787 01788 // If it is a folded reference, then it's not safe to clobber. 01789 bool Folded = FoldedSS.count(FrameIdx); 01790 // Otherwise, if it wasn't available, remember that it is now! 01791 Spills.addAvailable(FrameIdx, &MI, DestReg, !Folded); 01792 goto ProcessNextInst; 01793 } 01794 01795 continue; 01796 } 01797 01798 unsigned SubIdx = MO.getSubReg(); 01799 bool DoReMat = VRM.isReMaterialized(VirtReg); 01800 if (DoReMat) 01801 ReMatDefs.insert(&MI); 01802 01803 // The only vregs left are stack slot definitions. 01804 int StackSlot = VRM.getStackSlot(VirtReg); 01805 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg); 01806 01807 // If this def is part of a two-address operand, make sure to execute 01808 // the store from the correct physical register. 01809 unsigned PhysReg; 01810 int TiedOp = MI.getDesc().findTiedToSrcOperand(i); 01811 if (TiedOp != -1) { 01812 PhysReg = MI.getOperand(TiedOp).getReg(); 01813 if (SubIdx) { 01814 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI); 01815 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg && 01816 "Can't find corresponding super-register!"); 01817 PhysReg = SuperReg; 01818 } 01819 } else { 01820 PhysReg = VRM.getPhys(VirtReg); 01821 if (ReusedOperands.isClobbered(PhysReg)) { 01822 // Another def has taken the assigned physreg. It must have been a 01823 // use&def which got it due to reuse. Undo the reuse! 01824 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 01825 Spills, MaybeDeadStores, RegKills, KillOps, VRM); 01826 } 01827 } 01828 01829 assert(PhysReg && "VR not assigned a physical register?"); 01830 RegInfo->setPhysRegUsed(PhysReg); 01831 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg; 01832 ReusedOperands.markClobbered(RReg); 01833 MI.getOperand(i).setReg(RReg); 01834 01835 if (!MO.isDead()) { 01836 MachineInstr *&LastStore = MaybeDeadStores[StackSlot]; 01837 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true, 01838 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM); 01839 NextMII = next(MII); 01840 01841 // Check to see if this is a noop copy. If so, eliminate the 01842 // instruction before considering the dest reg to be changed. 01843 { 01844 unsigned Src, Dst, SrcSR, DstSR; 01845 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) { 01846 ++NumDCE; 01847 DOUT << "Removing now-noop copy: " << MI; 01848 InvalidateKills(MI, RegKills, KillOps); 01849 VRM.RemoveMachineInstrFromMaps(&MI); 01850 MBB.erase(&MI); 01851 Erased = true; 01852 UpdateKills(*LastStore, RegKills, KillOps, TRI); 01853 goto ProcessNextInst; 01854 } 01855 } 01856 } 01857 } 01858 ProcessNextInst: 01859 DistanceMap.insert(std::make_pair(&MI, Dist++)); 01860 if (!Erased && !BackTracked) { 01861 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II) 01862 UpdateKills(*II, RegKills, KillOps, TRI); 01863 } 01864 MII = NextMII; 01865 } 01866 } 01867 01868 llvm::Spiller* llvm::createSpiller() { 01869 switch (SpillerOpt) { 01870 default: assert(0 && "Unreachable!"); 01871 case local: 01872 return new LocalSpiller(); 01873 case simple: 01874 return new SimpleSpiller(); 01875 } 01876 }