SplitKit.cpp 59 KB

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