LiveInterval.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. //===- LiveInterval.cpp - Live Interval Representation --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the LiveRange and LiveInterval classes. Given some
  10. // numbering of each the machine instructions an interval [i, j) is said to be a
  11. // live range for register v if there is no instruction with number j' >= j
  12. // such that v is live at j' and there is no instruction with number i' < i such
  13. // that v is live at i'. In this implementation ranges can have holes,
  14. // i.e. a range might look like [1,20), [50,65), [1000,1001). Each
  15. // individual segment is represented as an instance of LiveRange::Segment,
  16. // and the whole range is represented as an instance of LiveRange.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/CodeGen/LiveInterval.h"
  20. #include "LiveRangeUtils.h"
  21. #include "RegisterCoalescer.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/iterator_range.h"
  27. #include "llvm/CodeGen/LiveIntervals.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineInstr.h"
  30. #include "llvm/CodeGen/MachineOperand.h"
  31. #include "llvm/CodeGen/MachineRegisterInfo.h"
  32. #include "llvm/CodeGen/SlotIndexes.h"
  33. #include "llvm/CodeGen/TargetRegisterInfo.h"
  34. #include "llvm/Config/llvm-config.h"
  35. #include "llvm/MC/LaneBitmask.h"
  36. #include "llvm/Support/Compiler.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <cstddef>
  42. #include <iterator>
  43. #include <utility>
  44. using namespace llvm;
  45. namespace {
  46. //===----------------------------------------------------------------------===//
  47. // Implementation of various methods necessary for calculation of live ranges.
  48. // The implementation of the methods abstracts from the concrete type of the
  49. // segment collection.
  50. //
  51. // Implementation of the class follows the Template design pattern. The base
  52. // class contains generic algorithms that call collection-specific methods,
  53. // which are provided in concrete subclasses. In order to avoid virtual calls
  54. // these methods are provided by means of C++ template instantiation.
  55. // The base class calls the methods of the subclass through method impl(),
  56. // which casts 'this' pointer to the type of the subclass.
  57. //
  58. //===----------------------------------------------------------------------===//
  59. template <typename ImplT, typename IteratorT, typename CollectionT>
  60. class CalcLiveRangeUtilBase {
  61. protected:
  62. LiveRange *LR;
  63. protected:
  64. CalcLiveRangeUtilBase(LiveRange *LR) : LR(LR) {}
  65. public:
  66. using Segment = LiveRange::Segment;
  67. using iterator = IteratorT;
  68. /// A counterpart of LiveRange::createDeadDef: Make sure the range has a
  69. /// value defined at @p Def.
  70. /// If @p ForVNI is null, and there is no value defined at @p Def, a new
  71. /// value will be allocated using @p VNInfoAllocator.
  72. /// If @p ForVNI is null, the return value is the value defined at @p Def,
  73. /// either a pre-existing one, or the one newly created.
  74. /// If @p ForVNI is not null, then @p Def should be the location where
  75. /// @p ForVNI is defined. If the range does not have a value defined at
  76. /// @p Def, the value @p ForVNI will be used instead of allocating a new
  77. /// one. If the range already has a value defined at @p Def, it must be
  78. /// same as @p ForVNI. In either case, @p ForVNI will be the return value.
  79. VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator *VNInfoAllocator,
  80. VNInfo *ForVNI) {
  81. assert(!Def.isDead() && "Cannot define a value at the dead slot");
  82. assert((!ForVNI || ForVNI->def == Def) &&
  83. "If ForVNI is specified, it must match Def");
  84. iterator I = impl().find(Def);
  85. if (I == segments().end()) {
  86. VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
  87. impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI));
  88. return VNI;
  89. }
  90. Segment *S = segmentAt(I);
  91. if (SlotIndex::isSameInstr(Def, S->start)) {
  92. assert((!ForVNI || ForVNI == S->valno) && "Value number mismatch");
  93. assert(S->valno->def == S->start && "Inconsistent existing value def");
  94. // It is possible to have both normal and early-clobber defs of the same
  95. // register on an instruction. It doesn't make a lot of sense, but it is
  96. // possible to specify in inline assembly.
  97. //
  98. // Just convert everything to early-clobber.
  99. Def = std::min(Def, S->start);
  100. if (Def != S->start)
  101. S->start = S->valno->def = Def;
  102. return S->valno;
  103. }
  104. assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def");
  105. VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
  106. segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI));
  107. return VNI;
  108. }
  109. VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) {
  110. if (segments().empty())
  111. return nullptr;
  112. iterator I =
  113. impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr));
  114. if (I == segments().begin())
  115. return nullptr;
  116. --I;
  117. if (I->end <= StartIdx)
  118. return nullptr;
  119. if (I->end < Use)
  120. extendSegmentEndTo(I, Use);
  121. return I->valno;
  122. }
  123. std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
  124. SlotIndex StartIdx, SlotIndex Use) {
  125. if (segments().empty())
  126. return std::make_pair(nullptr, false);
  127. SlotIndex BeforeUse = Use.getPrevSlot();
  128. iterator I = impl().findInsertPos(Segment(BeforeUse, Use, nullptr));
  129. if (I == segments().begin())
  130. return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
  131. --I;
  132. if (I->end <= StartIdx)
  133. return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
  134. if (I->end < Use) {
  135. if (LR->isUndefIn(Undefs, I->end, BeforeUse))
  136. return std::make_pair(nullptr, true);
  137. extendSegmentEndTo(I, Use);
  138. }
  139. return std::make_pair(I->valno, false);
  140. }
  141. /// This method is used when we want to extend the segment specified
  142. /// by I to end at the specified endpoint. To do this, we should
  143. /// merge and eliminate all segments that this will overlap
  144. /// with. The iterator is not invalidated.
  145. void extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
  146. assert(I != segments().end() && "Not a valid segment!");
  147. Segment *S = segmentAt(I);
  148. VNInfo *ValNo = I->valno;
  149. // Search for the first segment that we can't merge with.
  150. iterator MergeTo = std::next(I);
  151. for (; MergeTo != segments().end() && NewEnd >= MergeTo->end; ++MergeTo)
  152. assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
  153. // If NewEnd was in the middle of a segment, make sure to get its endpoint.
  154. S->end = std::max(NewEnd, std::prev(MergeTo)->end);
  155. // If the newly formed segment now touches the segment after it and if they
  156. // have the same value number, merge the two segments into one segment.
  157. if (MergeTo != segments().end() && MergeTo->start <= I->end &&
  158. MergeTo->valno == ValNo) {
  159. S->end = MergeTo->end;
  160. ++MergeTo;
  161. }
  162. // Erase any dead segments.
  163. segments().erase(std::next(I), MergeTo);
  164. }
  165. /// This method is used when we want to extend the segment specified
  166. /// by I to start at the specified endpoint. To do this, we should
  167. /// merge and eliminate all segments that this will overlap with.
  168. iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) {
  169. assert(I != segments().end() && "Not a valid segment!");
  170. Segment *S = segmentAt(I);
  171. VNInfo *ValNo = I->valno;
  172. // Search for the first segment that we can't merge with.
  173. iterator MergeTo = I;
  174. do {
  175. if (MergeTo == segments().begin()) {
  176. S->start = NewStart;
  177. segments().erase(MergeTo, I);
  178. return I;
  179. }
  180. assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
  181. --MergeTo;
  182. } while (NewStart <= MergeTo->start);
  183. // If we start in the middle of another segment, just delete a range and
  184. // extend that segment.
  185. if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
  186. segmentAt(MergeTo)->end = S->end;
  187. } else {
  188. // Otherwise, extend the segment right after.
  189. ++MergeTo;
  190. Segment *MergeToSeg = segmentAt(MergeTo);
  191. MergeToSeg->start = NewStart;
  192. MergeToSeg->end = S->end;
  193. }
  194. segments().erase(std::next(MergeTo), std::next(I));
  195. return MergeTo;
  196. }
  197. iterator addSegment(Segment S) {
  198. SlotIndex Start = S.start, End = S.end;
  199. iterator I = impl().findInsertPos(S);
  200. // If the inserted segment starts in the middle or right at the end of
  201. // another segment, just extend that segment to contain the segment of S.
  202. if (I != segments().begin()) {
  203. iterator B = std::prev(I);
  204. if (S.valno == B->valno) {
  205. if (B->start <= Start && B->end >= Start) {
  206. extendSegmentEndTo(B, End);
  207. return B;
  208. }
  209. } else {
  210. // Check to make sure that we are not overlapping two live segments with
  211. // different valno's.
  212. assert(B->end <= Start &&
  213. "Cannot overlap two segments with differing ValID's"
  214. " (did you def the same reg twice in a MachineInstr?)");
  215. }
  216. }
  217. // Otherwise, if this segment ends in the middle of, or right next
  218. // to, another segment, merge it into that segment.
  219. if (I != segments().end()) {
  220. if (S.valno == I->valno) {
  221. if (I->start <= End) {
  222. I = extendSegmentStartTo(I, Start);
  223. // If S is a complete superset of a segment, we may need to grow its
  224. // endpoint as well.
  225. if (End > I->end)
  226. extendSegmentEndTo(I, End);
  227. return I;
  228. }
  229. } else {
  230. // Check to make sure that we are not overlapping two live segments with
  231. // different valno's.
  232. assert(I->start >= End &&
  233. "Cannot overlap two segments with differing ValID's");
  234. }
  235. }
  236. // Otherwise, this is just a new segment that doesn't interact with
  237. // anything.
  238. // Insert it.
  239. return segments().insert(I, S);
  240. }
  241. private:
  242. ImplT &impl() { return *static_cast<ImplT *>(this); }
  243. CollectionT &segments() { return impl().segmentsColl(); }
  244. Segment *segmentAt(iterator I) { return const_cast<Segment *>(&(*I)); }
  245. };
  246. //===----------------------------------------------------------------------===//
  247. // Instantiation of the methods for calculation of live ranges
  248. // based on a segment vector.
  249. //===----------------------------------------------------------------------===//
  250. class CalcLiveRangeUtilVector;
  251. using CalcLiveRangeUtilVectorBase =
  252. CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator,
  253. LiveRange::Segments>;
  254. class CalcLiveRangeUtilVector : public CalcLiveRangeUtilVectorBase {
  255. public:
  256. CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {}
  257. private:
  258. friend CalcLiveRangeUtilVectorBase;
  259. LiveRange::Segments &segmentsColl() { return LR->segments; }
  260. void insertAtEnd(const Segment &S) { LR->segments.push_back(S); }
  261. iterator find(SlotIndex Pos) { return LR->find(Pos); }
  262. iterator findInsertPos(Segment S) { return llvm::upper_bound(*LR, S.start); }
  263. };
  264. //===----------------------------------------------------------------------===//
  265. // Instantiation of the methods for calculation of live ranges
  266. // based on a segment set.
  267. //===----------------------------------------------------------------------===//
  268. class CalcLiveRangeUtilSet;
  269. using CalcLiveRangeUtilSetBase =
  270. CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, LiveRange::SegmentSet::iterator,
  271. LiveRange::SegmentSet>;
  272. class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase {
  273. public:
  274. CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {}
  275. private:
  276. friend CalcLiveRangeUtilSetBase;
  277. LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; }
  278. void insertAtEnd(const Segment &S) {
  279. LR->segmentSet->insert(LR->segmentSet->end(), S);
  280. }
  281. iterator find(SlotIndex Pos) {
  282. iterator I =
  283. LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr));
  284. if (I == LR->segmentSet->begin())
  285. return I;
  286. iterator PrevI = std::prev(I);
  287. if (Pos < (*PrevI).end)
  288. return PrevI;
  289. return I;
  290. }
  291. iterator findInsertPos(Segment S) {
  292. iterator I = LR->segmentSet->upper_bound(S);
  293. if (I != LR->segmentSet->end() && !(S.start < *I))
  294. ++I;
  295. return I;
  296. }
  297. };
  298. } // end anonymous namespace
  299. //===----------------------------------------------------------------------===//
  300. // LiveRange methods
  301. //===----------------------------------------------------------------------===//
  302. LiveRange::iterator LiveRange::find(SlotIndex Pos) {
  303. // This algorithm is basically std::upper_bound.
  304. // Unfortunately, std::upper_bound cannot be used with mixed types until we
  305. // adopt C++0x. Many libraries can do it, but not all.
  306. if (empty() || Pos >= endIndex())
  307. return end();
  308. iterator I = begin();
  309. size_t Len = size();
  310. do {
  311. size_t Mid = Len >> 1;
  312. if (Pos < I[Mid].end) {
  313. Len = Mid;
  314. } else {
  315. I += Mid + 1;
  316. Len -= Mid + 1;
  317. }
  318. } while (Len);
  319. return I;
  320. }
  321. VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) {
  322. // Use the segment set, if it is available.
  323. if (segmentSet != nullptr)
  324. return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr);
  325. // Otherwise use the segment vector.
  326. return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr);
  327. }
  328. VNInfo *LiveRange::createDeadDef(VNInfo *VNI) {
  329. // Use the segment set, if it is available.
  330. if (segmentSet != nullptr)
  331. return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI);
  332. // Otherwise use the segment vector.
  333. return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI);
  334. }
  335. // overlaps - Return true if the intersection of the two live ranges is
  336. // not empty.
  337. //
  338. // An example for overlaps():
  339. //
  340. // 0: A = ...
  341. // 4: B = ...
  342. // 8: C = A + B ;; last use of A
  343. //
  344. // The live ranges should look like:
  345. //
  346. // A = [3, 11)
  347. // B = [7, x)
  348. // C = [11, y)
  349. //
  350. // A->overlaps(C) should return false since we want to be able to join
  351. // A and C.
  352. //
  353. bool LiveRange::overlapsFrom(const LiveRange& other,
  354. const_iterator StartPos) const {
  355. assert(!empty() && "empty range");
  356. const_iterator i = begin();
  357. const_iterator ie = end();
  358. const_iterator j = StartPos;
  359. const_iterator je = other.end();
  360. assert((StartPos->start <= i->start || StartPos == other.begin()) &&
  361. StartPos != other.end() && "Bogus start position hint!");
  362. if (i->start < j->start) {
  363. i = std::upper_bound(i, ie, j->start);
  364. if (i != begin()) --i;
  365. } else if (j->start < i->start) {
  366. ++StartPos;
  367. if (StartPos != other.end() && StartPos->start <= i->start) {
  368. assert(StartPos < other.end() && i < end());
  369. j = std::upper_bound(j, je, i->start);
  370. if (j != other.begin()) --j;
  371. }
  372. } else {
  373. return true;
  374. }
  375. if (j == je) return false;
  376. while (i != ie) {
  377. if (i->start > j->start) {
  378. std::swap(i, j);
  379. std::swap(ie, je);
  380. }
  381. if (i->end > j->start)
  382. return true;
  383. ++i;
  384. }
  385. return false;
  386. }
  387. bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
  388. const SlotIndexes &Indexes) const {
  389. assert(!empty() && "empty range");
  390. if (Other.empty())
  391. return false;
  392. // Use binary searches to find initial positions.
  393. const_iterator I = find(Other.beginIndex());
  394. const_iterator IE = end();
  395. if (I == IE)
  396. return false;
  397. const_iterator J = Other.find(I->start);
  398. const_iterator JE = Other.end();
  399. if (J == JE)
  400. return false;
  401. while (true) {
  402. // J has just been advanced to satisfy:
  403. assert(J->end >= I->start);
  404. // Check for an overlap.
  405. if (J->start < I->end) {
  406. // I and J are overlapping. Find the later start.
  407. SlotIndex Def = std::max(I->start, J->start);
  408. // Allow the overlap if Def is a coalescable copy.
  409. if (Def.isBlock() ||
  410. !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
  411. return true;
  412. }
  413. // Advance the iterator that ends first to check for more overlaps.
  414. if (J->end > I->end) {
  415. std::swap(I, J);
  416. std::swap(IE, JE);
  417. }
  418. // Advance J until J->end >= I->start.
  419. do
  420. if (++J == JE)
  421. return false;
  422. while (J->end < I->start);
  423. }
  424. }
  425. /// overlaps - Return true if the live range overlaps an interval specified
  426. /// by [Start, End).
  427. bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
  428. assert(Start < End && "Invalid range");
  429. const_iterator I = std::lower_bound(begin(), end(), End);
  430. return I != begin() && (--I)->end > Start;
  431. }
  432. bool LiveRange::covers(const LiveRange &Other) const {
  433. if (empty())
  434. return Other.empty();
  435. const_iterator I = begin();
  436. for (const Segment &O : Other.segments) {
  437. I = advanceTo(I, O.start);
  438. if (I == end() || I->start > O.start)
  439. return false;
  440. // Check adjacent live segments and see if we can get behind O.end.
  441. while (I->end < O.end) {
  442. const_iterator Last = I;
  443. // Get next segment and abort if it was not adjacent.
  444. ++I;
  445. if (I == end() || Last->end != I->start)
  446. return false;
  447. }
  448. }
  449. return true;
  450. }
  451. /// ValNo is dead, remove it. If it is the largest value number, just nuke it
  452. /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
  453. /// it can be nuked later.
  454. void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
  455. if (ValNo->id == getNumValNums()-1) {
  456. do {
  457. valnos.pop_back();
  458. } while (!valnos.empty() && valnos.back()->isUnused());
  459. } else {
  460. ValNo->markUnused();
  461. }
  462. }
  463. /// RenumberValues - Renumber all values in order of appearance and delete the
  464. /// remaining unused values.
  465. void LiveRange::RenumberValues() {
  466. SmallPtrSet<VNInfo*, 8> Seen;
  467. valnos.clear();
  468. for (const Segment &S : segments) {
  469. VNInfo *VNI = S.valno;
  470. if (!Seen.insert(VNI).second)
  471. continue;
  472. assert(!VNI->isUnused() && "Unused valno used by live segment");
  473. VNI->id = (unsigned)valnos.size();
  474. valnos.push_back(VNI);
  475. }
  476. }
  477. void LiveRange::addSegmentToSet(Segment S) {
  478. CalcLiveRangeUtilSet(this).addSegment(S);
  479. }
  480. LiveRange::iterator LiveRange::addSegment(Segment S) {
  481. // Use the segment set, if it is available.
  482. if (segmentSet != nullptr) {
  483. addSegmentToSet(S);
  484. return end();
  485. }
  486. // Otherwise use the segment vector.
  487. return CalcLiveRangeUtilVector(this).addSegment(S);
  488. }
  489. void LiveRange::append(const Segment S) {
  490. // Check that the segment belongs to the back of the list.
  491. assert(segments.empty() || segments.back().end <= S.start);
  492. segments.push_back(S);
  493. }
  494. std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
  495. SlotIndex StartIdx, SlotIndex Kill) {
  496. // Use the segment set, if it is available.
  497. if (segmentSet != nullptr)
  498. return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill);
  499. // Otherwise use the segment vector.
  500. return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill);
  501. }
  502. VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
  503. // Use the segment set, if it is available.
  504. if (segmentSet != nullptr)
  505. return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill);
  506. // Otherwise use the segment vector.
  507. return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill);
  508. }
  509. /// Remove the specified segment from this range. Note that the segment must
  510. /// be in a single Segment in its entirety.
  511. void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
  512. bool RemoveDeadValNo) {
  513. // Find the Segment containing this span.
  514. iterator I = find(Start);
  515. assert(I != end() && "Segment is not in range!");
  516. assert(I->containsInterval(Start, End)
  517. && "Segment is not entirely in range!");
  518. // If the span we are removing is at the start of the Segment, adjust it.
  519. VNInfo *ValNo = I->valno;
  520. if (I->start == Start) {
  521. if (I->end == End) {
  522. if (RemoveDeadValNo) {
  523. // Check if val# is dead.
  524. bool isDead = true;
  525. for (const_iterator II = begin(), EE = end(); II != EE; ++II)
  526. if (II != I && II->valno == ValNo) {
  527. isDead = false;
  528. break;
  529. }
  530. if (isDead) {
  531. // Now that ValNo is dead, remove it.
  532. markValNoForDeletion(ValNo);
  533. }
  534. }
  535. segments.erase(I); // Removed the whole Segment.
  536. } else
  537. I->start = End;
  538. return;
  539. }
  540. // Otherwise if the span we are removing is at the end of the Segment,
  541. // adjust the other way.
  542. if (I->end == End) {
  543. I->end = Start;
  544. return;
  545. }
  546. // Otherwise, we are splitting the Segment into two pieces.
  547. SlotIndex OldEnd = I->end;
  548. I->end = Start; // Trim the old segment.
  549. // Insert the new one.
  550. segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
  551. }
  552. /// removeValNo - Remove all the segments defined by the specified value#.
  553. /// Also remove the value# from value# list.
  554. void LiveRange::removeValNo(VNInfo *ValNo) {
  555. if (empty()) return;
  556. segments.erase(remove_if(*this, [ValNo](const Segment &S) {
  557. return S.valno == ValNo;
  558. }), end());
  559. // Now that ValNo is dead, remove it.
  560. markValNoForDeletion(ValNo);
  561. }
  562. void LiveRange::join(LiveRange &Other,
  563. const int *LHSValNoAssignments,
  564. const int *RHSValNoAssignments,
  565. SmallVectorImpl<VNInfo *> &NewVNInfo) {
  566. verify();
  567. // Determine if any of our values are mapped. This is uncommon, so we want
  568. // to avoid the range scan if not.
  569. bool MustMapCurValNos = false;
  570. unsigned NumVals = getNumValNums();
  571. unsigned NumNewVals = NewVNInfo.size();
  572. for (unsigned i = 0; i != NumVals; ++i) {
  573. unsigned LHSValID = LHSValNoAssignments[i];
  574. if (i != LHSValID ||
  575. (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
  576. MustMapCurValNos = true;
  577. break;
  578. }
  579. }
  580. // If we have to apply a mapping to our base range assignment, rewrite it now.
  581. if (MustMapCurValNos && !empty()) {
  582. // Map the first live range.
  583. iterator OutIt = begin();
  584. OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
  585. for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
  586. VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
  587. assert(nextValNo && "Huh?");
  588. // If this live range has the same value # as its immediate predecessor,
  589. // and if they are neighbors, remove one Segment. This happens when we
  590. // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
  591. if (OutIt->valno == nextValNo && OutIt->end == I->start) {
  592. OutIt->end = I->end;
  593. } else {
  594. // Didn't merge. Move OutIt to the next segment,
  595. ++OutIt;
  596. OutIt->valno = nextValNo;
  597. if (OutIt != I) {
  598. OutIt->start = I->start;
  599. OutIt->end = I->end;
  600. }
  601. }
  602. }
  603. // If we merge some segments, chop off the end.
  604. ++OutIt;
  605. segments.erase(OutIt, end());
  606. }
  607. // Rewrite Other values before changing the VNInfo ids.
  608. // This can leave Other in an invalid state because we're not coalescing
  609. // touching segments that now have identical values. That's OK since Other is
  610. // not supposed to be valid after calling join();
  611. for (Segment &S : Other.segments)
  612. S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
  613. // Update val# info. Renumber them and make sure they all belong to this
  614. // LiveRange now. Also remove dead val#'s.
  615. unsigned NumValNos = 0;
  616. for (unsigned i = 0; i < NumNewVals; ++i) {
  617. VNInfo *VNI = NewVNInfo[i];
  618. if (VNI) {
  619. if (NumValNos >= NumVals)
  620. valnos.push_back(VNI);
  621. else
  622. valnos[NumValNos] = VNI;
  623. VNI->id = NumValNos++; // Renumber val#.
  624. }
  625. }
  626. if (NumNewVals < NumVals)
  627. valnos.resize(NumNewVals); // shrinkify
  628. // Okay, now insert the RHS live segments into the LHS.
  629. LiveRangeUpdater Updater(this);
  630. for (Segment &S : Other.segments)
  631. Updater.add(S);
  632. }
  633. /// Merge all of the segments in RHS into this live range as the specified
  634. /// value number. The segments in RHS are allowed to overlap with segments in
  635. /// the current range, but only if the overlapping segments have the
  636. /// specified value number.
  637. void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
  638. VNInfo *LHSValNo) {
  639. LiveRangeUpdater Updater(this);
  640. for (const Segment &S : RHS.segments)
  641. Updater.add(S.start, S.end, LHSValNo);
  642. }
  643. /// MergeValueInAsValue - Merge all of the live segments of a specific val#
  644. /// in RHS into this live range as the specified value number.
  645. /// The segments in RHS are allowed to overlap with segments in the
  646. /// current range, it will replace the value numbers of the overlaped
  647. /// segments with the specified value number.
  648. void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
  649. const VNInfo *RHSValNo,
  650. VNInfo *LHSValNo) {
  651. LiveRangeUpdater Updater(this);
  652. for (const Segment &S : RHS.segments)
  653. if (S.valno == RHSValNo)
  654. Updater.add(S.start, S.end, LHSValNo);
  655. }
  656. /// MergeValueNumberInto - This method is called when two value nubmers
  657. /// are found to be equivalent. This eliminates V1, replacing all
  658. /// segments with the V1 value number with the V2 value number. This can
  659. /// cause merging of V1/V2 values numbers and compaction of the value space.
  660. VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
  661. assert(V1 != V2 && "Identical value#'s are always equivalent!");
  662. // This code actually merges the (numerically) larger value number into the
  663. // smaller value number, which is likely to allow us to compactify the value
  664. // space. The only thing we have to be careful of is to preserve the
  665. // instruction that defines the result value.
  666. // Make sure V2 is smaller than V1.
  667. if (V1->id < V2->id) {
  668. V1->copyFrom(*V2);
  669. std::swap(V1, V2);
  670. }
  671. // Merge V1 segments into V2.
  672. for (iterator I = begin(); I != end(); ) {
  673. iterator S = I++;
  674. if (S->valno != V1) continue; // Not a V1 Segment.
  675. // Okay, we found a V1 live range. If it had a previous, touching, V2 live
  676. // range, extend it.
  677. if (S != begin()) {
  678. iterator Prev = S-1;
  679. if (Prev->valno == V2 && Prev->end == S->start) {
  680. Prev->end = S->end;
  681. // Erase this live-range.
  682. segments.erase(S);
  683. I = Prev+1;
  684. S = Prev;
  685. }
  686. }
  687. // Okay, now we have a V1 or V2 live range that is maximally merged forward.
  688. // Ensure that it is a V2 live-range.
  689. S->valno = V2;
  690. // If we can merge it into later V2 segments, do so now. We ignore any
  691. // following V1 segments, as they will be merged in subsequent iterations
  692. // of the loop.
  693. if (I != end()) {
  694. if (I->start == S->end && I->valno == V2) {
  695. S->end = I->end;
  696. segments.erase(I);
  697. I = S+1;
  698. }
  699. }
  700. }
  701. // Now that V1 is dead, remove it.
  702. markValNoForDeletion(V1);
  703. return V2;
  704. }
  705. void LiveRange::flushSegmentSet() {
  706. assert(segmentSet != nullptr && "segment set must have been created");
  707. assert(
  708. segments.empty() &&
  709. "segment set can be used only initially before switching to the array");
  710. segments.append(segmentSet->begin(), segmentSet->end());
  711. segmentSet = nullptr;
  712. verify();
  713. }
  714. bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
  715. ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
  716. ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
  717. // If there are no regmask slots, we have nothing to search.
  718. if (SlotI == SlotE)
  719. return false;
  720. // Start our search at the first segment that ends after the first slot.
  721. const_iterator SegmentI = find(*SlotI);
  722. const_iterator SegmentE = end();
  723. // If there are no segments that end after the first slot, we're done.
  724. if (SegmentI == SegmentE)
  725. return false;
  726. // Look for each slot in the live range.
  727. for ( ; SlotI != SlotE; ++SlotI) {
  728. // Go to the next segment that ends after the current slot.
  729. // The slot may be within a hole in the range.
  730. SegmentI = advanceTo(SegmentI, *SlotI);
  731. if (SegmentI == SegmentE)
  732. return false;
  733. // If this segment contains the slot, we're done.
  734. if (SegmentI->contains(*SlotI))
  735. return true;
  736. // Otherwise, look for the next slot.
  737. }
  738. // We didn't find a segment containing any of the slots.
  739. return false;
  740. }
  741. void LiveInterval::freeSubRange(SubRange *S) {
  742. S->~SubRange();
  743. // Memory was allocated with BumpPtr allocator and is not freed here.
  744. }
  745. void LiveInterval::removeEmptySubRanges() {
  746. SubRange **NextPtr = &SubRanges;
  747. SubRange *I = *NextPtr;
  748. while (I != nullptr) {
  749. if (!I->empty()) {
  750. NextPtr = &I->Next;
  751. I = *NextPtr;
  752. continue;
  753. }
  754. // Skip empty subranges until we find the first nonempty one.
  755. do {
  756. SubRange *Next = I->Next;
  757. freeSubRange(I);
  758. I = Next;
  759. } while (I != nullptr && I->empty());
  760. *NextPtr = I;
  761. }
  762. }
  763. void LiveInterval::clearSubRanges() {
  764. for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
  765. Next = I->Next;
  766. freeSubRange(I);
  767. }
  768. SubRanges = nullptr;
  769. }
  770. /// For each VNI in \p SR, check whether or not that value defines part
  771. /// of the mask describe by \p LaneMask and if not, remove that value
  772. /// from \p SR.
  773. static void stripValuesNotDefiningMask(unsigned Reg, LiveInterval::SubRange &SR,
  774. LaneBitmask LaneMask,
  775. const SlotIndexes &Indexes,
  776. const TargetRegisterInfo &TRI) {
  777. // Phys reg should not be tracked at subreg level.
  778. // Same for noreg (Reg == 0).
  779. if (!Register::isVirtualRegister(Reg) || !Reg)
  780. return;
  781. // Remove the values that don't define those lanes.
  782. SmallVector<VNInfo *, 8> ToBeRemoved;
  783. for (VNInfo *VNI : SR.valnos) {
  784. if (VNI->isUnused())
  785. continue;
  786. // PHI definitions don't have MI attached, so there is nothing
  787. // we can use to strip the VNI.
  788. if (VNI->isPHIDef())
  789. continue;
  790. const MachineInstr *MI = Indexes.getInstructionFromIndex(VNI->def);
  791. assert(MI && "Cannot find the definition of a value");
  792. bool hasDef = false;
  793. for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
  794. if (!MOI->isReg() || !MOI->isDef())
  795. continue;
  796. if (MOI->getReg() != Reg)
  797. continue;
  798. if ((TRI.getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
  799. continue;
  800. hasDef = true;
  801. break;
  802. }
  803. if (!hasDef)
  804. ToBeRemoved.push_back(VNI);
  805. }
  806. for (VNInfo *VNI : ToBeRemoved)
  807. SR.removeValNo(VNI);
  808. // If the subrange is empty at this point, the MIR is invalid. Do not assert
  809. // and let the verifier catch this case.
  810. }
  811. void LiveInterval::refineSubRanges(
  812. BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
  813. std::function<void(LiveInterval::SubRange &)> Apply,
  814. const SlotIndexes &Indexes, const TargetRegisterInfo &TRI) {
  815. LaneBitmask ToApply = LaneMask;
  816. for (SubRange &SR : subranges()) {
  817. LaneBitmask SRMask = SR.LaneMask;
  818. LaneBitmask Matching = SRMask & LaneMask;
  819. if (Matching.none())
  820. continue;
  821. SubRange *MatchingRange;
  822. if (SRMask == Matching) {
  823. // The subrange fits (it does not cover bits outside \p LaneMask).
  824. MatchingRange = &SR;
  825. } else {
  826. // We have to split the subrange into a matching and non-matching part.
  827. // Reduce lanemask of existing lane to non-matching part.
  828. SR.LaneMask = SRMask & ~Matching;
  829. // Create a new subrange for the matching part
  830. MatchingRange = createSubRangeFrom(Allocator, Matching, SR);
  831. // Now that the subrange is split in half, make sure we
  832. // only keep in the subranges the VNIs that touch the related half.
  833. stripValuesNotDefiningMask(reg, *MatchingRange, Matching, Indexes, TRI);
  834. stripValuesNotDefiningMask(reg, SR, SR.LaneMask, Indexes, TRI);
  835. }
  836. Apply(*MatchingRange);
  837. ToApply &= ~Matching;
  838. }
  839. // Create a new subrange if there are uncovered bits left.
  840. if (ToApply.any()) {
  841. SubRange *NewRange = createSubRange(Allocator, ToApply);
  842. Apply(*NewRange);
  843. }
  844. }
  845. unsigned LiveInterval::getSize() const {
  846. unsigned Sum = 0;
  847. for (const Segment &S : segments)
  848. Sum += S.start.distance(S.end);
  849. return Sum;
  850. }
  851. void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
  852. LaneBitmask LaneMask,
  853. const MachineRegisterInfo &MRI,
  854. const SlotIndexes &Indexes) const {
  855. assert(Register::isVirtualRegister(reg));
  856. LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg);
  857. assert((VRegMask & LaneMask).any());
  858. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  859. for (const MachineOperand &MO : MRI.def_operands(reg)) {
  860. if (!MO.isUndef())
  861. continue;
  862. unsigned SubReg = MO.getSubReg();
  863. assert(SubReg != 0 && "Undef should only be set on subreg defs");
  864. LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
  865. LaneBitmask UndefMask = VRegMask & ~DefMask;
  866. if ((UndefMask & LaneMask).any()) {
  867. const MachineInstr &MI = *MO.getParent();
  868. bool EarlyClobber = MO.isEarlyClobber();
  869. SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber);
  870. Undefs.push_back(Pos);
  871. }
  872. }
  873. }
  874. raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) {
  875. return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
  876. }
  877. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  878. LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
  879. dbgs() << *this << '\n';
  880. }
  881. #endif
  882. void LiveRange::print(raw_ostream &OS) const {
  883. if (empty())
  884. OS << "EMPTY";
  885. else {
  886. for (const Segment &S : segments) {
  887. OS << S;
  888. assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
  889. }
  890. }
  891. // Print value number info.
  892. if (getNumValNums()) {
  893. OS << " ";
  894. unsigned vnum = 0;
  895. for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
  896. ++i, ++vnum) {
  897. const VNInfo *vni = *i;
  898. if (vnum) OS << ' ';
  899. OS << vnum << '@';
  900. if (vni->isUnused()) {
  901. OS << 'x';
  902. } else {
  903. OS << vni->def;
  904. if (vni->isPHIDef())
  905. OS << "-phi";
  906. }
  907. }
  908. }
  909. }
  910. void LiveInterval::SubRange::print(raw_ostream &OS) const {
  911. OS << " L" << PrintLaneMask(LaneMask) << ' '
  912. << static_cast<const LiveRange&>(*this);
  913. }
  914. void LiveInterval::print(raw_ostream &OS) const {
  915. OS << printReg(reg) << ' ';
  916. super::print(OS);
  917. // Print subranges
  918. for (const SubRange &SR : subranges())
  919. OS << SR;
  920. OS << " weight:" << weight;
  921. }
  922. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  923. LLVM_DUMP_METHOD void LiveRange::dump() const {
  924. dbgs() << *this << '\n';
  925. }
  926. LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
  927. dbgs() << *this << '\n';
  928. }
  929. LLVM_DUMP_METHOD void LiveInterval::dump() const {
  930. dbgs() << *this << '\n';
  931. }
  932. #endif
  933. #ifndef NDEBUG
  934. void LiveRange::verify() const {
  935. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  936. assert(I->start.isValid());
  937. assert(I->end.isValid());
  938. assert(I->start < I->end);
  939. assert(I->valno != nullptr);
  940. assert(I->valno->id < valnos.size());
  941. assert(I->valno == valnos[I->valno->id]);
  942. if (std::next(I) != E) {
  943. assert(I->end <= std::next(I)->start);
  944. if (I->end == std::next(I)->start)
  945. assert(I->valno != std::next(I)->valno);
  946. }
  947. }
  948. }
  949. void LiveInterval::verify(const MachineRegisterInfo *MRI) const {
  950. super::verify();
  951. // Make sure SubRanges are fine and LaneMasks are disjunct.
  952. LaneBitmask Mask;
  953. LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg)
  954. : LaneBitmask::getAll();
  955. for (const SubRange &SR : subranges()) {
  956. // Subrange lanemask should be disjunct to any previous subrange masks.
  957. assert((Mask & SR.LaneMask).none());
  958. Mask |= SR.LaneMask;
  959. // subrange mask should not contained in maximum lane mask for the vreg.
  960. assert((Mask & ~MaxMask).none());
  961. // empty subranges must be removed.
  962. assert(!SR.empty());
  963. SR.verify();
  964. // Main liverange should cover subrange.
  965. assert(covers(SR));
  966. }
  967. }
  968. #endif
  969. //===----------------------------------------------------------------------===//
  970. // LiveRangeUpdater class
  971. //===----------------------------------------------------------------------===//
  972. //
  973. // The LiveRangeUpdater class always maintains these invariants:
  974. //
  975. // - When LastStart is invalid, Spills is empty and the iterators are invalid.
  976. // This is the initial state, and the state created by flush().
  977. // In this state, isDirty() returns false.
  978. //
  979. // Otherwise, segments are kept in three separate areas:
  980. //
  981. // 1. [begin; WriteI) at the front of LR.
  982. // 2. [ReadI; end) at the back of LR.
  983. // 3. Spills.
  984. //
  985. // - LR.begin() <= WriteI <= ReadI <= LR.end().
  986. // - Segments in all three areas are fully ordered and coalesced.
  987. // - Segments in area 1 precede and can't coalesce with segments in area 2.
  988. // - Segments in Spills precede and can't coalesce with segments in area 2.
  989. // - No coalescing is possible between segments in Spills and segments in area
  990. // 1, and there are no overlapping segments.
  991. //
  992. // The segments in Spills are not ordered with respect to the segments in area
  993. // 1. They need to be merged.
  994. //
  995. // When they exist, Spills.back().start <= LastStart,
  996. // and WriteI[-1].start <= LastStart.
  997. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  998. void LiveRangeUpdater::print(raw_ostream &OS) const {
  999. if (!isDirty()) {
  1000. if (LR)
  1001. OS << "Clean updater: " << *LR << '\n';
  1002. else
  1003. OS << "Null updater.\n";
  1004. return;
  1005. }
  1006. assert(LR && "Can't have null LR in dirty updater.");
  1007. OS << " updater with gap = " << (ReadI - WriteI)
  1008. << ", last start = " << LastStart
  1009. << ":\n Area 1:";
  1010. for (const auto &S : make_range(LR->begin(), WriteI))
  1011. OS << ' ' << S;
  1012. OS << "\n Spills:";
  1013. for (unsigned I = 0, E = Spills.size(); I != E; ++I)
  1014. OS << ' ' << Spills[I];
  1015. OS << "\n Area 2:";
  1016. for (const auto &S : make_range(ReadI, LR->end()))
  1017. OS << ' ' << S;
  1018. OS << '\n';
  1019. }
  1020. LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
  1021. print(errs());
  1022. }
  1023. #endif
  1024. // Determine if A and B should be coalesced.
  1025. static inline bool coalescable(const LiveRange::Segment &A,
  1026. const LiveRange::Segment &B) {
  1027. assert(A.start <= B.start && "Unordered live segments.");
  1028. if (A.end == B.start)
  1029. return A.valno == B.valno;
  1030. if (A.end < B.start)
  1031. return false;
  1032. assert(A.valno == B.valno && "Cannot overlap different values");
  1033. return true;
  1034. }
  1035. void LiveRangeUpdater::add(LiveRange::Segment Seg) {
  1036. assert(LR && "Cannot add to a null destination");
  1037. // Fall back to the regular add method if the live range
  1038. // is using the segment set instead of the segment vector.
  1039. if (LR->segmentSet != nullptr) {
  1040. LR->addSegmentToSet(Seg);
  1041. return;
  1042. }
  1043. // Flush the state if Start moves backwards.
  1044. if (!LastStart.isValid() || LastStart > Seg.start) {
  1045. if (isDirty())
  1046. flush();
  1047. // This brings us to an uninitialized state. Reinitialize.
  1048. assert(Spills.empty() && "Leftover spilled segments");
  1049. WriteI = ReadI = LR->begin();
  1050. }
  1051. // Remember start for next time.
  1052. LastStart = Seg.start;
  1053. // Advance ReadI until it ends after Seg.start.
  1054. LiveRange::iterator E = LR->end();
  1055. if (ReadI != E && ReadI->end <= Seg.start) {
  1056. // First try to close the gap between WriteI and ReadI with spills.
  1057. if (ReadI != WriteI)
  1058. mergeSpills();
  1059. // Then advance ReadI.
  1060. if (ReadI == WriteI)
  1061. ReadI = WriteI = LR->find(Seg.start);
  1062. else
  1063. while (ReadI != E && ReadI->end <= Seg.start)
  1064. *WriteI++ = *ReadI++;
  1065. }
  1066. assert(ReadI == E || ReadI->end > Seg.start);
  1067. // Check if the ReadI segment begins early.
  1068. if (ReadI != E && ReadI->start <= Seg.start) {
  1069. assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
  1070. // Bail if Seg is completely contained in ReadI.
  1071. if (ReadI->end >= Seg.end)
  1072. return;
  1073. // Coalesce into Seg.
  1074. Seg.start = ReadI->start;
  1075. ++ReadI;
  1076. }
  1077. // Coalesce as much as possible from ReadI into Seg.
  1078. while (ReadI != E && coalescable(Seg, *ReadI)) {
  1079. Seg.end = std::max(Seg.end, ReadI->end);
  1080. ++ReadI;
  1081. }
  1082. // Try coalescing Spills.back() into Seg.
  1083. if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
  1084. Seg.start = Spills.back().start;
  1085. Seg.end = std::max(Spills.back().end, Seg.end);
  1086. Spills.pop_back();
  1087. }
  1088. // Try coalescing Seg into WriteI[-1].
  1089. if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
  1090. WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
  1091. return;
  1092. }
  1093. // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
  1094. if (WriteI != ReadI) {
  1095. *WriteI++ = Seg;
  1096. return;
  1097. }
  1098. // Finally, append to LR or Spills.
  1099. if (WriteI == E) {
  1100. LR->segments.push_back(Seg);
  1101. WriteI = ReadI = LR->end();
  1102. } else
  1103. Spills.push_back(Seg);
  1104. }
  1105. // Merge as many spilled segments as possible into the gap between WriteI
  1106. // and ReadI. Advance WriteI to reflect the inserted instructions.
  1107. void LiveRangeUpdater::mergeSpills() {
  1108. // Perform a backwards merge of Spills and [SpillI;WriteI).
  1109. size_t GapSize = ReadI - WriteI;
  1110. size_t NumMoved = std::min(Spills.size(), GapSize);
  1111. LiveRange::iterator Src = WriteI;
  1112. LiveRange::iterator Dst = Src + NumMoved;
  1113. LiveRange::iterator SpillSrc = Spills.end();
  1114. LiveRange::iterator B = LR->begin();
  1115. // This is the new WriteI position after merging spills.
  1116. WriteI = Dst;
  1117. // Now merge Src and Spills backwards.
  1118. while (Src != Dst) {
  1119. if (Src != B && Src[-1].start > SpillSrc[-1].start)
  1120. *--Dst = *--Src;
  1121. else
  1122. *--Dst = *--SpillSrc;
  1123. }
  1124. assert(NumMoved == size_t(Spills.end() - SpillSrc));
  1125. Spills.erase(SpillSrc, Spills.end());
  1126. }
  1127. void LiveRangeUpdater::flush() {
  1128. if (!isDirty())
  1129. return;
  1130. // Clear the dirty state.
  1131. LastStart = SlotIndex();
  1132. assert(LR && "Cannot add to a null destination");
  1133. // Nothing to merge?
  1134. if (Spills.empty()) {
  1135. LR->segments.erase(WriteI, ReadI);
  1136. LR->verify();
  1137. return;
  1138. }
  1139. // Resize the WriteI - ReadI gap to match Spills.
  1140. size_t GapSize = ReadI - WriteI;
  1141. if (GapSize < Spills.size()) {
  1142. // The gap is too small. Make some room.
  1143. size_t WritePos = WriteI - LR->begin();
  1144. LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
  1145. // This also invalidated ReadI, but it is recomputed below.
  1146. WriteI = LR->begin() + WritePos;
  1147. } else {
  1148. // Shrink the gap if necessary.
  1149. LR->segments.erase(WriteI + Spills.size(), ReadI);
  1150. }
  1151. ReadI = WriteI + Spills.size();
  1152. mergeSpills();
  1153. LR->verify();
  1154. }
  1155. unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
  1156. // Create initial equivalence classes.
  1157. EqClass.clear();
  1158. EqClass.grow(LR.getNumValNums());
  1159. const VNInfo *used = nullptr, *unused = nullptr;
  1160. // Determine connections.
  1161. for (const VNInfo *VNI : LR.valnos) {
  1162. // Group all unused values into one class.
  1163. if (VNI->isUnused()) {
  1164. if (unused)
  1165. EqClass.join(unused->id, VNI->id);
  1166. unused = VNI;
  1167. continue;
  1168. }
  1169. used = VNI;
  1170. if (VNI->isPHIDef()) {
  1171. const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
  1172. assert(MBB && "Phi-def has no defining MBB");
  1173. // Connect to values live out of predecessors.
  1174. for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
  1175. PE = MBB->pred_end(); PI != PE; ++PI)
  1176. if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
  1177. EqClass.join(VNI->id, PVNI->id);
  1178. } else {
  1179. // Normal value defined by an instruction. Check for two-addr redef.
  1180. // FIXME: This could be coincidental. Should we really check for a tied
  1181. // operand constraint?
  1182. // Note that VNI->def may be a use slot for an early clobber def.
  1183. if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
  1184. EqClass.join(VNI->id, UVNI->id);
  1185. }
  1186. }
  1187. // Lump all the unused values in with the last used value.
  1188. if (used && unused)
  1189. EqClass.join(used->id, unused->id);
  1190. EqClass.compress();
  1191. return EqClass.getNumClasses();
  1192. }
  1193. void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
  1194. MachineRegisterInfo &MRI) {
  1195. // Rewrite instructions.
  1196. for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
  1197. RE = MRI.reg_end(); RI != RE;) {
  1198. MachineOperand &MO = *RI;
  1199. MachineInstr *MI = RI->getParent();
  1200. ++RI;
  1201. const VNInfo *VNI;
  1202. if (MI->isDebugValue()) {
  1203. // DBG_VALUE instructions don't have slot indexes, so get the index of
  1204. // the instruction before them. The value is defined there too.
  1205. SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
  1206. VNI = LI.Query(Idx).valueOut();
  1207. } else {
  1208. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  1209. LiveQueryResult LRQ = LI.Query(Idx);
  1210. VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
  1211. }
  1212. // In the case of an <undef> use that isn't tied to any def, VNI will be
  1213. // NULL. If the use is tied to a def, VNI will be the defined value.
  1214. if (!VNI)
  1215. continue;
  1216. if (unsigned EqClass = getEqClass(VNI))
  1217. MO.setReg(LIV[EqClass-1]->reg);
  1218. }
  1219. // Distribute subregister liveranges.
  1220. if (LI.hasSubRanges()) {
  1221. unsigned NumComponents = EqClass.getNumClasses();
  1222. SmallVector<unsigned, 8> VNIMapping;
  1223. SmallVector<LiveInterval::SubRange*, 8> SubRanges;
  1224. BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
  1225. for (LiveInterval::SubRange &SR : LI.subranges()) {
  1226. // Create new subranges in the split intervals and construct a mapping
  1227. // for the VNInfos in the subrange.
  1228. unsigned NumValNos = SR.valnos.size();
  1229. VNIMapping.clear();
  1230. VNIMapping.reserve(NumValNos);
  1231. SubRanges.clear();
  1232. SubRanges.resize(NumComponents-1, nullptr);
  1233. for (unsigned I = 0; I < NumValNos; ++I) {
  1234. const VNInfo &VNI = *SR.valnos[I];
  1235. unsigned ComponentNum;
  1236. if (VNI.isUnused()) {
  1237. ComponentNum = 0;
  1238. } else {
  1239. const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
  1240. assert(MainRangeVNI != nullptr
  1241. && "SubRange def must have corresponding main range def");
  1242. ComponentNum = getEqClass(MainRangeVNI);
  1243. if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
  1244. SubRanges[ComponentNum-1]
  1245. = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
  1246. }
  1247. }
  1248. VNIMapping.push_back(ComponentNum);
  1249. }
  1250. DistributeRange(SR, SubRanges.data(), VNIMapping);
  1251. }
  1252. LI.removeEmptySubRanges();
  1253. }
  1254. // Distribute main liverange.
  1255. DistributeRange(LI, LIV, EqClass);
  1256. }