RegisterScavenging.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the machine register scavenger. It can provide
  11. // information, such as unused registers, at any point in a machine basic block.
  12. // It also provides a mechanism to make registers available by evicting them to
  13. // spill slots.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #define DEBUG_TYPE "reg-scavenging"
  17. #include "llvm/CodeGen/RegisterScavenging.h"
  18. #include "llvm/CodeGen/MachineBasicBlock.h"
  19. #include "llvm/CodeGen/MachineFrameInfo.h"
  20. #include "llvm/CodeGen/MachineFunction.h"
  21. #include "llvm/CodeGen/MachineInstr.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/Target/TargetInstrInfo.h"
  27. #include "llvm/Target/TargetMachine.h"
  28. #include "llvm/Target/TargetRegisterInfo.h"
  29. using namespace llvm;
  30. /// setUsed - Set the register and its sub-registers as being used.
  31. void RegScavenger::setUsed(unsigned Reg) {
  32. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  33. SubRegs.isValid(); ++SubRegs)
  34. RegsAvailable.reset(*SubRegs);
  35. }
  36. bool RegScavenger::isAliasUsed(unsigned Reg) const {
  37. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  38. if (isUsed(*AI, *AI == Reg))
  39. return true;
  40. return false;
  41. }
  42. void RegScavenger::initRegState() {
  43. for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
  44. IE = Scavenged.end(); I != IE; ++I) {
  45. I->Reg = 0;
  46. I->Restore = NULL;
  47. }
  48. // All registers started out unused.
  49. RegsAvailable.set();
  50. if (!MBB)
  51. return;
  52. // Live-in registers are in use.
  53. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
  54. E = MBB->livein_end(); I != E; ++I)
  55. setUsed(*I);
  56. // Pristine CSRs are also unavailable.
  57. BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
  58. for (int I = PR.find_first(); I>0; I = PR.find_next(I))
  59. setUsed(I);
  60. }
  61. void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
  62. MachineFunction &MF = *mbb->getParent();
  63. const TargetMachine &TM = MF.getTarget();
  64. TII = TM.getInstrInfo();
  65. TRI = TM.getRegisterInfo();
  66. MRI = &MF.getRegInfo();
  67. assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
  68. "Target changed?");
  69. // It is not possible to use the register scavenger after late optimization
  70. // passes that don't preserve accurate liveness information.
  71. assert(MRI->tracksLiveness() &&
  72. "Cannot use register scavenger with inaccurate liveness");
  73. // Self-initialize.
  74. if (!MBB) {
  75. NumPhysRegs = TRI->getNumRegs();
  76. RegsAvailable.resize(NumPhysRegs);
  77. KillRegs.resize(NumPhysRegs);
  78. DefRegs.resize(NumPhysRegs);
  79. // Create callee-saved registers bitvector.
  80. CalleeSavedRegs.resize(NumPhysRegs);
  81. const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
  82. if (CSRegs != NULL)
  83. for (unsigned i = 0; CSRegs[i]; ++i)
  84. CalleeSavedRegs.set(CSRegs[i]);
  85. }
  86. MBB = mbb;
  87. initRegState();
  88. Tracking = false;
  89. }
  90. void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
  91. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  92. SubRegs.isValid(); ++SubRegs)
  93. BV.set(*SubRegs);
  94. }
  95. void RegScavenger::determineKillsAndDefs() {
  96. assert(Tracking && "Must be tracking to determine kills and defs");
  97. MachineInstr *MI = MBBI;
  98. assert(!MI->isDebugValue() && "Debug values have no kills or defs");
  99. // Find out which registers are early clobbered, killed, defined, and marked
  100. // def-dead in this instruction.
  101. // FIXME: The scavenger is not predication aware. If the instruction is
  102. // predicated, conservatively assume "kill" markers do not actually kill the
  103. // register. Similarly ignores "dead" markers.
  104. bool isPred = TII->isPredicated(MI);
  105. KillRegs.reset();
  106. DefRegs.reset();
  107. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  108. const MachineOperand &MO = MI->getOperand(i);
  109. if (MO.isRegMask())
  110. (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
  111. if (!MO.isReg())
  112. continue;
  113. unsigned Reg = MO.getReg();
  114. if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
  115. continue;
  116. if (MO.isUse()) {
  117. // Ignore undef uses.
  118. if (MO.isUndef())
  119. continue;
  120. if (!isPred && MO.isKill())
  121. addRegWithSubRegs(KillRegs, Reg);
  122. } else {
  123. assert(MO.isDef());
  124. if (!isPred && MO.isDead())
  125. addRegWithSubRegs(KillRegs, Reg);
  126. else
  127. addRegWithSubRegs(DefRegs, Reg);
  128. }
  129. }
  130. }
  131. void RegScavenger::unprocess() {
  132. assert(Tracking && "Cannot unprocess because we're not tracking");
  133. MachineInstr *MI = MBBI;
  134. if (!MI->isDebugValue()) {
  135. determineKillsAndDefs();
  136. // Commit the changes.
  137. setUsed(KillRegs);
  138. setUnused(DefRegs);
  139. }
  140. if (MBBI == MBB->begin()) {
  141. MBBI = MachineBasicBlock::iterator(NULL);
  142. Tracking = false;
  143. } else
  144. --MBBI;
  145. }
  146. void RegScavenger::forward() {
  147. // Move ptr forward.
  148. if (!Tracking) {
  149. MBBI = MBB->begin();
  150. Tracking = true;
  151. } else {
  152. assert(MBBI != MBB->end() && "Already past the end of the basic block!");
  153. MBBI = std::next(MBBI);
  154. }
  155. assert(MBBI != MBB->end() && "Already at the end of the basic block!");
  156. MachineInstr *MI = MBBI;
  157. for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
  158. IE = Scavenged.end(); I != IE; ++I) {
  159. if (I->Restore != MI)
  160. continue;
  161. I->Reg = 0;
  162. I->Restore = NULL;
  163. }
  164. if (MI->isDebugValue())
  165. return;
  166. determineKillsAndDefs();
  167. // Verify uses and defs.
  168. #ifndef NDEBUG
  169. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  170. const MachineOperand &MO = MI->getOperand(i);
  171. if (!MO.isReg())
  172. continue;
  173. unsigned Reg = MO.getReg();
  174. if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
  175. continue;
  176. if (MO.isUse()) {
  177. if (MO.isUndef())
  178. continue;
  179. if (!isUsed(Reg)) {
  180. // Check if it's partial live: e.g.
  181. // D0 = insert_subreg D0<undef>, S0
  182. // ... D0
  183. // The problem is the insert_subreg could be eliminated. The use of
  184. // D0 is using a partially undef value. This is not *incorrect* since
  185. // S1 is can be freely clobbered.
  186. // Ideally we would like a way to model this, but leaving the
  187. // insert_subreg around causes both correctness and performance issues.
  188. bool SubUsed = false;
  189. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  190. if (isUsed(*SubRegs)) {
  191. SubUsed = true;
  192. break;
  193. }
  194. if (!SubUsed) {
  195. MBB->getParent()->verify(NULL, "In Register Scavenger");
  196. llvm_unreachable("Using an undefined register!");
  197. }
  198. (void)SubUsed;
  199. }
  200. } else {
  201. assert(MO.isDef());
  202. #if 0
  203. // FIXME: Enable this once we've figured out how to correctly transfer
  204. // implicit kills during codegen passes like the coalescer.
  205. assert((KillRegs.test(Reg) || isUnused(Reg) ||
  206. isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
  207. "Re-defining a live register!");
  208. #endif
  209. }
  210. }
  211. #endif // NDEBUG
  212. // Commit the changes.
  213. setUnused(KillRegs);
  214. setUsed(DefRegs);
  215. }
  216. void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
  217. used = RegsAvailable;
  218. used.flip();
  219. if (includeReserved)
  220. used |= MRI->getReservedRegs();
  221. else
  222. used.reset(MRI->getReservedRegs());
  223. }
  224. unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
  225. for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
  226. I != E; ++I)
  227. if (!isAliasUsed(*I)) {
  228. DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
  229. "\n");
  230. return *I;
  231. }
  232. return 0;
  233. }
  234. /// getRegsAvailable - Return all available registers in the register class
  235. /// in Mask.
  236. BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
  237. BitVector Mask(TRI->getNumRegs());
  238. for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
  239. I != E; ++I)
  240. if (!isAliasUsed(*I))
  241. Mask.set(*I);
  242. return Mask;
  243. }
  244. /// findSurvivorReg - Return the candidate register that is unused for the
  245. /// longest after StargMII. UseMI is set to the instruction where the search
  246. /// stopped.
  247. ///
  248. /// No more than InstrLimit instructions are inspected.
  249. ///
  250. unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
  251. BitVector &Candidates,
  252. unsigned InstrLimit,
  253. MachineBasicBlock::iterator &UseMI) {
  254. int Survivor = Candidates.find_first();
  255. assert(Survivor > 0 && "No candidates for scavenging");
  256. MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
  257. assert(StartMI != ME && "MI already at terminator");
  258. MachineBasicBlock::iterator RestorePointMI = StartMI;
  259. MachineBasicBlock::iterator MI = StartMI;
  260. bool inVirtLiveRange = false;
  261. for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
  262. if (MI->isDebugValue()) {
  263. ++InstrLimit; // Don't count debug instructions
  264. continue;
  265. }
  266. bool isVirtKillInsn = false;
  267. bool isVirtDefInsn = false;
  268. // Remove any candidates touched by instruction.
  269. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  270. const MachineOperand &MO = MI->getOperand(i);
  271. if (MO.isRegMask())
  272. Candidates.clearBitsNotInMask(MO.getRegMask());
  273. if (!MO.isReg() || MO.isUndef() || !MO.getReg())
  274. continue;
  275. if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  276. if (MO.isDef())
  277. isVirtDefInsn = true;
  278. else if (MO.isKill())
  279. isVirtKillInsn = true;
  280. continue;
  281. }
  282. for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
  283. Candidates.reset(*AI);
  284. }
  285. // If we're not in a virtual reg's live range, this is a valid
  286. // restore point.
  287. if (!inVirtLiveRange) RestorePointMI = MI;
  288. // Update whether we're in the live range of a virtual register
  289. if (isVirtKillInsn) inVirtLiveRange = false;
  290. if (isVirtDefInsn) inVirtLiveRange = true;
  291. // Was our survivor untouched by this instruction?
  292. if (Candidates.test(Survivor))
  293. continue;
  294. // All candidates gone?
  295. if (Candidates.none())
  296. break;
  297. Survivor = Candidates.find_first();
  298. }
  299. // If we ran off the end, that's where we want to restore.
  300. if (MI == ME) RestorePointMI = ME;
  301. assert (RestorePointMI != StartMI &&
  302. "No available scavenger restore location!");
  303. // We ran out of candidates, so stop the search.
  304. UseMI = RestorePointMI;
  305. return Survivor;
  306. }
  307. static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
  308. unsigned i = 0;
  309. while (!MI->getOperand(i).isFI()) {
  310. ++i;
  311. assert(i < MI->getNumOperands() &&
  312. "Instr doesn't have FrameIndex operand!");
  313. }
  314. return i;
  315. }
  316. unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
  317. MachineBasicBlock::iterator I,
  318. int SPAdj) {
  319. // Consider all allocatable registers in the register class initially
  320. BitVector Candidates =
  321. TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
  322. // Exclude all the registers being used by the instruction.
  323. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  324. MachineOperand &MO = I->getOperand(i);
  325. if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
  326. !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  327. Candidates.reset(MO.getReg());
  328. }
  329. // Try to find a register that's unused if there is one, as then we won't
  330. // have to spill. Search explicitly rather than masking out based on
  331. // RegsAvailable, as RegsAvailable does not take aliases into account.
  332. // That's what getRegsAvailable() is for.
  333. BitVector Available = getRegsAvailable(RC);
  334. Available &= Candidates;
  335. if (Available.any())
  336. Candidates = Available;
  337. // Find the register whose use is furthest away.
  338. MachineBasicBlock::iterator UseMI;
  339. unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
  340. // If we found an unused register there is no reason to spill it.
  341. if (!isAliasUsed(SReg)) {
  342. DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
  343. return SReg;
  344. }
  345. // Find an available scavenging slot.
  346. unsigned SI;
  347. for (SI = 0; SI < Scavenged.size(); ++SI)
  348. if (Scavenged[SI].Reg == 0)
  349. break;
  350. if (SI == Scavenged.size()) {
  351. // We need to scavenge a register but have no spill slot, the target
  352. // must know how to do it (if not, we'll assert below).
  353. Scavenged.push_back(ScavengedInfo());
  354. }
  355. // Avoid infinite regress
  356. Scavenged[SI].Reg = SReg;
  357. // If the target knows how to save/restore the register, let it do so;
  358. // otherwise, use the emergency stack spill slot.
  359. if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
  360. // Spill the scavenged register before I.
  361. assert(Scavenged[SI].FrameIndex >= 0 &&
  362. "Cannot scavenge register without an emergency spill slot!");
  363. TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
  364. RC, TRI);
  365. MachineBasicBlock::iterator II = std::prev(I);
  366. unsigned FIOperandNum = getFrameIndexOperandNum(II);
  367. TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
  368. // Restore the scavenged register before its use (or first terminator).
  369. TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
  370. RC, TRI);
  371. II = std::prev(UseMI);
  372. FIOperandNum = getFrameIndexOperandNum(II);
  373. TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
  374. }
  375. Scavenged[SI].Restore = std::prev(UseMI);
  376. // Doing this here leads to infinite regress.
  377. // Scavenged[SI].Reg = SReg;
  378. DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
  379. "\n");
  380. return SReg;
  381. }