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