2
0

SplitKit.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
  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 contains the SplitAnalysis class as well as mutator functions for
  11. // live range splitting.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "SplitKit.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  17. #include "llvm/CodeGen/LiveRangeEdit.h"
  18. #include "llvm/CodeGen/MachineDominators.h"
  19. #include "llvm/CodeGen/MachineInstrBuilder.h"
  20. #include "llvm/CodeGen/MachineLoopInfo.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/VirtRegMap.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "llvm/Target/TargetInstrInfo.h"
  26. #include "llvm/Target/TargetMachine.h"
  27. using namespace llvm;
  28. #define DEBUG_TYPE "regalloc"
  29. STATISTIC(NumFinished, "Number of splits finished");
  30. STATISTIC(NumSimple, "Number of splits that were simple");
  31. STATISTIC(NumCopies, "Number of copies inserted for splitting");
  32. STATISTIC(NumRemats, "Number of rematerialized defs for splitting");
  33. STATISTIC(NumRepairs, "Number of invalid live ranges repaired");
  34. //===----------------------------------------------------------------------===//
  35. // Split Analysis
  36. //===----------------------------------------------------------------------===//
  37. SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
  38. const MachineLoopInfo &mli)
  39. : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
  40. TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr),
  41. LastSplitPoint(MF.getNumBlockIDs()) {}
  42. void SplitAnalysis::clear() {
  43. UseSlots.clear();
  44. UseBlocks.clear();
  45. ThroughBlocks.clear();
  46. CurLI = nullptr;
  47. DidRepairRange = false;
  48. }
  49. SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) {
  50. const MachineBasicBlock *MBB = MF.getBlockNumbered(Num);
  51. const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor();
  52. std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num];
  53. SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
  54. // Compute split points on the first call. The pair is independent of the
  55. // current live interval.
  56. if (!LSP.first.isValid()) {
  57. MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator();
  58. if (FirstTerm == MBB->end())
  59. LSP.first = MBBEnd;
  60. else
  61. LSP.first = LIS.getInstructionIndex(FirstTerm);
  62. // If there is a landing pad successor, also find the call instruction.
  63. if (!LPad)
  64. return LSP.first;
  65. // There may not be a call instruction (?) in which case we ignore LPad.
  66. LSP.second = LSP.first;
  67. for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin();
  68. I != E;) {
  69. --I;
  70. if (I->isCall()) {
  71. LSP.second = LIS.getInstructionIndex(I);
  72. break;
  73. }
  74. }
  75. }
  76. // If CurLI is live into a landing pad successor, move the last split point
  77. // back to the call that may throw.
  78. if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
  79. return LSP.first;
  80. // Find the value leaving MBB.
  81. const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd);
  82. if (!VNI)
  83. return LSP.first;
  84. // If the value leaving MBB was defined after the call in MBB, it can't
  85. // really be live-in to the landing pad. This can happen if the landing pad
  86. // has a PHI, and this register is undef on the exceptional edge.
  87. // <rdar://problem/10664933>
  88. if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd)
  89. return LSP.first;
  90. // Value is properly live-in to the landing pad.
  91. // Only allow splits before the call.
  92. return LSP.second;
  93. }
  94. MachineBasicBlock::iterator
  95. SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
  96. SlotIndex LSP = getLastSplitPoint(MBB->getNumber());
  97. if (LSP == LIS.getMBBEndIdx(MBB))
  98. return MBB->end();
  99. return LIS.getInstructionFromIndex(LSP);
  100. }
  101. /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
  102. void SplitAnalysis::analyzeUses() {
  103. assert(UseSlots.empty() && "Call clear first");
  104. // First get all the defs from the interval values. This provides the correct
  105. // slots for early clobbers.
  106. for (const VNInfo *VNI : CurLI->valnos)
  107. if (!VNI->isPHIDef() && !VNI->isUnused())
  108. UseSlots.push_back(VNI->def);
  109. // Get use slots form the use-def chain.
  110. const MachineRegisterInfo &MRI = MF.getRegInfo();
  111. for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg))
  112. if (!MO.isUndef())
  113. UseSlots.push_back(LIS.getInstructionIndex(MO.getParent()).getRegSlot());
  114. array_pod_sort(UseSlots.begin(), UseSlots.end());
  115. // Remove duplicates, keeping the smaller slot for each instruction.
  116. // That is what we want for early clobbers.
  117. UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
  118. SlotIndex::isSameInstr),
  119. UseSlots.end());
  120. // Compute per-live block info.
  121. if (!calcLiveBlockInfo()) {
  122. // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
  123. // I am looking at you, RegisterCoalescer!
  124. DidRepairRange = true;
  125. ++NumRepairs;
  126. DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
  127. const_cast<LiveIntervals&>(LIS)
  128. .shrinkToUses(const_cast<LiveInterval*>(CurLI));
  129. UseBlocks.clear();
  130. ThroughBlocks.clear();
  131. bool fixed = calcLiveBlockInfo();
  132. (void)fixed;
  133. assert(fixed && "Couldn't fix broken live interval");
  134. }
  135. DEBUG(dbgs() << "Analyze counted "
  136. << UseSlots.size() << " instrs in "
  137. << UseBlocks.size() << " blocks, through "
  138. << NumThroughBlocks << " blocks.\n");
  139. }
  140. /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
  141. /// where CurLI is live.
  142. bool SplitAnalysis::calcLiveBlockInfo() {
  143. ThroughBlocks.resize(MF.getNumBlockIDs());
  144. NumThroughBlocks = NumGapBlocks = 0;
  145. if (CurLI->empty())
  146. return true;
  147. LiveInterval::const_iterator LVI = CurLI->begin();
  148. LiveInterval::const_iterator LVE = CurLI->end();
  149. SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
  150. UseI = UseSlots.begin();
  151. UseE = UseSlots.end();
  152. // Loop over basic blocks where CurLI is live.
  153. MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
  154. for (;;) {
  155. BlockInfo BI;
  156. BI.MBB = MFI;
  157. SlotIndex Start, Stop;
  158. std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
  159. // If the block contains no uses, the range must be live through. At one
  160. // point, RegisterCoalescer could create dangling ranges that ended
  161. // mid-block.
  162. if (UseI == UseE || *UseI >= Stop) {
  163. ++NumThroughBlocks;
  164. ThroughBlocks.set(BI.MBB->getNumber());
  165. // The range shouldn't end mid-block if there are no uses. This shouldn't
  166. // happen.
  167. if (LVI->end < Stop)
  168. return false;
  169. } else {
  170. // This block has uses. Find the first and last uses in the block.
  171. BI.FirstInstr = *UseI;
  172. assert(BI.FirstInstr >= Start);
  173. do ++UseI;
  174. while (UseI != UseE && *UseI < Stop);
  175. BI.LastInstr = UseI[-1];
  176. assert(BI.LastInstr < Stop);
  177. // LVI is the first live segment overlapping MBB.
  178. BI.LiveIn = LVI->start <= Start;
  179. // When not live in, the first use should be a def.
  180. if (!BI.LiveIn) {
  181. assert(LVI->start == LVI->valno->def && "Dangling Segment start");
  182. assert(LVI->start == BI.FirstInstr && "First instr should be a def");
  183. BI.FirstDef = BI.FirstInstr;
  184. }
  185. // Look for gaps in the live range.
  186. BI.LiveOut = true;
  187. while (LVI->end < Stop) {
  188. SlotIndex LastStop = LVI->end;
  189. if (++LVI == LVE || LVI->start >= Stop) {
  190. BI.LiveOut = false;
  191. BI.LastInstr = LastStop;
  192. break;
  193. }
  194. if (LastStop < LVI->start) {
  195. // There is a gap in the live range. Create duplicate entries for the
  196. // live-in snippet and the live-out snippet.
  197. ++NumGapBlocks;
  198. // Push the Live-in part.
  199. BI.LiveOut = false;
  200. UseBlocks.push_back(BI);
  201. UseBlocks.back().LastInstr = LastStop;
  202. // Set up BI for the live-out part.
  203. BI.LiveIn = false;
  204. BI.LiveOut = true;
  205. BI.FirstInstr = BI.FirstDef = LVI->start;
  206. }
  207. // A Segment that starts in the middle of the block must be a def.
  208. assert(LVI->start == LVI->valno->def && "Dangling Segment start");
  209. if (!BI.FirstDef)
  210. BI.FirstDef = LVI->start;
  211. }
  212. UseBlocks.push_back(BI);
  213. // LVI is now at LVE or LVI->end >= Stop.
  214. if (LVI == LVE)
  215. break;
  216. }
  217. // Live segment ends exactly at Stop. Move to the next segment.
  218. if (LVI->end == Stop && ++LVI == LVE)
  219. break;
  220. // Pick the next basic block.
  221. if (LVI->start < Stop)
  222. ++MFI;
  223. else
  224. MFI = LIS.getMBBFromIndex(LVI->start);
  225. }
  226. assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
  227. return true;
  228. }
  229. unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
  230. if (cli->empty())
  231. return 0;
  232. LiveInterval *li = const_cast<LiveInterval*>(cli);
  233. LiveInterval::iterator LVI = li->begin();
  234. LiveInterval::iterator LVE = li->end();
  235. unsigned Count = 0;
  236. // Loop over basic blocks where li is live.
  237. MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
  238. SlotIndex Stop = LIS.getMBBEndIdx(MFI);
  239. for (;;) {
  240. ++Count;
  241. LVI = li->advanceTo(LVI, Stop);
  242. if (LVI == LVE)
  243. return Count;
  244. do {
  245. ++MFI;
  246. Stop = LIS.getMBBEndIdx(MFI);
  247. } while (Stop <= LVI->start);
  248. }
  249. }
  250. bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
  251. unsigned OrigReg = VRM.getOriginal(CurLI->reg);
  252. const LiveInterval &Orig = LIS.getInterval(OrigReg);
  253. assert(!Orig.empty() && "Splitting empty interval?");
  254. LiveInterval::const_iterator I = Orig.find(Idx);
  255. // Range containing Idx should begin at Idx.
  256. if (I != Orig.end() && I->start <= Idx)
  257. return I->start == Idx;
  258. // Range does not contain Idx, previous must end at Idx.
  259. return I != Orig.begin() && (--I)->end == Idx;
  260. }
  261. void SplitAnalysis::analyze(const LiveInterval *li) {
  262. clear();
  263. CurLI = li;
  264. analyzeUses();
  265. }
  266. //===----------------------------------------------------------------------===//
  267. // Split Editor
  268. //===----------------------------------------------------------------------===//
  269. /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
  270. SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
  271. MachineDominatorTree &mdt,
  272. MachineBlockFrequencyInfo &mbfi)
  273. : SA(sa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()),
  274. MDT(mdt), TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()),
  275. TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()),
  276. MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition),
  277. RegAssign(Allocator) {}
  278. void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
  279. Edit = &LRE;
  280. SpillMode = SM;
  281. OpenIdx = 0;
  282. RegAssign.clear();
  283. Values.clear();
  284. // Reset the LiveRangeCalc instances needed for this spill mode.
  285. LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
  286. &LIS.getVNInfoAllocator());
  287. if (SpillMode)
  288. LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
  289. &LIS.getVNInfoAllocator());
  290. // We don't need an AliasAnalysis since we will only be performing
  291. // cheap-as-a-copy remats anyway.
  292. Edit->anyRematerializable(nullptr);
  293. }
  294. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  295. void SplitEditor::dump() const {
  296. if (RegAssign.empty()) {
  297. dbgs() << " empty\n";
  298. return;
  299. }
  300. for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
  301. dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
  302. dbgs() << '\n';
  303. }
  304. #endif
  305. VNInfo *SplitEditor::defValue(unsigned RegIdx,
  306. const VNInfo *ParentVNI,
  307. SlotIndex Idx) {
  308. assert(ParentVNI && "Mapping NULL value");
  309. assert(Idx.isValid() && "Invalid SlotIndex");
  310. assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
  311. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  312. // Create a new value.
  313. VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
  314. // Use insert for lookup, so we can add missing values with a second lookup.
  315. std::pair<ValueMap::iterator, bool> InsP =
  316. Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
  317. ValueForcePair(VNI, false)));
  318. // This was the first time (RegIdx, ParentVNI) was mapped.
  319. // Keep it as a simple def without any liveness.
  320. if (InsP.second)
  321. return VNI;
  322. // If the previous value was a simple mapping, add liveness for it now.
  323. if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
  324. SlotIndex Def = OldVNI->def;
  325. LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI));
  326. // No longer a simple mapping. Switch to a complex, non-forced mapping.
  327. InsP.first->second = ValueForcePair();
  328. }
  329. // This is a complex mapping, add liveness for VNI
  330. SlotIndex Def = VNI->def;
  331. LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
  332. return VNI;
  333. }
  334. void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
  335. assert(ParentVNI && "Mapping NULL value");
  336. ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
  337. VNInfo *VNI = VFP.getPointer();
  338. // ParentVNI was either unmapped or already complex mapped. Either way, just
  339. // set the force bit.
  340. if (!VNI) {
  341. VFP.setInt(true);
  342. return;
  343. }
  344. // This was previously a single mapping. Make sure the old def is represented
  345. // by a trivial live range.
  346. SlotIndex Def = VNI->def;
  347. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  348. LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
  349. // Mark as complex mapped, forced.
  350. VFP = ValueForcePair(nullptr, true);
  351. }
  352. VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
  353. VNInfo *ParentVNI,
  354. SlotIndex UseIdx,
  355. MachineBasicBlock &MBB,
  356. MachineBasicBlock::iterator I) {
  357. MachineInstr *CopyMI = nullptr;
  358. SlotIndex Def;
  359. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  360. // We may be trying to avoid interference that ends at a deleted instruction,
  361. // so always begin RegIdx 0 early and all others late.
  362. bool Late = RegIdx != 0;
  363. // Attempt cheap-as-a-copy rematerialization.
  364. LiveRangeEdit::Remat RM(ParentVNI);
  365. if (Edit->canRematerializeAt(RM, UseIdx, true)) {
  366. Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
  367. ++NumRemats;
  368. } else {
  369. // Can't remat, just insert a copy from parent.
  370. CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
  371. .addReg(Edit->getReg());
  372. Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
  373. .getRegSlot();
  374. ++NumCopies;
  375. }
  376. // Define the value in Reg.
  377. return defValue(RegIdx, ParentVNI, Def);
  378. }
  379. /// Create a new virtual register and live interval.
  380. unsigned SplitEditor::openIntv() {
  381. // Create the complement as index 0.
  382. if (Edit->empty())
  383. Edit->createEmptyInterval();
  384. // Create the open interval.
  385. OpenIdx = Edit->size();
  386. Edit->createEmptyInterval();
  387. return OpenIdx;
  388. }
  389. void SplitEditor::selectIntv(unsigned Idx) {
  390. assert(Idx != 0 && "Cannot select the complement interval");
  391. assert(Idx < Edit->size() && "Can only select previously opened interval");
  392. DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n');
  393. OpenIdx = Idx;
  394. }
  395. SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
  396. assert(OpenIdx && "openIntv not called before enterIntvBefore");
  397. DEBUG(dbgs() << " enterIntvBefore " << Idx);
  398. Idx = Idx.getBaseIndex();
  399. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
  400. if (!ParentVNI) {
  401. DEBUG(dbgs() << ": not live\n");
  402. return Idx;
  403. }
  404. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  405. MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
  406. assert(MI && "enterIntvBefore called with invalid index");
  407. VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
  408. return VNI->def;
  409. }
  410. SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
  411. assert(OpenIdx && "openIntv not called before enterIntvAfter");
  412. DEBUG(dbgs() << " enterIntvAfter " << Idx);
  413. Idx = Idx.getBoundaryIndex();
  414. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
  415. if (!ParentVNI) {
  416. DEBUG(dbgs() << ": not live\n");
  417. return Idx;
  418. }
  419. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  420. MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
  421. assert(MI && "enterIntvAfter called with invalid index");
  422. VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
  423. std::next(MachineBasicBlock::iterator(MI)));
  424. return VNI->def;
  425. }
  426. SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
  427. assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
  428. SlotIndex End = LIS.getMBBEndIdx(&MBB);
  429. SlotIndex Last = End.getPrevSlot();
  430. DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
  431. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
  432. if (!ParentVNI) {
  433. DEBUG(dbgs() << ": not live\n");
  434. return End;
  435. }
  436. DEBUG(dbgs() << ": valno " << ParentVNI->id);
  437. VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
  438. SA.getLastSplitPointIter(&MBB));
  439. RegAssign.insert(VNI->def, End, OpenIdx);
  440. DEBUG(dump());
  441. return VNI->def;
  442. }
  443. /// useIntv - indicate that all instructions in MBB should use OpenLI.
  444. void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
  445. useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
  446. }
  447. void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
  448. assert(OpenIdx && "openIntv not called before useIntv");
  449. DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
  450. RegAssign.insert(Start, End, OpenIdx);
  451. DEBUG(dump());
  452. }
  453. SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
  454. assert(OpenIdx && "openIntv not called before leaveIntvAfter");
  455. DEBUG(dbgs() << " leaveIntvAfter " << Idx);
  456. // The interval must be live beyond the instruction at Idx.
  457. SlotIndex Boundary = Idx.getBoundaryIndex();
  458. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
  459. if (!ParentVNI) {
  460. DEBUG(dbgs() << ": not live\n");
  461. return Boundary.getNextSlot();
  462. }
  463. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  464. MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
  465. assert(MI && "No instruction at index");
  466. // In spill mode, make live ranges as short as possible by inserting the copy
  467. // before MI. This is only possible if that instruction doesn't redefine the
  468. // value. The inserted COPY is not a kill, and we don't need to recompute
  469. // the source live range. The spiller also won't try to hoist this copy.
  470. if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
  471. MI->readsVirtualRegister(Edit->getReg())) {
  472. forceRecompute(0, ParentVNI);
  473. defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
  474. return Idx;
  475. }
  476. VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
  477. std::next(MachineBasicBlock::iterator(MI)));
  478. return VNI->def;
  479. }
  480. SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
  481. assert(OpenIdx && "openIntv not called before leaveIntvBefore");
  482. DEBUG(dbgs() << " leaveIntvBefore " << Idx);
  483. // The interval must be live into the instruction at Idx.
  484. Idx = Idx.getBaseIndex();
  485. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
  486. if (!ParentVNI) {
  487. DEBUG(dbgs() << ": not live\n");
  488. return Idx.getNextSlot();
  489. }
  490. DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
  491. MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
  492. assert(MI && "No instruction at index");
  493. VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
  494. return VNI->def;
  495. }
  496. SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
  497. assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
  498. SlotIndex Start = LIS.getMBBStartIdx(&MBB);
  499. DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
  500. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
  501. if (!ParentVNI) {
  502. DEBUG(dbgs() << ": not live\n");
  503. return Start;
  504. }
  505. VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
  506. MBB.SkipPHIsAndLabels(MBB.begin()));
  507. RegAssign.insert(Start, VNI->def, OpenIdx);
  508. DEBUG(dump());
  509. return VNI->def;
  510. }
  511. void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
  512. assert(OpenIdx && "openIntv not called before overlapIntv");
  513. const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
  514. assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
  515. "Parent changes value in extended range");
  516. assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
  517. "Range cannot span basic blocks");
  518. // The complement interval will be extended as needed by LRCalc.extend().
  519. if (ParentVNI)
  520. forceRecompute(0, ParentVNI);
  521. DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
  522. RegAssign.insert(Start, End, OpenIdx);
  523. DEBUG(dump());
  524. }
  525. //===----------------------------------------------------------------------===//
  526. // Spill modes
  527. //===----------------------------------------------------------------------===//
  528. void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
  529. LiveInterval *LI = &LIS.getInterval(Edit->get(0));
  530. DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
  531. RegAssignMap::iterator AssignI;
  532. AssignI.setMap(RegAssign);
  533. for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
  534. SlotIndex Def = Copies[i]->def;
  535. MachineInstr *MI = LIS.getInstructionFromIndex(Def);
  536. assert(MI && "No instruction for back-copy");
  537. MachineBasicBlock *MBB = MI->getParent();
  538. MachineBasicBlock::iterator MBBI(MI);
  539. bool AtBegin;
  540. do AtBegin = MBBI == MBB->begin();
  541. while (!AtBegin && (--MBBI)->isDebugValue());
  542. DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
  543. LIS.removeVRegDefAt(*LI, Def);
  544. LIS.RemoveMachineInstrFromMaps(MI);
  545. MI->eraseFromParent();
  546. // Adjust RegAssign if a register assignment is killed at Def. We want to
  547. // avoid calculating the live range of the source register if possible.
  548. AssignI.find(Def.getPrevSlot());
  549. if (!AssignI.valid() || AssignI.start() >= Def)
  550. continue;
  551. // If MI doesn't kill the assigned register, just leave it.
  552. if (AssignI.stop() != Def)
  553. continue;
  554. unsigned RegIdx = AssignI.value();
  555. if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
  556. DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n');
  557. forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
  558. } else {
  559. SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot();
  560. DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI);
  561. AssignI.setStop(Kill);
  562. }
  563. }
  564. }
  565. MachineBasicBlock*
  566. SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
  567. MachineBasicBlock *DefMBB) {
  568. if (MBB == DefMBB)
  569. return MBB;
  570. assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
  571. const MachineLoopInfo &Loops = SA.Loops;
  572. const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
  573. MachineDomTreeNode *DefDomNode = MDT[DefMBB];
  574. // Best candidate so far.
  575. MachineBasicBlock *BestMBB = MBB;
  576. unsigned BestDepth = UINT_MAX;
  577. for (;;) {
  578. const MachineLoop *Loop = Loops.getLoopFor(MBB);
  579. // MBB isn't in a loop, it doesn't get any better. All dominators have a
  580. // higher frequency by definition.
  581. if (!Loop) {
  582. DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
  583. << MBB->getNumber() << " at depth 0\n");
  584. return MBB;
  585. }
  586. // We'll never be able to exit the DefLoop.
  587. if (Loop == DefLoop) {
  588. DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
  589. << MBB->getNumber() << " in the same loop\n");
  590. return MBB;
  591. }
  592. // Least busy dominator seen so far.
  593. unsigned Depth = Loop->getLoopDepth();
  594. if (Depth < BestDepth) {
  595. BestMBB = MBB;
  596. BestDepth = Depth;
  597. DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
  598. << MBB->getNumber() << " at depth " << Depth << '\n');
  599. }
  600. // Leave loop by going to the immediate dominator of the loop header.
  601. // This is a bigger stride than simply walking up the dominator tree.
  602. MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
  603. // Too far up the dominator tree?
  604. if (!IDom || !MDT.dominates(DefDomNode, IDom))
  605. return BestMBB;
  606. MBB = IDom->getBlock();
  607. }
  608. }
  609. void SplitEditor::hoistCopiesForSize() {
  610. // Get the complement interval, always RegIdx 0.
  611. LiveInterval *LI = &LIS.getInterval(Edit->get(0));
  612. LiveInterval *Parent = &Edit->getParent();
  613. // Track the nearest common dominator for all back-copies for each ParentVNI,
  614. // indexed by ParentVNI->id.
  615. typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
  616. SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
  617. // Find the nearest common dominator for parent values with multiple
  618. // back-copies. If a single back-copy dominates, put it in DomPair.second.
  619. for (VNInfo *VNI : LI->valnos) {
  620. if (VNI->isUnused())
  621. continue;
  622. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
  623. assert(ParentVNI && "Parent not live at complement def");
  624. // Don't hoist remats. The complement is probably going to disappear
  625. // completely anyway.
  626. if (Edit->didRematerialize(ParentVNI))
  627. continue;
  628. MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
  629. DomPair &Dom = NearestDom[ParentVNI->id];
  630. // Keep directly defined parent values. This is either a PHI or an
  631. // instruction in the complement range. All other copies of ParentVNI
  632. // should be eliminated.
  633. if (VNI->def == ParentVNI->def) {
  634. DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
  635. Dom = DomPair(ValMBB, VNI->def);
  636. continue;
  637. }
  638. // Skip the singly mapped values. There is nothing to gain from hoisting a
  639. // single back-copy.
  640. if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
  641. DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
  642. continue;
  643. }
  644. if (!Dom.first) {
  645. // First time we see ParentVNI. VNI dominates itself.
  646. Dom = DomPair(ValMBB, VNI->def);
  647. } else if (Dom.first == ValMBB) {
  648. // Two defs in the same block. Pick the earlier def.
  649. if (!Dom.second.isValid() || VNI->def < Dom.second)
  650. Dom.second = VNI->def;
  651. } else {
  652. // Different basic blocks. Check if one dominates.
  653. MachineBasicBlock *Near =
  654. MDT.findNearestCommonDominator(Dom.first, ValMBB);
  655. if (Near == ValMBB)
  656. // Def ValMBB dominates.
  657. Dom = DomPair(ValMBB, VNI->def);
  658. else if (Near != Dom.first)
  659. // None dominate. Hoist to common dominator, need new def.
  660. Dom = DomPair(Near, SlotIndex());
  661. }
  662. DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
  663. << " for parent " << ParentVNI->id << '@' << ParentVNI->def
  664. << " hoist to BB#" << Dom.first->getNumber() << ' '
  665. << Dom.second << '\n');
  666. }
  667. // Insert the hoisted copies.
  668. for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
  669. DomPair &Dom = NearestDom[i];
  670. if (!Dom.first || Dom.second.isValid())
  671. continue;
  672. // This value needs a hoisted copy inserted at the end of Dom.first.
  673. VNInfo *ParentVNI = Parent->getValNumInfo(i);
  674. MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
  675. // Get a less loopy dominator than Dom.first.
  676. Dom.first = findShallowDominator(Dom.first, DefMBB);
  677. SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
  678. Dom.second =
  679. defFromParent(0, ParentVNI, Last, *Dom.first,
  680. SA.getLastSplitPointIter(Dom.first))->def;
  681. }
  682. // Remove redundant back-copies that are now known to be dominated by another
  683. // def with the same value.
  684. SmallVector<VNInfo*, 8> BackCopies;
  685. for (VNInfo *VNI : LI->valnos) {
  686. if (VNI->isUnused())
  687. continue;
  688. VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
  689. const DomPair &Dom = NearestDom[ParentVNI->id];
  690. if (!Dom.first || Dom.second == VNI->def)
  691. continue;
  692. BackCopies.push_back(VNI);
  693. forceRecompute(0, ParentVNI);
  694. }
  695. removeBackCopies(BackCopies);
  696. }
  697. /// transferValues - Transfer all possible values to the new live ranges.
  698. /// Values that were rematerialized are left alone, they need LRCalc.extend().
  699. bool SplitEditor::transferValues() {
  700. bool Skipped = false;
  701. RegAssignMap::const_iterator AssignI = RegAssign.begin();
  702. for (const LiveRange::Segment &S : Edit->getParent()) {
  703. DEBUG(dbgs() << " blit " << S << ':');
  704. VNInfo *ParentVNI = S.valno;
  705. // RegAssign has holes where RegIdx 0 should be used.
  706. SlotIndex Start = S.start;
  707. AssignI.advanceTo(Start);
  708. do {
  709. unsigned RegIdx;
  710. SlotIndex End = S.end;
  711. if (!AssignI.valid()) {
  712. RegIdx = 0;
  713. } else if (AssignI.start() <= Start) {
  714. RegIdx = AssignI.value();
  715. if (AssignI.stop() < End) {
  716. End = AssignI.stop();
  717. ++AssignI;
  718. }
  719. } else {
  720. RegIdx = 0;
  721. End = std::min(End, AssignI.start());
  722. }
  723. // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
  724. DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
  725. LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
  726. // Check for a simply defined value that can be blitted directly.
  727. ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
  728. if (VNInfo *VNI = VFP.getPointer()) {
  729. DEBUG(dbgs() << ':' << VNI->id);
  730. LR.addSegment(LiveInterval::Segment(Start, End, VNI));
  731. Start = End;
  732. continue;
  733. }
  734. // Skip values with forced recomputation.
  735. if (VFP.getInt()) {
  736. DEBUG(dbgs() << "(recalc)");
  737. Skipped = true;
  738. Start = End;
  739. continue;
  740. }
  741. LiveRangeCalc &LRC = getLRCalc(RegIdx);
  742. // This value has multiple defs in RegIdx, but it wasn't rematerialized,
  743. // so the live range is accurate. Add live-in blocks in [Start;End) to the
  744. // LiveInBlocks.
  745. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
  746. SlotIndex BlockStart, BlockEnd;
  747. std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
  748. // The first block may be live-in, or it may have its own def.
  749. if (Start != BlockStart) {
  750. VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
  751. assert(VNI && "Missing def for complex mapped value");
  752. DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
  753. // MBB has its own def. Is it also live-out?
  754. if (BlockEnd <= End)
  755. LRC.setLiveOutValue(MBB, VNI);
  756. // Skip to the next block for live-in.
  757. ++MBB;
  758. BlockStart = BlockEnd;
  759. }
  760. // Handle the live-in blocks covered by [Start;End).
  761. assert(Start <= BlockStart && "Expected live-in block");
  762. while (BlockStart < End) {
  763. DEBUG(dbgs() << ">BB#" << MBB->getNumber());
  764. BlockEnd = LIS.getMBBEndIdx(MBB);
  765. if (BlockStart == ParentVNI->def) {
  766. // This block has the def of a parent PHI, so it isn't live-in.
  767. assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
  768. VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
  769. assert(VNI && "Missing def for complex mapped parent PHI");
  770. if (End >= BlockEnd)
  771. LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
  772. } else {
  773. // This block needs a live-in value. The last block covered may not
  774. // be live-out.
  775. if (End < BlockEnd)
  776. LRC.addLiveInBlock(LR, MDT[MBB], End);
  777. else {
  778. // Live-through, and we don't know the value.
  779. LRC.addLiveInBlock(LR, MDT[MBB]);
  780. LRC.setLiveOutValue(MBB, nullptr);
  781. }
  782. }
  783. BlockStart = BlockEnd;
  784. ++MBB;
  785. }
  786. Start = End;
  787. } while (Start != S.end);
  788. DEBUG(dbgs() << '\n');
  789. }
  790. LRCalc[0].calculateValues();
  791. if (SpillMode)
  792. LRCalc[1].calculateValues();
  793. return Skipped;
  794. }
  795. void SplitEditor::extendPHIKillRanges() {
  796. // Extend live ranges to be live-out for successor PHI values.
  797. for (const VNInfo *PHIVNI : Edit->getParent().valnos) {
  798. if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
  799. continue;
  800. unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
  801. LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
  802. LiveRangeCalc &LRC = getLRCalc(RegIdx);
  803. MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
  804. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  805. PE = MBB->pred_end(); PI != PE; ++PI) {
  806. SlotIndex End = LIS.getMBBEndIdx(*PI);
  807. SlotIndex LastUse = End.getPrevSlot();
  808. // The predecessor may not have a live-out value. That is OK, like an
  809. // undef PHI operand.
  810. if (Edit->getParent().liveAt(LastUse)) {
  811. assert(RegAssign.lookup(LastUse) == RegIdx &&
  812. "Different register assignment in phi predecessor");
  813. LRC.extend(LR, End);
  814. }
  815. }
  816. }
  817. }
  818. /// rewriteAssigned - Rewrite all uses of Edit->getReg().
  819. void SplitEditor::rewriteAssigned(bool ExtendRanges) {
  820. for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
  821. RE = MRI.reg_end(); RI != RE;) {
  822. MachineOperand &MO = *RI;
  823. MachineInstr *MI = MO.getParent();
  824. ++RI;
  825. // LiveDebugVariables should have handled all DBG_VALUE instructions.
  826. if (MI->isDebugValue()) {
  827. DEBUG(dbgs() << "Zapping " << *MI);
  828. MO.setReg(0);
  829. continue;
  830. }
  831. // <undef> operands don't really read the register, so it doesn't matter
  832. // which register we choose. When the use operand is tied to a def, we must
  833. // use the same register as the def, so just do that always.
  834. SlotIndex Idx = LIS.getInstructionIndex(MI);
  835. if (MO.isDef() || MO.isUndef())
  836. Idx = Idx.getRegSlot(MO.isEarlyClobber());
  837. // Rewrite to the mapped register at Idx.
  838. unsigned RegIdx = RegAssign.lookup(Idx);
  839. LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
  840. MO.setReg(LI->reg);
  841. DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'
  842. << Idx << ':' << RegIdx << '\t' << *MI);
  843. // Extend liveness to Idx if the instruction reads reg.
  844. if (!ExtendRanges || MO.isUndef())
  845. continue;
  846. // Skip instructions that don't read Reg.
  847. if (MO.isDef()) {
  848. if (!MO.getSubReg() && !MO.isEarlyClobber())
  849. continue;
  850. // We may wan't to extend a live range for a partial redef, or for a use
  851. // tied to an early clobber.
  852. Idx = Idx.getPrevSlot();
  853. if (!Edit->getParent().liveAt(Idx))
  854. continue;
  855. } else
  856. Idx = Idx.getRegSlot(true);
  857. getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot());
  858. }
  859. }
  860. void SplitEditor::deleteRematVictims() {
  861. SmallVector<MachineInstr*, 8> Dead;
  862. for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
  863. LiveInterval *LI = &LIS.getInterval(*I);
  864. for (const LiveRange::Segment &S : LI->segments) {
  865. // Dead defs end at the dead slot.
  866. if (S.end != S.valno->def.getDeadSlot())
  867. continue;
  868. MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def);
  869. assert(MI && "Missing instruction for dead def");
  870. MI->addRegisterDead(LI->reg, &TRI);
  871. if (!MI->allDefsAreDead())
  872. continue;
  873. DEBUG(dbgs() << "All defs dead: " << *MI);
  874. Dead.push_back(MI);
  875. }
  876. }
  877. if (Dead.empty())
  878. return;
  879. Edit->eliminateDeadDefs(Dead);
  880. }
  881. void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
  882. ++NumFinished;
  883. // At this point, the live intervals in Edit contain VNInfos corresponding to
  884. // the inserted copies.
  885. // Add the original defs from the parent interval.
  886. for (const VNInfo *ParentVNI : Edit->getParent().valnos) {
  887. if (ParentVNI->isUnused())
  888. continue;
  889. unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
  890. defValue(RegIdx, ParentVNI, ParentVNI->def);
  891. // Force rematted values to be recomputed everywhere.
  892. // The new live ranges may be truncated.
  893. if (Edit->didRematerialize(ParentVNI))
  894. for (unsigned i = 0, e = Edit->size(); i != e; ++i)
  895. forceRecompute(i, ParentVNI);
  896. }
  897. // Hoist back-copies to the complement interval when in spill mode.
  898. switch (SpillMode) {
  899. case SM_Partition:
  900. // Leave all back-copies as is.
  901. break;
  902. case SM_Size:
  903. hoistCopiesForSize();
  904. break;
  905. case SM_Speed:
  906. llvm_unreachable("Spill mode 'speed' not implemented yet");
  907. }
  908. // Transfer the simply mapped values, check if any are skipped.
  909. bool Skipped = transferValues();
  910. if (Skipped)
  911. extendPHIKillRanges();
  912. else
  913. ++NumSimple;
  914. // Rewrite virtual registers, possibly extending ranges.
  915. rewriteAssigned(Skipped);
  916. // Delete defs that were rematted everywhere.
  917. if (Skipped)
  918. deleteRematVictims();
  919. // Get rid of unused values and set phi-kill flags.
  920. for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) {
  921. LiveInterval &LI = LIS.getInterval(*I);
  922. LI.RenumberValues();
  923. }
  924. // Provide a reverse mapping from original indices to Edit ranges.
  925. if (LRMap) {
  926. LRMap->clear();
  927. for (unsigned i = 0, e = Edit->size(); i != e; ++i)
  928. LRMap->push_back(i);
  929. }
  930. // Now check if any registers were separated into multiple components.
  931. ConnectedVNInfoEqClasses ConEQ(LIS);
  932. for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
  933. // Don't use iterators, they are invalidated by create() below.
  934. LiveInterval *li = &LIS.getInterval(Edit->get(i));
  935. unsigned NumComp = ConEQ.Classify(li);
  936. if (NumComp <= 1)
  937. continue;
  938. DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
  939. SmallVector<LiveInterval*, 8> dups;
  940. dups.push_back(li);
  941. for (unsigned j = 1; j != NumComp; ++j)
  942. dups.push_back(&Edit->createEmptyInterval());
  943. ConEQ.Distribute(&dups[0], MRI);
  944. // The new intervals all map back to i.
  945. if (LRMap)
  946. LRMap->resize(Edit->size(), i);
  947. }
  948. // Calculate spill weight and allocation hints for new intervals.
  949. Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI);
  950. assert(!LRMap || LRMap->size() == Edit->size());
  951. }
  952. //===----------------------------------------------------------------------===//
  953. // Single Block Splitting
  954. //===----------------------------------------------------------------------===//
  955. bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
  956. bool SingleInstrs) const {
  957. // Always split for multiple instructions.
  958. if (!BI.isOneInstr())
  959. return true;
  960. // Don't split for single instructions unless explicitly requested.
  961. if (!SingleInstrs)
  962. return false;
  963. // Splitting a live-through range always makes progress.
  964. if (BI.LiveIn && BI.LiveOut)
  965. return true;
  966. // No point in isolating a copy. It has no register class constraints.
  967. if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
  968. return false;
  969. // Finally, don't isolate an end point that was created by earlier splits.
  970. return isOriginalEndpoint(BI.FirstInstr);
  971. }
  972. void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
  973. openIntv();
  974. SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
  975. SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
  976. LastSplitPoint));
  977. if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
  978. useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
  979. } else {
  980. // The last use is after the last valid split point.
  981. SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
  982. useIntv(SegStart, SegStop);
  983. overlapIntv(SegStop, BI.LastInstr);
  984. }
  985. }
  986. //===----------------------------------------------------------------------===//
  987. // Global Live Range Splitting Support
  988. //===----------------------------------------------------------------------===//
  989. // These methods support a method of global live range splitting that uses a
  990. // global algorithm to decide intervals for CFG edges. They will insert split
  991. // points and color intervals in basic blocks while avoiding interference.
  992. //
  993. // Note that splitSingleBlock is also useful for blocks where both CFG edges
  994. // are on the stack.
  995. void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
  996. unsigned IntvIn, SlotIndex LeaveBefore,
  997. unsigned IntvOut, SlotIndex EnterAfter){
  998. SlotIndex Start, Stop;
  999. std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
  1000. DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
  1001. << ") intf " << LeaveBefore << '-' << EnterAfter
  1002. << ", live-through " << IntvIn << " -> " << IntvOut);
  1003. assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
  1004. assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
  1005. assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
  1006. assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
  1007. MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
  1008. if (!IntvOut) {
  1009. DEBUG(dbgs() << ", spill on entry.\n");
  1010. //
  1011. // <<<<<<<<< Possible LeaveBefore interference.
  1012. // |-----------| Live through.
  1013. // -____________ Spill on entry.
  1014. //
  1015. selectIntv(IntvIn);
  1016. SlotIndex Idx = leaveIntvAtTop(*MBB);
  1017. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1018. (void)Idx;
  1019. return;
  1020. }
  1021. if (!IntvIn) {
  1022. DEBUG(dbgs() << ", reload on exit.\n");
  1023. //
  1024. // >>>>>>> Possible EnterAfter interference.
  1025. // |-----------| Live through.
  1026. // ___________-- Reload on exit.
  1027. //
  1028. selectIntv(IntvOut);
  1029. SlotIndex Idx = enterIntvAtEnd(*MBB);
  1030. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1031. (void)Idx;
  1032. return;
  1033. }
  1034. if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
  1035. DEBUG(dbgs() << ", straight through.\n");
  1036. //
  1037. // |-----------| Live through.
  1038. // ------------- Straight through, same intv, no interference.
  1039. //
  1040. selectIntv(IntvOut);
  1041. useIntv(Start, Stop);
  1042. return;
  1043. }
  1044. // We cannot legally insert splits after LSP.
  1045. SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
  1046. assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
  1047. if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
  1048. LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
  1049. DEBUG(dbgs() << ", switch avoiding interference.\n");
  1050. //
  1051. // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
  1052. // |-----------| Live through.
  1053. // ------======= Switch intervals between interference.
  1054. //
  1055. selectIntv(IntvOut);
  1056. SlotIndex Idx;
  1057. if (LeaveBefore && LeaveBefore < LSP) {
  1058. Idx = enterIntvBefore(LeaveBefore);
  1059. useIntv(Idx, Stop);
  1060. } else {
  1061. Idx = enterIntvAtEnd(*MBB);
  1062. }
  1063. selectIntv(IntvIn);
  1064. useIntv(Start, Idx);
  1065. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1066. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1067. return;
  1068. }
  1069. DEBUG(dbgs() << ", create local intv for interference.\n");
  1070. //
  1071. // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
  1072. // |-----------| Live through.
  1073. // ==---------== Switch intervals before/after interference.
  1074. //
  1075. assert(LeaveBefore <= EnterAfter && "Missed case");
  1076. selectIntv(IntvOut);
  1077. SlotIndex Idx = enterIntvAfter(EnterAfter);
  1078. useIntv(Idx, Stop);
  1079. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1080. selectIntv(IntvIn);
  1081. Idx = leaveIntvBefore(LeaveBefore);
  1082. useIntv(Start, Idx);
  1083. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1084. }
  1085. void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
  1086. unsigned IntvIn, SlotIndex LeaveBefore) {
  1087. SlotIndex Start, Stop;
  1088. std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
  1089. DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
  1090. << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
  1091. << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
  1092. << (BI.LiveOut ? ", stack-out" : ", killed in block"));
  1093. assert(IntvIn && "Must have register in");
  1094. assert(BI.LiveIn && "Must be live-in");
  1095. assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
  1096. if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
  1097. DEBUG(dbgs() << " before interference.\n");
  1098. //
  1099. // <<< Interference after kill.
  1100. // |---o---x | Killed in block.
  1101. // ========= Use IntvIn everywhere.
  1102. //
  1103. selectIntv(IntvIn);
  1104. useIntv(Start, BI.LastInstr);
  1105. return;
  1106. }
  1107. SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
  1108. if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
  1109. //
  1110. // <<< Possible interference after last use.
  1111. // |---o---o---| Live-out on stack.
  1112. // =========____ Leave IntvIn after last use.
  1113. //
  1114. // < Interference after last use.
  1115. // |---o---o--o| Live-out on stack, late last use.
  1116. // ============ Copy to stack after LSP, overlap IntvIn.
  1117. // \_____ Stack interval is live-out.
  1118. //
  1119. if (BI.LastInstr < LSP) {
  1120. DEBUG(dbgs() << ", spill after last use before interference.\n");
  1121. selectIntv(IntvIn);
  1122. SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
  1123. useIntv(Start, Idx);
  1124. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1125. } else {
  1126. DEBUG(dbgs() << ", spill before last split point.\n");
  1127. selectIntv(IntvIn);
  1128. SlotIndex Idx = leaveIntvBefore(LSP);
  1129. overlapIntv(Idx, BI.LastInstr);
  1130. useIntv(Start, Idx);
  1131. assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
  1132. }
  1133. return;
  1134. }
  1135. // The interference is overlapping somewhere we wanted to use IntvIn. That
  1136. // means we need to create a local interval that can be allocated a
  1137. // different register.
  1138. unsigned LocalIntv = openIntv();
  1139. (void)LocalIntv;
  1140. DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
  1141. if (!BI.LiveOut || BI.LastInstr < LSP) {
  1142. //
  1143. // <<<<<<< Interference overlapping uses.
  1144. // |---o---o---| Live-out on stack.
  1145. // =====----____ Leave IntvIn before interference, then spill.
  1146. //
  1147. SlotIndex To = leaveIntvAfter(BI.LastInstr);
  1148. SlotIndex From = enterIntvBefore(LeaveBefore);
  1149. useIntv(From, To);
  1150. selectIntv(IntvIn);
  1151. useIntv(Start, From);
  1152. assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
  1153. return;
  1154. }
  1155. // <<<<<<< Interference overlapping uses.
  1156. // |---o---o--o| Live-out on stack, late last use.
  1157. // =====------- Copy to stack before LSP, overlap LocalIntv.
  1158. // \_____ Stack interval is live-out.
  1159. //
  1160. SlotIndex To = leaveIntvBefore(LSP);
  1161. overlapIntv(To, BI.LastInstr);
  1162. SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
  1163. useIntv(From, To);
  1164. selectIntv(IntvIn);
  1165. useIntv(Start, From);
  1166. assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
  1167. }
  1168. void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
  1169. unsigned IntvOut, SlotIndex EnterAfter) {
  1170. SlotIndex Start, Stop;
  1171. std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
  1172. DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
  1173. << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
  1174. << ", reg-out " << IntvOut << ", enter after " << EnterAfter
  1175. << (BI.LiveIn ? ", stack-in" : ", defined in block"));
  1176. SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
  1177. assert(IntvOut && "Must have register out");
  1178. assert(BI.LiveOut && "Must be live-out");
  1179. assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
  1180. if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
  1181. DEBUG(dbgs() << " after interference.\n");
  1182. //
  1183. // >>>> Interference before def.
  1184. // | o---o---| Defined in block.
  1185. // ========= Use IntvOut everywhere.
  1186. //
  1187. selectIntv(IntvOut);
  1188. useIntv(BI.FirstInstr, Stop);
  1189. return;
  1190. }
  1191. if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
  1192. DEBUG(dbgs() << ", reload after interference.\n");
  1193. //
  1194. // >>>> Interference before def.
  1195. // |---o---o---| Live-through, stack-in.
  1196. // ____========= Enter IntvOut before first use.
  1197. //
  1198. selectIntv(IntvOut);
  1199. SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
  1200. useIntv(Idx, Stop);
  1201. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1202. return;
  1203. }
  1204. // The interference is overlapping somewhere we wanted to use IntvOut. That
  1205. // means we need to create a local interval that can be allocated a
  1206. // different register.
  1207. DEBUG(dbgs() << ", interference overlaps uses.\n");
  1208. //
  1209. // >>>>>>> Interference overlapping uses.
  1210. // |---o---o---| Live-through, stack-in.
  1211. // ____---====== Create local interval for interference range.
  1212. //
  1213. selectIntv(IntvOut);
  1214. SlotIndex Idx = enterIntvAfter(EnterAfter);
  1215. useIntv(Idx, Stop);
  1216. assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
  1217. openIntv();
  1218. SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));
  1219. useIntv(From, Idx);
  1220. }