Spiller.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. //===-- llvm/CodeGen/Spiller.cpp - Spiller -------------------------------===//
  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. #define DEBUG_TYPE "spiller"
  10. #include "Spiller.h"
  11. #include "VirtRegMap.h"
  12. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  13. #include "llvm/CodeGen/MachineFrameInfo.h"
  14. #include "llvm/CodeGen/MachineFunction.h"
  15. #include "llvm/CodeGen/MachineRegisterInfo.h"
  16. #include "llvm/Target/TargetMachine.h"
  17. #include "llvm/Target/TargetInstrInfo.h"
  18. #include "llvm/Support/CommandLine.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include <set>
  22. using namespace llvm;
  23. namespace {
  24. enum SpillerName { trivial, standard, splitting };
  25. }
  26. static cl::opt<SpillerName>
  27. spillerOpt("spiller",
  28. cl::desc("Spiller to use: (default: standard)"),
  29. cl::Prefix,
  30. cl::values(clEnumVal(trivial, "trivial spiller"),
  31. clEnumVal(standard, "default spiller"),
  32. clEnumVal(splitting, "splitting spiller"),
  33. clEnumValEnd),
  34. cl::init(standard));
  35. // Spiller virtual destructor implementation.
  36. Spiller::~Spiller() {}
  37. namespace {
  38. /// Utility class for spillers.
  39. class SpillerBase : public Spiller {
  40. protected:
  41. MachineFunction *mf;
  42. LiveIntervals *lis;
  43. MachineFrameInfo *mfi;
  44. MachineRegisterInfo *mri;
  45. const TargetInstrInfo *tii;
  46. VirtRegMap *vrm;
  47. /// Construct a spiller base.
  48. SpillerBase(MachineFunction *mf, LiveIntervals *lis, VirtRegMap *vrm)
  49. : mf(mf), lis(lis), vrm(vrm)
  50. {
  51. mfi = mf->getFrameInfo();
  52. mri = &mf->getRegInfo();
  53. tii = mf->getTarget().getInstrInfo();
  54. }
  55. /// Add spill ranges for every use/def of the live interval, inserting loads
  56. /// immediately before each use, and stores after each def. No folding or
  57. /// remat is attempted.
  58. std::vector<LiveInterval*> trivialSpillEverywhere(LiveInterval *li) {
  59. DEBUG(errs() << "Spilling everywhere " << *li << "\n");
  60. assert(li->weight != HUGE_VALF &&
  61. "Attempting to spill already spilled value.");
  62. assert(!li->isStackSlot() &&
  63. "Trying to spill a stack slot.");
  64. DEBUG(errs() << "Trivial spill everywhere of reg" << li->reg << "\n");
  65. std::vector<LiveInterval*> added;
  66. const TargetRegisterClass *trc = mri->getRegClass(li->reg);
  67. unsigned ss = vrm->assignVirt2StackSlot(li->reg);
  68. // Iterate over reg uses/defs.
  69. for (MachineRegisterInfo::reg_iterator
  70. regItr = mri->reg_begin(li->reg); regItr != mri->reg_end();) {
  71. // Grab the use/def instr.
  72. MachineInstr *mi = &*regItr;
  73. DEBUG(errs() << " Processing " << *mi);
  74. // Step regItr to the next use/def instr.
  75. do {
  76. ++regItr;
  77. } while (regItr != mri->reg_end() && (&*regItr == mi));
  78. // Collect uses & defs for this instr.
  79. SmallVector<unsigned, 2> indices;
  80. bool hasUse = false;
  81. bool hasDef = false;
  82. for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
  83. MachineOperand &op = mi->getOperand(i);
  84. if (!op.isReg() || op.getReg() != li->reg)
  85. continue;
  86. hasUse |= mi->getOperand(i).isUse();
  87. hasDef |= mi->getOperand(i).isDef();
  88. indices.push_back(i);
  89. }
  90. // Create a new vreg & interval for this instr.
  91. unsigned newVReg = mri->createVirtualRegister(trc);
  92. vrm->grow();
  93. vrm->assignVirt2StackSlot(newVReg, ss);
  94. LiveInterval *newLI = &lis->getOrCreateInterval(newVReg);
  95. newLI->weight = HUGE_VALF;
  96. // Update the reg operands & kill flags.
  97. for (unsigned i = 0; i < indices.size(); ++i) {
  98. unsigned mopIdx = indices[i];
  99. MachineOperand &mop = mi->getOperand(mopIdx);
  100. mop.setReg(newVReg);
  101. if (mop.isUse() && !mi->isRegTiedToDefOperand(mopIdx)) {
  102. mop.setIsKill(true);
  103. }
  104. }
  105. assert(hasUse || hasDef);
  106. // Insert reload if necessary.
  107. MachineBasicBlock::iterator miItr(mi);
  108. if (hasUse) {
  109. tii->loadRegFromStackSlot(*mi->getParent(), miItr, newVReg, ss, trc);
  110. MachineInstr *loadInstr(prior(miItr));
  111. SlotIndex loadIndex =
  112. lis->InsertMachineInstrInMaps(loadInstr).getDefIndex();
  113. SlotIndex endIndex = loadIndex.getNextIndex();
  114. VNInfo *loadVNI =
  115. newLI->getNextValue(loadIndex, 0, true, lis->getVNInfoAllocator());
  116. loadVNI->addKill(endIndex);
  117. newLI->addRange(LiveRange(loadIndex, endIndex, loadVNI));
  118. }
  119. // Insert store if necessary.
  120. if (hasDef) {
  121. tii->storeRegToStackSlot(*mi->getParent(), llvm::next(miItr), newVReg, true,
  122. ss, trc);
  123. MachineInstr *storeInstr(llvm::next(miItr));
  124. SlotIndex storeIndex =
  125. lis->InsertMachineInstrInMaps(storeInstr).getDefIndex();
  126. SlotIndex beginIndex = storeIndex.getPrevIndex();
  127. VNInfo *storeVNI =
  128. newLI->getNextValue(beginIndex, 0, true, lis->getVNInfoAllocator());
  129. storeVNI->addKill(storeIndex);
  130. newLI->addRange(LiveRange(beginIndex, storeIndex, storeVNI));
  131. }
  132. added.push_back(newLI);
  133. }
  134. return added;
  135. }
  136. };
  137. /// Spills any live range using the spill-everywhere method with no attempt at
  138. /// folding.
  139. class TrivialSpiller : public SpillerBase {
  140. public:
  141. TrivialSpiller(MachineFunction *mf, LiveIntervals *lis, VirtRegMap *vrm)
  142. : SpillerBase(mf, lis, vrm) {}
  143. std::vector<LiveInterval*> spill(LiveInterval *li,
  144. SmallVectorImpl<LiveInterval*> &spillIs,
  145. SlotIndex*) {
  146. // Ignore spillIs - we don't use it.
  147. return trivialSpillEverywhere(li);
  148. }
  149. };
  150. /// Falls back on LiveIntervals::addIntervalsForSpills.
  151. class StandardSpiller : public Spiller {
  152. protected:
  153. LiveIntervals *lis;
  154. const MachineLoopInfo *loopInfo;
  155. VirtRegMap *vrm;
  156. public:
  157. StandardSpiller(LiveIntervals *lis, const MachineLoopInfo *loopInfo,
  158. VirtRegMap *vrm)
  159. : lis(lis), loopInfo(loopInfo), vrm(vrm) {}
  160. /// Falls back on LiveIntervals::addIntervalsForSpills.
  161. std::vector<LiveInterval*> spill(LiveInterval *li,
  162. SmallVectorImpl<LiveInterval*> &spillIs,
  163. SlotIndex*) {
  164. return lis->addIntervalsForSpills(*li, spillIs, loopInfo, *vrm);
  165. }
  166. };
  167. /// When a call to spill is placed this spiller will first try to break the
  168. /// interval up into its component values (one new interval per value).
  169. /// If this fails, or if a call is placed to spill a previously split interval
  170. /// then the spiller falls back on the standard spilling mechanism.
  171. class SplittingSpiller : public StandardSpiller {
  172. public:
  173. SplittingSpiller(MachineFunction *mf, LiveIntervals *lis,
  174. const MachineLoopInfo *loopInfo, VirtRegMap *vrm)
  175. : StandardSpiller(lis, loopInfo, vrm) {
  176. mri = &mf->getRegInfo();
  177. tii = mf->getTarget().getInstrInfo();
  178. tri = mf->getTarget().getRegisterInfo();
  179. }
  180. std::vector<LiveInterval*> spill(LiveInterval *li,
  181. SmallVectorImpl<LiveInterval*> &spillIs,
  182. SlotIndex *earliestStart) {
  183. if (worthTryingToSplit(li)) {
  184. return tryVNISplit(li, earliestStart);
  185. }
  186. // else
  187. return StandardSpiller::spill(li, spillIs, earliestStart);
  188. }
  189. private:
  190. MachineRegisterInfo *mri;
  191. const TargetInstrInfo *tii;
  192. const TargetRegisterInfo *tri;
  193. DenseSet<LiveInterval*> alreadySplit;
  194. bool worthTryingToSplit(LiveInterval *li) const {
  195. return (!alreadySplit.count(li) && li->getNumValNums() > 1);
  196. }
  197. /// Try to break a LiveInterval into its component values.
  198. std::vector<LiveInterval*> tryVNISplit(LiveInterval *li,
  199. SlotIndex *earliestStart) {
  200. DEBUG(errs() << "Trying VNI split of %reg" << *li << "\n");
  201. std::vector<LiveInterval*> added;
  202. SmallVector<VNInfo*, 4> vnis;
  203. std::copy(li->vni_begin(), li->vni_end(), std::back_inserter(vnis));
  204. for (SmallVectorImpl<VNInfo*>::iterator vniItr = vnis.begin(),
  205. vniEnd = vnis.end(); vniItr != vniEnd; ++vniItr) {
  206. VNInfo *vni = *vniItr;
  207. // Skip unused VNIs, or VNIs with no kills.
  208. if (vni->isUnused() || vni->kills.empty())
  209. continue;
  210. DEBUG(errs() << " Extracted Val #" << vni->id << " as ");
  211. LiveInterval *splitInterval = extractVNI(li, vni);
  212. if (splitInterval != 0) {
  213. DEBUG(errs() << *splitInterval << "\n");
  214. added.push_back(splitInterval);
  215. alreadySplit.insert(splitInterval);
  216. if (earliestStart != 0) {
  217. if (splitInterval->beginIndex() < *earliestStart)
  218. *earliestStart = splitInterval->beginIndex();
  219. }
  220. } else {
  221. DEBUG(errs() << "0\n");
  222. }
  223. }
  224. DEBUG(errs() << "Original LI: " << *li << "\n");
  225. // If there original interval still contains some live ranges
  226. // add it to added and alreadySplit.
  227. if (!li->empty()) {
  228. added.push_back(li);
  229. alreadySplit.insert(li);
  230. if (earliestStart != 0) {
  231. if (li->beginIndex() < *earliestStart)
  232. *earliestStart = li->beginIndex();
  233. }
  234. }
  235. return added;
  236. }
  237. /// Extract the given value number from the interval.
  238. LiveInterval* extractVNI(LiveInterval *li, VNInfo *vni) const {
  239. assert(vni->isDefAccurate() || vni->isPHIDef());
  240. assert(!vni->kills.empty());
  241. // Create a new vreg and live interval, copy VNI kills & ranges over.
  242. const TargetRegisterClass *trc = mri->getRegClass(li->reg);
  243. unsigned newVReg = mri->createVirtualRegister(trc);
  244. vrm->grow();
  245. LiveInterval *newLI = &lis->getOrCreateInterval(newVReg);
  246. VNInfo *newVNI = newLI->createValueCopy(vni, lis->getVNInfoAllocator());
  247. // Start by copying all live ranges in the VN to the new interval.
  248. for (LiveInterval::iterator rItr = li->begin(), rEnd = li->end();
  249. rItr != rEnd; ++rItr) {
  250. if (rItr->valno == vni) {
  251. newLI->addRange(LiveRange(rItr->start, rItr->end, newVNI));
  252. }
  253. }
  254. // Erase the old VNI & ranges.
  255. li->removeValNo(vni);
  256. // Collect all current uses of the register belonging to the given VNI.
  257. // We'll use this to rename the register after we've dealt with the def.
  258. std::set<MachineInstr*> uses;
  259. for (MachineRegisterInfo::use_iterator
  260. useItr = mri->use_begin(li->reg), useEnd = mri->use_end();
  261. useItr != useEnd; ++useItr) {
  262. uses.insert(&*useItr);
  263. }
  264. // Process the def instruction for this VNI.
  265. if (newVNI->isPHIDef()) {
  266. // Insert a copy at the start of the MBB. The range proceeding the
  267. // copy will be attached to the original LiveInterval.
  268. MachineBasicBlock *defMBB = lis->getMBBFromIndex(newVNI->def);
  269. tii->copyRegToReg(*defMBB, defMBB->begin(), newVReg, li->reg, trc, trc);
  270. MachineInstr *copyMI = defMBB->begin();
  271. copyMI->addRegisterKilled(li->reg, tri);
  272. SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
  273. VNInfo *phiDefVNI = li->getNextValue(lis->getMBBStartIdx(defMBB),
  274. 0, false, lis->getVNInfoAllocator());
  275. phiDefVNI->setIsPHIDef(true);
  276. phiDefVNI->addKill(copyIdx.getDefIndex());
  277. li->addRange(LiveRange(phiDefVNI->def, copyIdx.getDefIndex(), phiDefVNI));
  278. LiveRange *oldPHIDefRange =
  279. newLI->getLiveRangeContaining(lis->getMBBStartIdx(defMBB));
  280. // If the old phi def starts in the middle of the range chop it up.
  281. if (oldPHIDefRange->start < lis->getMBBStartIdx(defMBB)) {
  282. LiveRange oldPHIDefRange2(copyIdx.getDefIndex(), oldPHIDefRange->end,
  283. oldPHIDefRange->valno);
  284. oldPHIDefRange->end = lis->getMBBStartIdx(defMBB);
  285. newLI->addRange(oldPHIDefRange2);
  286. } else if (oldPHIDefRange->start == lis->getMBBStartIdx(defMBB)) {
  287. // Otherwise if it's at the start of the range just trim it.
  288. oldPHIDefRange->start = copyIdx.getDefIndex();
  289. } else {
  290. assert(false && "PHI def range doesn't cover PHI def?");
  291. }
  292. newVNI->def = copyIdx.getDefIndex();
  293. newVNI->setCopy(copyMI);
  294. newVNI->setIsPHIDef(false); // not a PHI def anymore.
  295. newVNI->setIsDefAccurate(true);
  296. } else {
  297. // non-PHI def. Rename the def. If it's two-addr that means renaming the use
  298. // and inserting a new copy too.
  299. MachineInstr *defInst = lis->getInstructionFromIndex(newVNI->def);
  300. // We'll rename this now, so we can remove it from uses.
  301. uses.erase(defInst);
  302. unsigned defOpIdx = defInst->findRegisterDefOperandIdx(li->reg);
  303. bool isTwoAddr = defInst->isRegTiedToUseOperand(defOpIdx),
  304. twoAddrUseIsUndef = false;
  305. for (unsigned i = 0; i < defInst->getNumOperands(); ++i) {
  306. MachineOperand &mo = defInst->getOperand(i);
  307. if (mo.isReg() && (mo.isDef() || isTwoAddr) && (mo.getReg()==li->reg)) {
  308. mo.setReg(newVReg);
  309. if (isTwoAddr && mo.isUse() && mo.isUndef())
  310. twoAddrUseIsUndef = true;
  311. }
  312. }
  313. SlotIndex defIdx = lis->getInstructionIndex(defInst);
  314. newVNI->def = defIdx.getDefIndex();
  315. if (isTwoAddr && !twoAddrUseIsUndef) {
  316. MachineBasicBlock *defMBB = defInst->getParent();
  317. tii->copyRegToReg(*defMBB, defInst, newVReg, li->reg, trc, trc);
  318. MachineInstr *copyMI = prior(MachineBasicBlock::iterator(defInst));
  319. SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
  320. copyMI->addRegisterKilled(li->reg, tri);
  321. LiveRange *origUseRange =
  322. li->getLiveRangeContaining(newVNI->def.getUseIndex());
  323. VNInfo *origUseVNI = origUseRange->valno;
  324. origUseRange->end = copyIdx.getDefIndex();
  325. bool updatedKills = false;
  326. for (unsigned k = 0; k < origUseVNI->kills.size(); ++k) {
  327. if (origUseVNI->kills[k] == defIdx.getDefIndex()) {
  328. origUseVNI->kills[k] = copyIdx.getDefIndex();
  329. updatedKills = true;
  330. break;
  331. }
  332. }
  333. assert(updatedKills && "Failed to update VNI kill list.");
  334. VNInfo *copyVNI = newLI->getNextValue(copyIdx.getDefIndex(), copyMI,
  335. true, lis->getVNInfoAllocator());
  336. copyVNI->addKill(defIdx.getDefIndex());
  337. LiveRange copyRange(copyIdx.getDefIndex(),defIdx.getDefIndex(),copyVNI);
  338. newLI->addRange(copyRange);
  339. }
  340. }
  341. for (std::set<MachineInstr*>::iterator
  342. usesItr = uses.begin(), usesEnd = uses.end();
  343. usesItr != usesEnd; ++usesItr) {
  344. MachineInstr *useInst = *usesItr;
  345. SlotIndex useIdx = lis->getInstructionIndex(useInst);
  346. LiveRange *useRange =
  347. newLI->getLiveRangeContaining(useIdx.getUseIndex());
  348. // If this use doesn't belong to the new interval skip it.
  349. if (useRange == 0)
  350. continue;
  351. // This use doesn't belong to the VNI, skip it.
  352. if (useRange->valno != newVNI)
  353. continue;
  354. // Check if this instr is two address.
  355. unsigned useOpIdx = useInst->findRegisterUseOperandIdx(li->reg);
  356. bool isTwoAddress = useInst->isRegTiedToDefOperand(useOpIdx);
  357. // Rename uses (and defs for two-address instrs).
  358. for (unsigned i = 0; i < useInst->getNumOperands(); ++i) {
  359. MachineOperand &mo = useInst->getOperand(i);
  360. if (mo.isReg() && (mo.isUse() || isTwoAddress) &&
  361. (mo.getReg() == li->reg)) {
  362. mo.setReg(newVReg);
  363. }
  364. }
  365. // If this is a two address instruction we've got some extra work to do.
  366. if (isTwoAddress) {
  367. // We modified the def operand, so we need to copy back to the original
  368. // reg.
  369. MachineBasicBlock *useMBB = useInst->getParent();
  370. MachineBasicBlock::iterator useItr(useInst);
  371. tii->copyRegToReg(*useMBB, next(useItr), li->reg, newVReg, trc, trc);
  372. MachineInstr *copyMI = next(useItr);
  373. copyMI->addRegisterKilled(newVReg, tri);
  374. SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
  375. // Change the old two-address defined range & vni to start at
  376. // (and be defined by) the copy.
  377. LiveRange *origDefRange =
  378. li->getLiveRangeContaining(useIdx.getDefIndex());
  379. origDefRange->start = copyIdx.getDefIndex();
  380. origDefRange->valno->def = copyIdx.getDefIndex();
  381. origDefRange->valno->setCopy(copyMI);
  382. // Insert a new range & vni for the two-address-to-copy value. This
  383. // will be attached to the new live interval.
  384. VNInfo *copyVNI =
  385. newLI->getNextValue(useIdx.getDefIndex(), 0, true,
  386. lis->getVNInfoAllocator());
  387. copyVNI->addKill(copyIdx.getDefIndex());
  388. LiveRange copyRange(useIdx.getDefIndex(),copyIdx.getDefIndex(),copyVNI);
  389. newLI->addRange(copyRange);
  390. }
  391. }
  392. // Iterate over any PHI kills - we'll need to insert new copies for them.
  393. for (VNInfo::KillSet::iterator
  394. killItr = newVNI->kills.begin(), killEnd = newVNI->kills.end();
  395. killItr != killEnd; ++killItr) {
  396. SlotIndex killIdx(*killItr);
  397. if (killItr->isPHI()) {
  398. MachineBasicBlock *killMBB = lis->getMBBFromIndex(killIdx);
  399. LiveRange *oldKillRange =
  400. newLI->getLiveRangeContaining(killIdx);
  401. assert(oldKillRange != 0 && "No kill range?");
  402. tii->copyRegToReg(*killMBB, killMBB->getFirstTerminator(),
  403. li->reg, newVReg, trc, trc);
  404. MachineInstr *copyMI = prior(killMBB->getFirstTerminator());
  405. copyMI->addRegisterKilled(newVReg, tri);
  406. SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
  407. // Save the current end. We may need it to add a new range if the
  408. // current range runs of the end of the MBB.
  409. SlotIndex newKillRangeEnd = oldKillRange->end;
  410. oldKillRange->end = copyIdx.getDefIndex();
  411. if (newKillRangeEnd != lis->getMBBEndIdx(killMBB).getNextSlot()) {
  412. assert(newKillRangeEnd > lis->getMBBEndIdx(killMBB).getNextSlot() &&
  413. "PHI kill range doesn't reach kill-block end. Not sane.");
  414. newLI->addRange(LiveRange(lis->getMBBEndIdx(killMBB).getNextSlot(),
  415. newKillRangeEnd, newVNI));
  416. }
  417. *killItr = oldKillRange->end;
  418. VNInfo *newKillVNI = li->getNextValue(copyIdx.getDefIndex(),
  419. copyMI, true,
  420. lis->getVNInfoAllocator());
  421. newKillVNI->addKill(lis->getMBBTerminatorGap(killMBB));
  422. newKillVNI->setHasPHIKill(true);
  423. li->addRange(LiveRange(copyIdx.getDefIndex(),
  424. lis->getMBBEndIdx(killMBB).getNextSlot(),
  425. newKillVNI));
  426. }
  427. }
  428. newVNI->setHasPHIKill(false);
  429. return newLI;
  430. }
  431. };
  432. }
  433. llvm::Spiller* llvm::createSpiller(MachineFunction *mf, LiveIntervals *lis,
  434. const MachineLoopInfo *loopInfo,
  435. VirtRegMap *vrm) {
  436. switch (spillerOpt) {
  437. case trivial: return new TrivialSpiller(mf, lis, vrm); break;
  438. case standard: return new StandardSpiller(lis, loopInfo, vrm); break;
  439. case splitting: return new SplittingSpiller(mf, lis, loopInfo, vrm); break;
  440. default: llvm_unreachable("Unreachable!"); break;
  441. }
  442. }