LiveInterval.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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 = lower_bound(*this, 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. segments.erase(I); // Removed the whole Segment.
  523. if (RemoveDeadValNo)
  524. removeValNoIfDead(ValNo);
  525. } else
  526. I->start = End;
  527. return;
  528. }
  529. // Otherwise if the span we are removing is at the end of the Segment,
  530. // adjust the other way.
  531. if (I->end == End) {
  532. I->end = Start;
  533. return;
  534. }
  535. // Otherwise, we are splitting the Segment into two pieces.
  536. SlotIndex OldEnd = I->end;
  537. I->end = Start; // Trim the old segment.
  538. // Insert the new one.
  539. segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
  540. }
  541. LiveRange::iterator LiveRange::removeSegment(iterator I, bool RemoveDeadValNo) {
  542. VNInfo *ValNo = I->valno;
  543. I = segments.erase(I);
  544. if (RemoveDeadValNo)
  545. removeValNoIfDead(ValNo);
  546. return I;
  547. }
  548. void LiveRange::removeValNoIfDead(VNInfo *ValNo) {
  549. if (none_of(*this, [=](const Segment &S) { return S.valno == ValNo; }))
  550. markValNoForDeletion(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. llvm::erase_if(segments,
  557. [ValNo](const Segment &S) { return S.valno == ValNo; });
  558. // Now that ValNo is dead, remove it.
  559. markValNoForDeletion(ValNo);
  560. }
  561. void LiveRange::join(LiveRange &Other,
  562. const int *LHSValNoAssignments,
  563. const int *RHSValNoAssignments,
  564. SmallVectorImpl<VNInfo *> &NewVNInfo) {
  565. verify();
  566. // Determine if any of our values are mapped. This is uncommon, so we want
  567. // to avoid the range scan if not.
  568. bool MustMapCurValNos = false;
  569. unsigned NumVals = getNumValNums();
  570. unsigned NumNewVals = NewVNInfo.size();
  571. for (unsigned i = 0; i != NumVals; ++i) {
  572. unsigned LHSValID = LHSValNoAssignments[i];
  573. if (i != LHSValID ||
  574. (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
  575. MustMapCurValNos = true;
  576. break;
  577. }
  578. }
  579. // If we have to apply a mapping to our base range assignment, rewrite it now.
  580. if (MustMapCurValNos && !empty()) {
  581. // Map the first live range.
  582. iterator OutIt = begin();
  583. OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
  584. for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
  585. VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
  586. assert(nextValNo && "Huh?");
  587. // If this live range has the same value # as its immediate predecessor,
  588. // and if they are neighbors, remove one Segment. This happens when we
  589. // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
  590. if (OutIt->valno == nextValNo && OutIt->end == I->start) {
  591. OutIt->end = I->end;
  592. } else {
  593. // Didn't merge. Move OutIt to the next segment,
  594. ++OutIt;
  595. OutIt->valno = nextValNo;
  596. if (OutIt != I) {
  597. OutIt->start = I->start;
  598. OutIt->end = I->end;
  599. }
  600. }
  601. }
  602. // If we merge some segments, chop off the end.
  603. ++OutIt;
  604. segments.erase(OutIt, end());
  605. }
  606. // Rewrite Other values before changing the VNInfo ids.
  607. // This can leave Other in an invalid state because we're not coalescing
  608. // touching segments that now have identical values. That's OK since Other is
  609. // not supposed to be valid after calling join();
  610. for (Segment &S : Other.segments)
  611. S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
  612. // Update val# info. Renumber them and make sure they all belong to this
  613. // LiveRange now. Also remove dead val#'s.
  614. unsigned NumValNos = 0;
  615. for (unsigned i = 0; i < NumNewVals; ++i) {
  616. VNInfo *VNI = NewVNInfo[i];
  617. if (VNI) {
  618. if (NumValNos >= NumVals)
  619. valnos.push_back(VNI);
  620. else
  621. valnos[NumValNos] = VNI;
  622. VNI->id = NumValNos++; // Renumber val#.
  623. }
  624. }
  625. if (NumNewVals < NumVals)
  626. valnos.resize(NumNewVals); // shrinkify
  627. // Okay, now insert the RHS live segments into the LHS.
  628. LiveRangeUpdater Updater(this);
  629. for (Segment &S : Other.segments)
  630. Updater.add(S);
  631. }
  632. /// Merge all of the segments in RHS into this live range as the specified
  633. /// value number. The segments in RHS are allowed to overlap with segments in
  634. /// the current range, but only if the overlapping segments have the
  635. /// specified value number.
  636. void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
  637. VNInfo *LHSValNo) {
  638. LiveRangeUpdater Updater(this);
  639. for (const Segment &S : RHS.segments)
  640. Updater.add(S.start, S.end, LHSValNo);
  641. }
  642. /// MergeValueInAsValue - Merge all of the live segments of a specific val#
  643. /// in RHS into this live range as the specified value number.
  644. /// The segments in RHS are allowed to overlap with segments in the
  645. /// current range, it will replace the value numbers of the overlaped
  646. /// segments with the specified value number.
  647. void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
  648. const VNInfo *RHSValNo,
  649. VNInfo *LHSValNo) {
  650. LiveRangeUpdater Updater(this);
  651. for (const Segment &S : RHS.segments)
  652. if (S.valno == RHSValNo)
  653. Updater.add(S.start, S.end, LHSValNo);
  654. }
  655. /// MergeValueNumberInto - This method is called when two value nubmers
  656. /// are found to be equivalent. This eliminates V1, replacing all
  657. /// segments with the V1 value number with the V2 value number. This can
  658. /// cause merging of V1/V2 values numbers and compaction of the value space.
  659. VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
  660. assert(V1 != V2 && "Identical value#'s are always equivalent!");
  661. // This code actually merges the (numerically) larger value number into the
  662. // smaller value number, which is likely to allow us to compactify the value
  663. // space. The only thing we have to be careful of is to preserve the
  664. // instruction that defines the result value.
  665. // Make sure V2 is smaller than V1.
  666. if (V1->id < V2->id) {
  667. V1->copyFrom(*V2);
  668. std::swap(V1, V2);
  669. }
  670. // Merge V1 segments into V2.
  671. for (iterator I = begin(); I != end(); ) {
  672. iterator S = I++;
  673. if (S->valno != V1) continue; // Not a V1 Segment.
  674. // Okay, we found a V1 live range. If it had a previous, touching, V2 live
  675. // range, extend it.
  676. if (S != begin()) {
  677. iterator Prev = S-1;
  678. if (Prev->valno == V2 && Prev->end == S->start) {
  679. Prev->end = S->end;
  680. // Erase this live-range.
  681. segments.erase(S);
  682. I = Prev+1;
  683. S = Prev;
  684. }
  685. }
  686. // Okay, now we have a V1 or V2 live range that is maximally merged forward.
  687. // Ensure that it is a V2 live-range.
  688. S->valno = V2;
  689. // If we can merge it into later V2 segments, do so now. We ignore any
  690. // following V1 segments, as they will be merged in subsequent iterations
  691. // of the loop.
  692. if (I != end()) {
  693. if (I->start == S->end && I->valno == V2) {
  694. S->end = I->end;
  695. segments.erase(I);
  696. I = S+1;
  697. }
  698. }
  699. }
  700. // Now that V1 is dead, remove it.
  701. markValNoForDeletion(V1);
  702. return V2;
  703. }
  704. void LiveRange::flushSegmentSet() {
  705. assert(segmentSet != nullptr && "segment set must have been created");
  706. assert(
  707. segments.empty() &&
  708. "segment set can be used only initially before switching to the array");
  709. segments.append(segmentSet->begin(), segmentSet->end());
  710. segmentSet = nullptr;
  711. verify();
  712. }
  713. bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
  714. ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
  715. ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
  716. // If there are no regmask slots, we have nothing to search.
  717. if (SlotI == SlotE)
  718. return false;
  719. // Start our search at the first segment that ends after the first slot.
  720. const_iterator SegmentI = find(*SlotI);
  721. const_iterator SegmentE = end();
  722. // If there are no segments that end after the first slot, we're done.
  723. if (SegmentI == SegmentE)
  724. return false;
  725. // Look for each slot in the live range.
  726. for ( ; SlotI != SlotE; ++SlotI) {
  727. // Go to the next segment that ends after the current slot.
  728. // The slot may be within a hole in the range.
  729. SegmentI = advanceTo(SegmentI, *SlotI);
  730. if (SegmentI == SegmentE)
  731. return false;
  732. // If this segment contains the slot, we're done.
  733. if (SegmentI->contains(*SlotI))
  734. return true;
  735. // Otherwise, look for the next slot.
  736. }
  737. // We didn't find a segment containing any of the slots.
  738. return false;
  739. }
  740. void LiveInterval::freeSubRange(SubRange *S) {
  741. S->~SubRange();
  742. // Memory was allocated with BumpPtr allocator and is not freed here.
  743. }
  744. void LiveInterval::removeEmptySubRanges() {
  745. SubRange **NextPtr = &SubRanges;
  746. SubRange *I = *NextPtr;
  747. while (I != nullptr) {
  748. if (!I->empty()) {
  749. NextPtr = &I->Next;
  750. I = *NextPtr;
  751. continue;
  752. }
  753. // Skip empty subranges until we find the first nonempty one.
  754. do {
  755. SubRange *Next = I->Next;
  756. freeSubRange(I);
  757. I = Next;
  758. } while (I != nullptr && I->empty());
  759. *NextPtr = I;
  760. }
  761. }
  762. void LiveInterval::clearSubRanges() {
  763. for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
  764. Next = I->Next;
  765. freeSubRange(I);
  766. }
  767. SubRanges = nullptr;
  768. }
  769. /// For each VNI in \p SR, check whether or not that value defines part
  770. /// of the mask describe by \p LaneMask and if not, remove that value
  771. /// from \p SR.
  772. static void stripValuesNotDefiningMask(unsigned Reg, LiveInterval::SubRange &SR,
  773. LaneBitmask LaneMask,
  774. const SlotIndexes &Indexes,
  775. const TargetRegisterInfo &TRI,
  776. unsigned ComposeSubRegIdx) {
  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. LaneBitmask OrigMask = TRI.getSubRegIndexLaneMask(MOI->getSubReg());
  799. LaneBitmask ExpectedDefMask =
  800. ComposeSubRegIdx
  801. ? TRI.composeSubRegIndexLaneMask(ComposeSubRegIdx, OrigMask)
  802. : OrigMask;
  803. if ((ExpectedDefMask & LaneMask).none())
  804. continue;
  805. hasDef = true;
  806. break;
  807. }
  808. if (!hasDef)
  809. ToBeRemoved.push_back(VNI);
  810. }
  811. for (VNInfo *VNI : ToBeRemoved)
  812. SR.removeValNo(VNI);
  813. // If the subrange is empty at this point, the MIR is invalid. Do not assert
  814. // and let the verifier catch this case.
  815. }
  816. void LiveInterval::refineSubRanges(
  817. BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
  818. std::function<void(LiveInterval::SubRange &)> Apply,
  819. const SlotIndexes &Indexes, const TargetRegisterInfo &TRI,
  820. unsigned ComposeSubRegIdx) {
  821. LaneBitmask ToApply = LaneMask;
  822. for (SubRange &SR : subranges()) {
  823. LaneBitmask SRMask = SR.LaneMask;
  824. LaneBitmask Matching = SRMask & LaneMask;
  825. if (Matching.none())
  826. continue;
  827. SubRange *MatchingRange;
  828. if (SRMask == Matching) {
  829. // The subrange fits (it does not cover bits outside \p LaneMask).
  830. MatchingRange = &SR;
  831. } else {
  832. // We have to split the subrange into a matching and non-matching part.
  833. // Reduce lanemask of existing lane to non-matching part.
  834. SR.LaneMask = SRMask & ~Matching;
  835. // Create a new subrange for the matching part
  836. MatchingRange = createSubRangeFrom(Allocator, Matching, SR);
  837. // Now that the subrange is split in half, make sure we
  838. // only keep in the subranges the VNIs that touch the related half.
  839. stripValuesNotDefiningMask(reg(), *MatchingRange, Matching, Indexes, TRI,
  840. ComposeSubRegIdx);
  841. stripValuesNotDefiningMask(reg(), SR, SR.LaneMask, Indexes, TRI,
  842. ComposeSubRegIdx);
  843. }
  844. Apply(*MatchingRange);
  845. ToApply &= ~Matching;
  846. }
  847. // Create a new subrange if there are uncovered bits left.
  848. if (ToApply.any()) {
  849. SubRange *NewRange = createSubRange(Allocator, ToApply);
  850. Apply(*NewRange);
  851. }
  852. }
  853. unsigned LiveInterval::getSize() const {
  854. unsigned Sum = 0;
  855. for (const Segment &S : segments)
  856. Sum += S.start.distance(S.end);
  857. return Sum;
  858. }
  859. void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
  860. LaneBitmask LaneMask,
  861. const MachineRegisterInfo &MRI,
  862. const SlotIndexes &Indexes) const {
  863. assert(Register::isVirtualRegister(reg()));
  864. LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg());
  865. assert((VRegMask & LaneMask).any());
  866. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  867. for (const MachineOperand &MO : MRI.def_operands(reg())) {
  868. if (!MO.isUndef())
  869. continue;
  870. unsigned SubReg = MO.getSubReg();
  871. assert(SubReg != 0 && "Undef should only be set on subreg defs");
  872. LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
  873. LaneBitmask UndefMask = VRegMask & ~DefMask;
  874. if ((UndefMask & LaneMask).any()) {
  875. const MachineInstr &MI = *MO.getParent();
  876. bool EarlyClobber = MO.isEarlyClobber();
  877. SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber);
  878. Undefs.push_back(Pos);
  879. }
  880. }
  881. }
  882. raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) {
  883. return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
  884. }
  885. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  886. LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
  887. dbgs() << *this << '\n';
  888. }
  889. #endif
  890. void LiveRange::print(raw_ostream &OS) const {
  891. if (empty())
  892. OS << "EMPTY";
  893. else {
  894. for (const Segment &S : segments) {
  895. OS << S;
  896. assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
  897. }
  898. }
  899. // Print value number info.
  900. if (getNumValNums()) {
  901. OS << ' ';
  902. unsigned vnum = 0;
  903. for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
  904. ++i, ++vnum) {
  905. const VNInfo *vni = *i;
  906. if (vnum) OS << ' ';
  907. OS << vnum << '@';
  908. if (vni->isUnused()) {
  909. OS << 'x';
  910. } else {
  911. OS << vni->def;
  912. if (vni->isPHIDef())
  913. OS << "-phi";
  914. }
  915. }
  916. }
  917. }
  918. void LiveInterval::SubRange::print(raw_ostream &OS) const {
  919. OS << " L" << PrintLaneMask(LaneMask) << ' '
  920. << static_cast<const LiveRange &>(*this);
  921. }
  922. void LiveInterval::print(raw_ostream &OS) const {
  923. OS << printReg(reg()) << ' ';
  924. super::print(OS);
  925. // Print subranges
  926. for (const SubRange &SR : subranges())
  927. OS << SR;
  928. OS << " weight:" << Weight;
  929. }
  930. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  931. LLVM_DUMP_METHOD void LiveRange::dump() const {
  932. dbgs() << *this << '\n';
  933. }
  934. LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
  935. dbgs() << *this << '\n';
  936. }
  937. LLVM_DUMP_METHOD void LiveInterval::dump() const {
  938. dbgs() << *this << '\n';
  939. }
  940. #endif
  941. #ifndef NDEBUG
  942. void LiveRange::verify() const {
  943. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  944. assert(I->start.isValid());
  945. assert(I->end.isValid());
  946. assert(I->start < I->end);
  947. assert(I->valno != nullptr);
  948. assert(I->valno->id < valnos.size());
  949. assert(I->valno == valnos[I->valno->id]);
  950. if (std::next(I) != E) {
  951. assert(I->end <= std::next(I)->start);
  952. if (I->end == std::next(I)->start)
  953. assert(I->valno != std::next(I)->valno);
  954. }
  955. }
  956. }
  957. void LiveInterval::verify(const MachineRegisterInfo *MRI) const {
  958. super::verify();
  959. // Make sure SubRanges are fine and LaneMasks are disjunct.
  960. LaneBitmask Mask;
  961. LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg())
  962. : LaneBitmask::getAll();
  963. for (const SubRange &SR : subranges()) {
  964. // Subrange lanemask should be disjunct to any previous subrange masks.
  965. assert((Mask & SR.LaneMask).none());
  966. Mask |= SR.LaneMask;
  967. // subrange mask should not contained in maximum lane mask for the vreg.
  968. assert((Mask & ~MaxMask).none());
  969. // empty subranges must be removed.
  970. assert(!SR.empty());
  971. SR.verify();
  972. // Main liverange should cover subrange.
  973. assert(covers(SR));
  974. }
  975. }
  976. #endif
  977. //===----------------------------------------------------------------------===//
  978. // LiveRangeUpdater class
  979. //===----------------------------------------------------------------------===//
  980. //
  981. // The LiveRangeUpdater class always maintains these invariants:
  982. //
  983. // - When LastStart is invalid, Spills is empty and the iterators are invalid.
  984. // This is the initial state, and the state created by flush().
  985. // In this state, isDirty() returns false.
  986. //
  987. // Otherwise, segments are kept in three separate areas:
  988. //
  989. // 1. [begin; WriteI) at the front of LR.
  990. // 2. [ReadI; end) at the back of LR.
  991. // 3. Spills.
  992. //
  993. // - LR.begin() <= WriteI <= ReadI <= LR.end().
  994. // - Segments in all three areas are fully ordered and coalesced.
  995. // - Segments in area 1 precede and can't coalesce with segments in area 2.
  996. // - Segments in Spills precede and can't coalesce with segments in area 2.
  997. // - No coalescing is possible between segments in Spills and segments in area
  998. // 1, and there are no overlapping segments.
  999. //
  1000. // The segments in Spills are not ordered with respect to the segments in area
  1001. // 1. They need to be merged.
  1002. //
  1003. // When they exist, Spills.back().start <= LastStart,
  1004. // and WriteI[-1].start <= LastStart.
  1005. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1006. void LiveRangeUpdater::print(raw_ostream &OS) const {
  1007. if (!isDirty()) {
  1008. if (LR)
  1009. OS << "Clean updater: " << *LR << '\n';
  1010. else
  1011. OS << "Null updater.\n";
  1012. return;
  1013. }
  1014. assert(LR && "Can't have null LR in dirty updater.");
  1015. OS << " updater with gap = " << (ReadI - WriteI)
  1016. << ", last start = " << LastStart
  1017. << ":\n Area 1:";
  1018. for (const auto &S : make_range(LR->begin(), WriteI))
  1019. OS << ' ' << S;
  1020. OS << "\n Spills:";
  1021. for (unsigned I = 0, E = Spills.size(); I != E; ++I)
  1022. OS << ' ' << Spills[I];
  1023. OS << "\n Area 2:";
  1024. for (const auto &S : make_range(ReadI, LR->end()))
  1025. OS << ' ' << S;
  1026. OS << '\n';
  1027. }
  1028. LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
  1029. print(errs());
  1030. }
  1031. #endif
  1032. // Determine if A and B should be coalesced.
  1033. static inline bool coalescable(const LiveRange::Segment &A,
  1034. const LiveRange::Segment &B) {
  1035. assert(A.start <= B.start && "Unordered live segments.");
  1036. if (A.end == B.start)
  1037. return A.valno == B.valno;
  1038. if (A.end < B.start)
  1039. return false;
  1040. assert(A.valno == B.valno && "Cannot overlap different values");
  1041. return true;
  1042. }
  1043. void LiveRangeUpdater::add(LiveRange::Segment Seg) {
  1044. assert(LR && "Cannot add to a null destination");
  1045. // Fall back to the regular add method if the live range
  1046. // is using the segment set instead of the segment vector.
  1047. if (LR->segmentSet != nullptr) {
  1048. LR->addSegmentToSet(Seg);
  1049. return;
  1050. }
  1051. // Flush the state if Start moves backwards.
  1052. if (!LastStart.isValid() || LastStart > Seg.start) {
  1053. if (isDirty())
  1054. flush();
  1055. // This brings us to an uninitialized state. Reinitialize.
  1056. assert(Spills.empty() && "Leftover spilled segments");
  1057. WriteI = ReadI = LR->begin();
  1058. }
  1059. // Remember start for next time.
  1060. LastStart = Seg.start;
  1061. // Advance ReadI until it ends after Seg.start.
  1062. LiveRange::iterator E = LR->end();
  1063. if (ReadI != E && ReadI->end <= Seg.start) {
  1064. // First try to close the gap between WriteI and ReadI with spills.
  1065. if (ReadI != WriteI)
  1066. mergeSpills();
  1067. // Then advance ReadI.
  1068. if (ReadI == WriteI)
  1069. ReadI = WriteI = LR->find(Seg.start);
  1070. else
  1071. while (ReadI != E && ReadI->end <= Seg.start)
  1072. *WriteI++ = *ReadI++;
  1073. }
  1074. assert(ReadI == E || ReadI->end > Seg.start);
  1075. // Check if the ReadI segment begins early.
  1076. if (ReadI != E && ReadI->start <= Seg.start) {
  1077. assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
  1078. // Bail if Seg is completely contained in ReadI.
  1079. if (ReadI->end >= Seg.end)
  1080. return;
  1081. // Coalesce into Seg.
  1082. Seg.start = ReadI->start;
  1083. ++ReadI;
  1084. }
  1085. // Coalesce as much as possible from ReadI into Seg.
  1086. while (ReadI != E && coalescable(Seg, *ReadI)) {
  1087. Seg.end = std::max(Seg.end, ReadI->end);
  1088. ++ReadI;
  1089. }
  1090. // Try coalescing Spills.back() into Seg.
  1091. if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
  1092. Seg.start = Spills.back().start;
  1093. Seg.end = std::max(Spills.back().end, Seg.end);
  1094. Spills.pop_back();
  1095. }
  1096. // Try coalescing Seg into WriteI[-1].
  1097. if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
  1098. WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
  1099. return;
  1100. }
  1101. // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
  1102. if (WriteI != ReadI) {
  1103. *WriteI++ = Seg;
  1104. return;
  1105. }
  1106. // Finally, append to LR or Spills.
  1107. if (WriteI == E) {
  1108. LR->segments.push_back(Seg);
  1109. WriteI = ReadI = LR->end();
  1110. } else
  1111. Spills.push_back(Seg);
  1112. }
  1113. // Merge as many spilled segments as possible into the gap between WriteI
  1114. // and ReadI. Advance WriteI to reflect the inserted instructions.
  1115. void LiveRangeUpdater::mergeSpills() {
  1116. // Perform a backwards merge of Spills and [SpillI;WriteI).
  1117. size_t GapSize = ReadI - WriteI;
  1118. size_t NumMoved = std::min(Spills.size(), GapSize);
  1119. LiveRange::iterator Src = WriteI;
  1120. LiveRange::iterator Dst = Src + NumMoved;
  1121. LiveRange::iterator SpillSrc = Spills.end();
  1122. LiveRange::iterator B = LR->begin();
  1123. // This is the new WriteI position after merging spills.
  1124. WriteI = Dst;
  1125. // Now merge Src and Spills backwards.
  1126. while (Src != Dst) {
  1127. if (Src != B && Src[-1].start > SpillSrc[-1].start)
  1128. *--Dst = *--Src;
  1129. else
  1130. *--Dst = *--SpillSrc;
  1131. }
  1132. assert(NumMoved == size_t(Spills.end() - SpillSrc));
  1133. Spills.erase(SpillSrc, Spills.end());
  1134. }
  1135. void LiveRangeUpdater::flush() {
  1136. if (!isDirty())
  1137. return;
  1138. // Clear the dirty state.
  1139. LastStart = SlotIndex();
  1140. assert(LR && "Cannot add to a null destination");
  1141. // Nothing to merge?
  1142. if (Spills.empty()) {
  1143. LR->segments.erase(WriteI, ReadI);
  1144. LR->verify();
  1145. return;
  1146. }
  1147. // Resize the WriteI - ReadI gap to match Spills.
  1148. size_t GapSize = ReadI - WriteI;
  1149. if (GapSize < Spills.size()) {
  1150. // The gap is too small. Make some room.
  1151. size_t WritePos = WriteI - LR->begin();
  1152. LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
  1153. // This also invalidated ReadI, but it is recomputed below.
  1154. WriteI = LR->begin() + WritePos;
  1155. } else {
  1156. // Shrink the gap if necessary.
  1157. LR->segments.erase(WriteI + Spills.size(), ReadI);
  1158. }
  1159. ReadI = WriteI + Spills.size();
  1160. mergeSpills();
  1161. LR->verify();
  1162. }
  1163. unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
  1164. // Create initial equivalence classes.
  1165. EqClass.clear();
  1166. EqClass.grow(LR.getNumValNums());
  1167. const VNInfo *used = nullptr, *unused = nullptr;
  1168. // Determine connections.
  1169. for (const VNInfo *VNI : LR.valnos) {
  1170. // Group all unused values into one class.
  1171. if (VNI->isUnused()) {
  1172. if (unused)
  1173. EqClass.join(unused->id, VNI->id);
  1174. unused = VNI;
  1175. continue;
  1176. }
  1177. used = VNI;
  1178. if (VNI->isPHIDef()) {
  1179. const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
  1180. assert(MBB && "Phi-def has no defining MBB");
  1181. // Connect to values live out of predecessors.
  1182. for (MachineBasicBlock *Pred : MBB->predecessors())
  1183. if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(Pred)))
  1184. EqClass.join(VNI->id, PVNI->id);
  1185. } else {
  1186. // Normal value defined by an instruction. Check for two-addr redef.
  1187. // FIXME: This could be coincidental. Should we really check for a tied
  1188. // operand constraint?
  1189. // Note that VNI->def may be a use slot for an early clobber def.
  1190. if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
  1191. EqClass.join(VNI->id, UVNI->id);
  1192. }
  1193. }
  1194. // Lump all the unused values in with the last used value.
  1195. if (used && unused)
  1196. EqClass.join(used->id, unused->id);
  1197. EqClass.compress();
  1198. return EqClass.getNumClasses();
  1199. }
  1200. void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
  1201. MachineRegisterInfo &MRI) {
  1202. // Rewrite instructions.
  1203. for (MachineOperand &MO :
  1204. llvm::make_early_inc_range(MRI.reg_operands(LI.reg()))) {
  1205. MachineInstr *MI = MO.getParent();
  1206. const VNInfo *VNI;
  1207. if (MI->isDebugValue()) {
  1208. // DBG_VALUE instructions don't have slot indexes, so get the index of
  1209. // the instruction before them. The value is defined there too.
  1210. SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
  1211. VNI = LI.Query(Idx).valueOut();
  1212. } else {
  1213. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  1214. LiveQueryResult LRQ = LI.Query(Idx);
  1215. VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
  1216. }
  1217. // In the case of an <undef> use that isn't tied to any def, VNI will be
  1218. // NULL. If the use is tied to a def, VNI will be the defined value.
  1219. if (!VNI)
  1220. continue;
  1221. if (unsigned EqClass = getEqClass(VNI))
  1222. MO.setReg(LIV[EqClass - 1]->reg());
  1223. }
  1224. // Distribute subregister liveranges.
  1225. if (LI.hasSubRanges()) {
  1226. unsigned NumComponents = EqClass.getNumClasses();
  1227. SmallVector<unsigned, 8> VNIMapping;
  1228. SmallVector<LiveInterval::SubRange*, 8> SubRanges;
  1229. BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
  1230. for (LiveInterval::SubRange &SR : LI.subranges()) {
  1231. // Create new subranges in the split intervals and construct a mapping
  1232. // for the VNInfos in the subrange.
  1233. unsigned NumValNos = SR.valnos.size();
  1234. VNIMapping.clear();
  1235. VNIMapping.reserve(NumValNos);
  1236. SubRanges.clear();
  1237. SubRanges.resize(NumComponents-1, nullptr);
  1238. for (unsigned I = 0; I < NumValNos; ++I) {
  1239. const VNInfo &VNI = *SR.valnos[I];
  1240. unsigned ComponentNum;
  1241. if (VNI.isUnused()) {
  1242. ComponentNum = 0;
  1243. } else {
  1244. const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
  1245. assert(MainRangeVNI != nullptr
  1246. && "SubRange def must have corresponding main range def");
  1247. ComponentNum = getEqClass(MainRangeVNI);
  1248. if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
  1249. SubRanges[ComponentNum-1]
  1250. = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
  1251. }
  1252. }
  1253. VNIMapping.push_back(ComponentNum);
  1254. }
  1255. DistributeRange(SR, SubRanges.data(), VNIMapping);
  1256. }
  1257. LI.removeEmptySubRanges();
  1258. }
  1259. // Distribute main liverange.
  1260. DistributeRange(LI, LIV, EqClass);
  1261. }